Search in sources :

Example 1 with Index

use of org.hibernate.mapping.Index 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)

Example 2 with Index

use of org.hibernate.mapping.Index in project hibernate-orm by hibernate.

the class AbstractJPAIndexTest method testSecondaryTableIndex.

@Test
public void testSecondaryTableIndex() {
    PersistentClass entity = metadata().getEntityBinding(Car.class.getName());
    Join join = (Join) entity.getJoinIterator().next();
    Iterator<Index> itr = join.getTable().getIndexIterator();
    assertTrue(itr.hasNext());
    Index index = itr.next();
    assertFalse(itr.hasNext());
    assertTrue("index name is not generated", StringHelper.isNotEmpty(index.getName()));
    assertEquals(2, index.getColumnSpan());
    Iterator<Column> columnIterator = index.getColumnIterator();
    Column column = columnIterator.next();
    assertEquals("dealer_name", column.getName());
    column = columnIterator.next();
    assertEquals("rate", column.getName());
    assertSame(join.getTable(), index.getTable());
}
Also used : Column(org.hibernate.mapping.Column) Join(org.hibernate.mapping.Join) Index(org.hibernate.mapping.Index) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Example 3 with Index

use of org.hibernate.mapping.Index 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 4 with Index

use of org.hibernate.mapping.Index in project hibernate-orm by hibernate.

the class AbstractSchemaMigrator method applyIndexes.

protected void applyIndexes(Table table, TableInformation tableInformation, Dialect dialect, Metadata metadata, Formatter formatter, ExecutionOptions options, GenerationTarget... targets) {
    final Exporter<Index> exporter = dialect.getIndexExporter();
    final Iterator<Index> indexItr = table.getIndexIterator();
    while (indexItr.hasNext()) {
        final Index index = indexItr.next();
        if (!StringHelper.isEmpty(index.getName())) {
            IndexInformation existingIndex = null;
            if (tableInformation != null) {
                existingIndex = findMatchingIndex(index, tableInformation);
            }
            if (existingIndex == null) {
                applySqlStrings(false, exporter.getSqlCreateStrings(index, metadata), formatter, options, targets);
            }
        }
    }
}
Also used : IndexInformation(org.hibernate.tool.schema.extract.spi.IndexInformation) Index(org.hibernate.mapping.Index)

Example 5 with Index

use of org.hibernate.mapping.Index in project hibernate-orm by hibernate.

the class AbstractJPAIndexTest method testCollectionTableIndex.

@Test
public void testCollectionTableIndex() {
    PersistentClass entity = metadata().getEntityBinding(Car.class.getName());
    Property property = entity.getProperty("otherDealers");
    Set set = (Set) property.getValue();
    Table collectionTable = set.getCollectionTable();
    Iterator<Index> itr = collectionTable.getIndexIterator();
    assertTrue(itr.hasNext());
    Index index = itr.next();
    assertFalse(itr.hasNext());
    assertTrue("index name is not generated", StringHelper.isNotEmpty(index.getName()));
    assertEquals(1, index.getColumnSpan());
    Iterator<Column> columnIterator = index.getColumnIterator();
    Column column = columnIterator.next();
    assertEquals("name", column.getName());
    assertSame(collectionTable, index.getTable());
}
Also used : Set(org.hibernate.mapping.Set) Table(org.hibernate.mapping.Table) Column(org.hibernate.mapping.Column) Index(org.hibernate.mapping.Index) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Aggregations

Index (org.hibernate.mapping.Index)10 Column (org.hibernate.mapping.Column)6 Table (org.hibernate.mapping.Table)5 UniqueKey (org.hibernate.mapping.UniqueKey)5 Test (org.junit.Test)5 PersistentClass (org.hibernate.mapping.PersistentClass)4 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 Identifier (org.hibernate.boot.model.naming.Identifier)2 ForeignKey (org.hibernate.mapping.ForeignKey)2 Property (org.hibernate.mapping.Property)2 List (java.util.List)1 AnnotationException (org.hibernate.AnnotationException)1 DuplicateMappingException (org.hibernate.DuplicateMappingException)1 MappingException (org.hibernate.MappingException)1 ImplicitIndexNameSource (org.hibernate.boot.model.naming.ImplicitIndexNameSource)1 ImplicitUniqueKeyNameSource (org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource)1 AuxiliaryDatabaseObject (org.hibernate.boot.model.relational.AuxiliaryDatabaseObject)1 Database (org.hibernate.boot.model.relational.Database)1