Search in sources :

Example 1 with ColumnInformation

use of org.hibernate.tool.schema.extract.spi.ColumnInformation in project hibernate-orm by hibernate.

the class CheckForExistingForeignKeyTest method getForeignKeyInformation.

/**
 * @param referencedTableName - String
 * @param referencingColumnName - String
 * @param keyName - String
 * @return ForeignKeyInformation
 */
private ForeignKeyInformation getForeignKeyInformation(String referencedTableName, String referencingColumnName, String keyName) {
    List<ColumnReferenceMapping> columnMappingList = new ArrayList<>();
    ColumnInformation referencingColumnMetadata = getColumnInformation("-", referencingColumnName);
    ColumnInformation referencedColumnMetadata = getColumnInformation(referencedTableName, "-");
    ColumnReferenceMapping columnReferenceMapping = new ColumnReferenceMappingImpl(referencingColumnMetadata, referencedColumnMetadata);
    columnMappingList.add(columnReferenceMapping);
    ForeignKeyInformationImpl foreignKeyInformation = new ForeignKeyInformationImpl(new Identifier(keyName, false), columnMappingList);
    return foreignKeyInformation;
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier) ForeignKeyInformationImpl(org.hibernate.tool.schema.extract.internal.ForeignKeyInformationImpl) ColumnInformation(org.hibernate.tool.schema.extract.spi.ColumnInformation) ArrayList(java.util.ArrayList) ColumnReferenceMapping(org.hibernate.tool.schema.extract.spi.ForeignKeyInformation.ColumnReferenceMapping)

Example 2 with ColumnInformation

use of org.hibernate.tool.schema.extract.spi.ColumnInformation in project hibernate-orm by hibernate.

the class AbstractSchemaValidator method validateTable.

protected void validateTable(Table table, TableInformation tableInformation, Metadata metadata, ExecutionOptions options, Dialect dialect) {
    if (tableInformation == null) {
        throw new SchemaManagementException(String.format("Schema-validation: missing table [%s]", table.getQualifiedTableName().toString()));
    }
    final Iterator selectableItr = table.getColumnIterator();
    while (selectableItr.hasNext()) {
        final Selectable selectable = (Selectable) selectableItr.next();
        if (Column.class.isInstance(selectable)) {
            final Column column = (Column) selectable;
            final ColumnInformation existingColumn = tableInformation.getColumn(Identifier.toIdentifier(column.getQuotedName()));
            if (existingColumn == null) {
                throw new SchemaManagementException(String.format("Schema-validation: missing column [%s] in table [%s]", column.getName(), table.getQualifiedTableName()));
            }
            validateColumnType(table, column, existingColumn, metadata, options, dialect);
        }
    }
}
Also used : Selectable(org.hibernate.mapping.Selectable) Column(org.hibernate.mapping.Column) SchemaManagementException(org.hibernate.tool.schema.spi.SchemaManagementException) ColumnInformation(org.hibernate.tool.schema.extract.spi.ColumnInformation) Iterator(java.util.Iterator)

Example 3 with ColumnInformation

use of org.hibernate.tool.schema.extract.spi.ColumnInformation in project hibernate-orm by hibernate.

the class InformationExtractorJdbcDatabaseMetaDataImpl method getIndexes.

@Override
public Iterable<IndexInformation> getIndexes(TableInformation tableInformation) {
    final Map<Identifier, IndexInformationImpl.Builder> builders = 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().getIndexInfo(catalogFilter, schemaFilter, tableName.getTableName().getText(), // DO NOT limit to just unique
        false, // DO require up-to-date results
        true);
        try {
            while (resultSet.next()) {
                if (resultSet.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic) {
                    continue;
                }
                final Identifier indexIdentifier = DatabaseIdentifier.toIdentifier(resultSet.getString("INDEX_NAME"));
                IndexInformationImpl.Builder builder = builders.get(indexIdentifier);
                if (builder == null) {
                    builder = IndexInformationImpl.builder(indexIdentifier);
                    builders.put(indexIdentifier, builder);
                }
                final Identifier columnIdentifier = DatabaseIdentifier.toIdentifier(resultSet.getString("COLUMN_NAME"));
                final ColumnInformation columnInformation = tableInformation.getColumn(columnIdentifier);
                if (columnInformation == null) {
                    // See HHH-10191: this may happen when dealing with Oracle/PostgreSQL function indexes
                    log.logCannotLocateIndexColumnInformation(columnIdentifier.getText(), indexIdentifier.getText());
                }
                builder.addColumn(columnInformation);
            }
        } finally {
            resultSet.close();
        }
    } catch (SQLException e) {
        throw convertSQLException(e, "Error accessing index information: " + tableInformation.getName().toString());
    }
    final List<IndexInformation> indexes = new ArrayList<IndexInformation>();
    for (IndexInformationImpl.Builder builder : builders.values()) {
        IndexInformationImpl index = builder.build();
        indexes.add(index);
    }
    return indexes;
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) IndexInformation(org.hibernate.tool.schema.extract.spi.IndexInformation) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) DatabaseIdentifier(org.hibernate.boot.model.naming.DatabaseIdentifier) Identifier(org.hibernate.boot.model.naming.Identifier) ColumnInformation(org.hibernate.tool.schema.extract.spi.ColumnInformation) ResultSet(java.sql.ResultSet)

Example 4 with ColumnInformation

use of org.hibernate.tool.schema.extract.spi.ColumnInformation in project hibernate-orm by hibernate.

the class InformationExtractorJdbcDatabaseMetaDataImpl method getPrimaryKey.

@Override
public PrimaryKeyInformation getPrimaryKey(TableInformationImpl tableInformation) {
    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().getPrimaryKeys(catalogFilter, schemaFilter, tableInformation.getName().getTableName().getText());
        final List<ColumnInformation> pkColumns = new ArrayList<ColumnInformation>();
        boolean firstPass = true;
        Identifier pkIdentifier = null;
        try {
            while (resultSet.next()) {
                final String currentPkName = resultSet.getString("PK_NAME");
                final Identifier currentPkIdentifier = currentPkName == null ? null : DatabaseIdentifier.toIdentifier(currentPkName);
                if (firstPass) {
                    pkIdentifier = currentPkIdentifier;
                    firstPass = false;
                } else {
                    if (!EqualsHelper.equals(pkIdentifier, currentPkIdentifier)) {
                        throw new SchemaExtractionException(String.format("Encountered primary keys differing name on table %s", tableInformation.getName().toString()));
                    }
                }
                final int columnPosition = resultSet.getInt("KEY_SEQ");
                final Identifier columnIdentifier = DatabaseIdentifier.toIdentifier(resultSet.getString("COLUMN_NAME"));
                final ColumnInformation column = tableInformation.getColumn(columnIdentifier);
                pkColumns.add(columnPosition - 1, column);
            }
        } finally {
            resultSet.close();
        }
        if (firstPass) {
            // we did not find any results (no pk)
            return null;
        } else {
            // validate column list is properly contiguous
            for (int i = 0; i < pkColumns.size(); i++) {
                if (pkColumns.get(i) == null) {
                    throw new SchemaExtractionException("Primary Key information was missing for KEY_SEQ = " + (i + 1));
                }
            }
            // build the return
            return new PrimaryKeyInformationImpl(pkIdentifier, pkColumns);
        }
    } catch (SQLException e) {
        throw convertSQLException(e, "Error while reading primary key meta data for " + tableInformation.getName().toString());
    }
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) DatabaseIdentifier(org.hibernate.boot.model.naming.DatabaseIdentifier) Identifier(org.hibernate.boot.model.naming.Identifier) SQLException(java.sql.SQLException) ColumnInformation(org.hibernate.tool.schema.extract.spi.ColumnInformation) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) SchemaExtractionException(org.hibernate.tool.schema.extract.spi.SchemaExtractionException)

Example 5 with ColumnInformation

use of org.hibernate.tool.schema.extract.spi.ColumnInformation in project hibernate-orm by hibernate.

the class Table method sqlAlterStrings.

public Iterator sqlAlterStrings(Dialect dialect, Metadata metadata, TableInformation tableInfo, String defaultCatalog, String defaultSchema) throws HibernateException {
    final JdbcEnvironment jdbcEnvironment = metadata.getDatabase().getJdbcEnvironment();
    Identifier quotedCatalog = catalog != null && catalog.isQuoted() ? new Identifier(tableInfo.getName().getCatalogName().getText(), true) : tableInfo.getName().getCatalogName();
    Identifier quotedSchema = schema != null && schema.isQuoted() ? new Identifier(tableInfo.getName().getSchemaName().getText(), true) : tableInfo.getName().getSchemaName();
    Identifier quotedTable = name != null && name.isQuoted() ? new Identifier(tableInfo.getName().getObjectName().getText(), true) : tableInfo.getName().getObjectName();
    final String tableName = jdbcEnvironment.getQualifiedObjectNameFormatter().format(new QualifiedTableName(quotedCatalog, quotedSchema, quotedTable), dialect);
    StringBuilder root = new StringBuilder(dialect.getAlterTableString(tableName)).append(' ').append(dialect.getAddColumnString());
    Iterator iter = getColumnIterator();
    List results = new ArrayList();
    while (iter.hasNext()) {
        final Column column = (Column) iter.next();
        final ColumnInformation columnInfo = tableInfo.getColumn(Identifier.toIdentifier(column.getName(), column.isQuoted()));
        if (columnInfo == null) {
            // the column doesnt exist at all.
            StringBuilder alter = new StringBuilder(root.toString()).append(' ').append(column.getQuotedName(dialect)).append(' ').append(column.getSqlType(dialect, metadata));
            String defaultValue = column.getDefaultValue();
            if (defaultValue != null) {
                alter.append(" default ").append(defaultValue);
            }
            if (column.isNullable()) {
                alter.append(dialect.getNullColumnString());
            } else {
                alter.append(" not null");
            }
            if (column.isUnique()) {
                String keyName = Constraint.generateName("UK_", this, column);
                UniqueKey uk = getOrCreateUniqueKey(keyName);
                uk.addColumn(column);
                alter.append(dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(column));
            }
            if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) {
                alter.append(" check(").append(column.getCheckConstraint()).append(")");
            }
            String columnComment = column.getComment();
            if (columnComment != null) {
                alter.append(dialect.getColumnComment(columnComment));
            }
            alter.append(dialect.getAddColumnSuffixString());
            results.add(alter.toString());
        }
    }
    if (results.isEmpty()) {
        log.debugf("No alter strings for table : %s", getQuotedName());
    }
    return results.iterator();
}
Also used : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) Identifier(org.hibernate.boot.model.naming.Identifier) ColumnInformation(org.hibernate.tool.schema.extract.spi.ColumnInformation) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)

Aggregations

ColumnInformation (org.hibernate.tool.schema.extract.spi.ColumnInformation)5 ArrayList (java.util.ArrayList)4 Identifier (org.hibernate.boot.model.naming.Identifier)4 QualifiedTableName (org.hibernate.boot.model.relational.QualifiedTableName)3 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 Iterator (java.util.Iterator)2 DatabaseIdentifier (org.hibernate.boot.model.naming.DatabaseIdentifier)2 HashMap (java.util.HashMap)1 List (java.util.List)1 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)1 Column (org.hibernate.mapping.Column)1 Selectable (org.hibernate.mapping.Selectable)1 ForeignKeyInformationImpl (org.hibernate.tool.schema.extract.internal.ForeignKeyInformationImpl)1 ColumnReferenceMapping (org.hibernate.tool.schema.extract.spi.ForeignKeyInformation.ColumnReferenceMapping)1 IndexInformation (org.hibernate.tool.schema.extract.spi.IndexInformation)1 SchemaExtractionException (org.hibernate.tool.schema.extract.spi.SchemaExtractionException)1 SchemaManagementException (org.hibernate.tool.schema.spi.SchemaManagementException)1