Search in sources :

Example 1 with QualifiedTableName

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

the class SchemaUpdateTableBackedSequenceTest method testCreateTableOnUpdate.

@Test
public void testCreateTableOnUpdate() throws SQLException {
    Metadata metadata = new MetadataSources(ssr).buildMetadata();
    Database database = metadata.getDatabase();
    TableStructure tableStructure = new TableStructure(database.getJdbcEnvironment(), new QualifiedTableName(null, null, Identifier.toIdentifier("test_seq")), Identifier.toIdentifier("nextval"), 20, 30, Long.class);
    tableStructure.registerExportables(database);
    // lets make sure the InitCommand is there
    assertEquals(1, database.getDefaultNamespace().getTables().size());
    Table table = database.getDefaultNamespace().getTables().iterator().next();
    assertEquals(1, table.getInitCommands().size());
    final TargetImpl target = new TargetImpl();
    ssr.getService(SchemaManagementTool.class).getSchemaMigrator(Collections.emptyMap()).doMigration(metadata, new ExecutionOptions() {

        @Override
        public boolean shouldManageNamespaces() {
            return true;
        }

        @Override
        public Map getConfigurationValues() {
            return ssr.getService(ConfigurationService.class).getSettings();
        }

        @Override
        public ExceptionHandler getExceptionHandler() {
            return ExceptionHandlerLoggedImpl.INSTANCE;
        }
    }, new TargetDescriptor() {

        @Override
        public EnumSet<TargetType> getTargetTypes() {
            return EnumSet.of(TargetType.SCRIPT, TargetType.DATABASE);
        }

        @Override
        public ScriptTargetOutput getScriptTargetOutput() {
            return target;
        }
    });
    assertTrue(target.found);
    new SchemaExport().drop(EnumSet.of(TargetType.DATABASE), metadata);
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) Table(org.hibernate.mapping.Table) EnumSet(java.util.EnumSet) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) TargetDescriptor(org.hibernate.tool.schema.spi.TargetDescriptor) ExceptionHandler(org.hibernate.tool.schema.spi.ExceptionHandler) ExecutionOptions(org.hibernate.tool.schema.spi.ExecutionOptions) TableStructure(org.hibernate.id.enhanced.TableStructure) Database(org.hibernate.boot.model.relational.Database) ScriptTargetOutput(org.hibernate.tool.schema.spi.ScriptTargetOutput) Map(java.util.Map) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test)

Example 2 with QualifiedTableName

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

the class InformationExtractorJdbcDatabaseMetaDataImpl method extractTableInformation.

private TableInformation extractTableInformation(ResultSet resultSet) throws SQLException {
    final QualifiedTableName tableName = extractTableName(resultSet);
    final TableInformationImpl tableInformation = new TableInformationImpl(this, identifierHelper(), tableName, isPhysicalTableType(resultSet.getString("TABLE_TYPE")), resultSet.getString("REMARKS"));
    return tableInformation;
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName)

Example 3 with QualifiedTableName

use of org.hibernate.boot.model.relational.QualifiedTableName 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 4 with QualifiedTableName

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

the class InformationExtractorJdbcDatabaseMetaDataImpl method extractTableName.

private QualifiedTableName extractTableName(ResultSet resultSet) throws SQLException {
    final String incomingCatalogName = resultSet.getString("TABLE_CAT");
    final String incomingSchemaName = resultSet.getString("TABLE_SCHEM");
    final String incomingTableName = resultSet.getString("TABLE_NAME");
    final DatabaseIdentifier catalog = DatabaseIdentifier.toIdentifier(incomingCatalogName);
    final DatabaseIdentifier schema = DatabaseIdentifier.toIdentifier(incomingSchemaName);
    final DatabaseIdentifier table = DatabaseIdentifier.toIdentifier(incomingTableName);
    return new QualifiedTableName(catalog, schema, table);
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) DatabaseIdentifier(org.hibernate.boot.model.naming.DatabaseIdentifier)

Example 5 with QualifiedTableName

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

the class EntityBinder method addJoin.

private Join addJoin(SecondaryTable secondaryTable, JoinTable joinTable, PropertyHolder propertyHolder, boolean noDelayInPkColumnCreation) {
    // A non null propertyHolder means than we process the Pk creation without delay
    Join join = new Join();
    join.setPersistentClass(persistentClass);
    final String schema;
    final String catalog;
    final Object joinColumns;
    final List<UniqueConstraintHolder> uniqueConstraintHolders;
    final QualifiedTableName logicalName;
    if (secondaryTable != null) {
        schema = secondaryTable.schema();
        catalog = secondaryTable.catalog();
        logicalName = new QualifiedTableName(Identifier.toIdentifier(catalog), Identifier.toIdentifier(schema), context.getMetadataCollector().getDatabase().getJdbcEnvironment().getIdentifierHelper().toIdentifier(secondaryTable.name()));
        joinColumns = secondaryTable.pkJoinColumns();
        uniqueConstraintHolders = TableBinder.buildUniqueConstraintHolders(secondaryTable.uniqueConstraints());
    } else if (joinTable != null) {
        schema = joinTable.schema();
        catalog = joinTable.catalog();
        logicalName = new QualifiedTableName(Identifier.toIdentifier(catalog), Identifier.toIdentifier(schema), context.getMetadataCollector().getDatabase().getJdbcEnvironment().getIdentifierHelper().toIdentifier(joinTable.name()));
        joinColumns = joinTable.joinColumns();
        uniqueConstraintHolders = TableBinder.buildUniqueConstraintHolders(joinTable.uniqueConstraints());
    } else {
        throw new AssertionFailure("Both JoinTable and SecondaryTable are null");
    }
    final Table table = TableBinder.buildAndFillTable(schema, catalog, logicalName.getTableName(), false, uniqueConstraintHolders, null, null, context, null, null);
    final InFlightMetadataCollector.EntityTableXref tableXref = context.getMetadataCollector().getEntityTableXref(persistentClass.getEntityName());
    assert tableXref != null : "Could not locate EntityTableXref for entity [" + persistentClass.getEntityName() + "]";
    tableXref.addSecondaryTable(logicalName, join);
    if (secondaryTable != null) {
        TableBinder.addIndexes(table, secondaryTable.indexes(), context);
    }
    // no check constraints available on joins
    join.setTable(table);
    // somehow keep joins() for later.
    // Has to do the work later because it needs persistentClass id!
    LOG.debugf("Adding secondary table to entity %s -> %s", persistentClass.getEntityName(), join.getTable().getName());
    org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation(join);
    if (matchingTable != null) {
        join.setSequentialSelect(FetchMode.JOIN != matchingTable.fetch());
        join.setInverse(matchingTable.inverse());
        join.setOptional(matchingTable.optional());
        if (!BinderHelper.isEmptyAnnotationValue(matchingTable.sqlInsert().sql())) {
            join.setCustomSQLInsert(matchingTable.sqlInsert().sql().trim(), matchingTable.sqlInsert().callable(), ExecuteUpdateResultCheckStyle.fromExternalName(matchingTable.sqlInsert().check().toString().toLowerCase(Locale.ROOT)));
        }
        if (!BinderHelper.isEmptyAnnotationValue(matchingTable.sqlUpdate().sql())) {
            join.setCustomSQLUpdate(matchingTable.sqlUpdate().sql().trim(), matchingTable.sqlUpdate().callable(), ExecuteUpdateResultCheckStyle.fromExternalName(matchingTable.sqlUpdate().check().toString().toLowerCase(Locale.ROOT)));
        }
        if (!BinderHelper.isEmptyAnnotationValue(matchingTable.sqlDelete().sql())) {
            join.setCustomSQLDelete(matchingTable.sqlDelete().sql().trim(), matchingTable.sqlDelete().callable(), ExecuteUpdateResultCheckStyle.fromExternalName(matchingTable.sqlDelete().check().toString().toLowerCase(Locale.ROOT)));
        }
    } else {
        // default
        join.setSequentialSelect(false);
        join.setInverse(false);
        // perhaps not quite per-spec, but a Good Thing anyway
        join.setOptional(true);
    }
    if (noDelayInPkColumnCreation) {
        createPrimaryColumnsToSecondaryTable(joinColumns, propertyHolder, join);
    } else {
        secondaryTables.put(table.getQuotedName(), join);
        secondaryTableJoins.put(table.getQuotedName(), joinColumns);
    }
    return join;
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) UniqueConstraintHolder(org.hibernate.cfg.UniqueConstraintHolder) AssertionFailure(org.hibernate.AssertionFailure) JoinTable(javax.persistence.JoinTable) SecondaryTable(javax.persistence.SecondaryTable) Table(org.hibernate.mapping.Table) Join(org.hibernate.mapping.Join) InFlightMetadataCollector(org.hibernate.boot.spi.InFlightMetadataCollector)

Aggregations

QualifiedTableName (org.hibernate.boot.model.relational.QualifiedTableName)15 Identifier (org.hibernate.boot.model.naming.Identifier)10 ArrayList (java.util.ArrayList)8 DatabaseIdentifier (org.hibernate.boot.model.naming.DatabaseIdentifier)6 Table (org.hibernate.mapping.Table)6 TableInformation (org.hibernate.tool.schema.extract.spi.TableInformation)6 Name (org.hibernate.boot.model.relational.Namespace.Name)5 TableInformationImpl (org.hibernate.tool.schema.extract.internal.TableInformationImpl)5 ForeignKeyInformation (org.hibernate.tool.schema.extract.spi.ForeignKeyInformation)5 Test (org.junit.Test)5 Method (java.lang.reflect.Method)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 IdentifierHelper (org.hibernate.engine.jdbc.env.spi.IdentifierHelper)4 Column (org.hibernate.mapping.Column)4 ForeignKey (org.hibernate.mapping.ForeignKey)4 InformationExtractor (org.hibernate.tool.schema.extract.spi.InformationExtractor)4 AbstractSchemaMigrator (org.hibernate.tool.schema.internal.AbstractSchemaMigrator)4 ColumnInformation (org.hibernate.tool.schema.extract.spi.ColumnInformation)3 HashMap (java.util.HashMap)2