@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};
  }
  protected String generateSingleColumnSQL(AddColumnStatement statement, Database database) {
    DatabaseDataType columnType =
        DataTypeFactory.getInstance()
            .fromDescription(
                statement.getColumnType()
                    + (statement.isAutoIncrement() ? "{autoIncrement:true}" : ""),
                database)
            .toDatabaseDataType(database);

    String alterTable =
        " ADD "
            + database.escapeColumnName(
                statement.getCatalogName(),
                statement.getSchemaName(),
                statement.getTableName(),
                statement.getColumnName())
            + " "
            + columnType;

    if (statement.isAutoIncrement() && database.supportsAutoIncrement()) {
      AutoIncrementConstraint autoIncrementConstraint = statement.getAutoIncrementConstraint();
      alterTable +=
          " "
              + database.getAutoIncrementClause(
                  autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy());
    }

    alterTable += getDefaultClause(statement, database);

    if (!statement.isNullable()) {
      alterTable += " NOT NULL";
    } else {
      if (database instanceof SybaseDatabase
          || database instanceof SybaseASADatabase
          || database instanceof MySQLDatabase
          || (database instanceof MSSQLDatabase
              && columnType.toString().equalsIgnoreCase("timestamp"))) {
        alterTable += " NULL";
      }
    }

    if (statement.isPrimaryKey()) {
      alterTable += " PRIMARY KEY";
    }

    if (database instanceof MySQLDatabase && statement.getRemarks() != null) {
      alterTable += " COMMENT '" + statement.getRemarks() + "' ";
    }

    if (statement.getAddAfterColumn() != null && !statement.getAddAfterColumn().isEmpty()) {
      alterTable += " AFTER `" + statement.getAddAfterColumn() + "` ";
    }

    return alterTable;
  }
 // Copied from liquibase.sqlgenerator.core.InsertOrUpdateGeneratorMySQL
 private String convertToString(Object newValue, Database database) {
   String sqlString;
   if (newValue == null
       || newValue.toString().equals("")
       || newValue.toString().equalsIgnoreCase("NULL")) {
     sqlString = "NULL";
   } else if (newValue instanceof String
       && !looksLikeFunctionCall(((String) newValue), database)) {
     sqlString = "'" + database.escapeStringForDatabase(newValue.toString()) + "'";
   } else if (newValue instanceof Date) {
     sqlString = database.getDateLiteral(((Date) newValue));
   } else if (newValue instanceof Boolean) {
     if (((Boolean) newValue)) {
       sqlString = DataTypeFactory.getInstance().getTrueBooleanValue(database);
     } else {
       sqlString = DataTypeFactory.getInstance().getFalseBooleanValue(database);
     }
   } else {
     sqlString = newValue.toString();
   }
   return sqlString;
 }
 private String getDefaultClause(AddColumnStatement statement, Database database) {
   String clause = "";
   Object defaultValue = statement.getDefaultValue();
   if (defaultValue != null) {
     if (database instanceof OracleDatabase
         && defaultValue.toString().startsWith("GENERATED ALWAYS ")) {
       clause +=
           " "
               + DataTypeFactory.getInstance()
                   .fromObject(defaultValue, database)
                   .objectToSql(defaultValue, database);
     } else {
       if (database instanceof MSSQLDatabase) {
         clause +=
             " CONSTRAINT "
                 + ((MSSQLDatabase) database)
                     .generateDefaultConstraintName(
                         statement.getTableName(), statement.getColumnName());
       }
       if (defaultValue instanceof DatabaseFunction) {
         clause +=
             " DEFAULT "
                 + DataTypeFactory.getInstance()
                     .fromObject(defaultValue, database)
                     .objectToSql(defaultValue, database);
       } else {
         clause +=
             " DEFAULT "
                 + DataTypeFactory.getInstance()
                     .fromDescription(statement.getColumnType(), database)
                     .objectToSql(defaultValue, database);
       }
     }
   }
   return clause;
 }
 @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))
   };
 }
Esempio n. 6
0
  public static Object parseValue(Database database, Object val, DataType type) {
    if (!(val instanceof String)) {
      return val;
    }

    int typeId = Integer.MIN_VALUE;
    if (type.getDataTypeId() != null) {
      typeId = type.getDataTypeId();
    }
    String typeName = type.getTypeName();

    LiquibaseDataType liquibaseDataType = DataTypeFactory.getInstance().from(type, database);

    String stringVal = (String) val;
    if (stringVal.isEmpty()) {
      if (liquibaseDataType instanceof CharType) {
        return "";
      } else {
        return null;
      }
    }

    if (database instanceof OracleDatabase
        && !stringVal.startsWith("'")
        && !stringVal.endsWith("'")) {
      // oracle returns functions without quotes
      Object maybeDate = null;

      if (liquibaseDataType instanceof DateType || typeId == Types.DATE) {
        if (stringVal.endsWith("'HH24:MI:SS')")) {
          maybeDate =
              DataTypeFactory.getInstance()
                  .fromDescription("time", database)
                  .sqlToObject(stringVal, database);
        } else {
          maybeDate =
              DataTypeFactory.getInstance()
                  .fromDescription("date", database)
                  .sqlToObject(stringVal, database);
        }
      } else if (liquibaseDataType instanceof DateTimeType || typeId == Types.TIMESTAMP) {
        maybeDate =
            DataTypeFactory.getInstance()
                .fromDescription("datetime", database)
                .sqlToObject(stringVal, database);
      } else {
        return new DatabaseFunction(stringVal);
      }
      if (maybeDate != null) {
        if (maybeDate instanceof java.util.Date) {
          return maybeDate;
        } else {
          return new DatabaseFunction(stringVal);
        }
      }
    }

    if (stringVal.startsWith("'") && stringVal.endsWith("'")) {
      stringVal = stringVal.substring(1, stringVal.length() - 1);
    } else if (stringVal.startsWith("((") && stringVal.endsWith("))")) {
      stringVal = stringVal.substring(2, stringVal.length() - 2);
    } else if (stringVal.startsWith("('") && stringVal.endsWith("')")) {
      stringVal = stringVal.substring(2, stringVal.length() - 2);
    } else if (stringVal.startsWith("(") && stringVal.endsWith(")")) {
      return new DatabaseFunction(stringVal.substring(1, stringVal.length() - 1));
    }

    Scanner scanner = new Scanner(stringVal.trim());
    if (typeId == Types.ARRAY) {
      return new DatabaseFunction(stringVal);
    } else if ((liquibaseDataType instanceof BigIntType || typeId == Types.BIGINT)) {
      if (scanner.hasNextBigInteger()) {
        return scanner.nextBigInteger();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if (typeId == Types.BINARY) {
      return new DatabaseFunction(stringVal.trim());
    } else if (typeId == Types.BIT) {
      if (stringVal.startsWith("b'")) { // mysql returns boolean values as b'0' and b'1'
        stringVal = stringVal.replaceFirst("b'", "").replaceFirst("'$", "");
      }
      stringVal = stringVal.trim();
      if (scanner.hasNextBoolean()) {
        return scanner.nextBoolean();
      } else {
        return new Integer(stringVal);
      }
    } else if (liquibaseDataType instanceof BlobType || typeId == Types.BLOB) {
      return new DatabaseFunction(stringVal);
    } else if ((liquibaseDataType instanceof BooleanType || typeId == Types.BOOLEAN)) {
      if (scanner.hasNextBoolean()) {
        return scanner.nextBoolean();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if (liquibaseDataType instanceof CharType || typeId == Types.CHAR) {
      return stringVal;
    } else if (liquibaseDataType instanceof ClobType || typeId == Types.CLOB) {
      return stringVal;
    } else if (typeId == Types.DATALINK) {
      return new DatabaseFunction(stringVal);
    } else if (liquibaseDataType instanceof DateType || typeId == Types.DATE) {
      if (typeName.equalsIgnoreCase("year")) {
        return stringVal.trim();
      }
      return DataTypeFactory.getInstance()
          .fromDescription("date", database)
          .sqlToObject(stringVal, database);
    } else if ((liquibaseDataType instanceof DecimalType || typeId == Types.DECIMAL)) {
      if (scanner.hasNextBigDecimal()) {
        return scanner.nextBigDecimal();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if (typeId == Types.DISTINCT) {
      return new DatabaseFunction(stringVal);
    } else if ((liquibaseDataType instanceof DoubleType || typeId == Types.DOUBLE)) {
      if (scanner.hasNextDouble()) {
        return scanner.nextDouble();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if ((liquibaseDataType instanceof FloatType || typeId == Types.FLOAT)) {
      if (scanner.hasNextFloat()) {
        return scanner.nextFloat();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if ((liquibaseDataType instanceof IntType || typeId == Types.INTEGER)) {
      if (scanner.hasNextInt()) {
        return scanner.nextInt();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if (typeId == Types.JAVA_OBJECT) {
      return new DatabaseFunction(stringVal);
    } else if (typeId == Types.LONGNVARCHAR) {
      return stringVal;
    } else if (typeId == Types.LONGVARBINARY) {
      return new DatabaseFunction(stringVal);
    } else if (typeId == Types.LONGVARCHAR) {
      return stringVal;
    } else if (liquibaseDataType instanceof NCharType || typeId == Types.NCHAR) {
      return stringVal;
    } else if (typeId == Types.NCLOB) {
      return stringVal;
    } else if (typeId == Types.NULL) {
      return null;
    } else if ((liquibaseDataType instanceof NumberType || typeId == Types.NUMERIC)) {
      if (scanner.hasNextBigDecimal()) {
        return scanner.nextBigDecimal();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if (liquibaseDataType instanceof NVarcharType || typeId == Types.NVARCHAR) {
      return stringVal;
    } else if (typeId == Types.OTHER) {
      if (database instanceof DB2Database && typeName.equalsIgnoreCase("DECFLOAT")) {
        return new BigDecimal(stringVal);
      }
      return new DatabaseFunction(stringVal);
    } else if (typeId == Types.REAL) {
      return new BigDecimal(stringVal.trim());
    } else if (typeId == Types.REF) {
      return new DatabaseFunction(stringVal);
    } else if (typeId == Types.ROWID) {
      return new DatabaseFunction(stringVal);
    } else if ((liquibaseDataType instanceof SmallIntType || typeId == Types.SMALLINT)) {
      if (scanner.hasNextInt()) {
        return scanner.nextInt();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if (typeId == Types.SQLXML) {
      return new DatabaseFunction(stringVal);
    } else if (typeId == Types.STRUCT) {
      return new DatabaseFunction(stringVal);
    } else if (liquibaseDataType instanceof TimeType || typeId == Types.TIME) {
      return DataTypeFactory.getInstance()
          .fromDescription("time", database)
          .sqlToObject(stringVal, database);
    } else if (liquibaseDataType instanceof DateTimeType
        || liquibaseDataType instanceof TimestampType
        || typeId == Types.TIMESTAMP) {
      return DataTypeFactory.getInstance()
          .fromDescription("datetime", database)
          .sqlToObject(stringVal, database);
    } else if ((liquibaseDataType instanceof TinyIntType || typeId == Types.TINYINT)) {
      if (scanner.hasNextInt()) {
        return scanner.nextInt();
      } else {
        return new DatabaseFunction(stringVal);
      }
    } else if (typeId == Types.VARBINARY) {
      return new DatabaseFunction(stringVal);
    } else if (liquibaseDataType instanceof VarcharType || typeId == Types.VARCHAR) {
      return stringVal;
    } else if (database instanceof MySQLDatabase && typeName.toLowerCase().startsWith("enum")) {
      return stringVal;
    } else {
      LogFactory.getLogger()
          .info(
              "Unknown default value: value '"
                  + stringVal
                  + "' type "
                  + typeName
                  + " ("
                  + type
                  + "), assuming it is a function");
      return new DatabaseFunction(stringVal);
    }
  }
  @Override
  public Sql[] generateSql(
      CreateDatabaseChangeLogTableStatement statement,
      Database database,
      SqlGeneratorChain sqlGeneratorChain) {
    /* Because Informix has some limitations on the primary key column cumulative size (same is for unique indices),
     * the ID's column has been made the sole primary key, and also has a reduced size.
     *
     * The original configuration provided by the base class causes the database changelog table not to be created.
     */

    CreateTableStatement createTableStatement =
        new CreateTableStatement(
                database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogTableName())
            .addPrimaryKeyColumn(
                "ID",
                DataTypeFactory.getInstance().fromDescription("VARCHAR(" + getIdColumnSize() + ")"),
                null,
                null,
                null,
                new NotNullConstraint())
            .addColumn(
                "AUTHOR",
                DataTypeFactory.getInstance()
                    .fromDescription("VARCHAR(" + getAuthorColumnSize() + ")"),
                null,
                null,
                null,
                new NotNullConstraint())
            .addColumn(
                "FILENAME",
                DataTypeFactory.getInstance()
                    .fromDescription("VARCHAR(" + getFilenameColumnSize() + ")"),
                null,
                null,
                null,
                new NotNullConstraint())
            .addColumn(
                "DATEEXECUTED",
                DataTypeFactory.getInstance().fromDescription("datetime"),
                null,
                new NotNullConstraint())
            .addColumn(
                "ORDEREXECUTED",
                DataTypeFactory.getInstance().fromDescription("INT"),
                new NotNullConstraint())
            .addColumn(
                "EXECTYPE",
                DataTypeFactory.getInstance().fromDescription("VARCHAR(10)"),
                new NotNullConstraint())
            .addColumn("MD5SUM", DataTypeFactory.getInstance().fromDescription("VARCHAR(35)"))
            .addColumn("DESCRIPTION", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)"))
            .addColumn("COMMENTS", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)"))
            .addColumn("TAG", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)"))
            .addColumn("LIQUIBASE", DataTypeFactory.getInstance().fromDescription("VARCHAR(20)"));

    return SqlGeneratorFactory.getInstance().generateSql(createTableStatement, database);
  }