Search in sources :

Example 1 with SqlStringGenerationContext

use of org.hibernate.boot.model.relational.SqlStringGenerationContext in project hibernate-orm by hibernate.

the class Db2GenerationTest method testNewGeneratorTableCreationOnDb2.

@Test
@TestForIssue(jiraKey = "HHH-9850")
public void testNewGeneratorTableCreationOnDb2() {
    final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().applySetting(AvailableSettings.DIALECT, DB2Dialect.class.getName()).build();
    try {
        final Metadata metadata = new MetadataSources(ssr).buildMetadata();
        assertEquals(0, metadata.getDatabase().getDefaultNamespace().getTables().size());
        final TableGenerator generator = new TableGenerator();
        generator.configure(metadata.getDatabase().getTypeConfiguration().getBasicTypeRegistry().resolve(StandardBasicTypes.INTEGER), new Properties(), ssr);
        generator.registerExportables(metadata.getDatabase());
        assertEquals(1, metadata.getDatabase().getDefaultNamespace().getTables().size());
        Database database = metadata.getDatabase();
        final Table table = database.getDefaultNamespace().getTables().iterator().next();
        SqlStringGenerationContext sqlStringGenerationContext = SqlStringGenerationContextImpl.forTests(database.getJdbcEnvironment());
        final String[] createCommands = new DB2Dialect().getTableExporter().getSqlCreateStrings(table, metadata, sqlStringGenerationContext);
        assertThat(createCommands[0], containsString("sequence_name varchar(255) not null"));
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : Table(org.hibernate.mapping.Table) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) Database(org.hibernate.boot.model.relational.Database) TableGenerator(org.hibernate.id.enhanced.TableGenerator) Matchers.containsString(org.hamcrest.Matchers.containsString) Properties(java.util.Properties) DB2Dialect(org.hibernate.dialect.DB2Dialect) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) Test(org.junit.jupiter.api.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 2 with SqlStringGenerationContext

use of org.hibernate.boot.model.relational.SqlStringGenerationContext in project hibernate-orm by hibernate.

the class SQLQueryParser method substituteBrackets.

// TODO: should "record" how many properties we have referred to - and if we
// don't get them all we throw an exception! Way better than trial and error ;)
protected String substituteBrackets(String sqlQuery) throws QueryException {
    if (PREPARED_STATEMENT_PATTERN.matcher(sqlQuery.trim()).matches()) {
        return sqlQuery;
    }
    final StringBuilder result = new StringBuilder(sqlQuery.length() + 20);
    int left, right;
    SqlStringGenerationContext sqlStringGenerationContext = factory.getSqlStringGenerationContext();
    // replace {....} with corresponding column aliases
    for (int curr = 0; curr < sqlQuery.length(); curr = right + 1) {
        if ((left = sqlQuery.indexOf('{', curr)) < 0) {
            // No additional open braces found in the string, append the
            // rest of the string in its entirety and quit this loop
            result.append(sqlQuery.substring(curr));
            break;
        }
        // append everything up until the next encountered open brace
        result.append(sqlQuery, curr, left);
        if ((right = sqlQuery.indexOf('}', left + 1)) < 0) {
            throw new QueryException("Unmatched braces for alias path", sqlQuery);
        }
        final String aliasPath = sqlQuery.substring(left + 1, right);
        boolean isPlaceholder = aliasPath.startsWith(HIBERNATE_PLACEHOLDER_PREFIX);
        if (isPlaceholder) {
            // Domain replacement
            switch(aliasPath) {
                case DOMAIN_PLACEHOLDER:
                    {
                        final Identifier catalogName = sqlStringGenerationContext.getDefaultCatalog();
                        if (catalogName != null) {
                            result.append(catalogName.render(sqlStringGenerationContext.getDialect()));
                            result.append(".");
                        }
                        final Identifier schemaName = sqlStringGenerationContext.getDefaultSchema();
                        if (schemaName != null) {
                            result.append(schemaName.render(sqlStringGenerationContext.getDialect()));
                            result.append(".");
                        }
                        break;
                    }
                // Schema replacement
                case SCHEMA_PLACEHOLDER:
                    {
                        final Identifier schemaName = sqlStringGenerationContext.getDefaultSchema();
                        if (schemaName != null) {
                            result.append(schemaName.render(sqlStringGenerationContext.getDialect()));
                            result.append(".");
                        }
                        break;
                    }
                // Catalog replacement
                case CATALOG_PLACEHOLDER:
                    {
                        final Identifier catalogName = sqlStringGenerationContext.getDefaultCatalog();
                        if (catalogName != null) {
                            result.append(catalogName.render(sqlStringGenerationContext.getDialect()));
                            result.append(".");
                        }
                        break;
                    }
                default:
                    throw new QueryException("Unknown placeholder ", aliasPath);
            }
        } else if (context != null) {
            int firstDot = aliasPath.indexOf('.');
            if (firstDot == -1) {
                if (context.isEntityAlias(aliasPath)) {
                    // it is a simple table alias {foo}
                    result.append(aliasPath);
                    aliasesFound++;
                } else {
                    // passing through anything we do not know : to support jdbc escape sequences HB-898
                    result.append('{').append(aliasPath).append('}');
                }
            } else {
                final String aliasName = aliasPath.substring(0, firstDot);
                if (context.isCollectionAlias(aliasName)) {
                    // The current alias is referencing the collection to be eagerly fetched
                    String propertyName = aliasPath.substring(firstDot + 1);
                    result.append(resolveCollectionProperties(aliasName, propertyName));
                    aliasesFound++;
                } else if (context.isEntityAlias(aliasName)) {
                    // it is a property reference {foo.bar}
                    String propertyName = aliasPath.substring(firstDot + 1);
                    result.append(resolveProperties(aliasName, propertyName));
                    aliasesFound++;
                } else {
                    // passing through anything we do not know : to support jdbc escape sequences HB-898
                    result.append('{').append(aliasPath).append('}');
                }
            }
        } else {
            result.append('{').append(aliasPath).append('}');
        }
    }
    return result.toString();
}
Also used : QueryException(org.hibernate.QueryException) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) Identifier(org.hibernate.boot.model.naming.Identifier)

Example 3 with SqlStringGenerationContext

use of org.hibernate.boot.model.relational.SqlStringGenerationContext in project hibernate-orm by hibernate.

the class AbstractSchemaValidator method doValidation.

@Override
public void doValidation(Metadata metadata, ExecutionOptions options, ContributableMatcher contributableInclusionFilter) {
    SqlStringGenerationContext sqlStringGenerationContext = SqlStringGenerationContextImpl.fromConfigurationMap(tool.getServiceRegistry().getService(JdbcEnvironment.class), metadata.getDatabase(), options.getConfigurationValues());
    final JdbcContext jdbcContext = tool.resolveJdbcContext(options.getConfigurationValues());
    final DdlTransactionIsolator isolator = tool.getDdlTransactionIsolator(jdbcContext);
    final DatabaseInformation databaseInformation = Helper.buildDatabaseInformation(tool.getServiceRegistry(), isolator, sqlStringGenerationContext, tool);
    try {
        performValidation(metadata, databaseInformation, options, contributableInclusionFilter, jdbcContext.getDialect());
    } finally {
        try {
            databaseInformation.cleanup();
        } catch (Exception e) {
            log.debug("Problem releasing DatabaseInformation : " + e.getMessage());
        }
        isolator.release();
    }
}
Also used : DatabaseInformation(org.hibernate.tool.schema.extract.spi.DatabaseInformation) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) JdbcContext(org.hibernate.tool.schema.internal.exec.JdbcContext) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) DdlTransactionIsolator(org.hibernate.resource.transaction.spi.DdlTransactionIsolator) SchemaManagementException(org.hibernate.tool.schema.spi.SchemaManagementException)

Example 4 with SqlStringGenerationContext

use of org.hibernate.boot.model.relational.SqlStringGenerationContext in project hibernate-orm by hibernate.

the class UnionSubclassEntityPersister method generateSubquery.

protected String generateSubquery(PersistentClass model, Metadata mapping) {
    Dialect dialect = getFactory().getJdbcServices().getDialect();
    SqlStringGenerationContext sqlStringGenerationContext = getFactory().getSqlStringGenerationContext();
    if (!model.hasSubclasses()) {
        return model.getTable().getQualifiedName(sqlStringGenerationContext);
    }
    Set<Column> columns = new LinkedHashSet<>();
    for (Table table : model.getSubclassTableClosure()) {
        if (!table.isAbstractUnionTable()) {
            columns.addAll(table.getColumns());
        }
    }
    StringBuilder buf = new StringBuilder().append("( ");
    List<PersistentClass> classes = new JoinedList<>(List.of(model), Collections.unmodifiableList(model.getSubclasses()));
    for (PersistentClass clazz : classes) {
        Table table = clazz.getTable();
        if (!table.isAbstractUnionTable()) {
            // TODO: move to .sql package!!
            buf.append("select ");
            for (Column col : columns) {
                if (!table.containsColumn(col)) {
                    int sqlType = col.getSqlTypeCode(mapping);
                    buf.append(dialect.getSelectClauseNullString(sqlType)).append(" as ");
                }
                buf.append(col.getQuotedName(dialect));
                buf.append(", ");
            }
            buf.append(clazz.getSubclassId()).append(" as clazz_");
            buf.append(" from ").append(table.getQualifiedName(sqlStringGenerationContext));
            buf.append(" union ");
            if (dialect.supportsUnionAll()) {
                buf.append("all ");
            }
        }
    }
    if (buf.length() > 2) {
        // chop the last union (all)
        buf.setLength(buf.length() - (dialect.supportsUnionAll() ? 11 : 7));
    }
    return buf.append(" )").toString();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) Table(org.hibernate.mapping.Table) Column(org.hibernate.mapping.Column) Dialect(org.hibernate.dialect.Dialect) JoinedList(org.hibernate.internal.util.collections.JoinedList) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 5 with SqlStringGenerationContext

use of org.hibernate.boot.model.relational.SqlStringGenerationContext in project hibernate-orm by hibernate.

the class SchemaCreatorImpl method createFromMetadata.

@Internal
public void createFromMetadata(Metadata metadata, ExecutionOptions options, ContributableMatcher contributableInclusionMatcher, Dialect dialect, Formatter formatter, GenerationTarget... targets) {
    boolean tryToCreateCatalogs = false;
    boolean tryToCreateSchemas = false;
    if (options.shouldManageNamespaces()) {
        if (dialect.canCreateSchema()) {
            tryToCreateSchemas = true;
        }
        if (dialect.canCreateCatalog()) {
            tryToCreateCatalogs = true;
        }
    }
    final Database database = metadata.getDatabase();
    final JdbcEnvironment jdbcEnvironment = database.getJdbcEnvironment();
    SqlStringGenerationContext sqlStringGenerationContext = SqlStringGenerationContextImpl.fromConfigurationMap(jdbcEnvironment, database, options.getConfigurationValues());
    final Set<String> exportIdentifiers = CollectionHelper.setOfSize(50);
    // first, create each catalog/schema
    if (tryToCreateCatalogs || tryToCreateSchemas) {
        Set<Identifier> exportedCatalogs = new HashSet<>();
        for (Namespace namespace : database.getNamespaces()) {
            if (!options.getSchemaFilter().includeNamespace(namespace)) {
                continue;
            }
            if (tryToCreateCatalogs) {
                final Identifier catalogLogicalName = namespace.getName().getCatalog();
                final Identifier catalogPhysicalName = sqlStringGenerationContext.catalogWithDefault(namespace.getPhysicalName().getCatalog());
                if (catalogPhysicalName != null && !exportedCatalogs.contains(catalogLogicalName)) {
                    applySqlStrings(dialect.getCreateCatalogCommand(catalogPhysicalName.render(dialect)), formatter, options, targets);
                    exportedCatalogs.add(catalogLogicalName);
                }
            }
            final Identifier schemaPhysicalName = sqlStringGenerationContext.schemaWithDefault(namespace.getPhysicalName().getSchema());
            if (tryToCreateSchemas && schemaPhysicalName != null) {
                applySqlStrings(dialect.getCreateSchemaCommand(schemaPhysicalName.render(dialect)), formatter, options, targets);
            }
        }
    }
    // next, create all "before table" auxiliary objects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (!auxiliaryDatabaseObject.beforeTablesOnCreation()) {
            continue;
        }
        if (auxiliaryDatabaseObject.appliesToDialect(dialect)) {
            checkExportIdentifier(auxiliaryDatabaseObject, exportIdentifiers);
            applySqlStrings(dialect.getAuxiliaryDatabaseObjectExporter().getSqlCreateStrings(auxiliaryDatabaseObject, metadata, sqlStringGenerationContext), formatter, options, targets);
        }
    }
    // then, create all schema objects (tables, sequences, constraints, etc) in each schema
    for (Namespace namespace : database.getNamespaces()) {
        if (!options.getSchemaFilter().includeNamespace(namespace)) {
            continue;
        }
        // sequences
        for (Sequence sequence : namespace.getSequences()) {
            if (!options.getSchemaFilter().includeSequence(sequence)) {
                continue;
            }
            if (!contributableInclusionMatcher.matches(sequence)) {
                continue;
            }
            checkExportIdentifier(sequence, exportIdentifiers);
            applySqlStrings(dialect.getSequenceExporter().getSqlCreateStrings(sequence, metadata, sqlStringGenerationContext), // ),
            formatter, options, targets);
        }
        // tables
        for (Table table : namespace.getTables()) {
            if (!table.isPhysicalTable()) {
                continue;
            }
            if (!options.getSchemaFilter().includeTable(table)) {
                continue;
            }
            if (!contributableInclusionMatcher.matches(table)) {
                continue;
            }
            checkExportIdentifier(table, exportIdentifiers);
            applySqlStrings(dialect.getTableExporter().getSqlCreateStrings(table, metadata, sqlStringGenerationContext), formatter, options, targets);
        }
        for (Table table : namespace.getTables()) {
            if (!table.isPhysicalTable()) {
                continue;
            }
            if (!options.getSchemaFilter().includeTable(table)) {
                continue;
            }
            if (!contributableInclusionMatcher.matches(table)) {
                continue;
            }
            // indexes
            final Iterator<Index> indexItr = table.getIndexIterator();
            while (indexItr.hasNext()) {
                final Index index = indexItr.next();
                checkExportIdentifier(index, exportIdentifiers);
                applySqlStrings(dialect.getIndexExporter().getSqlCreateStrings(index, metadata, sqlStringGenerationContext), formatter, options, targets);
            }
            // unique keys
            for (UniqueKey uniqueKey : table.getUniqueKeys().values()) {
                checkExportIdentifier(uniqueKey, exportIdentifiers);
                applySqlStrings(dialect.getUniqueKeyExporter().getSqlCreateStrings(uniqueKey, metadata, sqlStringGenerationContext), formatter, options, targets);
            }
        }
    }
    // NOTE : Foreign keys must be created *after* all tables of all namespaces for cross namespace fks. see HHH-10420
    for (Namespace namespace : database.getNamespaces()) {
        if (!options.getSchemaFilter().includeNamespace(namespace)) {
            continue;
        }
        for (Table table : namespace.getTables()) {
            if (!options.getSchemaFilter().includeTable(table)) {
                continue;
            }
            if (!contributableInclusionMatcher.matches(table)) {
                continue;
            }
            // foreign keys
            for (ForeignKey foreignKey : table.getForeignKeys().values()) {
                applySqlStrings(dialect.getForeignKeyExporter().getSqlCreateStrings(foreignKey, metadata, sqlStringGenerationContext), formatter, options, targets);
            }
        }
    }
    // next, create all "after table" auxiliary objects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (auxiliaryDatabaseObject.appliesToDialect(dialect) && !auxiliaryDatabaseObject.beforeTablesOnCreation()) {
            checkExportIdentifier(auxiliaryDatabaseObject, exportIdentifiers);
            applySqlStrings(dialect.getAuxiliaryDatabaseObjectExporter().getSqlCreateStrings(auxiliaryDatabaseObject, metadata, sqlStringGenerationContext), formatter, options, targets);
        }
    }
    // and finally add all init commands
    for (InitCommand initCommand : database.getInitCommands()) {
        // todo: this should alo probably use the DML formatter...
        applySqlStrings(initCommand.getInitCommands(), formatter, options, targets);
    }
}
Also used : SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) Table(org.hibernate.mapping.Table) InitCommand(org.hibernate.boot.model.relational.InitCommand) Index(org.hibernate.mapping.Index) AuxiliaryDatabaseObject(org.hibernate.boot.model.relational.AuxiliaryDatabaseObject) Sequence(org.hibernate.boot.model.relational.Sequence) ForeignKey(org.hibernate.mapping.ForeignKey) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) Namespace(org.hibernate.boot.model.relational.Namespace) Identifier(org.hibernate.boot.model.naming.Identifier) UniqueKey(org.hibernate.mapping.UniqueKey) Database(org.hibernate.boot.model.relational.Database) HashSet(java.util.HashSet) Internal(org.hibernate.Internal)

Aggregations

SqlStringGenerationContext (org.hibernate.boot.model.relational.SqlStringGenerationContext)14 Database (org.hibernate.boot.model.relational.Database)7 Table (org.hibernate.mapping.Table)5 Metadata (org.hibernate.boot.Metadata)3 MetadataSources (org.hibernate.boot.MetadataSources)3 Identifier (org.hibernate.boot.model.naming.Identifier)3 AuxiliaryDatabaseObject (org.hibernate.boot.model.relational.AuxiliaryDatabaseObject)3 Namespace (org.hibernate.boot.model.relational.Namespace)3 Sequence (org.hibernate.boot.model.relational.Sequence)3 Dialect (org.hibernate.dialect.Dialect)3 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)3 IdentifierGenerator (org.hibernate.id.IdentifierGenerator)3 PersistentClass (org.hibernate.mapping.PersistentClass)3 DatabaseInformation (org.hibernate.tool.schema.extract.spi.DatabaseInformation)3 HashSet (java.util.HashSet)2 QualifiedTableName (org.hibernate.boot.model.relational.QualifiedTableName)2 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)2 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)2 SequenceStyleGenerator (org.hibernate.id.enhanced.SequenceStyleGenerator)2 TestForIssue (org.hibernate.testing.TestForIssue)2