Java Code Examples for org.apache.ddlutils.model.Table

The following examples show how to use org.apache.ddlutils.model.Table. These examples are extracted from open source projects. 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 Project: gemfirexd-oss   Source File: Db2Platform.java    License: 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 2
Source Project: gemfirexd-oss   Source File: ModelBasedResultSetIterator.java    License: 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 3
Source Project: gemfirexd-oss   Source File: FirebirdBuilder.java    License: 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 4
Source Project: gemfirexd-oss   Source File: SybasePlatform.java    License: 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 5
Source Project: gemfirexd-oss   Source File: SybasePlatform.java    License: 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 6
Source Project: gemfirexd-oss   Source File: AddColumnChange.java    License: 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 7
Source Project: gemfirexd-oss   Source File: TestPlatformImplBase.java    License: 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 Project: gemfirexd-oss   Source File: SapDbBuilder.java    License: 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 9
Source Project: gemfirexd-oss   Source File: MySqlBuilder.java    License: 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 10
Source Project: gemfirexd-oss   Source File: Oracle8Builder.java    License: 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 11
Source Project: gemfirexd-oss   Source File: Db2ModelReader.java    License: 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 12
Source Project: gemfirexd-oss   Source File: ModelComparator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates change objects for indexes 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 checkForRemovedIndexes(Database sourceModel,
                                      Table    sourceTable,
                                      Database intermediateModel,
                                      Table    intermediateTable,
                                      Database targetModel,
                                      Table    targetTable)
{
    List    changes = new ArrayList();
    Index[] indexes = intermediateTable.getIndices();

    for (int indexIdx = 0; indexIdx < indexes.length; indexIdx++)
    {
        Index sourceIndex = indexes[indexIdx];
        Index targetIndex = findCorrespondingIndex(targetTable, sourceIndex);

        if (targetIndex == null)
        {
            if (_log.isInfoEnabled())
            {
                _log.info("Index " + sourceIndex.getName() + " needs to be removed from table " + intermediateTable.getQualifiedName());
            }

            RemoveIndexChange change = new RemoveIndexChange(intermediateTable.getQualifiedName(), sourceIndex);

            changes.add(change);
            change.apply(intermediateModel, _caseSensitive);
        }
    }
    return changes;
}
 
Example 13
Source Project: gemfirexd-oss   Source File: SybaseBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void copyData(Table sourceTable, Table targetTable) throws IOException
{
    // We need to turn on identity override except when the identity column was added to the column
    Column[] targetAutoIncrCols   = targetTable.getAutoIncrementColumns();
    boolean  needIdentityOverride = false;

    if (targetAutoIncrCols.length > 0)
    {
        needIdentityOverride = true;
        // Sybase only allows for one identity column per table
        if (sourceTable.findColumn(targetAutoIncrCols[0].getName(), getPlatform().isDelimitedIdentifierModeOn()) == null)
        {
            needIdentityOverride = false;
        }
    }
    if (needIdentityOverride)
    {
        print(getEnableIdentityOverrideSql(targetTable));
        printEndOfStatement();
    }
    super.copyData(sourceTable, targetTable);
    if (needIdentityOverride)
    {
        print(getDisableIdentityOverrideSql(targetTable));
        printEndOfStatement();
    }
}
 
Example 14
Source Project: gemfirexd-oss   Source File: SybaseBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeColumn(Table table, Column column) throws IOException
{
       printIdentifier(getColumnName(column));
       print(" ");
       print(getSqlType(column));
       writeColumnDefaultValueStmt(table, column);
       // Sybase does not like NULL/NOT NULL and IDENTITY together
       if (column.isAutoIncrement())
       {
           print(" ");
           writeColumnAutoIncrementStmt(table, column);
       }
       else
       {
           print(" ");
           if (column.isRequired())
           {
               writeColumnNotNullableStmt();
           }
           else
           {
               // we'll write a NULL for all columns that are not required 
               writeColumnNullableStmt();
           }
       }
}
 
Example 15
Source Project: gemfirexd-oss   Source File: PostgreSqlBuilder.java    License: Apache License 2.0 5 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++)
        {
            if (idx > 0)
            {
                result.append(", ");
            }
            result.append("currval('");
            result.append(getDelimitedIdentifier(getConstraintName(null, table, columns[idx].getName(), "seq")));
            result.append("') AS ");
            result.append(getDelimitedIdentifier(columns[idx].getName()));
        }
        return result.toString();
    }
}
 
Example 16
Source Project: gemfirexd-oss   Source File: TestDataReaderAndWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests the reader & writer behavior when a column value contains an invalid character.
 */
public void testColumnValueContainsInvalidCharacters() throws Exception
{
    Database model       = new Database("test");
    Table    table       = new Table();
    Column   idColumn    = new Column();
    Column   valueColumn = new Column();
    String   columnName  = "the\u0000value";

    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 = "Some Text";

    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>" + testedValue + "</column-value>\n" +
                  "    </column>\n" +
                  "  </test>\n" +
                  "</data>\n");
}
 
Example 17
Source Project: gemfirexd-oss   Source File: MySqlBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dropTable(Table table) throws IOException
{ 
    print("DROP TABLE IF EXISTS ");
    printIdentifier(getTableName(table));
    printEndOfStatement();
}
 
Example 18
Source Project: gemfirexd-oss   Source File: MSSqlPlatform.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void beforeInsert(Connection connection, Table table) throws SQLException
{
    if (useIdentityOverrideFor(table))
    {
        MSSqlBuilder builder = (MSSqlBuilder)getSqlBuilder();

        connection.createStatement().execute(builder.getEnableIdentityOverrideSql(table));
    }
}
 
Example 19
Source Project: gemfirexd-oss   Source File: FirebirdBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void addColumn(Database model, Table table, Column newColumn) throws IOException
{
    print("ALTER TABLE ");
    printlnIdentifier(getTableName(table));
    printIndent();
    print("ADD ");
    writeColumn(table, newColumn);
    printEndOfStatement();
    if (newColumn.isAutoIncrement())
    {
        writeAutoIncrementCreateStmts(model, table, newColumn);
    }
}
 
Example 20
Source Project: gemfirexd-oss   Source File: MSSqlModelComparator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected List checkForAddedForeignKeys(Database sourceModel,
                                        Database intermediateModel,
                                        Database targetModel)
{
    List changes           = super.checkForAddedForeignKeys(sourceModel, intermediateModel, targetModel);
    List additionalChanges = new ArrayList();

    // re-adding 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());
        Table intermediateTable = intermediateModel.findTable(targetTable.getName(), isCaseSensitive());

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

                if ((sourceFk != null) && (intermediateFk == null))
                {
                    additionalChanges.add(new AddForeignKeyChange(intermediateTable.getName(), targetFk));
                }
            }
        }
    }
    for (Iterator changeIt = additionalChanges.iterator(); changeIt.hasNext();)
    {
        ((AddForeignKeyChange)changeIt.next()).apply(intermediateModel, isCaseSensitive());
    }
    changes.addAll(additionalChanges);
    return changes;
}
 
Example 21
Source Project: gemfirexd-oss   Source File: TestDynaSqlQueries.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests the store method.
 */
public void testStoreNew() throws Exception
{
    createDatabase(
        "<?xml version='1.0' encoding='ISO-8859-1'?>\n"+
        "<database xmlns='" + DatabaseIO.DDLUTILS_NAMESPACE + "' name='ddlutils'>\n"+
        "  <table name='TestTable'>\n"+
        "    <column name='TheId' type='INTEGER' primaryKey='true' required='true'/>\n"+
        "    <column name='TheText' type='VARCHAR' size='15'/>\n"+
        "  </table>\n"+
        "</database>");

    SqlDynaClass dynaClass = SqlDynaClass.newInstance(getModel().getTable(0));
    DynaBean     dynaBean  = new SqlDynaBean(dynaClass);

    dynaBean.set("TheId", new Integer(1));
    dynaBean.set("TheText", "Text 1"); 

    getPlatform().store(getModel(), dynaBean);

    List beans = getPlatform().fetch(getModel(),
                                     "SELECT * FROM " + asIdentifier("TestTable"),
                                     new Table[] { getModel().getTable(0) });

    assertEquals(1,
                 beans.size());

    DynaBean bean = (DynaBean)beans.get(0);

    assertEquals(new Integer(1),
                 getPropertyValue(bean, "TheId"));
    assertEquals("Text 1",
                 getPropertyValue(bean, "TheText"));
}
 
Example 22
Source Project: gemfirexd-oss   Source File: GemFireXDBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeAddIdentityColumnUsingAlterTable(Table table,
    Column column) throws IOException {
  writeTableAlterStmt(table);
  print("ALTER COLUMN ");
  print(getColumnName(column));
  print(" SET GENERATED ALWAYS AS IDENTITY");
  printEndOfStatement();
}
 
Example 23
Source Project: gemfirexd-oss   Source File: TestAgainstLiveDatabaseBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a row into the designated table.
 * 
 * @param tableName    The name of the table (case insensitive)
 * @param columnValues The values for the columns in order of definition
 * @return The dyna bean for the row
 */
protected DynaBean insertRow(String tableName, Object[] columnValues)
{
    Table    table = getModel().findTable(tableName);
    DynaBean bean  = getModel().createDynaBeanFor(table);

    for (int idx = 0; (idx < table.getColumnCount()) && (idx < columnValues.length); idx++)
    {
        Column column = table.getColumn(idx);

        bean.set(column.getName(), columnValues[idx]);
    }
    getPlatform().insert(getModel(), bean);
    return bean;
}
 
Example 24
Source Project: gemfirexd-oss   Source File: ColumnChangeImplBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Column findChangedColumn(Database model, boolean caseSensitive)
{
	Table table = findChangedTable(model, caseSensitive);

	return table == null ? null : table.findColumn(_columnName, caseSensitive);
}
 
Example 25
Source Project: gemfirexd-oss   Source File: MySqlPlatform.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes the removal of a primary key from 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,
                          RemovePrimaryKeyChange change) throws IOException
{
    Table changedTable = findChangedTable(currentModel, change);

    ((MySqlBuilder)getSqlBuilder()).dropPrimaryKey(changedTable);
    change.apply(currentModel, isDelimitedIdentifierModeOn());
}
 
Example 26
Source Project: gemfirexd-oss   Source File: DerbyBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dropIndex(Table table, Index index) throws IOException
{
    // Index names in Derby are unique to a schema and hence Derby does not
    // use the ON <tablename> clause
    print("DROP INDEX ");
    printIdentifier(getIndexName(index));
    printEndOfStatement();
}
 
Example 27
Source Project: gemfirexd-oss   Source File: FirebirdModelReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Table readTable(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
    Table table = super.readTable(metaData, values);

    if (table != null)
    {
    	determineAutoIncrementColumns(table);
    }

    return table;
}
 
Example 28
Source Project: gemfirexd-oss   Source File: DropTablesCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void execute(DatabaseTaskBase task, Database model) throws BuildException
{
    BasicDataSource dataSource = getDataSource();

    if (dataSource == null)
    {
        throw new BuildException("No database specified.");
    }

    Platform platform    = getPlatform();
    Database targetModel = new Database();

    if ((_tableNames != null) || (_tableNameRegExp != null))
    {
        targetModel = new CloneHelper().clone(model);
        targetModel.initialize();

        Table[] tables = _tableNames != null ? targetModel.findTables(_tableNames, task.isUseDelimitedSqlIdentifiers())
                                             : targetModel.findTables(_tableNameRegExp, task.isUseDelimitedSqlIdentifiers());

        new ModelHelper().removeForeignKeysToAndFromTables(targetModel, tables);
        targetModel.removeTables(tables);
    }
    try
    {
        platform.alterModel(model, targetModel, isFailOnError());

        _log.info("Dropped tables");
    }
    catch (Exception ex)
    {
        handleException(ex, ex.getMessage());
    }
}
 
Example 29
Source Project: gemfirexd-oss   Source File: MSSqlModelReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether there is a pk for the table with the given name.
 * 
 * @param metaData The database metadata
 * @param table    The table
 * @param name     The pk name
 * @return <code>true</code> if there is such a pk
 */
private boolean existsPKWithName(DatabaseMetaDataWrapper metaData, Table table, String name) throws SQLException
{
    ResultSet pks = null;

    try
    {
        pks = metaData.getPrimaryKeys(metaData.escapeForSearch(table.getName()));
        // GemStone changes BEGIN
        //pks = metaData.getPrimaryKeys(metaData.escapeForSearch(table.getName()));
      
        //The underlying DatabaseMetaData.getPrimaryKeys does not take the string pattern,
        //so do not need escape the _, see ticket 44911
        pks = metaData.getPrimaryKeys(table.getName());
        // GemStone changes BEGIN  

        while (pks.next())
        {
            if (name.equals(pks.getString("PK_NAME")))
            {
                return true;
            }
        }
        return false;
    }
    finally
    {
        closeResultSet(pks);
    }
}
 
Example 30
Source Project: gemfirexd-oss   Source File: AddPrimaryKeyChange.java    License: 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);
    }
}