public static void connectToDB() throws Exception {
    if (connection == null) {
      info = new Properties();
      info.load(new FileInputStream("src/java-test/tests.properties"));

      url = info.getProperty("url");
      driver =
          (Driver)
              Class.forName(
                      DatabaseFactory.getInstance().findDefaultDriver(url),
                      true,
                      Thread.currentThread().getContextClassLoader())
                  .newInstance();

      connection = driver.connect(url, info);

      if (connection == null) {
        throw new DatabaseException(
            "Connection could not be created to "
                + url
                + " with driver "
                + driver.getClass().getName()
                + ".  Possibly the wrong driver for the given database URL");
      }

      jdbcConnection = new JdbcConnection(connection);
    }
  }
  public static void main(String[] args) {

    VerticaDatabase verticaDatabase = new VerticaDatabase();
    liquibase.database.DatabaseFactory.getInstance().register(verticaDatabase);
    liquibase.snapshot.SnapshotGeneratorFactory.getInstance()
        .unregister(UniqueConstraintSnapshotGenerator.class);
    ChangeGeneratorFactory.getInstance().unregister(MissingColumnChangeGenerator.class);
    Properties myProp = new Properties();

    String defaultCatalogName = "yaron_secondary";
    String defaultSchemaName = defaultCatalogName;
    String password = defaultCatalogName + "_123";
    String changeLogFilePath = "c:\\liquibaseChangeSet.xml";
    String dataOutputDirectory = "c:\\liquibase_output";
    String connectionString = "jdbc:vertica://mydphdb0082.hpswlabs.adapps.hp.com:5433/eummobile";
    String changeSetAuthor = "jony";

    myProp.put("user", defaultCatalogName);
    myProp.put("password", password);

    Connection conn = null;
    try {
      File changeLogFile = new File(changeLogFilePath);
      changeLogFile.delete();

      conn = DriverManager.getConnection(connectionString, myProp);
      conn.setAutoCommit(false);
      DatabaseConnection dc = new JdbcConnection(conn);
      verticaDatabase.setConnection(dc);
      String diffTypes = null;
      String changeSetContext = null;
      boolean includeCatalog =
          false; // Boolean.parseBoolean(getCommandParam("includeCatalog", "false"));
      boolean includeSchema =
          false; // Boolean.parseBoolean(getCommandParam("includeSchema", "false"));
      boolean includeTablespace =
          false; // Boolean.parseBoolean(getCommandParam("includeTablespace", "false"));
      DiffOutputControl diffOutputControl =
          new DiffOutputControl(includeCatalog, includeSchema, includeTablespace);
      CommandLineUtils.doGenerateChangeLog(
          changeLogFilePath,
          verticaDatabase,
          defaultCatalogName,
          defaultSchemaName,
          StringUtils.trimToNull(diffTypes),
          StringUtils.trimToNull(changeSetAuthor),
          StringUtils.trimToNull(changeSetContext),
          StringUtils.trimToNull(dataOutputDirectory),
          diffOutputControl);
      postChangeSetGenerationProcessing(changeLogFile);
    } catch (Exception e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
  }
Exemple #3
0
  private static void initDB() throws LiquibaseException {
    Database database =
        DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(conn));

    // TODO: We should not point to a relative file outside of the project.
    liquibase =
        new Liquibase(
            "../task-management/src/main/resources/db/changelog/db.changelog-1.0.0.xml",
            new FileSystemResourceAccessor(),
            database);
    liquibase.update((String) null);
  }
  private void runLiquibaseUpdate(Connection connection) {
    try {
      ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor();
      Database database =
          DatabaseFactory.getInstance()
              .findCorrectDatabaseImplementation(new JdbcConnection(connection));
      Liquibase liquibase = new Liquibase(getChangeLogFile(), resourceAccessor, database);

      liquibase.update(getContext());
    } catch (LiquibaseException e) {
      throw new RuntimeException(e);
    }
  }
 private Liquibase newLiquibase(Application application)
     throws ClassNotFoundException, SQLException, LiquibaseException {
   JDBC jdbc = application.plugin(JDBC.class);
   Connection connection =
       application.config().has("liquibase.datasource")
           ? jdbc.connection(application.config().string("liquibase.datasource"))
           : jdbc.connection();
   Liquibase liquibase =
       new Liquibase(
           application.config().string("liquibase.changelog"),
           new ClassLoaderResourceAccessor(application.classLoader()),
           DatabaseFactory.getInstance()
               .findCorrectDatabaseImplementation(new JdbcConnection(connection)));
   return liquibase;
 }
  @Test
  public void lessThanMinimumFails() throws Exception {
    ChangeFactory changeFactory = ChangeFactory.getInstance();
    for (String changeName : changeFactory.getDefinedChanges()) {
      for (Database database : DatabaseFactory.getInstance().getImplementedDatabases()) {
        if (database.getShortName() == null) {
          continue;
        }

        Change change = changeFactory.create(changeName);
        if (!change.supports(database)) {
          continue;
        }
        if (change.generateStatementsVolatile(database)) {
          continue;
        }
        ChangeMetaData changeMetaData = ChangeFactory.getInstance().getChangeMetaData(change);

        change.setResourceAccessor(new JUnitResourceAccessor());

        ArrayList<String> requiredParams =
            new ArrayList<String>(changeMetaData.getRequiredParameters(database).keySet());
        for (String paramName : requiredParams) {
          ChangeParameterMetaData param = changeMetaData.getParameters().get(paramName);
          Object paramValue = param.getExampleValue();
          param.setValue(change, paramValue);
        }

        for (int i = 0; i < requiredParams.size(); i++) {
          String paramToRemove = requiredParams.get(i);
          ChangeParameterMetaData paramToRemoveMetadata =
              changeMetaData.getParameters().get(paramToRemove);
          Object currentValue = paramToRemoveMetadata.getCurrentValue(change);
          paramToRemoveMetadata.setValue(change, null);

          assertTrue(
              "No errors even with "
                  + changeMetaData.getName()
                  + " with a null "
                  + paramToRemove
                  + " on "
                  + database.getShortName(),
              change.validate(database).hasErrors());
          paramToRemoveMetadata.setValue(change, currentValue);
        }
      }
    }
  }
 public void checkSchema(String schema) throws LiquibaseException {
   Connection connection = resolveConnection();
   ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
   ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(classLoader);
   Database database =
       DatabaseFactory.getInstance()
           .findCorrectDatabaseImplementation(new JdbcConnection(connection));
   Liquibase liquibase = new Liquibase(schema, resourceAccessor, database);
   liquibase.forceReleaseLocks();
   LOG.info("Comprobando actualizaciones de esquema de BBDD");
   liquibase.update("");
   LOG.info("Comprobacion de esquema de BBDD finalizada");
   try {
     connection.close();
   } catch (SQLException ignore) {
   }
 }
 public void contextInitialized(ServletContextEvent arg0) {
   try {
     ConfigDBMapper.getInstance().setDefaultConnectionName("fatec");
     Connection conn = ConfigDBMapper.getInstance().getDefaultConnection();
     Database database =
         DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(conn));
     Liquibase liquibase =
         new Liquibase(
             "br/com/fatec/aulas/liquibase/changelog-master.xml",
             new ClassLoaderResourceAccessor(),
             database);
     liquibase.forceReleaseLocks();
     liquibase.update("fatec");
     conn.prepareStatement("COMMIT;").execute();
   } catch (Exception e) {
     // TODO: handle exception
   }
 }
  public TestController() {
    System.err.println("============= Nyitas =================");
    context = new ContextService(ContextService.EJBTYPE.SERVER);

    // ----------------------
    // Gain the database
    // ----------------------
    DataSource ds;
    try {
      ds = context.getDatabase();
      conn = ds.getConnection();
      database =
          DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(conn));
    } catch (NamingException | DatabaseException | SQLException e) {
      // e.printStackTrace();
      throw new Error(e);
    }
  }
  public DatabaseUpgradeTestUtil(String initialDatabasePath) throws IOException, SQLException {
    InputStream databaseInputStream = getClass().getResourceAsStream(initialDatabasePath);

    tempDir = File.createTempFile("openmrs-tests-temp-", "");
    tempDir.delete();
    tempDir.mkdir();
    tempDir.deleteOnExit();

    tempDBFile = new File(tempDir, "openmrs.h2.db");
    tempDBFile.delete();
    try {
      tempDBFile.createNewFile();
    } catch (IOException e) {
      tempDir.delete();
      throw e;
    }
    tempDBFile.deleteOnExit();

    FileOutputStream tempDBOutputStream = new FileOutputStream(tempDBFile);

    try {
      IOUtils.copy(databaseInputStream, tempDBOutputStream);

      databaseInputStream.close();
      tempDBOutputStream.close();
    } catch (IOException e) {
      tempDBFile.delete();
      tempDir.delete();

      throw e;
    } finally {
      IOUtils.closeQuietly(databaseInputStream);
      IOUtils.closeQuietly(tempDBOutputStream);
    }

    String databaseUrl = tempDir.getAbsolutePath().replace("\\", "/") + "/openmrs";

    connectionUrl = "jdbc:h2:" + databaseUrl + ";AUTO_RECONNECT=TRUE;DB_CLOSE_DELAY=-1";

    connection = DriverManager.getConnection(connectionUrl, "sa", "sa");
    connection.setAutoCommit(true);

    try {
      liqubaseConnection =
          DatabaseFactory.getInstance()
              .findCorrectDatabaseImplementation(new JdbcConnection(connection));
      liqubaseConnection.setDatabaseChangeLogTableName("LIQUIBASECHANGELOG");
      liqubaseConnection.setDatabaseChangeLogLockTableName("LIQUIBASECHANGELOGLOCK");
    } catch (LiquibaseException e) {
      tempDir.delete();
      tempDBFile.delete();

      throw new SQLException(e);
    }

    try {
      dbUnitConnection = new DatabaseConnection(connection);
      dbUnitConnection
          .getConfig()
          .setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new H2DataTypeFactory());
    } catch (DatabaseUnitException e) {
      tempDir.delete();
      tempDBFile.delete();

      throw new SQLException(e);
    }
  }
  @Test
  public void minimumRequiredIsValidSql() throws Exception {
    ChangeFactory changeFactory = ChangeFactory.getInstance();
    for (String changeName : changeFactory.getDefinedChanges()) {
      if (changeName.equals("addDefaultValue")) {
        continue; // need to better handle strange "one of defaultValue* is required" logic
      }
      if (changeName.equals("changeWithNestedTags") || changeName.equals("sampleChange")) {
        continue; // not a real change
      }
      for (Database database : DatabaseFactory.getInstance().getImplementedDatabases()) {
        if (database.getShortName() == null) {
          continue;
        }

        TestState state =
            new TestState(
                name.getMethodName(), changeName, database.getShortName(), TestState.Type.SQL);
        state.addComment("Database: " + database.getShortName());

        Change change = changeFactory.create(changeName);
        if (!change.supports(database)) {
          continue;
        }
        if (change.generateStatementsVolatile(database)) {
          continue;
        }
        ChangeMetaData changeMetaData = ChangeFactory.getInstance().getChangeMetaData(change);

        change.setResourceAccessor(new JUnitResourceAccessor());

        for (String paramName :
            new TreeSet<String>(changeMetaData.getRequiredParameters(database).keySet())) {
          ChangeParameterMetaData param = changeMetaData.getParameters().get(paramName);
          Object paramValue = param.getExampleValue();
          String serializedValue;
          serializedValue = formatParameter(paramValue);
          state.addComment("Change Parameter: " + param.getParameterName() + "=" + serializedValue);
          param.setValue(change, paramValue);
        }

        ValidationErrors errors = change.validate(database);
        assertFalse(
            "Validation errors for "
                + changeMetaData.getName()
                + " on "
                + database.getShortName()
                + ": "
                + errors.toString(),
            errors.hasErrors());

        SqlStatement[] sqlStatements = change.generateStatements(database);
        for (SqlStatement statement : sqlStatements) {
          Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
          if (sql == null) {
            System.out.println("Null sql for " + statement + " on " + database.getShortName());
          } else {
            for (Sql line : sql) {
              String sqlLine = line.toSql();
              assertFalse(
                  "Change "
                      + changeMetaData.getName()
                      + " contains 'null' for "
                      + database.getShortName()
                      + ": "
                      + sqlLine,
                  sqlLine.contains(" null "));

              state.addValue(sqlLine + ";");
            }
          }
        }
        state.test();
      }
    }
  }
  @Test
  public void extraParamsIsValidSql() throws Exception {
    ChangeFactory changeFactory = ChangeFactory.getInstance();
    for (String changeName : changeFactory.getDefinedChanges()) {
      if (changeName.equals("addDefaultValue")) {
        continue; // need to better handle strange "one of defaultValue* is required" logic
      }

      for (Database database : DatabaseFactory.getInstance().getImplementedDatabases()) {
        if (database.getShortName() == null) {
          continue;
        }

        TestState state =
            new TestState(
                name.getMethodName(), changeName, database.getShortName(), TestState.Type.SQL);
        state.addComment("Database: " + database.getShortName());

        Change baseChange = changeFactory.create(changeName);
        if (!baseChange.supports(database)) {
          continue;
        }
        if (baseChange.generateStatementsVolatile(database)) {
          continue;
        }
        ChangeMetaData changeMetaData = ChangeFactory.getInstance().getChangeMetaData(baseChange);
        ArrayList<String> optionalParameters =
            new ArrayList<String>(changeMetaData.getOptionalParameters(database).keySet());
        Collections.sort(optionalParameters);

        List<List<String>> paramLists = powerSet(optionalParameters);
        Collections.sort(
            paramLists,
            new Comparator<List<String>>() {
              @Override
              public int compare(List<String> o1, List<String> o2) {
                int comp = Integer.valueOf(o1.size()).compareTo(o2.size());
                if (comp == 0) {
                  comp = StringUtils.join(o1, ",").compareTo(StringUtils.join(o2, ","));
                }
                return comp;
              }
            });
        for (List<String> permutation : paramLists) {
          Change change = changeFactory.create(changeName);
          change.setResourceAccessor(new JUnitResourceAccessor());
          //
          for (String paramName :
              new TreeSet<String>(changeMetaData.getRequiredParameters(database).keySet())) {
            ChangeParameterMetaData param = changeMetaData.getParameters().get(paramName);
            Object paramValue = param.getExampleValue();
            String serializedValue;
            serializedValue = formatParameter(paramValue);
            state.addComment(
                "Required Change Parameter: " + param.getParameterName() + "=" + serializedValue);
            param.setValue(change, paramValue);
          }

          for (String paramName : permutation) {
            ChangeParameterMetaData param = changeMetaData.getParameters().get(paramName);
            if (!param.supports(database)) {
              continue;
            }
            Object paramValue = param.getExampleValue();
            String serializedValue;
            serializedValue = formatParameter(paramValue);
            state.addComment(
                "Optional Change Parameter: " + param.getParameterName() + "=" + serializedValue);
            param.setValue(change, paramValue);
          }

          ValidationErrors errors = change.validate(database);
          assertFalse(
              "Validation errors for "
                  + changeMetaData.getName()
                  + " on "
                  + database.getShortName()
                  + ": "
                  + errors.toString(),
              errors.hasErrors());
          //
          //                    SqlStatement[] sqlStatements = change.generateStatements(database);
          //                    for (SqlStatement statement : sqlStatements) {
          //                        Sql[] sql =
          // SqlGeneratorFactory.getInstance().generateSql(statement, database);
          //                        if (sql == null) {
          //                            System.out.println("Null sql for "+statement+" on
          // "+database.getShortName());
          //                        } else {
          //                            for (Sql line : sql) {
          //                                state.addValue(line.toSql()+";");
          //                            }
          //                        }
          //                    }
          //                    state.test();
        }
      }
    }
  }