liquibase.datatype.DataTypeFactory Java Examples

The following examples show how to use liquibase.datatype.DataTypeFactory. 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: liquibase-impala   Author: eselyavka   File: MetastoreCreateDatabaseChangeLogTableGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(CreateDatabaseChangeLogTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String TypeNameChar = "STRING";

    CreateTableStatement createTableStatement = new CreateTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())
            .setTablespace(database.getLiquibaseTablespaceName())
            .addColumn("ID", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("AUTHOR", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("FILENAME", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("DATEEXECUTED", DataTypeFactory.getInstance().fromDescription("TIMESTAMP", database))
            .addColumn("ORDEREXECUTED", DataTypeFactory.getInstance().fromDescription("INT", database))
            .addColumn("EXECTYPE", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("MD5SUM", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("DESCRIPTION", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("COMMENTS", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("TAG", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("LIQUIBASE", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("CONTEXTS", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("LABELS", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("DEPLOYMENT_ID", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database));

    return CustomSqlGenerator.generateSql(database, UserSessionSettings.syncDdlStart(), createTableStatement, UserSessionSettings.syncDdlStop());
}
 
Example #2
Source Project: liquibase-percona   Author: adangel   File: PerconaModifyDataTypeChange.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String generateAlterStatement(Database database) {
    StringBuilder alter = new StringBuilder();

    alter.append("MODIFY ");
    String columnName = database.escapeColumnName(getCatalogName(), getSchemaName(), getTableName(), getColumnName());
    alter.append(columnName);

    alter.append(' ');
    if (getNewDataType() != null) {
        String dataType = String.valueOf(DataTypeFactory.getInstance().fromDescription(getNewDataType(), database).toDatabaseDataType(database));
        alter.append(dataType);
    }

    return alter.toString();
}
 
Example #3
Source Project: liquibase-spatial   Author: lonnyj   File: AddGeometryColumnGeneratorGeoDB.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ValidationErrors validate(final AddColumnStatement statement,
      final Database database, final SqlGeneratorChain sqlGeneratorChain) {
   final ValidationErrors errors = new ValidationErrors();
   final LiquibaseDataType dataType = DataTypeFactory.getInstance()
         .fromDescription(statement.getColumnType(), database);

   // Ensure that the SRID parameter is provided.
   if (dataType instanceof GeometryType) {
      final GeometryType geometryType = (GeometryType) dataType;
      if (geometryType.getSRID() == null) {
         errors.addError("The SRID parameter is required on the geometry type");
      }
   }
   final ValidationErrors chainErrors = sqlGeneratorChain.validate(
         statement, database);
   if (chainErrors != null) {
      errors.addAll(chainErrors);
   }
   return errors;
}
 
Example #4
Source Project: liquibase-impala   Author: eselyavka   File: HiveInsertGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateValues(StringBuilder sql, HiveInsertStatement statement, Database database) {
    sql.append("(");

    for (Object newValue : statement.getColumnValues()) {
        if (newValue == null || newValue.toString().equalsIgnoreCase("NULL")) {
            sql.append("NULL");
        } else if (newValue instanceof String && !looksLikeFunctionCall(((String) newValue), database)) {
            sql.append(DataTypeFactory.getInstance().fromObject(newValue, database).objectToSql(newValue, database));
        } else if (newValue instanceof Date) {
            sql.append(database.getDateLiteral(((Date) newValue)));
        } else if (newValue instanceof Boolean) {
            if (((Boolean) newValue)) {
                sql.append(DataTypeFactory.getInstance().getTrueBooleanValue(database));
            } else {
                sql.append(DataTypeFactory.getInstance().getFalseBooleanValue(database));
            }
        } else if (newValue instanceof DatabaseFunction) {
            sql.append(database.generateDatabaseFunctionValue((DatabaseFunction) newValue));
        } else {
            sql.append(newValue);
        }
        sql.append(", ");
    }

    sql.deleteCharAt(sql.lastIndexOf(" "));
    int lastComma = sql.lastIndexOf(",");
    if (lastComma >= 0) {
        sql.deleteCharAt(lastComma);
    }

    sql.append(")");
}
 
Example #5
@Override
public Sql[] generateSql(CreateDatabaseChangeLogLockTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    CreateTableStatement createTableStatement = new CreateTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName())
            .addColumn("ID", DataTypeFactory.getInstance().fromDescription("INT", database))
            .addColumn("LOCKED", DataTypeFactory.getInstance().fromDescription("BOOLEAN", database))
            .addColumn("LOCKGRANTED", DataTypeFactory.getInstance().fromDescription("TIMESTAMP", database))
            .addColumn("LOCKEDBY", DataTypeFactory.getInstance().fromDescription("STRING", database));

    return CustomSqlGenerator.generateSql(database, UserSessionSettings.syncDdlStart(), createTableStatement, UserSessionSettings.syncDdlStop());
}
 
Example #6
Source Project: liquibase-percona   Author: adangel   File: PerconaAddColumnChange.java    License: Apache License 2.0 5 votes vote down vote up
String convertColumnToSql(AddColumnConfig column, Database database) {
    String nullable = "";
    ConstraintsConfig constraintsConfig = column.getConstraints();
    if (constraintsConfig != null && !constraintsConfig.isNullable()) {
        nullable = " NOT NULL";
    } else {
        nullable = " NULL";
    }
    String defaultValue =  "";
    if (column.getDefaultValueObject() != null) {
        defaultValue = " DEFAULT " + DataTypeFactory.getInstance().fromObject(column.getDefaultValueObject(), database).objectToSql(column.getDefaultValueObject(), database);
    }
    String comment = "";
    if (StringUtil.isNotEmpty(column.getRemarks())) {
        comment += " COMMENT '" + column.getRemarks() + "'";
    }
    String after = "";
    if (StringUtil.isNotEmpty(column.getAfterColumn())) {
        after += " AFTER " + database.escapeColumnName(null, null, null, column.getAfterColumn());
    }

    String constraints = "";
    constraints += addForeignKeyConstraint(column, database);
    constraints += addUniqueKeyConstraint(column, database);

    return "ADD COLUMN " + database.escapeColumnName(null, null, null, column.getName())
            + " " + DataTypeFactory.getInstance().fromDescription(column.getType(), database).toDatabaseDataType(database)
            + nullable
            + defaultValue
            + comment
            + after
            + constraints;
}
 
Example #7
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_CR1.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String realmClientTableName = database.correctObjectName("REALM_CLIENT", Table.class);

    try {
        String trueValue = DataTypeFactory.getInstance().getTrueBooleanValue(database);
        PreparedStatement statement = jdbcConnection.prepareStatement("select CLIENT.REALM_ID, CLIENT.ID CLIENT_ID from " + getTableName("CLIENT") + " CLIENT where CLIENT.CONSENT_REQUIRED = " + trueValue);

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String realmId = resultSet.getString("REALM_ID");
                    String oauthClientId = resultSet.getString("CLIENT_ID");

                    InsertStatement realmClientInsert = new InsertStatement(null, null, realmClientTableName)
                            .addColumnValue("REALM_ID", realmId)
                            .addColumnValue("CLIENT_ID", oauthClientId);
                    statements.add(realmClientInsert);
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Inserted " + statements.size() + " OAuth Clients to REALM_CLIENT table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #8
Source Project: liquibase-impala   Author: eselyavka   File: MetastoreAddColumnGenerator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected String generateSingleColumnSQL(AddColumnStatement statement, Database database) {
    DatabaseDataType databaseColumnType = DataTypeFactory.getInstance().fromDescription(statement.getColumnType(), database).toDatabaseDataType(database);
    return " ADD COLUMNS (" + database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), statement.getColumnName()) + " " + databaseColumnType + ")";
}
 
Example #9
Source Project: liquibase-impala   Author: eselyavka   File: ImpalaAddColumnGenerator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected String generateSingleColumnSQL(AddColumnStatement statement, Database database) {
    DatabaseDataType databaseColumnType = DataTypeFactory.getInstance().fromDescription(statement.getColumnType(), database).toDatabaseDataType(database);
    return " ADD COLUMNS (" + database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), statement.getColumnName()) + " " + databaseColumnType + ")";
}
 
Example #10
Source Project: liquibase-spatial   Author: lonnyj   File: AddGeometryColumnGeneratorGeoDB.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Sql[] generateSql(final AddColumnStatement statement,
      final Database database, final SqlGeneratorChain sqlGeneratorChain) {

   GeometryType geometryType = null;
   final LiquibaseDataType dataType = DataTypeFactory.getInstance()
         .fromDescription(statement.getColumnType(), database);
   if (dataType instanceof GeometryType) {
      geometryType = (GeometryType) dataType;
   }

   final boolean isGeometryColumn = geometryType != null;

   // The AddGeometryColumn procedure handles the column already being
   // present, so let a
   // downstream SQL generator handle the typical column addition logic (e.g.
   // placement in the
   // table) then invoke the procedure.
   final List<Sql> list = new ArrayList<Sql>();
   list.addAll(Arrays.asList(sqlGeneratorChain.generateSql(statement,
         database)));
   if (isGeometryColumn) {
      String schemaName = statement.getSchemaName();
      if (schemaName == null) {
         schemaName = database.getDefaultSchemaName();
      }
      final String tableName = statement.getTableName();
      final String columnName = statement.getColumnName();

      final int srid = geometryType.getSRID();
      final String geomType = StringUtils.trimToNull(geometryType
            .getGeometryType()) == null ? "'Geometry'" : "'"
            + database.escapeStringForDatabase(geometryType
                  .getGeometryType()) + "'";
      final String sql = "CALL AddGeometryColumn('" + schemaName + "', '"
            + tableName + "', '" + columnName + "', " + srid + ", "
            + geomType + ", 2)";
      final Sql addGeometryColumn = new UnparsedSql(sql);
      list.add(addGeometryColumn);
   }
   return list.toArray(new Sql[list.size()]);
}
 
Example #11
Source Project: keycloak   Author: keycloak   File: DefaultLiquibaseConnectionProvider.java    License: Apache License 2.0 4 votes vote down vote up
protected void baseLiquibaseInitialization() {
    ServiceLocator sl = ServiceLocator.getInstance();
    sl.setResourceAccessor(new ClassLoaderResourceAccessor(getClass().getClassLoader()));

    if (!System.getProperties().containsKey("liquibase.scan.packages")) {
        if (sl.getPackages().remove("liquibase.core")) {
            sl.addPackageToScan("liquibase.core.xml");
        }

        if (sl.getPackages().remove("liquibase.parser")) {
            sl.addPackageToScan("liquibase.parser.core.xml");
        }

        if (sl.getPackages().remove("liquibase.serializer")) {
            sl.addPackageToScan("liquibase.serializer.core.xml");
        }

        sl.getPackages().remove("liquibase.ext");
        sl.getPackages().remove("liquibase.sdk");

        String lockPackageName = DummyLockService.class.getPackage().getName();
        logger.debugf("Added package %s to liquibase", lockPackageName);
        sl.addPackageToScan(lockPackageName);
    }

    LogFactory.setInstance(new LogWrapper());

    // Adding PostgresPlus support to liquibase
    DatabaseFactory.getInstance().register(new PostgresPlusDatabase());
    // Adding newer version of MySQL/MariaDB support to liquibase
    DatabaseFactory.getInstance().register(new UpdatedMySqlDatabase());
    DatabaseFactory.getInstance().register(new UpdatedMariaDBDatabase());

    // Adding CustomVarcharType for MySQL 8 and newer
    DataTypeFactory.getInstance().register(MySQL8VarcharType.class);

    // Change command for creating lock and drop DELETE lock record from it
    SqlGeneratorFactory.getInstance().register(new CustomInsertLockRecordGenerator());

    // Use "SELECT FOR UPDATE" for locking database
    SqlGeneratorFactory.getInstance().register(new CustomLockDatabaseChangeLogGenerator());
}
 
Example #12
Source Project: keycloak   Author: keycloak   File: QuarkusLiquibaseConnectionProvider.java    License: Apache License 2.0 4 votes vote down vote up
protected void baseLiquibaseInitialization(KeycloakSession session) {
    resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader());
    FastServiceLocator locator = (FastServiceLocator) ServiceLocator.getInstance();

    JpaConnectionProviderFactory jpaConnectionProvider = (JpaConnectionProviderFactory) session
            .getKeycloakSessionFactory().getProviderFactory(JpaConnectionProvider.class);

    // register our custom databases
    locator.register(new PostgresPlusDatabase());
    locator.register(new UpdatedMySqlDatabase());
    locator.register(new UpdatedMariaDBDatabase());
    
    // registers only the database we are using
    try (Connection connection = jpaConnectionProvider.getConnection()) {
        Database database = DatabaseFactory.getInstance()
                .findCorrectDatabaseImplementation(new JdbcConnection(connection));
        if (database.getDatabaseProductName().equals(MySQLDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        } else if (database.getDatabaseProductName().equals(MariaDBDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        }

        DatabaseFactory.getInstance().clearRegistry();
        locator.register(database);
    } catch (Exception cause) {
        throw new RuntimeException("Failed to configure Liquibase database", cause);
    }

    // disables XML validation
    for (ChangeLogParser parser : ChangeLogParserFactory.getInstance().getParsers()) {
        if (parser instanceof XMLChangeLogSAXParser) {
            Method getSaxParserFactory = null;
            try {
                getSaxParserFactory = XMLChangeLogSAXParser.class.getDeclaredMethod("getSaxParserFactory");
                getSaxParserFactory.setAccessible(true);
                SAXParserFactory saxParserFactory = (SAXParserFactory) getSaxParserFactory.invoke(parser);
                saxParserFactory.setValidating(false);
                saxParserFactory.setSchema(null);
            } catch (Exception e) {
                logger.warnf("Failed to disable liquibase XML validations");
            } finally {
                if (getSaxParserFactory != null) {
                    getSaxParserFactory.setAccessible(false);
                }
            }
        }
    }
}