Java Code Examples for org.apache.ddlutils.model.Table#getForeignKeyCount()

The following examples show how to use org.apache.ddlutils.model.Table#getForeignKeyCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataToDatabaseSink.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void start() throws DataSinkException
{
    _fkTables.clear();
    _waitingObjects.clear();
    if (_ensureFkOrder)
    {
        for (int tableIdx = 0; tableIdx < _model.getTableCount(); tableIdx++)
        {
            Table table = _model.getTable(tableIdx);

            for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
            {
                ForeignKey curFk = table.getForeignKey(fkIdx);

                _fkTables.add(curFk.getForeignTable());
            }
        }
    }
    try
    {
        _connection = _platform.borrowConnection();
    }
    catch (DatabaseOperationException ex)
    {
        throw new DataSinkException(ex);
    }
}
 
Example 2
Source File: ForeignKeyChangeImplBase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ForeignKey findChangedForeignKey(Database model, boolean caseSensitive)
{
	Table table = findChangedTable(model, caseSensitive);

	if (table != null)
	{
        for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
        {
            ForeignKey curFk = table.getForeignKey(fkIdx);

            if (curFk.getReferenceCount() == _referenceColumnNames.size())
            {
                for (int refIdx = 0; refIdx < curFk.getReferenceCount(); refIdx++)
                {
                    Reference ref      = curFk.getReference(refIdx);
                    Pair      colNames = (Pair)_referenceColumnNames.get(refIdx);

                    if (caseSensitive)
                    {
                        if (ref.getLocalColumnName().equals((String)colNames.getFirst()) &&
                            ref.getForeignColumnName().equals((String)colNames.getSecond()))
                        {
                            return curFk;
                        }
                    }
                    else
                    {
                        if (ref.getLocalColumnName().equalsIgnoreCase((String)colNames.getFirst()) &&
                            ref.getForeignColumnName().equalsIgnoreCase((String)colNames.getSecond()))
                        {
                            return curFk;
                        }
                    }
                }
            }
        }
	}
    return null;
}
 
Example 3
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the foreign key constraints inside a create table () clause.
 * 
 * @param database The database model
 * @param table    The table
 */
protected void writeEmbeddedForeignKeysStmt(Database database, Table table) throws IOException
{
    for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
    {
        ForeignKey foreignKey = table.getForeignKey(idx);

        if (foreignKey.getForeignTableName() == null)
        {
            _log.warn("Foreign key table is null for key " + foreignKey);
        }
        else
        {
            printStartOfEmbeddedStatement();
            if (getPlatformInfo().isEmbeddedForeignKeysNamed())
            {
                print("CONSTRAINT ");
                printIdentifier(getForeignKeyName(table, foreignKey));
                print(" ");
            }
            print("FOREIGN KEY (");
            writeLocalReferences(foreignKey);
            print(") REFERENCES ");
            printIdentifier(getTableName(database.findTable(foreignKey.getForeignTableName())));
            print(" (");
            writeForeignReferences(foreignKey);
            print(")");
            writeForeignKeyOnDeleteAction(table, foreignKey);
            writeForeignKeyOnUpdateAction(table, foreignKey);
        }
    }
}
 
Example 4
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates external foreignkey drop statements.
 * 
 * @param table The table
 */
public void dropForeignKeys(Table table) throws IOException
{
    for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
    {
        dropForeignKey(table, table.getForeignKey(idx));
    }
}
 
Example 5
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates external foreignkey creation statements if necessary.
 * 
 * @param database The database model
 * @param table    The table
 */
public void createForeignKeys(Database database, Table table) throws IOException
{
    for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
    {
        createForeignKey(database, table, table.getForeignKey(idx));
    }
}
 
Example 6
Source File: DataToDatabaseSink.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void start() throws DataSinkException
{
    _fkTables.clear();
    _waitingObjects.clear();
    if (_ensureFkOrder)
    {
        for (int tableIdx = 0; tableIdx < _model.getTableCount(); tableIdx++)
        {
            Table table = _model.getTable(tableIdx);

            for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
            {
                ForeignKey curFk = table.getForeignKey(fkIdx);

                _fkTables.add(curFk.getForeignTable());
            }
        }
    }
    try
    {
        _connection = _platform.borrowConnection();
    }
    catch (DatabaseOperationException ex)
    {
        throw new DataSinkException(ex);
    }
}
 
Example 7
Source File: DatabaseIO.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
     * Writes the table object to the given XML writer.
     * 
     * @param table     The table object
     * @param xmlWriter The XML writer
     */
    private void writeTableElement(Table table, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException
    {
        xmlWriter.indentIfPrettyPrinting(1);
        writeElementStart(xmlWriter, QNAME_ELEMENT_TABLE);
// GemStone changes BEGIN
        // write fully qualified table name
        final String tableName = table.getQualifiedName();
        writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, tableName);
        /* (original code)
        writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME,        table.getName());
        */
// GemStone changes END
        writeAttribute(xmlWriter, QNAME_ATTRIBUTE_DESCRIPTION, table.getDescription());
        if ((table.getColumnCount() > 0) || (table.getForeignKeyCount() > 0) || (table.getIndexCount() > 0))
        {
            xmlWriter.printlnIfPrettyPrinting();
            for (int idx = 0; idx < table.getColumnCount(); idx++)
            {
                writeColumnElement(table.getColumn(idx), xmlWriter);
            }
            for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
            {
                writeForeignKeyElement(table.getForeignKey(idx), xmlWriter);
            }
            for (int idx = 0; idx < table.getIndexCount(); idx++)
            {
                writeIndexElement(table.getIndex(idx), xmlWriter);
            }
            xmlWriter.indentIfPrettyPrinting(1);
        }
        writeElementEnd(xmlWriter);
    }
 
Example 8
Source File: ModelComparator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Searches in the given table for a corresponding foreign key. If the given key
 * has no name, then a foreign key to the same table with the same columns (but not
 * necessarily in the same order) is searched. If the given key has a name, then the
 * corresponding key also needs to have the same name, or no name at all, but not a
 * different one. 
 * 
 * @param table The table to search in
 * @param fk    The original foreign key
 * @return The corresponding foreign key if found
 */
protected ForeignKey findCorrespondingForeignKey(Table table, ForeignKey fk)
{
    for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
    {
        ForeignKey curFk = table.getForeignKey(fkIdx);

        if ((_caseSensitive  && fk.equals(curFk)) ||
            (!_caseSensitive && fk.equalsIgnoreCase(curFk)))
        {
            return curFk;
        }
    }
    return null;
}
 
Example 9
Source File: JdbcModelReader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Removes system indices (generated by the database for primary and foreign keys)
 * from the table.
 * 
 * @param metaData The database meta data
 * @param table    The table
 */
protected void removeSystemIndices(DatabaseMetaDataWrapper metaData, Table table) throws SQLException
{
    removeInternalPrimaryKeyIndex(metaData, table);

    for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
    {
        removeInternalForeignKeyIndex(metaData, table, table.getForeignKey(fkIdx));
    }
}
 
Example 10
Source File: ForeignKeyChangeImplBase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ForeignKey findChangedForeignKey(Database model, boolean caseSensitive)
{
	Table table = findChangedTable(model, caseSensitive);

	if (table != null)
	{
        for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
        {
            ForeignKey curFk = table.getForeignKey(fkIdx);

            if (curFk.getReferenceCount() == _referenceColumnNames.size())
            {
                for (int refIdx = 0; refIdx < curFk.getReferenceCount(); refIdx++)
                {
                    Reference ref      = curFk.getReference(refIdx);
                    Pair      colNames = (Pair)_referenceColumnNames.get(refIdx);

                    if (caseSensitive)
                    {
                        if (ref.getLocalColumnName().equals((String)colNames.getFirst()) &&
                            ref.getForeignColumnName().equals((String)colNames.getSecond()))
                        {
                            return curFk;
                        }
                    }
                    else
                    {
                        if (ref.getLocalColumnName().equalsIgnoreCase((String)colNames.getFirst()) &&
                            ref.getForeignColumnName().equalsIgnoreCase((String)colNames.getSecond()))
                        {
                            return curFk;
                        }
                    }
                }
            }
        }
	}
    return null;
}
 
Example 11
Source File: ModelComparator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Searches in the given table for a corresponding foreign key. If the given key
 * has no name, then a foreign key to the same table with the same columns (but not
 * necessarily in the same order) is searched. If the given key has a name, then the
 * corresponding key also needs to have the same name, or no name at all, but not a
 * different one. 
 * 
 * @param table The table to search in
 * @param fk    The original foreign key
 * @return The corresponding foreign key if found
 */
protected ForeignKey findCorrespondingForeignKey(Table table, ForeignKey fk)
{
    for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
    {
        ForeignKey curFk = table.getForeignKey(fkIdx);

        if ((_caseSensitive  && fk.equals(curFk)) ||
            (!_caseSensitive && fk.equalsIgnoreCase(curFk)))
        {
            return curFk;
        }
    }
    return null;
}
 
Example 12
Source File: DataToDatabaseSink.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the values of the columns constituting the indicated foreign key with the values
 * of the given identity.
 * 
 * @param bean     The bean whose columns shall be updated
 * @param fkName   The name of the foreign key
 * @param identity The target identity
 */
private void updateFKColumns(DynaBean bean, String fkName, Identity identity)
{
    Table      sourceTable = ((SqlDynaClass)bean.getDynaClass()).getTable();
    Table      targetTable = identity.getTable();
    ForeignKey fk          = null;

    for (int idx = 0; idx < sourceTable.getForeignKeyCount(); idx++)
    {
        ForeignKey curFk = sourceTable.getForeignKey(idx);

        if (curFk.getForeignTableName().equalsIgnoreCase(targetTable.getQualifiedName()))
        {
            if (fkName.equals(getFKName(sourceTable, curFk)))
            {
                fk = curFk;
                break;
            }
        }
    }
    if (fk != null)
    {
        for (int idx = 0; idx < fk.getReferenceCount(); idx++)
        {
            Reference curRef       = fk.getReference(idx);
            Column    sourceColumn = curRef.getLocalColumn();
            Column    targetColumn = curRef.getForeignColumn();

            bean.set(sourceColumn.getName(), identity.getColumnValue(targetColumn.getName()));
        }
    }
}
 
Example 13
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the foreign key constraints inside a create table () clause.
 * 
 * @param database The database model
 * @param table    The table
 */
protected void writeEmbeddedForeignKeysStmt(Database database, Table table) throws IOException
{
    for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
    {
        ForeignKey foreignKey = table.getForeignKey(idx);

        if (foreignKey.getForeignTableName() == null)
        {
            _log.warn("Foreign key table is null for key " + foreignKey);
        }
        else
        {
            printStartOfEmbeddedStatement();
            if (getPlatformInfo().isEmbeddedForeignKeysNamed())
            {
                print("CONSTRAINT ");
                printIdentifier(getForeignKeyName(table, foreignKey));
                print(" ");
            }
            print("FOREIGN KEY (");
            writeLocalReferences(foreignKey);
            print(") REFERENCES ");
            printIdentifier(getTableName(database.findTable(foreignKey.getForeignTableName())));
            print(" (");
            writeForeignReferences(foreignKey);
            print(")");
            writeForeignKeyOnDeleteAction(table, foreignKey);
            writeForeignKeyOnUpdateAction(table, foreignKey);
        }
    }
}
 
Example 14
Source File: DatabaseIO.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
     * Writes the table object to the given XML writer.
     * 
     * @param table     The table object
     * @param xmlWriter The XML writer
     */
    private void writeTableElement(Table table, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException
    {
        xmlWriter.indentIfPrettyPrinting(1);
        writeElementStart(xmlWriter, QNAME_ELEMENT_TABLE);
// GemStone changes BEGIN
        // write fully qualified table name
        final String tableName = table.getQualifiedName();
        writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, tableName);
        /* (original code)
        writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME,        table.getName());
        */
// GemStone changes END
        writeAttribute(xmlWriter, QNAME_ATTRIBUTE_DESCRIPTION, table.getDescription());
        if ((table.getColumnCount() > 0) || (table.getForeignKeyCount() > 0) || (table.getIndexCount() > 0))
        {
            xmlWriter.printlnIfPrettyPrinting();
            for (int idx = 0; idx < table.getColumnCount(); idx++)
            {
                writeColumnElement(table.getColumn(idx), xmlWriter);
            }
            for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
            {
                writeForeignKeyElement(table.getForeignKey(idx), xmlWriter);
            }
            for (int idx = 0; idx < table.getIndexCount(); idx++)
            {
                writeIndexElement(table.getIndex(idx), xmlWriter);
            }
            xmlWriter.indentIfPrettyPrinting(1);
        }
        writeElementEnd(xmlWriter);
    }
 
Example 15
Source File: TestAgainstLiveDatabaseBase.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a copy of the given model adjusted for type changes because of the native type mappings
 * which when read back from the database will map to different types.
 * 
 * @param sourceModel The source model
 * @return The adjusted model
 */
protected Database adjustModel(Database sourceModel)
{
    Database model = new CloneHelper().clone(sourceModel);

    for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++)
    {
        Table table = model.getTable(tableIdx);

        for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++)
        {
            Column column     = table.getColumn(columnIdx);
            int    origType   = column.getTypeCode();
            int    targetType = getPlatformInfo().getTargetJdbcType(origType);

            // we adjust the column types if the native type would back-map to a
            // different jdbc type
            if (targetType != origType)
            {
                column.setTypeCode(targetType);
                // we should also adapt the default value
                if (column.getDefaultValue() != null)
                {
                    DefaultValueHelper helper = getPlatform().getSqlBuilder().getDefaultValueHelper();

                    column.setDefaultValue(helper.convert(column.getDefaultValue(), origType, targetType));
                }
            }
            // we also promote the default size if the column has no size
            // spec of its own
            if ((column.getSize() == null) && getPlatformInfo().hasSize(targetType))
            {
                Integer defaultSize = getPlatformInfo().getDefaultSize(targetType);

                if (defaultSize != null)
                {
                    column.setSize(defaultSize.toString());
                }
            }
            // finally the platform might return a synthetic default value if the column
            // is a primary key column
            if (getPlatformInfo().isSyntheticDefaultValueForRequiredReturned() &&
                (column.getDefaultValue() == null) && column.isRequired() && !column.isAutoIncrement())
            {
                switch (column.getTypeCode())
                {
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                        column.setDefaultValue("0");
                        break;
                    case Types.REAL:
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        column.setDefaultValue("0.0");
                        break;
                    case Types.BIT:
                        column.setDefaultValue("false");
                        break;
                    default:
                        column.setDefaultValue("");
                        break;
                }
            }
            if (column.isPrimaryKey() && getPlatformInfo().isPrimaryKeyColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
            if (column.isAutoIncrement() && getPlatformInfo().isIdentityColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
        }
        // we also add the default names to foreign keys that are initially unnamed
        for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
        {
            ForeignKey fk = table.getForeignKey(fkIdx);

            if (fk.getName() == null)
            {
                fk.setName(getPlatform().getSqlBuilder().getForeignKeyName(table, fk));
            }
        }
    }
    return model;
}
 
Example 16
Source File: DataToDatabaseSink.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
     * {@inheritDoc}
     */
    public void addBean(DynaBean bean) throws DataSinkException
    {
        Table    table        = _model.getDynaClassFor(bean).getTable();
        Identity origIdentity = buildIdentityFromPKs(table, bean);

// GemStone changes BEGIN
        if (_useBatchMode) {
            if (_lastTable != null) {
                if (table != _lastTable) {
                    purgeBatchQueue();
                }
            }
            else if (_platform.getPlatformInfo()
                    .isIdentityValueReadableInBatchUsingStatement()) {
                _origIdentityMap = new HashMap<DynaBean, Identity>();
            }
            _lastTable = table;
        }
// GemStone changes END
        if (_ensureFkOrder && (table.getForeignKeyCount() > 0))
        {
            WaitingObject waitingObj = new WaitingObject(bean, origIdentity);

            for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
            {
                ForeignKey fk         = table.getForeignKey(idx);
                Identity   fkIdentity = buildIdentityFromFK(table, fk, bean);

                if ((fkIdentity != null) && !fkIdentity.equals(origIdentity))
                {
                    Identity processedIdentity = (Identity)_identityMap.get(fkIdentity);

                    if (processedIdentity != null)
                    {
                        updateFKColumns(bean, fkIdentity.getForeignKeyName(), processedIdentity);
                    }
                    else
                    {
                        waitingObj.addPendingFK(fkIdentity);
                    }
                }
            }
            if (waitingObj.hasPendingFKs())
            {
                if (_log.isDebugEnabled())
                {
                    StringBuilder msg = new StringBuilder();

                    msg.append("Defering insertion of row ");
                    msg.append(buildIdentityFromPKs(table, bean).toString());
                    msg.append(" because it is waiting for:");
                    for (Iterator it = waitingObj.getPendingFKs(); it.hasNext();)
                    {
                        msg.append("\n  ");
                        msg.append(it.next().toString());
                    }
                    _log.debug(msg.toString());
                }
                _waitingObjects.add(waitingObj);
                return;
            }
        }

        insertBeanIntoDatabase(table, bean);

        if (_log.isDebugEnabled())
        {
            _log.debug("Inserted bean " + origIdentity);
        }

// GemStone changes BEGIN
        if (_origIdentityMap == null) {
            populateIdentityMap(table, bean, origIdentity);
        }
        else {
            _origIdentityMap.put(bean, origIdentity);
        }
    }
 
Example 17
Source File: TestAgainstLiveDatabaseBase.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Asserts that the two given database tables are equal.
 * 
 * @param expected      The expected table
 * @param actual        The actual table
 * @param caseSensitive Whether case matters when comparing
 */
protected void assertEquals(Table expected, Table actual, boolean caseSensitive)
{
    if (caseSensitive)
    {
        assertEquals("Table names do not match.",
                     getPlatform().getSqlBuilder().shortenName(expected.getName(), getSqlBuilder().getMaxTableNameLength()),
                     getPlatform().getSqlBuilder().shortenName(actual.getName(), getSqlBuilder().getMaxTableNameLength()));
    }
    else
    {
        assertEquals("Table names do not match (ignoring case).",
                     getPlatform().getSqlBuilder().shortenName(expected.getName().toUpperCase(), getSqlBuilder().getMaxTableNameLength()),
                     getPlatform().getSqlBuilder().shortenName(actual.getName().toUpperCase(), getSqlBuilder().getMaxTableNameLength()));
    }
    assertEquals("Not the same number of columns in table "+actual.getName()+".",
                 expected.getColumnCount(),
                 actual.getColumnCount());
    for (int columnIdx = 0; columnIdx < actual.getColumnCount(); columnIdx++)
    {
        assertEquals(expected.getColumn(columnIdx),
                     actual.getColumn(columnIdx),
                     caseSensitive);
    }
    assertEquals("Not the same number of foreign keys in table "+actual.getName()+".",
                 expected.getForeignKeyCount(),
                 actual.getForeignKeyCount());
    // order is not assumed with the way foreignkeys are returned.
    for (int expectedFkIdx = 0; expectedFkIdx < expected.getForeignKeyCount(); expectedFkIdx++)
    {
        ForeignKey expectedFk   = expected.getForeignKey(expectedFkIdx);
        String     expectedName = getPlatform().getSqlBuilder().shortenName(expectedFk.getName(), getSqlBuilder().getMaxForeignKeyNameLength());

        for (int actualFkIdx = 0; actualFkIdx < actual.getForeignKeyCount(); actualFkIdx++)
        {
            ForeignKey actualFk   = actual.getForeignKey(actualFkIdx);
            String     actualName = getPlatform().getSqlBuilder().shortenName(actualFk.getName(), getSqlBuilder().getMaxForeignKeyNameLength());

            if (StringUtilsExt.equals(expectedName, actualName, caseSensitive))
            {
                assertEquals(expectedFk,
                             actualFk,
                             caseSensitive);
            }
        }
    }
    assertEquals("Not the same number of indices in table "+actual.getName()+".",
                 expected.getIndexCount(),
                 actual.getIndexCount());
    for (int indexIdx = 0; indexIdx < actual.getIndexCount(); indexIdx++)
    {
        assertEquals(expected.getIndex(indexIdx),
                     actual.getIndex(indexIdx),
                     caseSensitive);
    }
}
 
Example 18
Source File: TestAgainstLiveDatabaseBase.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a copy of the given model adjusted for type changes because of the native type mappings
 * which when read back from the database will map to different types.
 * 
 * @param sourceModel The source model
 * @return The adjusted model
 */
protected Database adjustModel(Database sourceModel)
{
    Database model = new CloneHelper().clone(sourceModel);

    for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++)
    {
        Table table = model.getTable(tableIdx);

        for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++)
        {
            Column column     = table.getColumn(columnIdx);
            int    origType   = column.getTypeCode();
            int    targetType = getPlatformInfo().getTargetJdbcType(origType);

            // we adjust the column types if the native type would back-map to a
            // different jdbc type
            if (targetType != origType)
            {
                column.setTypeCode(targetType);
                // we should also adapt the default value
                if (column.getDefaultValue() != null)
                {
                    DefaultValueHelper helper = getPlatform().getSqlBuilder().getDefaultValueHelper();

                    column.setDefaultValue(helper.convert(column.getDefaultValue(), origType, targetType));
                }
            }
            // we also promote the default size if the column has no size
            // spec of its own
            if ((column.getSize() == null) && getPlatformInfo().hasSize(targetType))
            {
                Integer defaultSize = getPlatformInfo().getDefaultSize(targetType);

                if (defaultSize != null)
                {
                    column.setSize(defaultSize.toString());
                }
            }
            // finally the platform might return a synthetic default value if the column
            // is a primary key column
            if (getPlatformInfo().isSyntheticDefaultValueForRequiredReturned() &&
                (column.getDefaultValue() == null) && column.isRequired() && !column.isAutoIncrement())
            {
                switch (column.getTypeCode())
                {
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                        column.setDefaultValue("0");
                        break;
                    case Types.REAL:
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        column.setDefaultValue("0.0");
                        break;
                    case Types.BIT:
                        column.setDefaultValue("false");
                        break;
                    default:
                        column.setDefaultValue("");
                        break;
                }
            }
            if (column.isPrimaryKey() && getPlatformInfo().isPrimaryKeyColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
            if (column.isAutoIncrement() && getPlatformInfo().isIdentityColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
        }
        // we also add the default names to foreign keys that are initially unnamed
        for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
        {
            ForeignKey fk = table.getForeignKey(fkIdx);

            if (fk.getName() == null)
            {
                fk.setName(getPlatform().getSqlBuilder().getForeignKeyName(table, fk));
            }
        }
    }
    return model;
}
 
Example 19
Source File: DataToDatabaseSink.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
     * {@inheritDoc}
     */
    public void addBean(DynaBean bean) throws DataSinkException
    {
        Table    table        = _model.getDynaClassFor(bean).getTable();
        Identity origIdentity = buildIdentityFromPKs(table, bean);

// GemStone changes BEGIN
        if (_useBatchMode) {
            if (_lastTable != null) {
                if (table != _lastTable) {
                    purgeBatchQueue();
                }
            }
            else if (_platform.getPlatformInfo()
                    .isIdentityValueReadableInBatchUsingStatement()) {
                _origIdentityMap = new HashMap<DynaBean, Identity>();
            }
            _lastTable = table;
        }
// GemStone changes END
        if (_ensureFkOrder && (table.getForeignKeyCount() > 0))
        {
            WaitingObject waitingObj = new WaitingObject(bean, origIdentity);

            for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
            {
                ForeignKey fk         = table.getForeignKey(idx);
                Identity   fkIdentity = buildIdentityFromFK(table, fk, bean);

                if ((fkIdentity != null) && !fkIdentity.equals(origIdentity))
                {
                    Identity processedIdentity = (Identity)_identityMap.get(fkIdentity);

                    if (processedIdentity != null)
                    {
                        updateFKColumns(bean, fkIdentity.getForeignKeyName(), processedIdentity);
                    }
                    else
                    {
                        waitingObj.addPendingFK(fkIdentity);
                    }
                }
            }
            if (waitingObj.hasPendingFKs())
            {
                if (_log.isDebugEnabled())
                {
                    StringBuilder msg = new StringBuilder();

                    msg.append("Defering insertion of row ");
                    msg.append(buildIdentityFromPKs(table, bean).toString());
                    msg.append(" because it is waiting for:");
                    for (Iterator it = waitingObj.getPendingFKs(); it.hasNext();)
                    {
                        msg.append("\n  ");
                        msg.append(it.next().toString());
                    }
                    _log.debug(msg.toString());
                }
                _waitingObjects.add(waitingObj);
                return;
            }
        }

        insertBeanIntoDatabase(table, bean);

        if (_log.isDebugEnabled())
        {
            _log.debug("Inserted bean " + origIdentity);
        }

// GemStone changes BEGIN
        if (_origIdentityMap == null) {
            populateIdentityMap(table, bean, origIdentity);
        }
        else {
            _origIdentityMap.put(bean, origIdentity);
        }
    }
 
Example 20
Source File: MSSqlModelComparator.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected List checkForRemovedForeignKeys(Database sourceModel,
                                          Database intermediateModel,
                                          Database targetModel)
{
    List changes           = super.checkForRemovedForeignKeys(sourceModel, intermediateModel, targetModel);
    List additionalChanges = new ArrayList();

    // removing all foreign keys that are maintained and that use a changed column
    for (int tableIdx = 0; tableIdx < targetModel.getTableCount(); tableIdx++)
    {
        Table targetTable = targetModel.getTable(tableIdx);
        Table sourceTable = sourceModel.findTable(targetTable.getName(), isCaseSensitive());

        if (sourceTable != null)
        {
            List columns = getRelevantChangedColumns(sourceTable, targetTable);

            if (!columns.isEmpty())
            {
                for (int fkIdx = 0; fkIdx < targetTable.getForeignKeyCount(); fkIdx++)
                {
                    ForeignKey targetFk = targetTable.getForeignKey(fkIdx);
                    ForeignKey sourceFk = findCorrespondingForeignKey(sourceTable, targetFk);

                    if (sourceFk != null)
                    {
                        for (Iterator columnIt = columns.iterator(); columnIt.hasNext();)
                        {
                            Column targetColumn = (Column)columnIt.next();

                            if (targetFk.hasLocalColumn(targetColumn) || targetFk.hasForeignColumn(targetColumn))
                            {
                                additionalChanges.add(new RemoveForeignKeyChange(sourceTable.getName(), targetFk));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    for (Iterator changeIt = additionalChanges.iterator(); changeIt.hasNext();)
    {
        ((RemoveForeignKeyChange)changeIt.next()).apply(intermediateModel, isCaseSensitive());
    }
    changes.addAll(additionalChanges);
    return changes;
}