Search in sources :

Example 1 with IDdlBuilder

use of org.jumpmind.db.platform.IDdlBuilder in project symmetric-ds by JumpMind.

the class OracleDdlReader method isAutoIncrement.

/*
     * Tries to determine whether the given column is an identity column.
     *
     * @param table The table
     *
     * @param column The column
     *
     * @return <code>true</code> if the column is an identity column
     */
protected boolean isAutoIncrement(Connection connection, Table table, Column column) throws SQLException {
    // TODO: For now, we only check whether there is a sequence & trigger as
    // generated by DdlUtils
    // But once sequence/trigger support is in place, it might be possible
    // to 'parse' the
    // trigger body (via SELECT trigger_name, trigger_body FROM
    // user_triggers) in order to
    // determine whether it fits our auto-increment definition
    PreparedStatement prepStmt = null;
    IDdlBuilder builder = getPlatform().getDdlBuilder();
    String triggerName = builder.getConstraintName(OracleDdlBuilder.PREFIX_TRIGGER, table, column.getName(), null);
    String seqName = builder.getConstraintName(OracleDdlBuilder.PREFIX_SEQUENCE, table, column.getName(), null);
    if (!getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn()) {
        triggerName = triggerName.toUpperCase();
        seqName = seqName.toUpperCase();
    }
    try {
        prepStmt = connection.prepareStatement("SELECT * FROM user_triggers WHERE trigger_name = ?");
        prepStmt.setString(1, triggerName);
        ResultSet resultSet = prepStmt.executeQuery();
        if (!resultSet.next()) {
            resultSet.close();
            return false;
        }
        // we have a trigger, so lets check the sequence
        prepStmt.close();
        prepStmt = connection.prepareStatement("SELECT * FROM user_sequences WHERE sequence_name = ?");
        prepStmt.setString(1, seqName);
        resultSet = prepStmt.executeQuery();
        boolean resultFound = resultSet.next();
        resultSet.close();
        return resultFound;
    } finally {
        if (prepStmt != null) {
            prepStmt.close();
        }
    }
}
Also used : IDdlBuilder(org.jumpmind.db.platform.IDdlBuilder) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 2 with IDdlBuilder

use of org.jumpmind.db.platform.IDdlBuilder in project symmetric-ds by JumpMind.

the class FirebirdDdlReader method isInternalForeignKeyIndex.

@Override
protected boolean isInternalForeignKeyIndex(Connection connection, DatabaseMetaDataWrapper metaData, Table table, ForeignKey fk, IIndex index) throws SQLException {
    IDdlBuilder builder = getPlatform().getDdlBuilder();
    String tableName = builder.getTableName(table.getName());
    String indexName = builder.getIndexName(index);
    String fkName = builder.getForeignKeyName(table, fk);
    StringBuilder query = new StringBuilder();
    query.append("SELECT RDB$CONSTRAINT_NAME FROM RDB$RELATION_CONSTRAINTS where RDB$RELATION_NAME=? AND RDB$CONSTRAINT_TYPE=? AND RDB$CONSTRAINT_NAME=? AND RDB$INDEX_NAME=?");
    PreparedStatement stmt = connection.prepareStatement(query.toString());
    try {
        stmt.setString(1, getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn() ? tableName : tableName.toUpperCase());
        stmt.setString(2, "FOREIGN KEY");
        stmt.setString(3, fkName);
        stmt.setString(4, indexName);
        ResultSet resultSet = stmt.executeQuery();
        return resultSet.next();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}
Also used : IDdlBuilder(org.jumpmind.db.platform.IDdlBuilder) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 3 with IDdlBuilder

use of org.jumpmind.db.platform.IDdlBuilder in project symmetric-ds by JumpMind.

the class DatabasePlatformTest method testUpgradePrimaryKeyAutoIncrementFromIntToBigInt.

@Test
public void testUpgradePrimaryKeyAutoIncrementFromIntToBigInt() throws Exception {
    boolean upgradeSupported = !platform.getName().equals(DatabaseNamesConstants.DERBY) && !platform.getName().equals(DatabaseNamesConstants.HSQLDB2) && !platform.getName().equals(DatabaseNamesConstants.INFORMIX) && !platform.getName().equals(DatabaseNamesConstants.DB2) && !platform.getName().equals(DatabaseNamesConstants.ASE) && !platform.getName().equals(DatabaseNamesConstants.MSSQL2000) && !platform.getName().equals(DatabaseNamesConstants.MSSQL2005) && !platform.getName().equals(DatabaseNamesConstants.MSSQL2008) && !platform.getName().equals(DatabaseNamesConstants.SQLANYWHERE);
    if (upgradeSupported) {
        Table table = new Table("TEST_UPGRADE");
        table.addColumn(new Column("ID", true));
        table.getColumnWithName("ID").setTypeCode(Types.INTEGER);
        table.getColumnWithName("ID").setAutoIncrement(true);
        table.getColumnWithName("ID").setRequired(true);
        table.addColumn(new Column("NOTES"));
        table.getColumnWithName("NOTES").setTypeCode(Types.VARCHAR);
        table.getColumnWithName("NOTES").setSize("100");
        Table tableFromDatabase = dropCreateAndThenReadTable(table);
        assertNotNull(tableFromDatabase);
        assertTrue(tableFromDatabase.getColumnWithName("ID").isPrimaryKey());
        String insertSql = "insert into \"TEST_UPGRADE\" (\"ID\",\"NOTES\") values(null,?)";
        insertSql = insertSql.replaceAll("\"", platform.getDatabaseInfo().getDelimiterToken());
        long id1 = platform.getSqlTemplate().insertWithGeneratedKey(insertSql, "ID", getSequenceName(platform), new Object[] { "test" }, new int[] { Types.VARCHAR });
        table.getColumnWithName("ID").setTypeCode(Types.BIGINT);
        IDdlBuilder builder = platform.getDdlBuilder();
        String alterSql = builder.alterTable(tableFromDatabase, table);
        assertFalse(alterSql, alterSql.toLowerCase().contains("create table"));
        new SqlScript(alterSql, platform.getSqlTemplate(), true, platform.getSqlScriptReplacementTokens()).execute(true);
        tableFromDatabase = platform.getTableFromCache(table.getName(), true);
        assertEquals(Types.BIGINT, table.getColumnWithName("ID").getMappedTypeCode());
        assertTrue(tableFromDatabase.getColumnWithName("ID").isPrimaryKey());
        long id2 = platform.getSqlTemplate().insertWithGeneratedKey(insertSql, "ID", getSequenceName(platform), new Object[] { "test" }, new int[] { Types.VARCHAR });
        assertNotSame(id1, id2);
    }
}
Also used : Table(org.jumpmind.db.model.Table) Column(org.jumpmind.db.model.Column) IDdlBuilder(org.jumpmind.db.platform.IDdlBuilder) SqlScript(org.jumpmind.db.sql.SqlScript) Test(org.junit.Test)

Example 4 with IDdlBuilder

use of org.jumpmind.db.platform.IDdlBuilder in project symmetric-ds by JumpMind.

the class AbstractSymmetricDialect method createOrAlterTablesIfNecessary.

/*
     * @return true if SQL was executed.
     */
public boolean createOrAlterTablesIfNecessary(String... tableNames) {
    try {
        log.info("Checking if SymmetricDS tables need created or altered");
        Database modelFromXml = readSymmetricSchemaFromXml();
        Database modelFromDatabase = readSymmetricSchemaFromDatabase();
        if (tableNames != null && tableNames.length > 0) {
            tableNames = platform.alterCaseToMatchDatabaseDefaultCase(tableNames);
            modelFromXml.removeAllTablesExcept(tableNames);
            modelFromDatabase.removeAllTablesExcept(tableNames);
        }
        IDdlBuilder builder = platform.getDdlBuilder();
        List<IAlterDatabaseInterceptor> alterDatabaseInterceptors = extensionService.getExtensionPointList(IAlterDatabaseInterceptor.class);
        IAlterDatabaseInterceptor[] interceptors = alterDatabaseInterceptors.toArray(new IAlterDatabaseInterceptor[alterDatabaseInterceptors.size()]);
        if (builder.isAlterDatabase(modelFromDatabase, modelFromXml, interceptors)) {
            String delimiter = platform.getDatabaseInfo().getSqlCommandDelimiter();
            ISqlResultsListener resultsListener = new LogSqlResultsListener(log);
            List<IDatabaseUpgradeListener> databaseUpgradeListeners = extensionService.getExtensionPointList(IDatabaseUpgradeListener.class);
            String alterSql = builder.alterDatabase(modelFromDatabase, modelFromXml, interceptors);
            if (isNotBlank(alterSql)) {
                log.info("There are SymmetricDS tables that needed altered");
                for (IDatabaseUpgradeListener listener : databaseUpgradeListeners) {
                    String sql = listener.beforeUpgrade(this, this.parameterService.getTablePrefix(), modelFromDatabase, modelFromXml);
                    SqlScript script = new SqlScript(sql, getPlatform().getSqlTemplate(), true, false, false, delimiter, null);
                    script.setListener(resultsListener);
                    script.execute(platform.getDatabaseInfo().isRequiresAutoCommitForDdl());
                }
                log.debug("Alter SQL generated: {}", alterSql);
                SqlScript script = new SqlScript(alterSql, getPlatform().getSqlTemplate(), true, false, false, delimiter, null);
                script.setListener(resultsListener);
                script.execute(platform.getDatabaseInfo().isRequiresAutoCommitForDdl());
                for (IDatabaseUpgradeListener listener : databaseUpgradeListeners) {
                    String sql = listener.afterUpgrade(this, this.parameterService.getTablePrefix(), modelFromXml);
                    script = new SqlScript(sql, getPlatform().getSqlTemplate(), true, false, false, delimiter, null);
                    script.setListener(resultsListener);
                    script.execute(platform.getDatabaseInfo().isRequiresAutoCommitForDdl());
                }
                log.info("Done with auto update of SymmetricDS tables");
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : IDatabaseUpgradeListener(org.jumpmind.symmetric.ext.IDatabaseUpgradeListener) IAlterDatabaseInterceptor(org.jumpmind.db.platform.IAlterDatabaseInterceptor) SqlException(org.jumpmind.db.sql.SqlException) IoException(org.jumpmind.exception.IoException) IOException(java.io.IOException) ISqlResultsListener(org.jumpmind.db.sql.ISqlResultsListener) IDdlBuilder(org.jumpmind.db.platform.IDdlBuilder) Database(org.jumpmind.db.model.Database) SqlScript(org.jumpmind.db.sql.SqlScript) LogSqlResultsListener(org.jumpmind.db.sql.LogSqlResultsListener)

Example 5 with IDdlBuilder

use of org.jumpmind.db.platform.IDdlBuilder in project symmetric-ds by JumpMind.

the class ConfigDatabaseUpgrader method upgrade.

public boolean upgrade() {
    try {
        if (logOutput) {
            log.info("Checking if config tables need created or altered");
        }
        Database modelFromXml = configDatabasePlatform.readDatabaseFromXml(schemaXml, true);
        configDatabasePlatform.prefixDatabase(tablePrefix, modelFromXml);
        Database modelFromDatabase = configDatabasePlatform.readFromDatabase(modelFromXml.getTables());
        IDdlBuilder builder = configDatabasePlatform.getDdlBuilder();
        if (builder.isAlterDatabase(modelFromDatabase, modelFromXml)) {
            if (logOutput) {
                log.info("There are config tables that needed altered");
            }
            String delimiter = configDatabasePlatform.getDatabaseInfo().getSqlCommandDelimiter();
            String alterSql = builder.alterDatabase(modelFromDatabase, modelFromXml);
            log.debug("Alter SQL generated: {}", alterSql);
            SqlScript script = new SqlScript(alterSql, configDatabasePlatform.getSqlTemplate(), true, false, false, delimiter, null);
            if (logOutput) {
                script.setListener(new LogSqlResultsListener(log));
            }
            script.execute(configDatabasePlatform.getDatabaseInfo().isRequiresAutoCommitForDdl());
            if (logOutput) {
                log.info("Done with auto update of config tables");
            }
            return true;
        } else {
            return false;
        }
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : IDdlBuilder(org.jumpmind.db.platform.IDdlBuilder) Database(org.jumpmind.db.model.Database) SqlScript(org.jumpmind.db.sql.SqlScript) LogSqlResultsListener(org.jumpmind.db.sql.LogSqlResultsListener)

Aggregations

IDdlBuilder (org.jumpmind.db.platform.IDdlBuilder)10 Database (org.jumpmind.db.model.Database)4 SqlScript (org.jumpmind.db.sql.SqlScript)4 PreparedStatement (java.sql.PreparedStatement)3 ResultSet (java.sql.ResultSet)3 LogSqlResultsListener (org.jumpmind.db.sql.LogSqlResultsListener)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Column (org.jumpmind.db.model.Column)1 Table (org.jumpmind.db.model.Table)1 AbstractJdbcDatabasePlatform (org.jumpmind.db.platform.AbstractJdbcDatabasePlatform)1 IAlterDatabaseInterceptor (org.jumpmind.db.platform.IAlterDatabaseInterceptor)1 ISqlResultsListener (org.jumpmind.db.sql.ISqlResultsListener)1 SqlException (org.jumpmind.db.sql.SqlException)1 IoException (org.jumpmind.exception.IoException)1 ISymmetricDialect (org.jumpmind.symmetric.db.ISymmetricDialect)1 IDatabaseUpgradeListener (org.jumpmind.symmetric.ext.IDatabaseUpgradeListener)1 StructureDataWriter (org.jumpmind.symmetric.io.data.writer.StructureDataWriter)1 ChannelMap (org.jumpmind.symmetric.model.ChannelMap)1 OutgoingBatch (org.jumpmind.symmetric.model.OutgoingBatch)1