Search in sources :

Example 36 with Identifier

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

the class InFlightMetadataCollectorImpl method buildUniqueKeyFromColumnNames.

private void buildUniqueKeyFromColumnNames(final Table table, String keyName, final String[] columnNames, String[] orderings, boolean unique, final MetadataBuildingContext buildingContext) {
    int size = columnNames.length;
    Column[] columns = new Column[size];
    Set<Column> unbound = new HashSet<Column>();
    Set<Column> unboundNoLogical = new HashSet<Column>();
    for (int index = 0; index < size; index++) {
        final String logicalColumnName = columnNames[index];
        try {
            final String physicalColumnName = getPhysicalColumnName(table, logicalColumnName);
            columns[index] = new Column(physicalColumnName);
            unbound.add(columns[index]);
        //column equals and hashcode is based on column name
        } catch (MappingException e) {
            // If at least 1 columnName does exist, 'columns' will contain a mix of Columns and nulls.  In order
            // to exhaustively report all of the unbound columns at once, w/o an NPE in
            // Constraint#generateName's array sorting, simply create a fake Column.
            columns[index] = new Column(logicalColumnName);
            unboundNoLogical.add(columns[index]);
        }
    }
    final String originalKeyName = keyName;
    if (unique) {
        final Identifier keyNameIdentifier = getMetadataBuildingOptions().getImplicitNamingStrategy().determineUniqueKeyName(new ImplicitUniqueKeyNameSource() {

            @Override
            public MetadataBuildingContext getBuildingContext() {
                return buildingContext;
            }

            @Override
            public Identifier getTableName() {
                return table.getNameIdentifier();
            }

            private List<Identifier> columnNameIdentifiers;

            @Override
            public List<Identifier> getColumnNames() {
                // be lazy about building these
                if (columnNameIdentifiers == null) {
                    columnNameIdentifiers = toIdentifiers(columnNames);
                }
                return columnNameIdentifiers;
            }

            @Override
            public Identifier getUserProvidedIdentifier() {
                return originalKeyName != null ? Identifier.toIdentifier(originalKeyName) : null;
            }
        });
        keyName = keyNameIdentifier.render(getDatabase().getJdbcEnvironment().getDialect());
        UniqueKey uk = table.getOrCreateUniqueKey(keyName);
        for (int i = 0; i < columns.length; i++) {
            Column column = columns[i];
            String order = orderings != null ? orderings[i] : null;
            if (table.containsColumn(column)) {
                uk.addColumn(column, order);
                unbound.remove(column);
            }
        }
    } else {
        final Identifier keyNameIdentifier = getMetadataBuildingOptions().getImplicitNamingStrategy().determineIndexName(new ImplicitIndexNameSource() {

            @Override
            public MetadataBuildingContext getBuildingContext() {
                return buildingContext;
            }

            @Override
            public Identifier getTableName() {
                return table.getNameIdentifier();
            }

            private List<Identifier> columnNameIdentifiers;

            @Override
            public List<Identifier> getColumnNames() {
                // be lazy about building these
                if (columnNameIdentifiers == null) {
                    columnNameIdentifiers = toIdentifiers(columnNames);
                }
                return columnNameIdentifiers;
            }

            @Override
            public Identifier getUserProvidedIdentifier() {
                return originalKeyName != null ? Identifier.toIdentifier(originalKeyName) : null;
            }
        });
        keyName = keyNameIdentifier.render(getDatabase().getJdbcEnvironment().getDialect());
        Index index = table.getOrCreateIndex(keyName);
        for (int i = 0; i < columns.length; i++) {
            Column column = columns[i];
            String order = orderings != null ? orderings[i] : null;
            if (table.containsColumn(column)) {
                index.addColumn(column, order);
                unbound.remove(column);
            }
        }
    }
    if (unbound.size() > 0 || unboundNoLogical.size() > 0) {
        StringBuilder sb = new StringBuilder("Unable to create ");
        if (unique) {
            sb.append("unique key constraint (");
        } else {
            sb.append("index (");
        }
        for (String columnName : columnNames) {
            sb.append(columnName).append(", ");
        }
        sb.setLength(sb.length() - 2);
        sb.append(") on table ").append(table.getName()).append(": database column ");
        for (Column column : unbound) {
            sb.append("'").append(column.getName()).append("', ");
        }
        for (Column column : unboundNoLogical) {
            sb.append("'").append(column.getName()).append("', ");
        }
        sb.setLength(sb.length() - 2);
        sb.append(" not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)");
        throw new AnnotationException(sb.toString());
    }
}
Also used : MetadataBuildingContext(org.hibernate.boot.spi.MetadataBuildingContext) LocalMetadataBuildingContext(org.hibernate.boot.model.source.spi.LocalMetadataBuildingContext) Index(org.hibernate.mapping.Index) DuplicateMappingException(org.hibernate.DuplicateMappingException) MappingException(org.hibernate.MappingException) Identifier(org.hibernate.boot.model.naming.Identifier) ImplicitIndexNameSource(org.hibernate.boot.model.naming.ImplicitIndexNameSource) Column(org.hibernate.mapping.Column) UniqueKey(org.hibernate.mapping.UniqueKey) AnnotationException(org.hibernate.AnnotationException) List(java.util.List) ArrayList(java.util.ArrayList) ImplicitUniqueKeyNameSource(org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource) HashSet(java.util.HashSet)

Example 37 with Identifier

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

the class InFlightMetadataCollectorImpl method addTable.

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Table handling
@Override
public Table addTable(String schemaName, String catalogName, String name, String subselectFragment, boolean isAbstract) {
    final Namespace namespace = getDatabase().locateNamespace(getDatabase().toIdentifier(catalogName), getDatabase().toIdentifier(schemaName));
    // annotation binding depends on the "table name" for @Subselect bindings
    // being set into the generated table (mainly to avoid later NPE), but for now we need to keep that :(
    final Identifier logicalName;
    if (name != null) {
        logicalName = getDatabase().toIdentifier(name);
    } else {
        logicalName = null;
    }
    if (subselectFragment != null) {
        return new Table(namespace, logicalName, subselectFragment, isAbstract);
    } else {
        Table table = namespace.locateTable(logicalName);
        if (table != null) {
            if (!isAbstract) {
                table.setAbstract(false);
            }
            return table;
        }
        return namespace.createTable(logicalName, isAbstract);
    }
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier) DenormalizedTable(org.hibernate.mapping.DenormalizedTable) Table(org.hibernate.mapping.Table) Namespace(org.hibernate.boot.model.relational.Namespace)

Example 38 with Identifier

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

the class InFlightMetadataCollectorImpl method secondPassCompileForeignKeys.

protected void secondPassCompileForeignKeys(final Table table, Set<ForeignKey> done, final MetadataBuildingContext buildingContext) throws MappingException {
    table.createForeignKeys();
    Iterator itr = table.getForeignKeyIterator();
    while (itr.hasNext()) {
        final ForeignKey fk = (ForeignKey) itr.next();
        if (!done.contains(fk)) {
            done.add(fk);
            final String referencedEntityName = fk.getReferencedEntityName();
            if (referencedEntityName == null) {
                throw new MappingException("An association from the table " + fk.getTable().getName() + " does not specify the referenced entity");
            }
            log.debugf("Resolving reference to class: %s", referencedEntityName);
            final PersistentClass referencedClass = getEntityBinding(referencedEntityName);
            if (referencedClass == null) {
                throw new MappingException("An association from the table " + fk.getTable().getName() + " refers to an unmapped class: " + referencedEntityName);
            }
            if (referencedClass.isJoinedSubclass()) {
                secondPassCompileForeignKeys(referencedClass.getSuperclass().getTable(), done, buildingContext);
            }
            fk.setReferencedTable(referencedClass.getTable());
            Identifier nameIdentifier;
            ImplicitForeignKeyNameSource foreignKeyNameSource = new ImplicitForeignKeyNameSource() {

                final List<Identifier> columnNames = extractColumnNames(fk.getColumns());

                List<Identifier> referencedColumnNames = null;

                @Override
                public Identifier getTableName() {
                    return table.getNameIdentifier();
                }

                @Override
                public List<Identifier> getColumnNames() {
                    return columnNames;
                }

                @Override
                public Identifier getReferencedTableName() {
                    return fk.getReferencedTable().getNameIdentifier();
                }

                @Override
                public List<Identifier> getReferencedColumnNames() {
                    if (referencedColumnNames == null) {
                        referencedColumnNames = extractColumnNames(fk.getReferencedColumns());
                    }
                    return referencedColumnNames;
                }

                @Override
                public Identifier getUserProvidedIdentifier() {
                    return fk.getName() != null ? Identifier.toIdentifier(fk.getName()) : null;
                }

                @Override
                public MetadataBuildingContext getBuildingContext() {
                    return buildingContext;
                }
            };
            nameIdentifier = getMetadataBuildingOptions().getImplicitNamingStrategy().determineForeignKeyName(foreignKeyNameSource);
            fk.setName(nameIdentifier.render(getDatabase().getJdbcEnvironment().getDialect()));
            fk.alignColumns();
        }
    }
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier) Iterator(java.util.Iterator) ImplicitForeignKeyNameSource(org.hibernate.boot.model.naming.ImplicitForeignKeyNameSource) List(java.util.List) ArrayList(java.util.ArrayList) ForeignKey(org.hibernate.mapping.ForeignKey) DuplicateMappingException(org.hibernate.DuplicateMappingException) MappingException(org.hibernate.MappingException) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 39 with Identifier

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

the class TableInformationImpl method indexes.

protected Map<Identifier, IndexInformation> indexes() {
    if (indexes == null) {
        final Map<Identifier, IndexInformation> indexMap = new HashMap<>();
        final Iterable<IndexInformation> indexes = extractor.getIndexes(this);
        for (IndexInformation index : indexes) {
            indexMap.put(index.getIndexIdentifier(), index);
        }
        this.indexes = indexMap;
    }
    return indexes;
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier) IndexInformation(org.hibernate.tool.schema.extract.spi.IndexInformation) HashMap(java.util.HashMap)

Example 40 with Identifier

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

the class AbstractSchemaMigrator method performMigration.

private void performMigration(Metadata metadata, DatabaseInformation existingDatabase, ExecutionOptions options, Dialect dialect, GenerationTarget... targets) {
    final boolean format = Helper.interpretFormattingEnabled(options.getConfigurationValues());
    final Formatter formatter = format ? FormatStyle.DDL.getFormatter() : FormatStyle.NONE.getFormatter();
    final Set<String> exportIdentifiers = new HashSet<String>(50);
    final Database database = metadata.getDatabase();
    // Drop all AuxiliaryDatabaseObjects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (auxiliaryDatabaseObject.appliesToDialect(dialect)) {
            applySqlStrings(true, dialect.getAuxiliaryDatabaseObjectExporter().getSqlDropStrings(auxiliaryDatabaseObject, metadata), formatter, options, targets);
        }
    }
    // Create beforeQuery-table AuxiliaryDatabaseObjects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (!auxiliaryDatabaseObject.beforeTablesOnCreation() && auxiliaryDatabaseObject.appliesToDialect(dialect)) {
            applySqlStrings(true, auxiliaryDatabaseObject.sqlCreateStrings(dialect), formatter, options, targets);
        }
    }
    boolean tryToCreateCatalogs = false;
    boolean tryToCreateSchemas = false;
    if (options.shouldManageNamespaces()) {
        if (dialect.canCreateSchema()) {
            tryToCreateSchemas = true;
        }
        if (dialect.canCreateCatalog()) {
            tryToCreateCatalogs = true;
        }
    }
    final Map<Namespace, NameSpaceTablesInformation> tablesInformation = new HashMap<>();
    Set<Identifier> exportedCatalogs = new HashSet<>();
    for (Namespace namespace : database.getNamespaces()) {
        final NameSpaceTablesInformation nameSpaceTablesInformation = performTablesMigration(metadata, existingDatabase, options, dialect, formatter, exportIdentifiers, tryToCreateCatalogs, tryToCreateSchemas, exportedCatalogs, namespace, targets);
        tablesInformation.put(namespace, nameSpaceTablesInformation);
        if (schemaFilter.includeNamespace(namespace)) {
            for (Sequence sequence : namespace.getSequences()) {
                checkExportIdentifier(sequence, exportIdentifiers);
                final SequenceInformation sequenceInformation = existingDatabase.getSequenceInformation(sequence.getName());
                if (sequenceInformation == null) {
                    applySqlStrings(false, dialect.getSequenceExporter().getSqlCreateStrings(sequence, 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)) {
            final NameSpaceTablesInformation nameSpaceTablesInformation = tablesInformation.get(namespace);
            for (Table table : namespace.getTables()) {
                if (schemaFilter.includeTable(table)) {
                    final TableInformation tableInformation = nameSpaceTablesInformation.getTableInformation(table);
                    if (tableInformation == null || (tableInformation != null && tableInformation.isPhysicalTable())) {
                        applyForeignKeys(table, tableInformation, dialect, metadata, formatter, options, targets);
                    }
                }
            }
        }
    }
    // Create afterQuery-table AuxiliaryDatabaseObjects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (auxiliaryDatabaseObject.beforeTablesOnCreation() && auxiliaryDatabaseObject.appliesToDialect(dialect)) {
            applySqlStrings(true, auxiliaryDatabaseObject.sqlCreateStrings(dialect), formatter, options, targets);
        }
    }
}
Also used : Table(org.hibernate.mapping.Table) HashMap(java.util.HashMap) Formatter(org.hibernate.engine.jdbc.internal.Formatter) AuxiliaryDatabaseObject(org.hibernate.boot.model.relational.AuxiliaryDatabaseObject) Sequence(org.hibernate.boot.model.relational.Sequence) Namespace(org.hibernate.boot.model.relational.Namespace) Identifier(org.hibernate.boot.model.naming.Identifier) NameSpaceTablesInformation(org.hibernate.tool.schema.extract.spi.NameSpaceTablesInformation) Database(org.hibernate.boot.model.relational.Database) TableInformation(org.hibernate.tool.schema.extract.spi.TableInformation) SequenceInformation(org.hibernate.tool.schema.extract.spi.SequenceInformation) 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