Search in sources :

Example 1 with UniqueKey

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

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

the class StandardTableExporter method getSqlCreateStrings.

@Override
public String[] getSqlCreateStrings(Table table, Metadata metadata) {
    final QualifiedName tableName = new QualifiedNameParser.NameParts(Identifier.toIdentifier(table.getCatalog(), table.isCatalogQuoted()), Identifier.toIdentifier(table.getSchema(), table.isSchemaQuoted()), table.getNameIdentifier());
    final JdbcEnvironment jdbcEnvironment = metadata.getDatabase().getJdbcEnvironment();
    StringBuilder buf = new StringBuilder(tableCreateString(table.hasPrimaryKey())).append(' ').append(jdbcEnvironment.getQualifiedObjectNameFormatter().format(tableName, jdbcEnvironment.getDialect())).append(" (");
    boolean isPrimaryKeyIdentity = table.hasPrimaryKey() && table.getIdentifierValue() != null && table.getIdentifierValue().isIdentityColumn(metadata.getIdentifierGeneratorFactory(), dialect);
    // this is the much better form moving forward as we move to metamodel
    //boolean isPrimaryKeyIdentity = hasPrimaryKey
    //				&& table.getPrimaryKey().getColumnSpan() == 1
    //				&& table.getPrimaryKey().getColumn( 0 ).isIdentity();
    // Try to find out the name of the primary key in case the dialect needs it to create an identity
    String pkColName = null;
    if (table.hasPrimaryKey()) {
        Column pkColumn = (Column) table.getPrimaryKey().getColumns().iterator().next();
        pkColName = pkColumn.getQuotedName(dialect);
    }
    final Iterator columnItr = table.getColumnIterator();
    boolean isFirst = true;
    while (columnItr.hasNext()) {
        final Column col = (Column) columnItr.next();
        if (isFirst) {
            isFirst = false;
        } else {
            buf.append(", ");
        }
        String colName = col.getQuotedName(dialect);
        buf.append(colName).append(' ');
        if (isPrimaryKeyIdentity && colName.equals(pkColName)) {
            // to support dialects that have their own identity data type
            if (dialect.getIdentityColumnSupport().hasDataTypeInIdentityColumn()) {
                buf.append(col.getSqlType(dialect, metadata));
            }
            buf.append(' ').append(dialect.getIdentityColumnSupport().getIdentityColumnString(col.getSqlTypeCode(metadata)));
        } else {
            buf.append(col.getSqlType(dialect, metadata));
            String defaultValue = col.getDefaultValue();
            if (defaultValue != null) {
                buf.append(" default ").append(defaultValue);
            }
            if (col.isNullable()) {
                buf.append(dialect.getNullColumnString());
            } else {
                buf.append(" not null");
            }
        }
        if (col.isUnique()) {
            String keyName = Constraint.generateName("UK_", table, col);
            UniqueKey uk = table.getOrCreateUniqueKey(keyName);
            uk.addColumn(col);
            buf.append(dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(col));
        }
        if (col.getCheckConstraint() != null && dialect.supportsColumnCheck()) {
            buf.append(" check (").append(col.getCheckConstraint()).append(")");
        }
        String columnComment = col.getComment();
        if (columnComment != null) {
            buf.append(dialect.getColumnComment(columnComment));
        }
    }
    if (table.hasPrimaryKey()) {
        buf.append(", ").append(table.getPrimaryKey().sqlConstraintString(dialect));
    }
    buf.append(dialect.getUniqueDelegate().getTableCreationUniqueConstraintsFragment(table));
    applyTableCheck(table, buf);
    buf.append(')');
    if (table.getComment() != null) {
        buf.append(dialect.getTableComment(table.getComment()));
    }
    applyTableTypeString(buf);
    List<String> sqlStrings = new ArrayList<String>();
    sqlStrings.add(buf.toString());
    applyComments(table, tableName, sqlStrings);
    applyInitCommands(table, sqlStrings);
    return sqlStrings.toArray(new String[sqlStrings.size()]);
}
Also used : Column(org.hibernate.mapping.Column) UniqueKey(org.hibernate.mapping.UniqueKey) QualifiedName(org.hibernate.boot.model.relational.QualifiedName) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)

Example 3 with UniqueKey

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

the class LongKeyNamingStrategyTest method testWithCustomNamingStrategy.

@Test
public void testWithCustomNamingStrategy() throws Exception {
    Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(Address.class).addAnnotatedClass(Person.class).getMetadataBuilder().applyImplicitNamingStrategy(new LongIdentifierNamingStrategy()).build();
    org.hibernate.mapping.ForeignKey foreignKey = (org.hibernate.mapping.ForeignKey) metadata.getEntityBinding(Address.class.getName()).getTable().getForeignKeyIterator().next();
    assertEquals("FK_way_longer_than_the_30_char", foreignKey.getName());
    UniqueKey uniqueKey = metadata.getEntityBinding(Address.class.getName()).getTable().getUniqueKeyIterator().next();
    assertEquals("UK_way_longer_than_the_30_char", uniqueKey.getName());
    org.hibernate.mapping.Index index = metadata.getEntityBinding(Address.class.getName()).getTable().getIndexIterator().next();
    assertEquals("IDX_way_longer_than_the_30_cha", index.getName());
}
Also used : UniqueKey(org.hibernate.mapping.UniqueKey) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) ForeignKey(javax.persistence.ForeignKey) Test(org.junit.Test)

Example 4 with UniqueKey

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

the class QuoteGlobalTest method testQuotedUniqueConstraint.

@Test
@TestForIssue(jiraKey = "HHH-7890")
public void testQuotedUniqueConstraint() {
    Iterator<UniqueKey> itr = metadata().getEntityBinding(Person.class.getName()).getTable().getUniqueKeyIterator();
    while (itr.hasNext()) {
        UniqueKey uk = itr.next();
        assertEquals(uk.getColumns().size(), 1);
        assertEquals(uk.getColumn(0).getName(), "name");
        return;
    }
    fail("GLOBALLY_QUOTED_IDENTIFIERS caused the unique key creation to fail.");
}
Also used : UniqueKey(org.hibernate.mapping.UniqueKey) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 5 with UniqueKey

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

the class ConstraintTest method testConstraintNameLength.

@Test
@TestForIssue(jiraKey = "HHH-1904")
public void testConstraintNameLength() {
    int foundCount = 0;
    for (Namespace namespace : metadata().getDatabase().getNamespaces()) {
        for (org.hibernate.mapping.Table table : namespace.getTables()) {
            Iterator fkItr = table.getForeignKeyIterator();
            while (fkItr.hasNext()) {
                ForeignKey fk = (ForeignKey) fkItr.next();
                assertTrue(fk.getName().length() <= MAX_NAME_LENGTH);
                // ensure the randomly generated constraint name doesn't
                // happen if explicitly given
                Column column = fk.getColumn(0);
                if (column.getName().equals("explicit_native")) {
                    foundCount++;
                    assertEquals(fk.getName(), EXPLICIT_FK_NAME_NATIVE);
                } else if (column.getName().equals("explicit_jpa")) {
                    foundCount++;
                    assertEquals(fk.getName(), EXPLICIT_FK_NAME_JPA);
                }
            }
            Iterator ukItr = table.getUniqueKeyIterator();
            while (ukItr.hasNext()) {
                UniqueKey uk = (UniqueKey) ukItr.next();
                assertTrue(uk.getName().length() <= MAX_NAME_LENGTH);
                // ensure the randomly generated constraint name doesn't
                // happen if explicitly given
                Column column = uk.getColumn(0);
                if (column.getName().equals("explicit")) {
                    foundCount++;
                    assertEquals(uk.getName(), EXPLICIT_UK_NAME);
                }
            }
        }
    }
    assertEquals("Could not find the necessary columns.", 3, foundCount);
}
Also used : JoinColumn(javax.persistence.JoinColumn) Column(org.hibernate.mapping.Column) UniqueKey(org.hibernate.mapping.UniqueKey) Iterator(java.util.Iterator) ForeignKey(org.hibernate.mapping.ForeignKey) UniqueConstraint(javax.persistence.UniqueConstraint) Namespace(org.hibernate.boot.model.relational.Namespace) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Aggregations

UniqueKey (org.hibernate.mapping.UniqueKey)10 Iterator (java.util.Iterator)5 Column (org.hibernate.mapping.Column)5 Index (org.hibernate.mapping.Index)5 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 ForeignKey (org.hibernate.mapping.ForeignKey)3 HashSet (java.util.HashSet)2 Identifier (org.hibernate.boot.model.naming.Identifier)2 Namespace (org.hibernate.boot.model.relational.Namespace)2 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)2 Table (org.hibernate.mapping.Table)2 TestForIssue (org.hibernate.testing.TestForIssue)2 List (java.util.List)1 ForeignKey (javax.persistence.ForeignKey)1 JoinColumn (javax.persistence.JoinColumn)1 UniqueConstraint (javax.persistence.UniqueConstraint)1 AnnotationException (org.hibernate.AnnotationException)1 DuplicateMappingException (org.hibernate.DuplicateMappingException)1 MappingException (org.hibernate.MappingException)1