/** * Create a schema exporter for the given Configuration, using the supplied connection for connectivity. * * @param configuration The configuration to use. * @param connection The JDBC connection to use. * @throws HibernateException Indicates problem preparing for schema export. */ public SchemaExport(Configuration configuration, Connection connection) throws HibernateException { this.connectionHelper = new SuppliedConnectionHelper( connection ); this.sqlStatementLogger = new SqlStatementLogger( false, true ); this.formatter = FormatStyle.DDL.getFormatter(); this.sqlExceptionHelper = new SqlExceptionHelper(); this.importFiles = ConfigurationHelper.getString( AvailableSettings.HBM2DDL_IMPORT_FILES, configuration.getProperties(), DEFAULT_IMPORT_FILE ); final Dialect dialect = Dialect.getDialect( configuration.getProperties() ); this.dropSQL = configuration.generateDropSchemaScript( dialect ); this.createSQL = configuration.generateSchemaCreationScript( dialect ); }
/** * Determine the table name to use for the generator values. * <p/> * Called during {@link #configure configuration}. * * @see #getTableName() * @param params The params supplied in the generator config (plus some standard useful extras). * @param dialect The dialect in effect * @return The table name to use. */ protected String determineGeneratorTableName(Properties params, Dialect dialect) { String name = ConfigurationHelper.getString( TABLE_PARAM, params, DEF_TABLE ); final boolean isGivenNameUnqualified = name.indexOf( '.' ) < 0; if ( isGivenNameUnqualified ) { final ObjectNameNormalizer normalizer = (ObjectNameNormalizer) params.get( IDENTIFIER_NORMALIZER ); name = normalizer.normalizeIdentifierQuoting( name ); // if the given name is un-qualified we may neen to qualify it final String schemaName = normalizer.normalizeIdentifierQuoting( params.getProperty( SCHEMA ) ); final String catalogName = normalizer.normalizeIdentifierQuoting( params.getProperty( CATALOG ) ); name = Table.qualify( dialect.quote( catalogName ), dialect.quote( schemaName ), dialect.quote( name) ); } // if already qualified there is not much we can do in a portable manner so we pass it // through and assume the user has set up the name correctly. return name; }
/** * Determine the appropriate Dialect to use given the connection. * * @param resolutionInfoSource Access to DialectResolutionInfo used to resolve the Dialect. * * @return The appropriate dialect instance. * * @throws HibernateException No connection given or no resolver could make * the determination from the given connection. */ private Dialect determineDialect(DialectResolutionInfoSource resolutionInfoSource) { if ( resolutionInfoSource == null ) { throw new HibernateException( "Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set" ); } final DialectResolutionInfo info = resolutionInfoSource.getDialectResolutionInfo(); final Dialect dialect = dialectResolver.resolveDialect( info ); if ( dialect == null ) { throw new HibernateException( "Unable to determine Dialect to use [name=" + info.getDatabaseName() + ", majorVersion=" + info.getDatabaseMajorVersion() + "]; user must register resolver or explicitly set 'hibernate.dialect'" ); } return dialect; }
@Override @SuppressWarnings("unchecked") public String getRenderText(SessionFactoryImplementor sessionFactory) { final Type type = expectedType == null ? heuristicType : Number.class.isAssignableFrom( heuristicType.getReturnedClass() ) ? heuristicType : expectedType; try { final LiteralType literalType = (LiteralType) type; final Dialect dialect = factory.getDialect(); return literalType.objectToSQLString( constantValue, dialect ); } catch (Exception t) { throw new QueryException( QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + constantExpression, t ); } }
/** * Execute schema drop script, determined by the Configuration object * used for creating the SessionFactory. A replacement for Hibernate's * SchemaExport class, to be invoked on application setup. * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed * SessionFactory to be able to invoke this method, e.g. via * {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");}. * <p>Uses the SessionFactory that this bean generates for accessing a * JDBC connection to perform the script. * @throws org.springframework.dao.DataAccessException in case of script execution errors * @see org.hibernate.cfg.Configuration#generateDropSchemaScript * @see org.hibernate.tool.hbm2ddl.SchemaExport#drop */ public void dropDatabaseSchema() throws DataAccessException { logger.info("Dropping database schema for Hibernate SessionFactory"); SessionFactory sessionFactory = getSessionFactory(); final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect(); HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); hibernateTemplate.execute( new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { @SuppressWarnings("deprecation") Connection con = session.connection(); String[] sql = getConfiguration().generateDropSchemaScript(dialect); executeSchemaScript(con, sql); return null; } } ); }
/** * Create a schema exporter for the given Configuration, with the given * database connection properties. * * @param configuration The configuration from which to build a schema export. * @param properties The properties from which to configure connectivity etc. * @throws HibernateException Indicates problem preparing for schema export. * * @deprecated properties may be specified via the Configuration object */ @Deprecated public SchemaExport(Configuration configuration, Properties properties) throws HibernateException { final Dialect dialect = Dialect.getDialect( properties ); Properties props = new Properties(); props.putAll( dialect.getDefaultProperties() ); props.putAll( properties ); this.connectionHelper = new ManagedProviderConnectionHelper( props ); this.sqlStatementLogger = new SqlStatementLogger( false, true ); this.formatter = FormatStyle.DDL.getFormatter(); this.sqlExceptionHelper = new SqlExceptionHelper(); this.importFiles = ConfigurationHelper.getString( AvailableSettings.HBM2DDL_IMPORT_FILES, properties, DEFAULT_IMPORT_FILE ); this.dropSQL = configuration.generateDropSchemaScript( dialect ); this.createSQL = configuration.generateSchemaCreationScript( dialect ); }
@Test public void testGetProcessesMatchesIgnoreCaseNoResults() { Dialect dialect = (Dialect) applicationContext.getBean("dialect"); if (dialect instanceof AlfrescoSQLServerDialect) { // REPO-1104: we do not run this test on MS SQL server because it will fail // until the Activiti defect related to REPO-1104 will be fixed // this test could fail on other DBs where the LIKE operator behaves as case insensitive return; } CollectionWithPagingInfo<ProcessInfo> result = queryMatchesProcesses("test workflow api calls review and approve"); assertNotNull(result); assertNotNull(result.getCollection()); assertTrue(result.getTotalItems() == 0 ); }
/** * Build a SQLExceptionConverter instance. * <p/> * First, looks for a {@link Environment#SQL_EXCEPTION_CONVERTER} property to see * if the configuration specified the class of a specific converter to use. If this * property is set, attempt to construct an instance of that class. If not set, or * if construction fails, the converter specific to the dialect will be used. * * @param dialect The defined dialect. * @param properties The configuration properties. * @return An appropriate SQLExceptionConverter instance. * @throws HibernateException There was an error building the SQLExceptionConverter. */ public static SQLExceptionConverter buildSQLExceptionConverter(Dialect dialect, Properties properties) throws HibernateException { SQLExceptionConverter converter = null; String converterClassName = (String) properties.get( Environment.SQL_EXCEPTION_CONVERTER ); if ( StringHelper.isNotEmpty( converterClassName ) ) { converter = constructConverter( converterClassName, dialect.getViolatedConstraintNameExtracter() ); } if ( converter == null ) { LOG.trace( "Using dialect defined converter" ); converter = dialect.buildSQLExceptionConverter(); } if ( converter instanceof Configurable ) { try { ( (Configurable) converter ).configure( properties ); } catch (HibernateException e) { LOG.unableToConfigureSqlExceptionConverter( e ); throw e; } } return converter; }
public String sqlTemporaryTableCreateString(Dialect dialect, Mapping mapping) throws HibernateException { StringBuilder buffer = new StringBuilder( dialect.getCreateTemporaryTableString() ) .append( ' ' ) .append( name ) .append( " (" ); Iterator itr = getColumnIterator(); while ( itr.hasNext() ) { final Column column = (Column) itr.next(); buffer.append( column.getQuotedName( dialect ) ).append( ' ' ); buffer.append( column.getSqlType( dialect, mapping ) ); if ( column.isNullable() ) { buffer.append( dialect.getNullColumnString() ); } else { buffer.append( " not null" ); } if ( itr.hasNext() ) { buffer.append( ", " ); } } buffer.append( ") " ); buffer.append( dialect.getCreateTemporaryTablePostfix() ); return buffer.toString(); }
@Override public final Dialect resolveDialect(DialectResolutionInfo info) { final String databaseName = info.getDatabaseName(); final int databaseMajorVersion = info.getDatabaseMajorVersion(); final int databaseMinorVersion = info.getDatabaseMinorVersion(); if ( nameToMatch.equalsIgnoreCase( databaseName ) && ( majorVersionToMatch == NO_VERSION || majorVersionToMatch == databaseMajorVersion ) && ( minorVersionToMatch == NO_VERSION || majorVersionToMatch == databaseMinorVersion ) ) { try { return (Dialect) dialectClass.newInstance(); } catch ( HibernateException e ) { // conceivable that the dialect ctor could throw HibernateExceptions, so don't re-wrap throw e; } catch ( Throwable t ) { throw new HibernateException( "Could not instantiate specified Dialect class [" + dialectClass.getName() + "]", t ); } } return null; }
@Around("execution(java.lang.String org.hibernate.mapping.PrimaryKey.sqlConstraintString(..))") public String sqlConstraintStringAround(ProceedingJoinPoint joinPoint) throws Throwable { Dialect dialect = (Dialect) joinPoint.getArgs()[0]; if (!(dialect instanceof PhoenixDialect)) { // Nothing to deal with return (String) joinPoint.proceed(); } String statement = (String) joinPoint.proceed(); return "CONSTRAINT pk " + statement; }
public Delegate(PostInsertIdentityPersister persister, Dialect dialect, String sequenceName) { super( persister ); this.dialect = dialect; this.sequenceNextValFragment = dialect.getSelectSequenceNextValString( sequenceName ); this.keyColumns = getPersister().getRootTableKeyColumnNames(); if ( keyColumns.length > 1 ) { throw new HibernateException( "sequence-identity generator cannot be used with with multi-column keys" ); } }
/** * @see #DEFAULT_MAX_STRING_LENGTH */ public static final void setMaxStringLength(int length, Dialect dialect) { int max = (dialect instanceof AlfrescoMySQLClusterNDBDialect ? DEFAULT_MAX_STRING_LENGTH_NDB : DEFAULT_MAX_STRING_LENGTH); if (length < max) { throw new AlfrescoRuntimeException("The maximum string length must >= "+max+" characters."); } SchemaBootstrap.maxStringLength = length; }
/** * Replaces the dialect placeholder in the resource URL and attempts to find a file for * it. If not found, the dialect hierarchy will be walked until a compatible resource is * found. This makes it possible to have resources that are generic to all dialects. * * @return The Resource, otherwise null */ private Resource getDialectResource(Class<?> dialectClass, String resourceUrl) { // replace the dialect placeholder String dialectResourceUrl = resolveDialectUrl(dialectClass, resourceUrl); // get a handle on the resource Resource resource = rpr.getResource(dialectResourceUrl); if (!resource.exists()) { // it wasn't found. Get the superclass of the dialect and try again Class<?> superClass = dialectClass.getSuperclass(); if (Dialect.class.isAssignableFrom(superClass)) { // we still have a Dialect - try again return getDialectResource(superClass, resourceUrl); } else { // we have exhausted all options return null; } } else { // we have a handle to it return resource; } }
public String toAliasString(String sqlIdentifier) { char begin = sqlIdentifier.charAt(0); int quoteType = Dialect.QUOTE.indexOf(begin); String unquoted = getUnquotedAliasString(sqlIdentifier, quoteType); if ( quoteType >= 0 ) { char endQuote = Dialect.CLOSED_QUOTE.charAt(quoteType); return begin + unquoted + endQuote; } else { return unquoted; } }
/** * Same functionality as {@link #renderWhereStringTemplate(String, String, Dialect, SQLFunctionRegistry)}, * except that a SQLFunctionRegistry is not provided (i.e., only the dialect-defined functions are * considered). This is only intended for use by the annotations project until the * many-to-many/map-key-from-target-table feature is pulled into core. * * @deprecated Only intended for annotations usage; use {@link #renderWhereStringTemplate(String, String, Dialect, SQLFunctionRegistry)} instead */ @Deprecated @SuppressWarnings({ "JavaDoc" }) public static String renderWhereStringTemplate(String sqlWhereString, String placeholder, Dialect dialect) { return renderWhereStringTemplate( sqlWhereString, placeholder, dialect, new SQLFunctionRegistry( dialect, java.util.Collections.<String, SQLFunction>emptyMap() ) ); }
@Override protected String applyLocks( String sql, QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) throws QueryException { final LockOptions lockOptions = parameters.getLockOptions(); if ( lockOptions == null || ( lockOptions.getLockMode() == LockMode.NONE && lockOptions.getAliasLockCount() == 0 ) ) { return sql; } // user is request locking, lets see if we can apply locking directly to the SQL... // some dialects wont allow locking with paging... afterLoadActions.add( new AfterLoadAction() { private final LockOptions originalLockOptions = lockOptions.makeCopy(); @Override public void afterLoad(SessionImplementor session, Object entity, Loadable persister) { ( (Session) session ).buildLockRequest( originalLockOptions ).lock( persister.getEntityName(), entity ); } } ); parameters.getLockOptions().setLockMode( LockMode.READ ); return sql; }
/** * MNT-10067: use a script to delete the orphaned audit data (property values). */ public void testScriptCanDeleteOrphanedProps() throws Exception { Dialect dialect = (Dialect) ctx.getBean("dialect"); if (dialect instanceof AlfrescoMySQLClusterNDBDialect) { throw new Exception("TODO review this test case with NDB - note: throw exeception here else causes later tests to fail (when running via AllDBTestTestSuite)"); } // single test scriptCanDeleteOrphanedPropsWork(false); }
@Before public void setUp() throws Exception { ctx = ApplicationContextHelper.getApplicationContext(); dataSource = (DataSource) ctx.getBean("dataSource"); tx = (PlatformTransactionManager) ctx.getBean("transactionManager"); jdbcTemplate = new SimpleJdbcTemplate(dataSource); exporter = new ExportDb(ctx); exporter.setNamePrefix("export_test_"); dialect = (Dialect) ctx.getBean("dialect"); }
/** * Append <tt>FOR UPDATE OF</tt> clause, if necessary. This * empty superclass implementation merely returns its first * argument. */ protected String applyLocks( String sql, QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) throws HibernateException { return sql; }
@Override public String getQualifiedName(Dialect dialect) { return new StringBuilder( select.length() + 4 ) .append( "( " ) .append( select ) .append( " )" ) .toString(); }
public String[] sqlCreateStrings(Dialect dialect) { if ( isCreationVetoed( dialect ) ) { return null; } else { return new String[] { new StringBuilder( "alter table " ) .append( getTable().getQualifiedName( dialect ) ) .append( sqlConstraintStringInAlterTable( dialect ) ) .toString() }; } }
/** * Execute schema creation script, determined by the Configuration object * used for creating the SessionFactory. A replacement for Hibernate's * SchemaValidator class, to be invoked after application startup. * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed * SessionFactory to be able to invoke this method, e.g. via * {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");}. * <p>Uses the SessionFactory that this bean generates for accessing a * JDBC connection to perform the script. * @throws DataAccessException in case of script execution errors * @see org.hibernate.cfg.Configuration#validateSchema * @see org.hibernate.tool.hbm2ddl.SchemaValidator */ public void validateDatabaseSchema() throws DataAccessException { logger.info("Validating database schema for Hibernate SessionFactory"); DataSource dataSource = getDataSource(); if (dataSource != null) { // Make given DataSource available for the schema update. configTimeDataSourceHolder.set(dataSource); } try { SessionFactory sessionFactory = getSessionFactory(); final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect(); HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); hibernateTemplate.execute( new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { @SuppressWarnings("deprecation") Connection con = session.connection(); DatabaseMetadata metadata = new DatabaseMetadata(con, dialect, false); getConfiguration().validateSchema(dialect, metadata); return null; } } ); } finally { if (dataSource != null) { configTimeDataSourceHolder.remove(); } } }
@Override @SuppressWarnings( {"deprecation"}) public String[] sqlCreateStrings(Dialect dialect) throws HibernateException { String[] ddl = dialect.getCreateSequenceStrings( sequenceName ); if ( parameters != null ) { ddl[ddl.length - 1] += ' ' + parameters; } return ddl; }
@Override public void configure(Type type, Properties params, Dialect d) { super.configure( type, params, d ); maxLo = ConfigurationHelper.getInt( MAX_LO, params, Short.MAX_VALUE ); if ( maxLo >= 1 ) { hiloOptimizer = new LegacyHiLoAlgorithmOptimizer( type.getReturnedClass(), maxLo ); } }
public static void addBitwiseOperationsToDialect() { SessionFactoryImplementor hibSessionFactory = (SessionFactoryImplementor)new _RootDAO().getSession().getSessionFactory(); Dialect dialect = hibSessionFactory.getDialect(); if (!dialect.getFunctions().containsKey("bit_and")) { if (isOracle()) dialect.getFunctions().put("bit_and", new StandardSQLFunction("bitand", IntegerType.INSTANCE)); else dialect.getFunctions().put("bit_and", new SQLFunctionTemplate(IntegerType.INSTANCE, "?1 & ?2")); } }
public String toText(Dialect dialect) { if ( dialect == null ) { throw new IllegalArgumentException( "dialect must be non-null." ); } return qualify( encloseInQuotesIfQuoted( schema, dialect ), encloseInQuotesIfQuoted( catalog, dialect ), encloseInQuotesIfQuoted( name, dialect ) ); }
@Override public Dialect resolveDialect(DialectResolutionInfo info) { if ("DB2".equals(info.getDatabaseName())) { LOG.debug("DB2 detected returning DB2390Dialect"); return new DB2390Dialect(); } return null; }
private static void addSqlDropStrings( Dialect dialect, Set<String> exportIdentifiers, List<String> script, Exportable exportable) { addSqlStrings( exportIdentifiers, script, exportable.getExportIdentifier(), exportable.sqlDropStrings( dialect ) ); }
public void processBoolean(AST constant) { // TODO: something much better - look at the type of the other expression! // TODO: Have comparisonExpression and/or arithmeticExpression rules complete the resolution of boolean nodes. String replacement = (String) walker.getTokenReplacements().get( constant.getText() ); if ( replacement != null ) { constant.setText( replacement ); } else { boolean bool = "true".equals( constant.getText().toLowerCase() ); Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect(); constant.setText( dialect.toBooleanValueString( bool ) ); } }
public static String buildSqlCreateIndexString( Dialect dialect, String name, Table table, Iterator<Column> columns, java.util.Map<Column, String> columnOrderMap, boolean unique, String defaultCatalog, String defaultSchema ) { StringBuilder buf = new StringBuilder( "create" ) .append( unique ? " unique" : "" ) .append( " index " ) .append( dialect.qualifyIndexName() ? name : StringHelper.unqualify( name ) ) .append( " on " ) .append( table.getQualifiedName( dialect, defaultCatalog, defaultSchema ) ) .append( " (" ); while ( columns.hasNext() ) { Column column = columns.next(); buf.append( column.getQuotedName( dialect ) ); if ( columnOrderMap.containsKey( column ) ) { buf.append( " " ).append( columnOrderMap.get( column ) ); } if ( columns.hasNext() ) buf.append( ", " ); } buf.append( ")" ); return buf.toString(); }
public String sqlConstraintString(Dialect dialect) { StringBuilder buf = new StringBuilder( " index (" ); Iterator iter = getColumnIterator(); while ( iter.hasNext() ) { buf.append( ( (Column) iter.next() ).getQuotedName( dialect ) ); if ( iter.hasNext() ) buf.append( ", " ); } return buf.append( ')' ).toString(); }
public String sqlDropString(Dialect dialect, String defaultCatalog, String defaultSchema) { return "drop index " + StringHelper.qualify( table.getQualifiedName( dialect, defaultCatalog, defaultSchema ), name ); }
public String[] sqlDropStrings(Dialect dialect) { return new String[] { new StringBuilder( "drop index " ) .append( StringHelper.qualify( getTable().getQualifiedName( dialect ), getName() ) ).toString() }; }
public String getQualifiedName(Dialect dialect, String defaultCatalog, String defaultSchema) { if ( subselect != null ) { return "( " + subselect + " )"; } String quotedName = getQuotedName( dialect ); String usedSchema = schema == null ? defaultSchema : getQuotedSchema( dialect ); String usedCatalog = catalog == null ? defaultCatalog : getQuotedCatalog( dialect ); return qualify( usedCatalog, usedSchema, quotedName ); }
public static String buildSqlDropIndexString( Dialect dialect, TableSpecification table, String name ) { return "drop index " + StringHelper.qualify( table.getQualifiedName( dialect ), name ); }
public void prepareTemporaryTables(Mapping mapping, Dialect dialect) { temporaryIdTableName = dialect.generateTemporaryTableName( getTable().getName() ); if ( dialect.supportsTemporaryTables() ) { Table table = new Table(); table.setName( temporaryIdTableName ); Iterator itr = getTable().getPrimaryKey().getColumnIterator(); while( itr.hasNext() ) { Column column = (Column) itr.next(); table.addColumn( column.clone() ); } temporaryIdTableDDL = table.sqlTemporaryTableCreateString( dialect, mapping ); } }
public String sqlConstraintStringInCreateTable(Dialect dialect) { StringBuilder buf = new StringBuilder("primary key ("); boolean first = true; for ( Column column : getColumns() ) { if ( first ) { first = false; } else { buf.append(", "); } buf.append( column.getColumnName().encloseInQuotesIfQuoted( dialect ) ); } return buf.append(')').toString(); }