org.apache.ddlutils.model.Table Java Examples

The following examples show how to use org.apache.ddlutils.model.Table. 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: Oracle8Builder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void createTable(Database database, Table table, Map parameters) throws IOException
{
    // lets create any sequences
    Column[] columns = table.getAutoIncrementColumns();

    for (int idx = 0; idx < columns.length; idx++)
    {
        createAutoIncrementSequence(table, columns[idx]);
    }

    super.createTable(database, table, parameters);

    for (int idx = 0; idx < columns.length; idx++)
    {
        createAutoIncrementTrigger(table, columns[idx]);
    }
}
 
Example #2
Source File: SapDbBuilder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the SQL to set the required status of the given column.
 * 
 * @param table      The table
 * @param column     The column to change
 * @param isRequired Whether the column shall be required
 */
public void changeColumnRequiredStatus(Table table, Column column, boolean isRequired) throws IOException
{
    print("ALTER TABLE ");
    printlnIdentifier(getTableName(table));
    printIndent();
    print("COLUMN ");
    printIdentifier(getColumnName(column));
    if (isRequired)
    {
        print(" NOT NULL");
    }
    else
    {
        print(" DEFAULT NULL");
    }
    printEndOfStatement();
}
 
Example #3
Source File: Db2Platform.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the change of the primary key of a table.
 * 
 * @param currentModel The current database schema
 * @param params       The parameters used in the creation of new tables. Note that for existing
 *                     tables, the parameters won't be applied
 * @param change       The change object
 */
public void processChange(Database           currentModel,
                          CreationParameters params,
                          PrimaryKeyChange   change) throws IOException
{
    Table    changedTable     = findChangedTable(currentModel, change);
    String[] newPKColumnNames = change.getNewPrimaryKeyColumns();
    Column[] newPKColumns     = new Column[newPKColumnNames.length];

    for (int colIdx = 0; colIdx < newPKColumnNames.length; colIdx++)
    {
        newPKColumns[colIdx] = changedTable.findColumn(newPKColumnNames[colIdx], isDelimitedIdentifierModeOn());
    }
    ((Db2Builder)getSqlBuilder()).dropPrimaryKey(changedTable);
    getSqlBuilder().createPrimaryKey(changedTable, newPKColumns);
    change.apply(currentModel, isDelimitedIdentifierModeOn());
}
 
Example #4
Source File: Db2ModelReader.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
protected Table readTable(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
       String tableName = (String)values.get("TABLE_NAME");

       for (int idx = 0; idx < KNOWN_SYSTEM_TABLES.length; idx++)
       {
       	if (KNOWN_SYSTEM_TABLES[idx].equals(tableName))
       	{
       		return null;
       	}
       }

       Table table = super.readTable(metaData, values);

       if (table != null)
       {
           // Db2 does not return the auto-increment status via the database metadata
           determineAutoIncrementColumns(table);
       }
       return table;
}
 
Example #5
Source File: ModelBasedResultSetIterator.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new iterator.
 * 
 * @param platform           The platform
 * @param model              The database model
 * @param resultSet          The result set
 * @param queryHints         The tables that were queried in the query that produced the given result set
 *                           (optional)
 * @param cleanUpAfterFinish Whether to close the statement and connection after finishing
 *                           the iteration, upon on exception, or when this iterator is garbage collected
 */
public ModelBasedResultSetIterator(PlatformImplBase platform, Database model, ResultSet resultSet, Table[] queryHints, boolean cleanUpAfterFinish) throws DatabaseOperationException
{
    if (resultSet != null)
    {
        _platform           = platform;
        _resultSet          = resultSet;
        _cleanUpAfterFinish = cleanUpAfterFinish;
        _caseSensitive      = _platform.isDelimitedIdentifierModeOn();
        _preparedQueryHints = prepareQueryHints(queryHints);

        try
        {
            initFromMetaData(model);
        }
        catch (SQLException ex)
        {
            cleanUp();
            throw new DatabaseOperationException("Could not read the metadata of the result set", ex);
        }
    }
    else
    {
        _isAtEnd = true;
    }
}
 
Example #6
Source File: FirebirdBuilder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String getSelectLastIdentityValues(Table table)
{
    Column[] columns = table.getAutoIncrementColumns();

    if (columns.length == 0)
    {
        return null;
    }
    else
    {
        StringBuilder result = new StringBuilder();

        result.append("SELECT ");
        for (int idx = 0; idx < columns.length; idx++)
        {
            result.append("GEN_ID(");
            result.append(getDelimitedIdentifier(getGeneratorName(table, columns[idx])));
            result.append(", 0)");
        }
        result.append(" FROM RDB$DATABASE");
        return result.toString();
    }
}
 
Example #7
Source File: TestPlatformImplBase.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Test the toColumnValues method.
 */
public void testToColumnValues()
{
    final String schema =
        "<?xml version='1.0' encoding='ISO-8859-1'?>\n"+
        "<database xmlns='" + DatabaseIO.DDLUTILS_NAMESPACE + "' name='ddlutils'>\n"+
        "  <table name='TestTable'>\n"+
        "    <column name='id' autoIncrement='true' type='INTEGER' primaryKey='true'/>\n"+
        "    <column name='name' type='VARCHAR' size='15'/>\n"+
        "  </table>\n"+
        "</database>";

    Database         database = parseDatabaseFromString(schema);
    PlatformImplBase platform = new TestPlatform();
    Table            table    = database.getTable(0);
    SqlDynaClass     clz      = SqlDynaClass.newInstance(table);
    DynaBean         db       = new SqlDynaBean(SqlDynaClass.newInstance(table));

    db.set("name", "name");

    Map map = platform.toColumnValues(clz.getSqlDynaProperties(), db);

    assertEquals("name",
                 map.get("name"));
    assertTrue(map.containsKey("id"));
}
 
Example #8
Source File: SybasePlatform.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the change of a column definition..
 * 
 * @param currentModel The current database schema
 * @param params       The parameters used in the creation of new tables. Note that for existing
 *                     tables, the parameters won't be applied
 * @param change       The change object
 */
public void processChange(Database               currentModel,
                          CreationParameters     params,
                          ColumnDefinitionChange change) throws IOException
{
    Table         changedTable  = findChangedTable(currentModel, change);
    Column        changedColumn = changedTable.findColumn(change.getChangedColumn(), isDelimitedIdentifierModeOn());
    Column        newColumn     = change.getNewColumn();
    SybaseBuilder sqlBuilder    = (SybaseBuilder)getSqlBuilder();

    // if we only change the default value, then we need to use different SQL
    if (!ColumnDefinitionChange.isTypeChanged(getPlatformInfo(), changedColumn, newColumn) &&
        !ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), changedColumn, newColumn) &&
        !ColumnDefinitionChange.isRequiredStatusChanged(changedColumn, newColumn) &&
        !ColumnDefinitionChange.isAutoIncrementChanged(changedColumn, newColumn))
    {
        sqlBuilder.changeColumnDefaultValue(changedTable, changedColumn, newColumn.getDefaultValue());
    }
    else
    {
        sqlBuilder.changeColumn(changedTable, changedColumn, newColumn);
    }
    change.apply(currentModel, isDelimitedIdentifierModeOn());
}
 
Example #9
Source File: AddColumnChange.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void apply(Database model, boolean caseSensitive)
{
    Table  table     = findChangedTable(model, caseSensitive);
    Column newColumn = new CloneHelper().clone(_newColumn, true);

    if (_previousColumnName != null)
    {
        Column prevColumn = table.findColumn(_previousColumnName, caseSensitive);
        int    idx        = table.getColumnIndex(prevColumn) + 1;

        table.addColumn(idx, newColumn);
    }
    else if (_nextColumnName != null)
    {
        table.addColumn(0, newColumn);
    }
    else
    {
        table.addColumn(newColumn);
    }
}
 
Example #10
Source File: SybasePlatform.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void beforeInsert(Connection connection, Table table) throws SQLException
{
    if (useIdentityOverrideFor(table))
    {
        SybaseBuilder builder          = (SybaseBuilder)getSqlBuilder();
        String        quotationOn      = builder.getQuotationOnStatement();
        String        identityInsertOn = builder.getEnableIdentityOverrideSql(table);
        Statement     stmt             = connection.createStatement();

        if (quotationOn.length() > 0)
        {
            stmt.execute(quotationOn);
        }
        stmt.execute(identityInsertOn);
        stmt.close();
    }
}
 
Example #11
Source File: MySqlBuilder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dropForeignKey(Table table, ForeignKey foreignKey) throws IOException
{
    writeTableAlterStmt(table);
    print("DROP FOREIGN KEY ");
    printIdentifier(getForeignKeyName(table, foreignKey));
    printEndOfStatement();

    // InnoDB won't drop the auto-index for the foreign key automatically, so we have to do it
    if (foreignKey.isAutoIndexPresent())
    {
        writeTableAlterStmt(table);
        print("DROP INDEX ");
        printIdentifier(getForeignKeyName(table, foreignKey));
        printEndOfStatement();
    }
}
 
Example #12
Source File: InterbaseBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dropTable(Table table) throws IOException
{
    // dropping generators for auto-increment
    Column[] columns = table.getAutoIncrementColumns();

    for (int idx = 0; idx < columns.length; idx++)
    {
        writeAutoIncrementDropStmts(table, columns[idx]);
    }
    super.dropTable(table);
}
 
Example #13
Source File: MySqlModelComparator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected List compareTables(Database sourceModel,
                             Table    sourceTable,
                             Database intermediateModel,
                             Table    intermediateTable,
                             Database targetModel, Table targetTable)
{
    // we need to drop and recreate foreign keys that reference columns whose data type will be changed (but not size)
    List changes     = super.compareTables(sourceModel, sourceTable, intermediateModel, intermediateTable, targetModel, targetTable);
    Set  columnNames = new HashSet();

    for (Iterator it = changes.iterator(); it.hasNext();)
    {
        Object change = it.next();

        if (change instanceof ColumnDefinitionChange)
        {
            ColumnDefinitionChange colDefChange = (ColumnDefinitionChange)change;
            Column                 sourceColumn = sourceTable.findColumn(colDefChange.getChangedColumn(), isCaseSensitive());

            if (ColumnDefinitionChange.isTypeChanged(getPlatformInfo(), sourceColumn, colDefChange.getNewColumn()))
            {
                columnNames.add(sourceColumn.getName());
            }
        }
    }
    if (!columnNames.isEmpty())
    {
        // we don't need to check for foreign columns as the data type of both local and foreign column need
        // to be changed, otherwise MySql will complain
        changes.addAll(getForeignKeyRecreationChanges(intermediateTable, targetTable, columnNames));
    }
    return changes;
}
 
Example #14
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 #15
Source File: Oracle8Builder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the SQL to drop the primary key of the given table.
 * 
 * @param table The table
 */
public void dropPrimaryKey(Table table) throws IOException
{
    print("ALTER TABLE ");
    printlnIdentifier(getTableName(table));
    printIndent();
    print("DROP PRIMARY KEY");
    printEndOfStatement();
}
 
Example #16
Source File: DataDtdWriter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the DTD for data xml files for the given database model, to the specified writer.
 * 
 * @param model  The database model
 * @param output The writer to write the DTD to
 */
public void writeDtd(Database model, Writer output) throws IOException
{
    PrintWriter writer = new PrintWriter(output);

    writer.println("<!-- DTD for XML data files for database "+model.getName()+" -->\n");
    writer.println("<!ELEMENT data (");
    for (int idx = 0; idx < model.getTableCount(); idx++)
    {
        Table table = model.getTable(idx);

        writer.print("    "+table.getQualifiedName());
        if (idx < model.getTableCount() - 1)
        {
            writer.println(" |");
        }
        else
        {
            writer.println();
        }
    }
    writer.println(")*>");
    for (int idx = 0; idx < model.getTableCount(); idx++)
    {
        writeTableElement(model.getTable(idx), writer);
    }
}
 
Example #17
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 #18
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 #19
Source File: Db2Builder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the SQL for dropping the primary key of the given table.
 * 
 * @param table The table
 */
public void dropPrimaryKey(Table table) throws IOException
{
    print("ALTER TABLE ");
    printlnIdentifier(getTableName(table));
    printIndent();
    print("DROP PRIMARY KEY");
    printEndOfStatement();
}
 
Example #20
Source File: ModelComparator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates change objects for columns that are present in the given source table but are no longer in the target
 * table, and applies them to the given intermediate model.
 * 
 * @param sourceModel       The source model
 * @param sourceTable       The source table
 * @param intermediateModel The intermediate model to apply the changes to
 * @param intermediateTable The table from the intermediate model corresponding to the source table
 * @param targetModel       The target model
 * @param targetTable       The target table
 * @return The changes
 */
protected List checkForRemovedColumns(Database sourceModel,
                                      Table    sourceTable,
                                      Database intermediateModel,
                                      Table    intermediateTable,
                                      Database targetModel,
                                      Table    targetTable)
{
    // if the platform does not support dropping pk columns, then the pk handling above will
    // generate appropriate pk changes

    List     changes = new ArrayList();
    Column[] columns = intermediateTable.getColumns();

    for (int columnIdx = 0; columnIdx < columns.length; columnIdx++)
    {
        Column sourceColumn = columns[columnIdx];
        Column targetColumn = targetTable.findColumn(sourceColumn.getName(), _caseSensitive);

        if (targetColumn == null)
        {
            if (_log.isInfoEnabled())
            {
                _log.info("Column " + sourceColumn.getName() + " needs to be removed from table " + intermediateTable.getQualifiedName());
            }

            RemoveColumnChange change = new RemoveColumnChange(intermediateTable.getQualifiedName(), sourceColumn.getName());

            changes.add(change);
            change.apply(intermediateModel, _caseSensitive);
        }
    }
    return changes;
}
 
Example #21
Source File: TestDataReaderAndWriter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the reader & writer behavior when a column name is not a valid tag,
 * and the value is invalid, and both are short.
 */
public void testColumnNameAndValueLongAndInvalid() throws Exception
{
    Database model       = new Database("test");
    Table    table       = new Table();
    Column   idColumn    = new Column();
    Column   valueColumn = new Column();
    String   columnName  = StringUtils.repeat("the\u0000name", 100);

    idColumn.setName("id");
    idColumn.setType("INTEGER");
    idColumn.setPrimaryKey(true);
    idColumn.setRequired(true);
    valueColumn.setName(columnName);
    valueColumn.setType("VARCHAR");
    valueColumn.setSize("50");
    valueColumn.setRequired(true);
    table.setName("test");
    table.addColumn(idColumn);
    table.addColumn(valueColumn);
    model.addTable(table);

    SqlDynaBean bean        = (SqlDynaBean)model.createDynaBeanFor(model.getTable(0));
    String      testedValue = StringUtils.repeat("the\u0000value", 40);

    bean.set("id", new Integer(1));
    bean.set(columnName, testedValue);

    roundtripTest(model, bean, "UTF-8",
                  "<?xml version='1.0' encoding='UTF-8'?>\n" +
                  "<data>\n" +
                  "  <test id=\"1\">\n" +
                  "    <column>\n" +
                  "      <column-name " + DatabaseIO.BASE64_ATTR_NAME + "=\"true\">" + new String(Base64.encodeBase64(columnName.getBytes("UTF-8")), "UTF-8") + "</column-name>\n" +
                  "      <column-value " + DatabaseIO.BASE64_ATTR_NAME + "=\"true\">" + new String(Base64.encodeBase64(testedValue.getBytes("UTF-8")), "UTF-8") + "</column-value>\n" +
                  "    </column>\n" +
                  "  </test>\n" +
                  "</data>\n");
}
 
Example #22
Source File: Db2Platform.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected TableDefinitionChangesPredicate getTableDefinitionChangesPredicate()
{
    return new DefaultTableDefinitionChangesPredicate()
    {
        protected boolean isSupported(Table intermediateTable, TableChange change)
        {
            if ((change instanceof RemoveColumnChange) ||
                (change instanceof PrimaryKeyChange) ||
                (change instanceof RemovePrimaryKeyChange))
            {
                return true;
            }
            else if (change instanceof AddColumnChange)
            {
                AddColumnChange addColumnChange = (AddColumnChange)change;

                // DB2 cannot add IDENTITY columns, and required columns need a default value
                return (addColumnChange.getNextColumn() == null) &&
                       !addColumnChange.getNewColumn().isAutoIncrement() &&
                       (!addColumnChange.getNewColumn().isRequired() || !StringUtilsExt.isEmpty(addColumnChange.getNewColumn().getDefaultValue()));
            }
            else
            {
                return false;
            }
        }
    };
}
 
Example #23
Source File: MSSqlModelComparator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected List checkForPrimaryKeyChanges(Database sourceModel,
                                         Table    sourceTable,
                                         Database intermediateModel,
                                         Table    intermediateTable,
                                         Database targetModel,
                                         Table    targetTable)
{
    List changes = super.checkForPrimaryKeyChanges(sourceModel, sourceTable, intermediateModel, intermediateTable, targetModel, targetTable);

    // now we add pk changes if one of the pk columns was changed
    // we only need to do this if there is no other pk change (which can only be a remove or add change or both)
    if (changes.isEmpty())
    {
        List columns = getRelevantChangedColumns(sourceTable, targetTable);

        for (Iterator it = columns.iterator(); it.hasNext();)
        {
            Column targetColumn = (Column)it.next();

            if (targetColumn.isPrimaryKey())
            {
                changes.add(new RemovePrimaryKeyChange(sourceTable.getName()));
                changes.add(new AddPrimaryKeyChange(sourceTable.getName(), sourceTable.getPrimaryKeyColumnNames()));
                break;
            }
        }
    }
    return changes;
}
 
Example #24
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 #25
Source File: AddPrimaryKeyChange.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void apply(Database model, boolean caseSensitive)
{
    Table table = findChangedTable(model, caseSensitive);

    for (int idx = 0; idx < _primaryKeyColumns.length; idx++)
    {
        Column column = table.findColumn(_primaryKeyColumns[idx], caseSensitive);

        column.setPrimaryKey(true);
    }
}
 
Example #26
Source File: FirebirdBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the statements to drop the auto-increment status for the given column.
 * 
 * @param table  The table
 * @param column The column to remove the auto-increment status for
 */
private void writeAutoIncrementDropStmts(Table table, Column column) throws IOException
{
    print("DROP TRIGGER ");
    printIdentifier(getConstraintName("trg", table, column.getName(), null));
    printEndOfStatement();

    print("DROP GENERATOR ");
    printIdentifier(getGeneratorName(table, column));
    printEndOfStatement();
}
 
Example #27
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the SQL for deleting an object from the specified table. Depending on
 * the value of <code>genPlaceholders</code>, the generated SQL will contain
 * prepared statement place holders or concrete values. Only those primary key
 * columns wil be used that are present in the given map. If the map is null or
 * completely empty, then the SQL will not have a WHERE clause. The SQL will contain
 * the columns in the order defined in the table.
 * 
 * @param table           The table
 * @param pkValues        The primary key columns to use, and optionally their values
 * @param genPlaceholders Whether to generate value placeholders for a
 *                        prepared statement
 * @return The delete sql
 */
public String getDeleteSql(Table table, Map pkValues, boolean genPlaceholders)
{
    StringBuilder buffer = new StringBuilder("DELETE FROM ");
    boolean      addSep  = false;

    buffer.append(getDelimitedIdentifier(getTableName(table)));
    if ((pkValues != null) && !pkValues.isEmpty())
    {
        buffer.append(" WHERE ");

        Column[] pkCols = table.getPrimaryKeyColumns();

        for (int pkColIdx = 0; pkColIdx < pkCols.length; pkColIdx++)
        {
            Column column = pkCols[pkColIdx];

            if (pkValues.containsKey(column.getName())) {
                if (addSep)
                {
                    buffer.append(" AND ");
                }
                buffer.append(getDelimitedIdentifier(column.getName()));
                buffer.append(" = ");
                if (genPlaceholders)
                {
                    buffer.append("?");
                }
                else
                {
                    buffer.append(getValueAsString(column, pkValues.get(column.getName())));
                }
                addSep = true;
            }
        }
    }
    return buffer.toString();
}
 
Example #28
Source File: SybaseBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the SQL to drop the primary key of the given table.
 * 
 * @param table The table
 */
public void dropPrimaryKey(Table table) throws IOException
{
    // this would be easier when named primary keys are supported
    // because then we can use ALTER TABLE DROP
    String tableName         = getTableName(table);
    String tableNameVar      = "tn" + createUniqueIdentifier();
    String constraintNameVar = "cn" + createUniqueIdentifier();

    println("BEGIN");
    println("  DECLARE @" + tableNameVar + " nvarchar(60), @" + constraintNameVar + " nvarchar(60)");
    println("  WHILE EXISTS(SELECT sysindexes.name");
    println("                 FROM sysindexes, sysobjects");
    print("                 WHERE sysobjects.name = ");
    printAlwaysSingleQuotedIdentifier(tableName);
    println(" AND sysobjects.id = sysindexes.id AND (sysindexes.status & 2048) > 0)");
    println("  BEGIN");
    println("    SELECT @" + tableNameVar + " = sysobjects.name, @" + constraintNameVar + " = sysindexes.name");
    println("      FROM sysindexes, sysobjects");
    print("      WHERE sysobjects.name = ");
    printAlwaysSingleQuotedIdentifier(tableName);
    print(" AND sysobjects.id = sysindexes.id AND (sysindexes.status & 2048) > 0");
    println("    EXEC ('ALTER TABLE '+@" + tableNameVar + "+' DROP CONSTRAINT '+@" + constraintNameVar + ")");
    println("  END");
    print("END");
    printEndOfStatement();
}
 
Example #29
Source File: PlatformImplBase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Iterator query(Database model, String sql, Table[] queryHints) throws DatabaseOperationException
{
    Connection connection = borrowConnection();
    Statement  statement  = null;
    ResultSet  resultSet  = null;
    Iterator   answer     = null;

    try
    {
        statement = connection.createStatement();
        resultSet = statement.executeQuery(sql);
        answer    = createResultSetIterator(model, resultSet, queryHints);
        return answer;
    }
    catch (SQLException ex)
    {
        throw new DatabaseOperationException("Error while performing a query", ex);
    }
    finally
    {
        // if any exceptions are thrown, close things down
        // otherwise we're leaving it open for the iterator
        if (answer == null)
        {
            closeStatement(statement);
            returnConnection(connection);
        }
    }
}
 
Example #30
Source File: InterbaseBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dropTable(Table table) throws IOException
{
    // dropping generators for auto-increment
    Column[] columns = table.getAutoIncrementColumns();

    for (int idx = 0; idx < columns.length; idx++)
    {
        writeAutoIncrementDropStmts(table, columns[idx]);
    }
    super.dropTable(table);
}