Search in sources :

Example 21 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class SequenceStyleGenerator method determineSequenceName.

/**
	 * Determine the name of the sequence (or table if this resolves to a physical table)
	 * to use.
	 * <p/>
	 * Called during {@link #configure configuration}.
	 *
	 * @param params The params supplied in the generator config (plus some standard useful extras).
	 * @param dialect The dialect in effect
	 * @param jdbcEnv The JdbcEnvironment
	 * @return The sequence name
	 */
@SuppressWarnings("UnusedParameters")
protected QualifiedName determineSequenceName(Properties params, Dialect dialect, JdbcEnvironment jdbcEnv) {
    final String sequencePerEntitySuffix = ConfigurationHelper.getString(CONFIG_SEQUENCE_PER_ENTITY_SUFFIX, params, DEF_SEQUENCE_SUFFIX);
    // JPA_ENTITY_NAME value honors <class ... entity-name="..."> (HBM) and @Entity#name (JPA) overrides.
    final String defaultSequenceName = ConfigurationHelper.getBoolean(CONFIG_PREFER_SEQUENCE_PER_ENTITY, params, false) ? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix : DEF_SEQUENCE_NAME;
    final String sequenceName = ConfigurationHelper.getString(SEQUENCE_PARAM, params, defaultSequenceName);
    if (sequenceName.contains(".")) {
        return QualifiedNameParser.INSTANCE.parse(sequenceName);
    } else {
        // todo : need to incorporate implicit catalog and schema names
        final Identifier catalog = jdbcEnv.getIdentifierHelper().toIdentifier(ConfigurationHelper.getString(CATALOG, params));
        final Identifier schema = jdbcEnv.getIdentifierHelper().toIdentifier(ConfigurationHelper.getString(SCHEMA, params));
        return new QualifiedNameParser.NameParts(catalog, schema, jdbcEnv.getIdentifierHelper().toIdentifier(sequenceName));
    }
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier)

Example 22 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class InformationExtractorJdbcDatabaseMetaDataImpl method locateTableInNamespace.

private TableInformation locateTableInNamespace(Identifier catalog, Identifier schema, Identifier tableName) {
    Identifier catalogToUse = null;
    Identifier schemaToUse = null;
    final String catalogFilter;
    final String schemaFilter;
    if (extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsCatalogs()) {
        if (catalog == null) {
            catalogFilter = "";
        } else {
            catalogToUse = catalog;
            catalogFilter = toMetaDataObjectName(catalog);
        }
    } else {
        catalogFilter = null;
    }
    if (extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsSchemas()) {
        if (schema == null) {
            schemaFilter = "";
        } else {
            schemaToUse = schema;
            schemaFilter = toMetaDataObjectName(schema);
        }
    } else {
        schemaFilter = null;
    }
    final String tableNameFilter = toMetaDataObjectName(tableName);
    try {
        ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getTables(catalogFilter, schemaFilter, tableNameFilter, tableTypes);
        return processTableResults(catalogToUse, schemaToUse, tableName, resultSet);
    } catch (SQLException sqlException) {
        throw convertSQLException(sqlException, "Error accessing table metadata");
    }
}
Also used : DatabaseIdentifier(org.hibernate.boot.model.naming.DatabaseIdentifier) Identifier(org.hibernate.boot.model.naming.Identifier) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet)

Example 23 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class InformationExtractorJdbcDatabaseMetaDataImpl method getForeignKeys.

@Override
public Iterable<ForeignKeyInformation> getForeignKeys(TableInformation tableInformation) {
    final Map<Identifier, ForeignKeyBuilder> fkBuilders = new HashMap<>();
    final QualifiedTableName tableName = tableInformation.getName();
    final Identifier catalog = tableName.getCatalogName();
    final Identifier schema = tableName.getSchemaName();
    final String catalogFilter;
    final String schemaFilter;
    if (catalog == null) {
        catalogFilter = "";
    } else {
        catalogFilter = catalog.getText();
    }
    if (schema == null) {
        schemaFilter = "";
    } else {
        schemaFilter = schema.getText();
    }
    try {
        ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getImportedKeys(catalogFilter, schemaFilter, tableInformation.getName().getTableName().getText());
        try {
            while (resultSet.next()) {
                // IMPL NOTE : The builder is mainly used to collect the column reference mappings
                final Identifier fkIdentifier = DatabaseIdentifier.toIdentifier(resultSet.getString("FK_NAME"));
                ForeignKeyBuilder fkBuilder = fkBuilders.get(fkIdentifier);
                if (fkBuilder == null) {
                    fkBuilder = generateForeignKeyBuilder(fkIdentifier);
                    fkBuilders.put(fkIdentifier, fkBuilder);
                }
                final QualifiedTableName incomingPkTableName = extractKeyTableName(resultSet, "PK");
                final TableInformation pkTableInformation = extractionContext.getDatabaseObjectAccess().locateTableInformation(incomingPkTableName);
                if (pkTableInformation == null) {
                    // should match.
                    continue;
                }
                final Identifier fkColumnIdentifier = DatabaseIdentifier.toIdentifier(resultSet.getString("FKCOLUMN_NAME"));
                final Identifier pkColumnIdentifier = DatabaseIdentifier.toIdentifier(resultSet.getString("PKCOLUMN_NAME"));
                fkBuilder.addColumnMapping(tableInformation.getColumn(fkColumnIdentifier), pkTableInformation.getColumn(pkColumnIdentifier));
            }
        } finally {
            resultSet.close();
        }
    } catch (SQLException e) {
        throw convertSQLException(e, "Error accessing column metadata: " + tableInformation.getName().toString());
    }
    final List<ForeignKeyInformation> fks = new ArrayList<ForeignKeyInformation>();
    for (ForeignKeyBuilder fkBuilder : fkBuilders.values()) {
        ForeignKeyInformation fk = fkBuilder.build();
        fks.add(fk);
    }
    return fks;
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) ForeignKeyInformation(org.hibernate.tool.schema.extract.spi.ForeignKeyInformation) DatabaseIdentifier(org.hibernate.boot.model.naming.DatabaseIdentifier) Identifier(org.hibernate.boot.model.naming.Identifier) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) TableInformation(org.hibernate.tool.schema.extract.spi.TableInformation)

Example 24 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class AbstractSchemaMigrator method createSchemaAndCatalog.

protected void createSchemaAndCatalog(DatabaseInformation existingDatabase, ExecutionOptions options, Dialect dialect, Formatter formatter, boolean tryToCreateCatalogs, boolean tryToCreateSchemas, Set<Identifier> exportedCatalogs, Namespace namespace, GenerationTarget[] targets) {
    if (tryToCreateCatalogs || tryToCreateSchemas) {
        if (tryToCreateCatalogs) {
            final Identifier catalogLogicalName = namespace.getName().getCatalog();
            final Identifier catalogPhysicalName = namespace.getPhysicalName().getCatalog();
            if (catalogPhysicalName != null && !exportedCatalogs.contains(catalogLogicalName) && !existingDatabase.catalogExists(catalogLogicalName)) {
                applySqlStrings(false, dialect.getCreateCatalogCommand(catalogPhysicalName.render(dialect)), formatter, options, targets);
                exportedCatalogs.add(catalogLogicalName);
            }
        }
        if (tryToCreateSchemas && namespace.getPhysicalName().getSchema() != null && !existingDatabase.schemaExists(namespace.getName())) {
            applySqlStrings(false, dialect.getCreateSchemaCommand(namespace.getPhysicalName().getSchema().render(dialect)), formatter, options, targets);
        }
    }
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier)

Example 25 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class SchemaCreatorImpl method createFromMetadata.

public void createFromMetadata(Metadata metadata, ExecutionOptions options, 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();
    final Set<String> exportIdentifiers = new HashSet<String>(50);
    // first, create each catalog/schema
    if (tryToCreateCatalogs || tryToCreateSchemas) {
        Set<Identifier> exportedCatalogs = new HashSet<Identifier>();
        for (Namespace namespace : database.getNamespaces()) {
            if (!schemaFilter.includeNamespace(namespace)) {
                continue;
            }
            if (tryToCreateCatalogs) {
                final Identifier catalogLogicalName = namespace.getName().getCatalog();
                final Identifier catalogPhysicalName = namespace.getPhysicalName().getCatalog();
                if (catalogPhysicalName != null && !exportedCatalogs.contains(catalogLogicalName)) {
                    applySqlStrings(dialect.getCreateCatalogCommand(catalogPhysicalName.render(dialect)), formatter, options, targets);
                    exportedCatalogs.add(catalogLogicalName);
                }
            }
            if (tryToCreateSchemas && namespace.getPhysicalName().getSchema() != null) {
                applySqlStrings(dialect.getCreateSchemaCommand(namespace.getPhysicalName().getSchema().render(dialect)), formatter, options, targets);
            }
        }
    }
    // next, create all "beforeQuery 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), formatter, options, targets);
        }
    }
    // then, create all schema objects (tables, sequences, constraints, etc) in each schema
    for (Namespace namespace : database.getNamespaces()) {
        if (!schemaFilter.includeNamespace(namespace)) {
            continue;
        }
        // sequences
        for (Sequence sequence : namespace.getSequences()) {
            if (!schemaFilter.includeSequence(sequence)) {
                continue;
            }
            checkExportIdentifier(sequence, exportIdentifiers);
            applySqlStrings(dialect.getSequenceExporter().getSqlCreateStrings(sequence, metadata), //						),
            formatter, options, targets);
        }
        // tables
        for (Table table : namespace.getTables()) {
            if (!table.isPhysicalTable()) {
                continue;
            }
            if (!schemaFilter.includeTable(table)) {
                continue;
            }
            checkExportIdentifier(table, exportIdentifiers);
            applySqlStrings(dialect.getTableExporter().getSqlCreateStrings(table, metadata), formatter, options, targets);
        }
        for (Table table : namespace.getTables()) {
            if (!table.isPhysicalTable()) {
                continue;
            }
            if (!schemaFilter.includeTable(table)) {
                continue;
            }
            // indexes
            final Iterator indexItr = table.getIndexIterator();
            while (indexItr.hasNext()) {
                final Index index = (Index) indexItr.next();
                checkExportIdentifier(index, exportIdentifiers);
                applySqlStrings(dialect.getIndexExporter().getSqlCreateStrings(index, metadata), formatter, options, targets);
            }
            // unique keys
            final Iterator ukItr = table.getUniqueKeyIterator();
            while (ukItr.hasNext()) {
                final UniqueKey uniqueKey = (UniqueKey) ukItr.next();
                checkExportIdentifier(uniqueKey, exportIdentifiers);
                applySqlStrings(dialect.getUniqueKeyExporter().getSqlCreateStrings(uniqueKey, metadata), formatter, options, targets);
            }
        }
    }
    //NOTE : Foreign keys must be created *afterQuery* all tables of all namespaces for cross namespace fks. see HHH-10420
    for (Namespace namespace : database.getNamespaces()) {
        if (!schemaFilter.includeNamespace(namespace)) {
            continue;
        }
        for (Table table : namespace.getTables()) {
            if (!schemaFilter.includeTable(table)) {
                continue;
            }
            // foreign keys
            final Iterator fkItr = table.getForeignKeyIterator();
            while (fkItr.hasNext()) {
                final ForeignKey foreignKey = (ForeignKey) fkItr.next();
                applySqlStrings(dialect.getForeignKeyExporter().getSqlCreateStrings(foreignKey, metadata), formatter, options, targets);
            }
        }
    }
    // next, create all "afterQuery table" auxiliary objects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (auxiliaryDatabaseObject.appliesToDialect(dialect) && !auxiliaryDatabaseObject.beforeTablesOnCreation()) {
            checkExportIdentifier(auxiliaryDatabaseObject, exportIdentifiers);
            applySqlStrings(dialect.getAuxiliaryDatabaseObjectExporter().getSqlCreateStrings(auxiliaryDatabaseObject, metadata), 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 : 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) Iterator(java.util.Iterator) HashSet(java.util.HashSet)

Aggregations

Identifier (org.hibernate.boot.model.naming.Identifier)46 Table (org.hibernate.mapping.Table)15 LocalMetadataBuildingContext (org.hibernate.boot.model.source.spi.LocalMetadataBuildingContext)10 DenormalizedTable (org.hibernate.mapping.DenormalizedTable)9 SimpleValue (org.hibernate.mapping.SimpleValue)9 HashMap (java.util.HashMap)7 MappingException (org.hibernate.boot.MappingException)7 Namespace (org.hibernate.boot.model.relational.Namespace)7 Database (org.hibernate.boot.model.relational.Database)6 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)5 ArrayList (java.util.ArrayList)5 DatabaseIdentifier (org.hibernate.boot.model.naming.DatabaseIdentifier)5 Column (org.hibernate.mapping.Column)5 Property (org.hibernate.mapping.Property)5 HashSet (java.util.HashSet)4 DuplicateMappingException (org.hibernate.DuplicateMappingException)4 ImplicitNamingStrategy (org.hibernate.boot.model.naming.ImplicitNamingStrategy)4 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)4 SyntheticProperty (org.hibernate.mapping.SyntheticProperty)4