liquibase.database.core.MySQLDatabase Java Examples

The following examples show how to use liquibase.database.core.MySQLDatabase. 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 File: AbstractPerconaChangeTest.java    From liquibase-percona with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setup() {
    System.setProperty(Configuration.LIQUIBASE_PASSWORD, "root");

    database = new MySQLDatabase();
    database.setLiquibaseSchemaName("testdb");
    DatabaseConnection conn = new MockDatabaseConnection("jdbc:mysql://user@localhost:3306/testdb",
            "user@localhost");
    database.setConnection(conn);
    JdbcExecutor executor = new JdbcExecutor();
    executor.setDatabase(database);
    ExecutorService.getInstance().setExecutor(database, executor);

    PTOnlineSchemaChangeStatement.available = true;
    PTOnlineSchemaChangeStatement.perconaToolkitVersion = null;
    System.setProperty(Configuration.FAIL_IF_NO_PT, "false");
    System.setProperty(Configuration.NO_ALTER_SQL_DRY_MODE, "false");
    System.setProperty(Configuration.SKIP_CHANGES, "");

    PerconaForeignKeyService.getInstance().disable();

    setupChange(change);
}
 
Example #2
Source File: DropSpatialIndexChange.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a {@link DropSpatialIndexStatement} followed by a {@link DropIndexStatement}, if
 * applicable. The first statement allows extra clean-up when dropping an index. The second
 * statement leverages the normal <code>DROP INDEX</code> logic.
 */
@Override
public SqlStatement[] generateStatements(final Database database) {
   final Collection<SqlStatement> statements = new ArrayList<SqlStatement>();
   // MySQL and PostgreSQL only need the normal DROP INDEX statement.
   if (!(database instanceof MySQLDatabase) && !(database instanceof PostgresDatabase)) {
      final DropSpatialIndexStatement dropSpatialIndex = new DropSpatialIndexStatement(
            this.indexName, this.catalogName, this.schemaName, this.tableName);
      statements.add(dropSpatialIndex);
   }

   // GeoDB doesn't use a tradition index structure so don't issue the normal DROP INDEX
   // statement.
   if (!(database instanceof DerbyDatabase) && !(database instanceof H2Database)) {
      final DropIndexStatement dropIndex = new DropIndexStatement(this.indexName,
            this.catalogName, this.schemaName, this.tableName, null);
      statements.add(dropIndex);
   }
   return statements.toArray(new SqlStatement[statements.size()]);
}
 
Example #3
Source File: CreateSpatialIndexGeneratorMySQLTest.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * Tests
 * {@link CreateSpatialIndexGeneratorMySQL#generateSql(CreateSpatialIndexStatement, Database, SqlGeneratorChain)}
 * with a variety of inputs.
 * 
 * @param statement
 */
@Test(dataProvider = "generateSqlTestData")
public void testGenerateSql(final CreateSpatialIndexStatement statement) {
   final CreateSpatialIndexGeneratorMySQL generator = new CreateSpatialIndexGeneratorMySQL();
   final Database database = new MySQLDatabase();
   final SqlGeneratorChain sqlGeneratorChain = mock(SqlGeneratorChain.class);
   final Sql[] result = generator.generateSql(statement, database, sqlGeneratorChain);
   assertNotNull(result);
   assertEquals(result.length, 1);
   final String sql = result[0].toSql();
   String pattern = "(?i)CREATE SPATIAL INDEX " + statement.getIndexName() + " ON ";
   if (statement.getTableCatalogName() != null) {
      pattern += statement.getTableCatalogName() + '.';
   } else if (statement.getTableSchemaName() != null) {
      pattern += statement.getTableSchemaName() + '.';
   }
   pattern += statement.getTableName() + "\\(" + statement.getColumns()[0] + "\\)";
   assertTrue(sql.matches(pattern), "'" + sql + "' does not match the pattern '" + pattern + "'");
   assertNotNull(result[0].getAffectedDatabaseObjects());
   assertTrue(result[0].getAffectedDatabaseObjects().size() > 1, result[0]
         .getAffectedDatabaseObjects().toString());
}
 
Example #4
Source File: PTOnlineSchemaChangeStatementTest.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    System.setProperty(Configuration.LIQUIBASE_PASSWORD, "root");

    database = new MySQLDatabase();
    database.setLiquibaseSchemaName("testdb");
    DatabaseConnection conn = new MockDatabaseConnection("jdbc:mysql://user@localhost:3306/testdb",
            "user@localhost");
    database.setConnection(conn);
}
 
Example #5
Source File: SpatialSupportedPrecondition.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
@Override
public Warnings warn(final Database database) {
   final Warnings warnings = new Warnings();
   if (!(database instanceof DerbyDatabase || database instanceof H2Database
         || database instanceof MySQLDatabase || database instanceof OracleDatabase || database instanceof PostgresDatabase)) {
      warnings.addWarning(database.getDatabaseProductName()
            + " is not supported by this extension");
   }
   return warnings;
}
 
Example #6
Source File: SpatialSupportedPrecondition.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
@Override
public ValidationErrors validate(final Database database) {
   final ValidationErrors errors = new ValidationErrors();
   if (!(database instanceof DerbyDatabase || database instanceof H2Database
         || database instanceof MySQLDatabase || database instanceof OracleDatabase || database instanceof PostgresDatabase)) {
      errors.addError(database.getDatabaseProductName() + " is not supported by this extension");
   }
   return errors;
}
 
Example #7
Source File: CreateSpatialIndexGeneratorMySQLTest.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link CreateSpatialIndexGeneratorMySQL#supports(CreateSpatialIndexStatement, Database)}
 */
@Test
public void testSupports() {
   final CreateSpatialIndexGeneratorMySQL generator = new CreateSpatialIndexGeneratorMySQL();
   final CreateSpatialIndexStatement statement = mock(CreateSpatialIndexStatement.class);
   assertTrue(generator.supports(statement, new MySQLDatabase()));
   assertFalse(generator.supports(statement, new H2Database()));
}
 
Example #8
Source File: CustomLockDatabaseChangeLogGenerator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Sql generateSelectForUpdate(Database database, int id) {
    String catalog = database.getLiquibaseCatalogName();
    String schema = database.getLiquibaseSchemaName();
    String rawLockTableName = database.getDatabaseChangeLogLockTableName();

    String lockTableName = database.escapeTableName(catalog, schema, rawLockTableName);
    String idColumnName  = database.escapeColumnName(catalog, schema, rawLockTableName, "ID");

    String sqlBase = "SELECT " + idColumnName + " FROM " + lockTableName;
    String sqlWhere = " WHERE " + idColumnName + "=" + id;

    String sql;
    if (database instanceof MySQLDatabase || database instanceof PostgresDatabase || database instanceof H2Database ||
            database instanceof OracleDatabase) {
        sql = sqlBase + sqlWhere + " FOR UPDATE";
    } else if (database instanceof MSSQLDatabase) {
        sql = sqlBase + " WITH (UPDLOCK, ROWLOCK)" + sqlWhere;
    } else if (database instanceof DB2Database) {
        sql = sqlBase + sqlWhere +  " FOR READ ONLY WITH RS USE AND KEEP UPDATE LOCKS";
    } else {
        sql = sqlBase + sqlWhere;
        logger.warnf("No direct support for database %s . Database lock may not work correctly", database.getClass().getName());
    }

    logger.debugf("SQL command for pessimistic lock: %s", sql);
    
    return new UnparsedSql(sql);
}
 
Example #9
Source File: MySQL8VarcharType.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
    if (database instanceof MySQLDatabase) {
        try {
            if (database.getDatabaseMajorVersion() >= 8 && getSize() > 255) {
                return new DatabaseDataType(database.escapeDataTypeName("TEXT"), getSize());
            }
        } catch (DatabaseException e) {
            throw new RuntimeException(e);
        }
    }
    return super.toDatabaseDataType(database);
}
 
Example #10
Source File: PerconaChangeUtil.java    From liquibase-percona with Apache License 2.0 4 votes vote down vote up
public static SqlStatement[] generateStatements(PerconaChange change,
        Database database, SqlStatement[] originalStatements) {

    String changeSetId = "unknown changeset id";
    if (change instanceof Change) {
        ChangeSet changeSet = ((Change)change).getChangeSet();
        if (changeSet != null) {
            changeSetId = changeSet.getId() + ":" + changeSet.getAuthor();
        }
    }

    if (change.getUsePercona() == null && !Configuration.getDefaultOn()) {
        log.debug("Not using percona toolkit, because property " + Configuration.DEFAULT_ON + " is false. " + changeSetId + ":" + change.getChangeName());
        return originalStatements;
    }
    if (change.getUsePercona() != null && !change.getUsePercona()) {
        log.debug("Not using percona toolkit, because usePercona flag is false for " + changeSetId + ":" + change.getChangeName());
        return originalStatements;
    }
    if (Configuration.skipChange(change.getChangeName())) {
        maybeLog("Not using percona toolkit, because skipChange for "
                + change.getChangeName() + " is active (property: " + Configuration.SKIP_CHANGES + ")!");
        return originalStatements;
    }

    List<SqlStatement> statements = new ArrayList<SqlStatement>(Arrays.asList(originalStatements));

    if (database instanceof MySQLDatabase) {
        if (PTOnlineSchemaChangeStatement.isAvailable()) {
            PTOnlineSchemaChangeStatement statement = new PTOnlineSchemaChangeStatement(
                    change.getTargetDatabaseName(),
                    change.getTargetTableName(),
                    change.generateAlterStatement(database));

            if (isDryRun(database)) {
                CommentStatement commentStatement = new CommentStatement(statement.printCommand(database));

                if (Configuration.noAlterSqlDryMode()) {
                    statements.clear();
                    statements.add(0, commentStatement);
                } else {
                    statements.add(0, commentStatement);
                    statements.add(1, new CommentStatement("Instead of the following statements, pt-online-schema-change will be used"));
                }
            } else {
                statements.clear();
                statements.add(statement);
            }
        } else {
            if (Configuration.failIfNoPT()) {
                throw new RuntimeException("No percona toolkit found!");
            }
            maybeLog("Not using percona toolkit, because it is not available!");
        }
    }

    return statements.toArray(new SqlStatement[statements.size()]);
}
 
Example #11
Source File: SpatialUpdateGeneratorMySQL.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(final UpdateStatement statement, final Database database) {
   return database instanceof MySQLDatabase;
}
 
Example #12
Source File: SpatialInsertGeneratorMySQL.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(final InsertStatement statement, final Database database) {
   return database instanceof MySQLDatabase;
}
 
Example #13
Source File: CreateSpatialIndexGeneratorMySQL.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(final CreateSpatialIndexStatement statement, final Database database) {
   return database instanceof MySQLDatabase;
}
 
Example #14
Source File: QuarkusLiquibaseConnectionProvider.java    From keycloak with 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);
                }
            }
        }
    }
}