@Override public void init() throws DatabaseException { boolean createdTable = false; Executor executor = ExecutorService.getInstance().getExecutor(database); if (!hasDatabaseChangeLogLockTable()) { executor.comment("Create Database Lock Table"); executor.execute(new CreateDatabaseChangeLogLockTableStatement()); database.commit(); LogFactory.getLogger() .debug( "Created database lock table with name: " + database.escapeTableName( database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName())); this.hasDatabaseChangeLogLockTable = true; createdTable = true; } if (!isDatabaseChangeLogLockTableInitialized(createdTable)) { executor.comment("Initialize Database Lock Table"); executor.execute(new InitializeDatabaseChangeLogLockTableStatement()); database.commit(); } if (database instanceof DerbyDatabase && ((DerbyDatabase) database) .supportsBooleanDataType()) { // check if the changelog table is of an old smallint vs. // boolean format String lockTable = database.escapeTableName( database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName()); Object obj = executor.queryForObject( new RawSqlStatement( "select min(locked) as test from " + lockTable + " fetch first row only"), Object.class); if (!(obj instanceof Boolean)) { // wrong type, need to recreate table executor.execute( new DropTableStatement( database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName(), false)); executor.execute(new CreateDatabaseChangeLogLockTableStatement()); executor.execute(new InitializeDatabaseChangeLogLockTableStatement()); } } }
public Sql[] generateSql( DropIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { List<String> associatedWith = StringUtils.splitAndTrim(statement.getAssociatedWith(), ","); if (associatedWith != null) { if (associatedWith.contains(Index.MARK_PRIMARY_KEY) || associatedWith.contains(Index.MARK_UNIQUE_CONSTRAINT)) { return new Sql[0]; } else if (associatedWith.contains(Index.MARK_FOREIGN_KEY)) { if (!(database instanceof OracleDatabase || database instanceof MSSQLDatabase)) { return new Sql[0]; } } } String schemaName = statement.getTableSchemaName(); if (database instanceof MySQLDatabase) { return new Sql[] { new UnparsedSql( "DROP INDEX " + database.escapeIndexName(null, null, statement.getIndexName()) + " ON " + database.escapeTableName( statement.getTableCatalogName(), schemaName, statement.getTableName())) }; } else if (database instanceof MSSQLDatabase) { return new Sql[] { new UnparsedSql( "DROP INDEX " + database.escapeTableName(null, schemaName, statement.getTableName()) + "." + database.escapeIndexName(null, null, statement.getIndexName())) }; } else if (database instanceof PostgresDatabase) { return new Sql[] { new UnparsedSql( "DROP INDEX " + database.escapeIndexName( statement.getTableCatalogName(), schemaName, statement.getIndexName())) }; } return new Sql[] { new UnparsedSql( "DROP INDEX " + database.escapeIndexName( statement.getTableCatalogName(), schemaName, statement.getIndexName())) }; }
@Override public Sql[] generateSql( AddDefaultValueStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { Object defaultValue = statement.getDefaultValue(); StringBuffer sql = new StringBuffer("ALTER TABLE "); sql.append( database.escapeTableName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())); sql.append(" MODIFY ("); sql.append( database.escapeColumnName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), statement.getColumnName())); sql.append(" "); sql.append( DataTypeFactory.getInstance().fromDescription(statement.getColumnDataType(), database)); sql.append(" DEFAULT "); sql.append( DataTypeFactory.getInstance() .fromObject(defaultValue, database) .objectToSql(defaultValue, database)); sql.append(")"); UnparsedSql unparsedSql = new UnparsedSql(sql.toString(), getAffectedColumn(statement)); return new Sql[] {unparsedSql}; }
public boolean isDatabaseChangeLogLockTableInitialized(final boolean tableJustCreated) throws DatabaseException { if (!isDatabaseChangeLogLockTableInitialized) { Executor executor = ExecutorService.getInstance().getExecutor(database); try { isDatabaseChangeLogLockTableInitialized = executor.queryForInt( new RawSqlStatement( "select count(*) from " + database.escapeTableName( database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName()))) > 0; } catch (LiquibaseException e) { if (executor.updatesDatabase()) { throw new UnexpectedLiquibaseException(e); } else { // probably didn't actually create the table yet. isDatabaseChangeLogLockTableInitialized = !tableJustCreated; } } } return isDatabaseChangeLogLockTableInitialized; }
@Override public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet) throws PreconditionFailedException, PreconditionErrorException { String currentSchemaName; String currentCatalogName; try { currentCatalogName = getCatalogName(); currentSchemaName = getSchemaName(); if (!SnapshotGeneratorFactory.getInstance() .has( new View() .setName(getViewName()) .setSchema(new Schema(currentCatalogName, currentSchemaName)), database)) { throw new PreconditionFailedException( "View " + database.escapeTableName(currentCatalogName, currentSchemaName, getViewName()) + " does not exist", changeLog, this); } } catch (PreconditionFailedException e) { throw e; } catch (Exception e) { throw new PreconditionErrorException(e, changeLog, this); } }
public Sql[] generateSql( SelectFromDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { String sql = "SELECT " + StringUtils.join(statement.getColumnsToSelect(), ",").toUpperCase() + " FROM " + database.escapeTableName( database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()); SelectFromDatabaseChangeLogStatement.WhereClause whereClause = statement.getWhereClause(); if (whereClause != null) { if (whereClause instanceof SelectFromDatabaseChangeLogStatement.ByTag) { sql += " WHERE TAG='" + ((SelectFromDatabaseChangeLogStatement.ByTag) whereClause).getTagName() + "'"; } else if (whereClause instanceof SelectFromDatabaseChangeLogStatement.ByNotNullCheckSum) { sql += " WHERE MD5SUM IS NOT NULL"; } else { throw new UnexpectedLiquibaseException( "Unknown where clause type: " + whereClause.getClass().getName()); } } if (statement.getOrderByColumns() != null && statement.getOrderByColumns().length > 0) { sql += " ORDER BY " + StringUtils.join(statement.getOrderByColumns(), ", ").toUpperCase(); } return new Sql[] {new UnparsedSql(sql)}; }
@Override @Test public void escapeTableName_withSchema() { Database database = getDatabase(); assertEquals( "catalogName.tableName", database.escapeTableName("catalogName", "schemaName", "tableName")); }
public Sql[] generateSql( DropColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { if (database instanceof DB2Database) { return new Sql[] { new UnparsedSql( "ALTER TABLE " + database.escapeTableName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " DROP COLUMN " + database.escapeColumnName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), statement.getColumnName())) }; } else if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof FirebirdDatabase || database instanceof InformixDatabase) { return new Sql[] { new UnparsedSql( "ALTER TABLE " + database.escapeTableName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " DROP " + database.escapeColumnName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), statement.getColumnName())) }; } return new Sql[] { new UnparsedSql( "ALTER TABLE " + database.escapeTableName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " DROP COLUMN " + database.escapeColumnName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), statement.getColumnName())) }; }
@Override public Sql[] generateSql( AddAutoIncrementStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { return new Sql[] { new UnparsedSql( "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " ALTER COLUMN " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getColumnName()) + " SET GENERATED ALWAYS AS IDENTITY", new Column() .setTable(new Table(statement.getTableName()).setSchema(statement.getSchemaName())) .setName(statement.getColumnName())) }; }
@Override public Sql[] generateSql( AddAutoIncrementStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { return new Sql[] { new UnparsedSql( "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " ALTER COLUMN " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getColumnName()) + " SET " + database.getAutoIncrementClause( statement.getStartWith(), statement.getIncrementBy()), new Column() .setTable(new Table(statement.getTableName()).setSchema(statement.getSchemaName())) .setName(statement.getColumnName())) }; }
@Override public Sql[] generateSql( AddAutoIncrementStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { return new Sql[] { new UnparsedSql( "ALTER TABLE " + database.escapeTableName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " MODIFY " + database.escapeColumnName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), statement.getColumnName()) + " " + DataTypeFactory.getInstance() .fromDescription(statement.getColumnDataType() + "{autoIncrement:true}") .toDatabaseDataType(database), getAffectedColumn(statement)) }; }
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet) throws PreconditionFailedException, PreconditionErrorException { String currentSchemaName; try { currentSchemaName = getSchemaName() == null ? (database == null ? null : database.getDefaultSchemaName()) : getSchemaName(); if (!DatabaseSnapshotGeneratorFactory.getInstance() .getGenerator(database) .hasView(currentSchemaName, getViewName(), database)) { throw new PreconditionFailedException( "View " + database.escapeTableName(currentSchemaName, getViewName()) + " does not exist", changeLog, this); } } catch (PreconditionFailedException e) { throw e; } catch (Exception e) { throw new PreconditionErrorException(e, changeLog, this); } }
@Override protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException { Database database = snapshot.getDatabase(); Relation relation = ((Column) example).getRelation(); if (((Column) example).getComputed() != null && ((Column) example).getComputed()) { return example; } Schema schema = relation.getSchema(); List<CachedRow> columnMetadataRs = null; try { JdbcDatabaseSnapshot.CachingDatabaseMetaData databaseMetaData = ((JdbcDatabaseSnapshot) snapshot).getMetaData(); columnMetadataRs = databaseMetaData.getColumns( ((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), relation.getName(), example.getName()); if (columnMetadataRs.size() > 0) { CachedRow data = columnMetadataRs.get(0); Column column = readColumn(data, relation, database); if (column != null && database instanceof MSSQLDatabase && database.getDatabaseMajorVersion() >= 8) { String sql; if (database.getDatabaseMajorVersion() >= 9) { // SQL Server 2005 or later // https://technet.microsoft.com/en-us/library/ms177541.aspx sql = "SELECT CAST([ep].[value] AS [nvarchar](MAX)) AS [REMARKS] " + "FROM [sys].[extended_properties] AS [ep] " + "WHERE [ep].[class] = 1 " + "AND [ep].[major_id] = OBJECT_ID(N'" + database.escapeStringForDatabase( database.escapeTableName( schema.getCatalogName(), schema.getName(), relation.getName())) + "') " + "AND [ep].[minor_id] = COLUMNPROPERTY([ep].[major_id], N'" + database.escapeStringForDatabase(column.getName()) + "', 'ColumnId') " + "AND [ep].[name] = 'MS_Description'"; } else { // SQL Server 2000 // https://technet.microsoft.com/en-us/library/aa224810%28v=sql.80%29.aspx sql = "SELECT CAST([p].[value] AS [ntext]) AS [REMARKS] " + "FROM [dbo].[sysproperties] AS [p] " + "WHERE [p].[id] = OBJECT_ID(N'" + database.escapeStringForDatabase( database.escapeTableName( schema.getCatalogName(), schema.getName(), relation.getName())) + "') " + "AND [p].[smallid] = COLUMNPROPERTY([p].[id], N'" + database.escapeStringForDatabase(column.getName()) + "', 'ColumnId') " + "AND [p].[type] = 4 " + "AND [p].[name] = 'MS_Description'"; } List<String> remarks = ExecutorService.getInstance() .getExecutor(snapshot.getDatabase()) .queryForList(new RawSqlStatement(sql), String.class); if (remarks != null && remarks.size() > 0) { column.setRemarks(StringUtils.trimToNull(remarks.iterator().next())); } } return column; } else { return null; } } catch (Exception e) { throw new DatabaseException(e); } }
protected Column readColumn(CachedRow columnMetadataResultSet, Relation table, Database database) throws SQLException, DatabaseException { String rawTableName = (String) columnMetadataResultSet.get("TABLE_NAME"); String rawColumnName = (String) columnMetadataResultSet.get("COLUMN_NAME"); String rawSchemaName = StringUtils.trimToNull((String) columnMetadataResultSet.get("TABLE_SCHEM")); String rawCatalogName = StringUtils.trimToNull((String) columnMetadataResultSet.get("TABLE_CAT")); String remarks = StringUtils.trimToNull((String) columnMetadataResultSet.get("REMARKS")); if (remarks != null) { remarks = remarks.replace("''", "'"); // come back escaped sometimes } Column column = new Column(); column.setName(StringUtils.trimToNull(rawColumnName)); column.setRelation(table); column.setRemarks(remarks); if (database instanceof OracleDatabase) { String nullable = columnMetadataResultSet.getString("NULLABLE"); if (nullable.equals("Y")) { column.setNullable(true); } else { column.setNullable(false); } } else { int nullable = columnMetadataResultSet.getInt("NULLABLE"); if (nullable == DatabaseMetaData.columnNoNulls) { column.setNullable(false); } else if (nullable == DatabaseMetaData.columnNullable) { column.setNullable(true); } else if (nullable == DatabaseMetaData.columnNullableUnknown) { LogFactory.getLogger() .info("Unknown nullable state for column " + column.toString() + ". Assuming nullable"); column.setNullable(true); } } if (database.supportsAutoIncrement()) { if (table instanceof Table) { if (columnMetadataResultSet.containsColumn("IS_AUTOINCREMENT")) { String isAutoincrement = (String) columnMetadataResultSet.get("IS_AUTOINCREMENT"); isAutoincrement = StringUtils.trimToNull(isAutoincrement); if (isAutoincrement == null) { column.setAutoIncrementInformation(null); } else if (isAutoincrement.equals("YES")) { column.setAutoIncrementInformation(new Column.AutoIncrementInformation()); } else if (isAutoincrement.equals("NO")) { column.setAutoIncrementInformation(null); } else if (isAutoincrement.equals("")) { LogFactory.getLogger() .info( "Unknown auto increment state for column " + column.toString() + ". Assuming not auto increment"); column.setAutoIncrementInformation(null); } else { throw new UnexpectedLiquibaseException( "Unknown is_autoincrement value: '" + isAutoincrement + "'"); } } else { // probably older version of java, need to select from the column to find out if it is // auto-increment String selectStatement; if (database.getDatabaseProductName().startsWith("DB2 UDB for AS/400")) { selectStatement = "select " + database.escapeColumnName( rawCatalogName, rawSchemaName, rawTableName, rawColumnName) + " from " + rawSchemaName + "." + rawTableName + " where 0=1"; LogFactory.getLogger().debug("rawCatalogName : <" + rawCatalogName + ">"); LogFactory.getLogger().debug("rawSchemaName : <" + rawSchemaName + ">"); LogFactory.getLogger().debug("rawTableName : <" + rawTableName + ">"); LogFactory.getLogger().debug("raw selectStatement : <" + selectStatement + ">"); } else { selectStatement = "select " + database.escapeColumnName( rawCatalogName, rawSchemaName, rawTableName, rawColumnName) + " from " + database.escapeTableName(rawCatalogName, rawSchemaName, rawTableName) + " where 0=1"; } LogFactory.getLogger() .debug( "Checking " + rawTableName + "." + rawCatalogName + " for auto-increment with SQL: '" + selectStatement + "'"); Connection underlyingConnection = ((JdbcConnection) database.getConnection()).getUnderlyingConnection(); Statement statement = null; ResultSet columnSelectRS = null; try { statement = underlyingConnection.createStatement(); columnSelectRS = statement.executeQuery(selectStatement); if (columnSelectRS.getMetaData().isAutoIncrement(1)) { column.setAutoIncrementInformation(new Column.AutoIncrementInformation()); } else { column.setAutoIncrementInformation(null); } } finally { try { if (statement != null) { statement.close(); } } catch (SQLException ignore) { } if (columnSelectRS != null) { columnSelectRS.close(); } } } } } DataType type = readDataType(columnMetadataResultSet, column, database); column.setType(type); column.setDefaultValue(readDefaultValue(columnMetadataResultSet, column, database)); return column; }
@Override public Sql[] generateSql( CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { // Default filter of index creation: // creation of all indexes with associations are switched off. List<String> associatedWith = StringUtils.splitAndTrim(statement.getAssociatedWith(), ","); if (associatedWith != null && (associatedWith.contains(Index.MARK_PRIMARY_KEY) || associatedWith.contains(Index.MARK_UNIQUE_CONSTRAINT) || associatedWith.contains(Index.MARK_FOREIGN_KEY))) { return new Sql[0]; } StringBuilder buffer = new StringBuilder(); buffer.append("CREATE "); if (statement.isUnique() != null && statement.isUnique()) { buffer.append("UNIQUE "); } buffer.append("INDEX "); if (statement.getIndexName() != null) { String indexSchema = statement.getTableSchemaName(); buffer .append(database.escapeIndexName(null, indexSchema, statement.getIndexName())) .append(" "); } buffer.append("ON "); buffer .append( database.escapeTableName( statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName())) .append("("); Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator(); while (iterator.hasNext()) { String column = iterator.next(); buffer.append( database.escapeColumnName( statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName(), column)); if (iterator.hasNext()) { buffer.append(", "); } } buffer.append(")"); if (StringUtils.trimToNull(statement.getTablespace()) != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { buffer.append(" ON ").append(statement.getTablespace()); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { buffer.append(" IN ").append(statement.getTablespace()); } else { buffer.append(" TABLESPACE ").append(statement.getTablespace()); } } return new Sql[] {new UnparsedSql(buffer.toString())}; }
/** override this method that could support cubrid syntax */ @Override public Sql[] generateSql( RenameColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { String sql; if (database instanceof MSSQLDatabase) { sql = "exec sp_rename '" + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + "." + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + "', '" + statement.getNewColumnName() + "'"; } else if (database instanceof MySQLDatabase) { sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " CHANGE " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + " " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getNewColumnName()) + " " + statement.getColumnDataType(); } else if (database instanceof HsqlDatabase || database instanceof H2Database) { sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " ALTER COLUMN " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + " RENAME TO " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getNewColumnName()); } else if (database instanceof FirebirdDatabase) { sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " ALTER COLUMN " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + " TO " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getNewColumnName()); } else if ((database instanceof MaxDBDatabase) || (database instanceof DerbyDatabase) || (database instanceof InformixDatabase)) { sql = "RENAME COLUMN " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + "." + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + " TO " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getNewColumnName()); } else if (database instanceof SybaseASADatabase) { sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " RENAME " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + " TO " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getNewColumnName()); } else if (database instanceof CUBRIDDatabase) { sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " RENAME COLUMN " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + " AS " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getNewColumnName()); } else { sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getTableName()) + " RENAME COLUMN " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getOldColumnName()) + " TO " + database.escapeColumnName( statement.getSchemaName(), statement.getTableName(), statement.getNewColumnName()); } return new Sql[] {new UnparsedSql(sql)}; }
@Override @Test public void escapeTableName_noSchema() { Database database = getDatabase(); assertEquals("tableName", database.escapeTableName(null, null, "tableName")); }
protected String generateSingleColumBaseSQL(AddColumnStatement statement, Database database) { return "ALTER TABLE " + database.escapeTableName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()); }
@Override public Sql[] generateSql( CreateTempTableStatementVertica statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuilder sql = new StringBuilder(); sql.append("CREATE "); if (statement.getIsGlobal() != null) sql.append(" GLOBAL "); else sql.append(" LOCAL "); sql.append(" TEMPORARY TABLE "); if (statement.getSchemaName() != null) sql.append(statement.getSchemaName()).append("."); else sql.append(database.getDefaultSchemaName()).append("."); if (statement.getTableName() != null) { sql.append(statement.getTableName()).append(" "); } boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; sql.append("( "); Iterator<String> columnIterator = statement.getColumns().iterator(); List<String> primaryKeyColumns = new LinkedList<String>(); while (columnIterator.hasNext()) { String column = columnIterator.next(); DatabaseDataType columnType = statement.getColumnTypes().get(column).toDatabaseDataType(database); sql.append( database.escapeColumnName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column)); // This is the difference between vertica & other RDBMS - the encoding part. AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if (isPrimaryKeyColumn) { primaryKeyColumns.add(column); } if (!isAutoIncrementColumn) { sql.append(" ").append(columnType); } // for the serial data type in postgres, there should be no default value if (!columnType.isAutoIncrement() && statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); sql.append(" DEFAULT "); sql.append(statement.getColumnTypes().get(column).objectToSql(defaultValue, database)); } // TODO: Change this - vertica supports both auto incremental & identity fields. if (isAutoIncrementColumn) { // TODO: check if database supports auto increment on non primary key column if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause( autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { sql.append(" ").append(autoIncrementClause); } if (database instanceof PostgresDatabase && autoIncrementConstraint.getStartWith() != null) { String sequenceName = statement.getTableName() + "_" + column + "_seq"; // additionalSql.add(new UnparsedSql("alter sequence // "+database.escapeSequenceName(statement.getCatalogName(), statement.getSchemaName(), // sequenceName)+" start with "+autoIncrementConstraint.getStartWith(), new // Sequence().setName(sequenceName).setSchema(statement.getCatalogName(), // statement.getSchemaName()))); } } else { LogFactory.getLogger() .warning( database.getShortName() + " does not support autoincrement columns as request for " + (database.escapeTableName( statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()))); } } if (isPrimaryKeyColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName != null) { sql.append(" CONSTRAINT "); sql.append(database.escapeConstraintName(pkName)); } sql.append(" PRIMARY KEY "); } if (statement.getNotNullColumns().contains(column)) { sql.append(" NOT NULL"); } if (statement.getColumnEncoding(column) != null) { sql.append(" ENCODING ").append(statement.getColumnEncoding(column)); } if (statement.getColumnAccessrank(column) != null) sql.append(" ACCESSRANK ").append(statement.getColumnAccessrank(column)); if (columnIterator.hasNext()) { sql.append(", "); } } sql.append(" )"); sql.append(" ON COMMIT "); if (statement.getIsPreserve()) sql.append(" PRESERVE "); else sql.append(" DELETE"); sql.append(" ROWS "); if (statement.getOrderby() != null) sql.append(" ORDER BY ").append(statement.getOrderby()); if (statement.getSegmentation() != null) { Segmentation seg = statement.getSegmentation(); if (seg.getUnsegmented() == true) { sql.append(" UNSEGMENTED "); } else { sql.append(" SEGMENTED BY "); sql.append(seg.getExpression()); } if (seg.getAllNodes()) { sql.append(" ALL NODES "); } else { sql.append(" NODES ").append(seg.getNodes()); if (seg.getOffset() != null) sql.append(" OFFSET ").append(seg.getOffset().toString()); } } if (statement.getKsafe() != null) sql.append(" KSAFE ").append(statement.getKsafe()); if (statement.getPartitionby() != null) sql.append(" PARTITION BY ").append(statement.getPartitionby()); System.out.println(sql.toString()); return new Sql[] {new UnparsedSql(sql.toString())}; }