org.eclipse.collections.impl.factory.Lists Java Examples

The following examples show how to use org.eclipse.collections.impl.factory.Lists. 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: BaselineTableChangeParser.java    From obevo with Apache License 2.0 6 votes vote down vote up
private MutableList<String> sortSqls(MutableList<String> sqls) {
    MutableList<String> orderedSqls = Lists.mutable.empty();
    MutableList<String> fkSqls = Lists.mutable.empty();
    MutableList<String> triggerSqls = Lists.mutable.empty();

    for (String sql : sqls) {
        Matcher matcher = RegexpPatterns.fkPattern.matcher(sql);
        Matcher triggerMatcher = RegexpPatterns.triggerPattern.matcher(sql);
        if (matcher.find()) {
            fkSqls.add(sql);
        } else if (triggerMatcher.find()) {
            triggerSqls.add(sql);
        } else {
            orderedSqls.add(sql);
        }
    }

    orderedSqls.addAll(fkSqls);
    orderedSqls.addAll(triggerSqls);
    return orderedSqls;
}
 
Example #2
Source File: DAStringUtil.java    From obevo with Apache License 2.0 6 votes vote down vote up
/**
 * See {@link #normalizeWhiteSpaceFromString(String)}. This is the "old" version of that method, with a slightly
 * harder-to-read implementation. I want to switch to {@link #normalizeWhiteSpaceFromString(String)} as it is
 * a more standard implementation and thus easier to vet.
 */
public static String normalizeWhiteSpaceFromStringOld(String content) {
    if (content == null) {
        return null;
    }
    String[] lines = content.split("\\r?\\n");

    MutableList<String> newContent = Lists.mutable.empty();
    for (String line : lines) {
        line = line.trim();
        if (!line.isEmpty()) {
            line = line.replaceAll("\\s+", " ");
            newContent.add(line.trim());
        }
    }

    return newContent.makeString(" ").trim();
}
 
Example #3
Source File: DefaultRollbackDetectorTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetActiveDeploymentsWithRollback() throws Exception {
    assertEquals(Lists.immutable.with(3L), rollbackDetector.getActiveDeployments(Sets.immutable.with(
            newExecution(1, "a")
            , newExecution(2, "b")
            , newExecution(3, "a", true)  // we go back to a; hence, erasing the impact of b
    )).collect(new Function<DeployExecution, Long>() {
        @Override
        public Long valueOf(DeployExecution deployExecution1) {
            return deployExecution1.getId();
        }
    }));

    assertEquals(Lists.immutable.with(3L, 4L, 5L), rollbackDetector.getActiveDeployments(Sets.immutable.with(
            newExecution(1, "a")
            , newExecution(2, "b")
            , newExecution(3, "a", true)  // we go back to a; hence, erasing the impact of b
            , newExecution(4, "b")
            , newExecution(5, "c")
    )).collect(new Function<DeployExecution, Long>() {
        @Override
        public Long valueOf(DeployExecution deployExecution) {
            return deployExecution.getId();
        }
    }));
}
 
Example #4
Source File: AggregationActionTest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
@Test
void shouldCreateCompleteApi() {
    Run<?, ?> owner = mock(Run.class);
    List<ResultAction> actions = Lists.fixedSize.of(
            createAction(JobStubs.SPOT_BUGS_ID, JobStubs.SPOT_BUGS_NAME, SIZE),
            createAction(JobStubs.CHECK_STYLE_NAME, JobStubs.CHECK_STYLE_NAME, SIZE)
    );
    when(owner.getActions(any())).thenAnswer(i -> actions);
    AggregationAction action = new AggregationAction();
    action.onLoad(owner);

    Api api = action.getApi();
    AggregationApi aggregationApi = (AggregationApi) api.bean;

    assertThat(aggregationApi.getTools()).hasSize(2);

    List<ToolApi> actually = action.getTools();

    assertThat(actually).hasSize(2);
}
 
Example #5
Source File: GraphEnricherImplTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetChangesCaseInsensitive() {
    this.enricher = new GraphEnricherImpl(String::toUpperCase);
    String schema1 = "schema1";
    String schema2 = "schema2";
    String type1 = "type1";

    SortableDependencyGroup sp1 = newChange(schema1, type1, "SP1", "n/a", 0, Sets.immutable.with("sp2"));
    SortableDependencyGroup sp2 = newChange(schema1, type1, "SP2", Sets.immutable.<String>with());
    SortableDependencyGroup sp3 = newChange(schema1, type1, "SP3", Sets.immutable.with("sp1", "sp2"));
    SortableDependencyGroup spA = newChange(schema1, type1, "SPA", Sets.immutable.with("sp3"));
    SortableDependencyGroup sp1Schema2 = newChange(schema2, type1, "sp1", "n/a", 0, Sets.immutable.with("sp2", schema1 + ".sp3"));
    SortableDependencyGroup sp2Schema2 = newChange(schema2, type1, "sP2", "n/a", 0, Sets.immutable.<String>with());

    Graph<SortableDependencyGroup, DefaultEdge> sortGraph = enricher.createDependencyGraph(Lists.mutable.with(
            sp1, sp2, sp3, spA, sp1Schema2, sp2Schema2), false);

    validateChange(sortGraph, sp1, Sets.immutable.with(sp2), Sets.immutable.with(sp3));
    validateChange(sortGraph, sp2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sp1, sp3));
    validateChange(sortGraph, sp3, Sets.immutable.with(sp1, sp2), Sets.immutable.with(spA, sp1Schema2));
    validateChange(sortGraph, spA, Sets.immutable.with(sp3), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sp1Schema2, Sets.immutable.with(sp2Schema2, sp3), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sp2Schema2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sp1Schema2));
}
 
Example #6
Source File: AbstractMain.java    From obevo with Apache License 2.0 6 votes vote down vote up
private RichIterable<EnvType> getRequestedEnvironments(String sourcePath, String... envNames) {
    MutableCollection<EnvType> environments = getRequestedSystem(sourcePath);

    MutableList<EnvType> requestedEnvs = Lists.mutable.empty();

    if (envNames == null || envNames.length == 0) {
        requestedEnvs.add(readSingleEnvironment(environments, sourcePath));
    } else {
        for (EnvType sysEnv : environments) {
            for (String envPattern : envNames) {
                if (Pattern.compile(RegexUtil.convertWildcardPatternToRegex(envPattern))
                        .matcher(sysEnv.getName())
                        .matches()) {
                    requestedEnvs.add(sysEnv);
                }
            }
        }
    }

    if (requestedEnvs.isEmpty()) {
        throw new IllegalArgumentException("No environment with name/s "
                + Lists.mutable.with(envNames).makeString("(", ",", ")") + " found");
    }

    return requestedEnvs;
}
 
Example #7
Source File: HsqlReveng.java    From obevo with Apache License 2.0 6 votes vote down vote up
public HsqlReveng() {
    // Note - HSQL Export currently
    super(
            new HsqlDbPlatform(),
            null,
            Lists.immutable.<Predicate<String>>of(
                    StringPredicates.startsWith("SET DATABASE")
                    , StringPredicates.startsWith("SET FILES")
                    , StringPredicates.startsWith("SET SCHEMA")
                    , StringPredicates.startsWith("INSERT INTO")
                    , StringPredicates.startsWith("CREATE USER")
                    , StringPredicates.startsWith("ALTER USER")
                    , StringPredicates.startsWith("CREATE ROLE")
                    , StringPredicates.startsWith("CREATE SCHEMA")
                    , StringPredicates.startsWith("GRANT ")
                    , StringPredicates.startsWith("ALTER SEQUENCE SYSTEM_LOBS")
            ),
            getRevengPatterns(),
            null
    );
    setStartQuote(QUOTE);
    setEndQuote(QUOTE);
}
 
Example #8
Source File: CsvReaderDataSourceTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
private void verifyCsv(String input, MutableList<String> keyFields, MutableMap<String, String>... rows) throws Exception {
    CsvReaderDataSource ds = new CsvReaderDataSource(csvVersion, "test", new StringReader(input), ',', StringFunctions.toLowerCase(), "null");
    ds.setCatoConfiguration(new CatoSimpleJavaConfiguration(new SimpleCatoProperties(keyFields)));
    ds.init();
    ds.open();
    final MutableList<Map<String, Object>> dataRows = IteratorIterate.collect(ds, new Function<CatoDataObject, Map<String, Object>>() {
        @Override
        public Map<String, Object> valueOf(CatoDataObject catoDataObject) {
            Map<String, Object> data = Maps.mutable.empty();
            for (String field : catoDataObject.getFields()) {
                data.put(field, catoDataObject.getValue(field));
            }
            data.remove(CsvReaderDataSource.ROW_NUMBER_FIELD);

            return data;
        }
    }, Lists.mutable.<Map<String, Object>>empty());
    ds.close();

    assertEquals(rows.length, dataRows.size());
    for (int i = 0; i < dataRows.size(); i++) {
        assertEquals("Error on row " + i, rows[i], dataRows.get(i));
    }
}
 
Example #9
Source File: DefaultRollbackDetectorTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
/**
 * This is for some legacy edge cases where the product version column was not consistently updated.
 */
@Test
public void testWithNullVersionNames() throws Exception {
    assertEquals(Lists.immutable.with(0L, 3L, 7L, 8L), rollbackDetector.getActiveDeployments(Sets.immutable.with(
            newExecution(0, null)
            , newExecution(1, "a")
            , newExecution(2, null)
            , newExecution(3, "a", true)  // we go back to a; hence, erasing the impact of execution #2
            , newExecution(4, "c")
            , newExecution(5, "d")
            , newExecution(6, null)
            , newExecution(7, "c", true)
            , newExecution(8, null)
    )).collect(new Function<DeployExecution, Long>() {
        @Override
        public Long valueOf(DeployExecution deployExecution) {
            return deployExecution.getId();
        }
    }));
}
 
Example #10
Source File: RerunnableChangeTypeCommandCalculatorTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleViews() {
    Change view1Dep = new ChangeRerunnable(viewChangeType(), "schema", "viewA", "hash", CONTENT);
    Change view1Src = new ChangeRerunnable(viewChangeType(), "schema", "viewA", "hashdiff", CONTENT);
    Change view2Dep = new ChangeRerunnable(viewChangeType(), "schema", "viewB", "samehash", CONTENT);
    Change view2Src = new ChangeRerunnable(viewChangeType(), "schema", "viewB", "samehash", CONTENT);
    Change view3Dep = new ChangeRerunnable(viewChangeType(), "schema", "viewC", "deletion", CONTENT);
    Change view4Src = new ChangeRerunnable(viewChangeType(), "schema", "viewD", "addition", CONTENT);

    MutableList<Change> allSourceChanges = Lists.mutable.with(
            view1Src, view2Src, view4Src
    );

    ListIterable<ChangeCommand> changeset = cmdCalc.calculateCommands(viewChangeType(), Lists.mutable.of(
            new ChangePair(view1Src, view1Dep)
            , new ChangePair(view2Src, view2Dep)
            , new ChangePair(null, view3Dep)
            , new ChangePair(view4Src, null)
    ), allSourceChanges, false);

    assertEquals(3, changeset.size());
    Verify.assertAnySatisfy(changeset, assertValue(DeployChangeCommand.class, view1Src));
    Verify.assertAnySatisfy(changeset, assertValue(DeployChangeCommand.class, view4Src));
    Verify.assertAnySatisfy(changeset, assertValue(DropObjectChangeCommand.class, view3Dep));
}
 
Example #11
Source File: OfficialLeelazAnalyzerV1.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
Rule EngineLine() {
    return Sequence(
            String("info"), pushInitialValueMap()
            , Spaces()
            , String("move")
            , Spaces()
            , Move(), saveMatchToValueMap("MOVE")
            , Spaces()
            , String("visits")
            , Spaces()
            , IntNumber(), saveMatchToValueMap("CALCULATION")
            , Spaces()
            , String("winrate")
            , Spaces()
            , DoubleNumber(), saveMatchToValueMap("VALUE")
            , Optional(
                    Spaces()
                    , FirstOf(String("network"), String("N"))
                    , Spaces()
                    , DoubleNumber(), saveMatchToValueMap("POLICY")
            )
            , Spaces()
            , String("pv"), saveAttrToValueMap("PV", Lists.mutable.empty())
            , ZeroOrMore(Sequence(Spaces(), Move(), pushMatchToList("PV")))
    );
}
 
Example #12
Source File: HsqlReveng.java    From obevo with Apache License 2.0 6 votes vote down vote up
private static ImmutableList<RevengPattern> getRevengPatterns() {
    String schemaNameSubPattern = getSchemaObjectPattern(QUOTE, QUOTE);
    String schemaSysNamePattern = getSchemaObjectWithPrefixPattern(QUOTE, QUOTE, "SYS_");
    NamePatternType namePatternType = RevengPattern.NamePatternType.TWO;
    return Lists.immutable.with(
            new RevengPattern(ChangeType.SEQUENCE_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?sequence\\s+" + schemaNameSubPattern).withPostProcessSql(REPLACE_TABLESPACE).withPostProcessSql(REMOVE_QUOTES),
            new RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)create\\s+(?:memory\\s+)table\\s+" + schemaNameSubPattern).withPostProcessSql(REPLACE_TABLESPACE).withPostProcessSql(REMOVE_QUOTES),
            new RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)alter\\s+table\\s+" + schemaNameSubPattern).withPostProcessSql(REMOVE_QUOTES),
            new RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)create\\s+unique\\s+index\\s+" + schemaSysNamePattern + "\\s+on\\s+" + schemaNameSubPattern, 2, 1, "excludeEnvs=\"%\" comment=\"this_is_potentially_a_redundant_primaryKey_index_please_double_check\"").withPostProcessSql(REPLACE_TABLESPACE).withPostProcessSql(REMOVE_QUOTES),
            new RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)create\\s+(?:unique\\s+)index\\s+" + schemaNameSubPattern + "\\s+on\\s+" + schemaNameSubPattern, 2, 1, "INDEX").withPostProcessSql(REPLACE_TABLESPACE).withPostProcessSql(REMOVE_QUOTES),
            new RevengPattern(ChangeType.FUNCTION_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?(?:force\\s+)?(?:editionable\\s+)?function\\s+" + schemaNameSubPattern),
            new RevengPattern(ChangeType.VIEW_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?(?:force\\s+)?(?:editionable\\s+)?view\\s+" + schemaNameSubPattern),
            new RevengPattern(ChangeType.SP_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?procedure\\s+" + schemaNameSubPattern),
            new RevengPattern(ChangeType.USERTYPE_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?type\\s+" + schemaNameSubPattern),
            new RevengPattern(ChangeType.TRIGGER_STR, namePatternType, "(?i)create\\s+or\\s+replace\\s+trigger\\s+" + schemaNameSubPattern)
    );
    //CREATE TYPE SCHEMA1.BOOLEAN2 AS SMALLINT
}
 
Example #13
Source File: GraphEnricherImplTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Test
public void testCycleValidation() {
    this.enricher = new GraphEnricherImpl(Functions.getStringPassThru()::valueOf);

    SortableDependencyGroup cyc1Obj1 = newChange(schema1, type1, "cyc1Obj1", Sets.immutable.with(schema2 + ".cyc1Obj3"));
    SortableDependencyGroup cyc1Obj2 = newChange(schema1, type2, "cyc1Obj2", Sets.immutable.with("cyc1Obj1"));
    SortableDependencyGroup cyc1Obj3 = newChange(schema2, type1, "cyc1Obj3", Sets.immutable.with(schema1 + ".cyc1Obj2", schema2 + ".cyc1Obj4", schema2 + ".notcyc1ObjB"));
    SortableDependencyGroup cyc1Obj4 = newChange(schema2, type1, "cyc1Obj4", Sets.immutable.with(schema2 + ".cyc1Obj5"));
    SortableDependencyGroup cyc1Obj5 = newChange(schema2, type1, "cyc1Obj5", Sets.immutable.with(schema2 + ".cyc1Obj3"));
    SortableDependencyGroup notcyc1ObjA = newChange(schema2, type1, "notcyc1ObjA", Sets.immutable.with(schema2 + ".cyc1Obj3"));  // inbound edge to cycle, but not in it
    SortableDependencyGroup notcyc1ObjB = newChange(schema2, type1, "notcyc1ObjB", Sets.immutable.<String>with());  // outbound edge from cycle, but not in it
    SortableDependencyGroup cyc2Obj1 = newChange(schema2, type1, "cyc2Obj1", Sets.immutable.with(schema2 + ".cyc2Obj2"));
    SortableDependencyGroup cyc2Obj2 = newChange(schema2, type1, "cyc2Obj2", Sets.immutable.with(schema2 + ".cyc2Obj3"));
    SortableDependencyGroup cyc2Obj3 = newChange(schema2, type1, "cyc2Obj3", Sets.immutable.with(schema2 + ".cyc2Obj1"));
    SortableDependencyGroup loneObj1 = newChange(schema2, type1, "loneObj1", Sets.immutable.<String>with());

    try {
        enricher.createDependencyGraph(Lists.mutable.with(
                cyc1Obj1, cyc1Obj2, cyc1Obj3, cyc1Obj4, cyc1Obj5, notcyc1ObjA, notcyc1ObjB, cyc2Obj1, cyc2Obj2, cyc2Obj3, loneObj1), false);
        fail("Expecting an exception here due to a cycle exception, but a cycle exception was not found");
    } catch (IllegalArgumentException exc) {
        exc.printStackTrace();
        assertThat(exc.getMessage(), containsString("Found cycles"));
    }
}
 
Example #14
Source File: Db2ReOrgStatementExecutorIT.java    From obevo with Apache License 2.0 6 votes vote down vote up
private void createTable(Connection conn, String tableName, boolean requireReorg) {
    try {
        executorJdbc.update(conn, "DROP TABLE " + tableName);
    } catch (Exception ignore) {
        // Ignoring the exception, as no clear "DROP TABLE IF EXISTS" is
        // available in DB2
    }

    executorJdbc.update(conn, "create table " + tableName + " (a integer, b integer, c integer, d integer, e integer) ");
    executorJdbc.update(conn, "insert into " + tableName + " (a) values (3)");
    MutableList<String> expectedColumns;
    if (requireReorg) {
        executorJdbc.update(conn, "alter table " + tableName + " drop column b");
        executorJdbc.update(conn, "alter table " + tableName + " drop column c");
        executorJdbc.update(conn, "alter table " + tableName + " drop column d");
        expectedColumns = Lists.mutable.with("A", "E");
    } else {
        expectedColumns = Lists.mutable.with("A", "B", "C", "D", "E");
    }
    // Assert the columns which are available in table A
    String columnListSql = "select colname from syscat.COLUMNS where tabschema = '" + physicalSchema.getPhysicalName() + "' AND tabname = '"
            + tableName + "'";
    List<String> columnsInTableA = this.db2JdbcTemplate.query(conn, columnListSql,
            new ColumnListHandler<String>());
    assertEquals(expectedColumns, FastList.newList(columnsInTableA));
}
 
Example #15
Source File: DbDataComparisonUtil.java    From obevo with Apache License 2.0 6 votes vote down vote up
private static MutableList<String> getKeyCols(DaTable tableInfo) {
    MutableList<String> keyCols = Lists.mutable.empty();
    DaIndex pk = tableInfo.getPrimaryKey();
    for (DaIndex index : tableInfo.getIndices()) {
        if (index.isUnique()) {
            pk = index;
            break;
        }
    }
    if (pk != null) {
        for (DaColumn col : pk.getColumns()) {
            keyCols.add(col.getName());
        }
    }
    return keyCols;
}
 
Example #16
Source File: Environment.java    From obevo with Apache License 2.0 6 votes vote down vote up
public void copyFieldsFrom(Environment<T> env) {
    this.name = env.name;
    this.platform = env.platform;
    this.cleanBuildAllowed = env.cleanBuildAllowed;
    this.tokens = env.tokens;
    this.defaultUserId = env.defaultUserId;
    this.defaultPassword = env.defaultPassword;
    this.coreSourcePath = env.coreSourcePath;
    this.additionalSourceDirs = Lists.mutable.withAll(env.additionalSourceDirs);
    this.sourceDirs = env.sourceDirs;
    this.dbSchemaPrefix = env.dbSchemaPrefix;
    this.dbSchemaSuffix = env.dbSchemaSuffix;
    this.allSchemas = env.allSchemas;
    this.schemaNameOverrides = env.schemaNameOverrides;
    this.rollbackDetectionEnabled = env.rollbackDetectionEnabled;
    this.acceptedExtensions = env.acceptedExtensions;
    this.sourceEncoding = env.sourceEncoding;
    this.legacyDirectoryStructureEnabledVersion = env.legacyDirectoryStructureEnabledVersion;
    this.metadataLineReaderVersion = env.metadataLineReaderVersion;
    this.forceEnvInfraSetup = env.forceEnvInfraSetup;
}
 
Example #17
Source File: PostgreSqlPgDumpReveng.java    From obevo with Apache License 2.0 6 votes vote down vote up
PostgreSqlPgDumpReveng() {
    super(
            new PostgreSqlDbPlatform(),
            new MultiLineStringSplitter("GO", true),  // the GO comes from a hack in AbstractReveng - should ideally be fixed
            Lists.immutable.<Predicate<String>>of(
                    StringPredicates.contains("-- PostgreSQL database dump").and(StringPredicates.contains("-- Dumped by pg_dump"))
            ),
            getRevengPatterns(),
            null
    );
    setSkipLinePredicates(Lists.immutable.<Predicate<String>>of(
            StringPredicates.startsWith("SET statement_timeout")
            , StringPredicates.startsWith("SET default_tablespace")
            , StringPredicates.startsWith("SET lock_timeout")
            , StringPredicates.startsWith("SET idle_in_transaction_session_timeout")
            , StringPredicates.startsWith("SET client_encoding")
            , StringPredicates.startsWith("SET standard_conforming_strings")
            , StringPredicates.startsWith("SET check_function_bodies")
            , StringPredicates.startsWith("SET client_min_messages")
            , StringPredicates.startsWith("SET row_security")
            , StringPredicates.startsWith("SET default_with_oids")
            , StringPredicates.startsWith("CREATE SCHEMA")
            , StringPredicates.startsWith("SET search_path")
    ));
}
 
Example #18
Source File: GraphEnricherImplTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
/**
 * The test data in this class is all written w/ case-sensitivy as the default.
 * If we pass caseInsensitive == true, then we enable that mode in the graph enricher and tweak the object names
 * a bit so that we can verify that the resolution works either way.
 */
private void testSchemaObjectDependencies(boolean caseInsensitive) {
    this.enricher = new GraphEnricherImpl(caseInsensitive ? String::toUpperCase : Functions.getStringPassThru()::valueOf);

    SortableDependencyGroup sch1Obj1 = newChange(schema1, type1, "obj1", Sets.immutable.with("obj3", schema2 + ".obj2"));
    SortableDependencyGroup sch1Obj2 = newChange(schema1, type2, "obj2", Sets.immutable.<String>with());
    // change the case of the object name to ensure others can still point to it
    SortableDependencyGroup sch1Obj3 = newChange(schema1, type1, caseInsensitive ? "obj3".toUpperCase() : "obj3", Sets.immutable.with("obj2"));
    // change the case of the dependency name to ensure that it can point to others
    SortableDependencyGroup sch2Obj1 = newChange(schema2, type1, "obj1", Sets.immutable.with(caseInsensitive ? "obj2".toUpperCase() : "obj2"));
    SortableDependencyGroup sch2Obj2 = newChange(schema2, type2, "obj2", Sets.immutable.with(schema1 + ".obj3"));

    Graph<SortableDependencyGroup, DefaultEdge> sortGraph = enricher.createDependencyGraph(Lists.mutable.with(
            sch1Obj1, sch1Obj2, sch1Obj3, sch2Obj1, sch2Obj2), false);

    validateChange(sortGraph, sch1Obj1, Sets.immutable.with(sch1Obj3, sch2Obj2), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sch1Obj2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sch1Obj3));
    validateChange(sortGraph, sch1Obj3, Sets.immutable.with(sch1Obj2), Sets.immutable.with(sch1Obj1, sch2Obj2));
    validateChange(sortGraph, sch2Obj1, Sets.immutable.with(sch2Obj2), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sch2Obj2, Sets.immutable.with(sch1Obj3), Sets.immutable.with(sch1Obj1, sch2Obj1));
}
 
Example #19
Source File: AseToHsqlTranslationDialect.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableList<PrepareDbChange> getAdditionalTranslators() {
    SqlTranslatorConfigHelper configHelper = SqlTranslatorConfigHelper.createInMemoryDefault();
    configHelper.setNameMapper(new AseSqlTranslatorNameMapper());
    configHelper.getColumnSqlTranslators()
            .with(new AseToHsqlSqlTranslator());
    configHelper.getPostColumnSqlTranslators()
            .with(new AseToHsqlSqlTranslator());
    configHelper.getPostParsedSqlTranslators()
            .with(new AseToInMemorySqlTranslator())
            .with(new DateFormatterPostParsedSqlTranslator(AseToInMemorySqlTranslator.ACCEPTED_DATE_FORMATS));
    configHelper.getUnparsedSqlTranslators()
            .with(new AseToInMemorySqlTranslator())
            .with(new AseToHsqlDomainSqlTranslator())
            .with(new AseRenameTranslator())
    ;

    return Lists.immutable.<PrepareDbChange>with(new InMemoryTranslator(configHelper));
}
 
Example #20
Source File: DefaultRollbackDetector.java    From obevo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the active deployments from the given list, i.e. removing the impact of those deployments rolled back.
 *
 * Logic:
 * -Play through the history of the DeployExecutions sorting by the ID field
 * -If a regular deploy is found, push it to the stack
 * -If a rollback is found, pop items from the stack until we find the corresponding version to be rolled back, and
 * then add the (new) rollback version to the stack. We assume the prior version must exist; if not, an exception is
 * thrown.
 */
@VisibleForTesting
ImmutableList<DeployExecution> getActiveDeployments(ImmutableCollection<DeployExecution> deployExecutions) {
    if (deployExecutions == null) {
        return Lists.immutable.empty();
    }

    MutableList<DeployExecution> idSortedExecutions = deployExecutions.toSortedListBy(new Function<DeployExecution, Long>() {
        @Override
        public Long valueOf(DeployExecution deployExecution) {
            return deployExecution.getId();
        }
    });
    MutableStack<DeployExecution> executionStack = Stacks.mutable.empty();

    for (DeployExecution currentExecution : idSortedExecutions) {
        if (!currentExecution.isRollback()) {
            executionStack.push(currentExecution);
        } else {
            while (true) {
                if (executionStack.isEmpty()) {
                    throw new IllegalStateException("Found a rollback deployment without the corresponding version: " + getDeployVersion(currentExecution) + ", " + currentExecution);
                } else {
                    DeployExecution previousExecution = executionStack.pop();
                    if (getDeployVersion(previousExecution).equals(getDeployVersion(currentExecution))) {
                        executionStack.push(currentExecution);
                        break;
                    }
                }
            }
        }
    }

    return executionStack.toList().reverseThis().toImmutable();
}
 
Example #21
Source File: ArtifactEnvironmentRestrictionsTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
private void assertTest(boolean result, String envName, final MutableSet<String> includes,
        final MutableSet<String> excludes) {
    Environment env = new Environment();
    env.setName(envName);

    Restrictable restrictable = new Restrictable() {
        @Override
        public ImmutableList<ArtifactRestrictions> getRestrictions() {
            return Lists.immutable.<ArtifactRestrictions>of(new ArtifactEnvironmentRestrictions(includes, excludes));
        }
    };

    Assert.assertEquals(result, ArtifactRestrictions.apply().accept(restrictable, env));
}
 
Example #22
Source File: DbChecksumCalculator.java    From obevo with Apache License 2.0 5 votes vote down vote up
public ImmutableCollection<ChecksumEntry> getChecksums(DaCatalog database) {
    MutableCollection<ChecksumEntry> checksums = Lists.mutable.empty();

    for (DaRoutine routine : database.getRoutines()) {
        checksums.withAll(getRoutineChecksums(routine));
    }
    for (DaTable tableOrView : database.getTables()) {
        checksums.withAll(getTableOrViewChecksums(tableOrView));
    }

    return checksums.toImmutable();
}
 
Example #23
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderingWithSubgraph() {
    String sp1 = "sp1";
    String sp2 = "sp2";
    String sp3 = "sp3";
    String sp4 = "sp4";
    String sp5 = "sp5";

    Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);

    for (String vertex : shuffledList(sp1, sp2, sp3, sp4, sp5)) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);
    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);

    ImmutableList<String> sorted = sorter.sortChanges(graph, Lists.mutable.with(sp1, sp2, sp3));

    // First, compare the root topological order (i.e. ensure that the dependencies are respected)
    assertEquals(3, sorted.size());
    assertThat(sorted.indexOf(sp1), greaterThan(sorted.indexOf(sp2)));

    // Now check that we can achieve a consistent order too (for easier debuggability for clients)
    assertEquals(Lists.immutable.with(sp2, sp1, sp3), sorted);
}
 
Example #24
Source File: GrantChangeParser.java    From obevo with Apache License 2.0 5 votes vote down vote up
ImmutableList<String> generateGrantChanges(RichIterable<Permission> permsToApply, final DbChangeType changeType, final PhysicalSchema physicalSchema, final String mainObjectName, RichIterable<String> objectNames, final boolean specific) {
    final MutableList<String> changes = Lists.mutable.empty();

    for (Permission perm : permsToApply) {
        for (final Grant grant : perm.getGrants()) {
            grant.validate();

            for (final String objectName : objectNames) {
                grant.getGrantTargets().forEachKeyValue(new Procedure2<GrantTargetType, String>() {
                    @Override
                    public void value(GrantTargetType grantTargetType, String grantTarget) {
                        for (String privilege : grant.getPrivileges()) {
                            changes.add(GrantChangeParser.this.createGrant(env, privilege, changeType, physicalSchema, objectName, grantTargetType, grantTarget, specific));
                        }
                    }
                });
            }
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(String.format("Applying grants on [%s] with [%d] permission entries on these qualified object names: [%s]",
                mainObjectName, permsToApply.size(), objectNames.makeString("; ")));
    }

    return changes.toImmutable();
}
 
Example #25
Source File: MapDataSource.java    From obevo with Apache License 2.0 5 votes vote down vote up
protected void openSource() throws Exception {
    List<CatoDataObject> dataObjs = Lists.mutable.empty();
    for (Map<String, ? extends Object> dataMap : this.dataMaps) {
        CatoDataObject dataObj = this.createDataObject();
        for (Entry<String, ? extends Object> entry : dataMap.entrySet()) {
            dataObj.setValue(entry.getKey(), entry.getValue());
        }
        dataObjs.add(dataObj);
    }
    this.catoObjs = dataObjs.iterator();
    this.dataMaps = null;  // set to null to release the reference to the map
}
 
Example #26
Source File: UnitTestDbBuilder.java    From obevo with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the deployer context. See the class Javadoc for more information
 */
private DbDeployerAppContext buildContextUncached() {
    validateBuilder();

    String[] envsToRequest = this.referenceEnvName != null ? new String[] { this.referenceEnvName } : new String[0];
    DbEnvironment referenceEnv = DbEnvironmentFactory.getInstance().readFromSourcePath(this.sourcePath, envsToRequest)
            .getFirst();

    DbEnvironment env = referenceEnv.createCopy();

    if (this.envName != null) {
        env.setName(this.envName);
    }

    env.setDisableAuditTracking(true);
    env.setPersistToFile(this.isPersistToFile());

    if (this.dbPlatform != null) {
        env.setPlatform(this.dbPlatform);
    }

    if (this.dbServer != null) {
        if (env.getJdbcUrl() != null) {
            LOG.debug("Unsetting existing JDBC URL value, as we can rely on the in-memory DB value to be set here");
            env.setJdbcUrl(null);
        }
        env.setDbServer(this.dbServer);
    }

    if (this.grantsDisabled) {
        env.setPermissions(Lists.immutable.<Permission>empty());
    }

    env.setDefaultUserId(credential.getUsername());
    env.setDefaultPassword(credential.getPassword());

    return env.getAppContextBuilder()
            .setWorkDir(workDir)
            .build();
}
 
Example #27
Source File: AbstractReveng.java    From obevo with Apache License 2.0 5 votes vote down vote up
private String replaceSchemaInSnippet(String sqlSnippet, String inputSchema, String objectName) {
    for (boolean useQuotes : Lists.fixedSize.of(true, false)) {
        String sQuote = useQuotes ? startQuote : "";
        String eQuote = useQuotes ? endQuote : "";
        sqlSnippet = sqlSnippet.replaceAll(sQuote + inputSchema + "\\s*" + eQuote + "\\." + sQuote + objectName + eQuote, objectName);
    }

    return sqlSnippet;
}
 
Example #28
Source File: EnvironmentFactory.java    From obevo with Apache License 2.0 5 votes vote down vote up
public <E extends Environment> ImmutableCollection<E> readFromSourcePath(String sourcePath, String... envNames) {
    EnvironmentLocator dbEnvironmentLocator = new EnvironmentLocator();
    ImmutableCollection<E> environments = dbEnvironmentLocator.readSystem(sourcePath);

    MutableList<E> requestedEnvs = Lists.mutable.empty();

    for (E env : environments) {
        if (envNames == null || envNames.length == 0) {
            requestedEnvs.add(env);
        } else {
            for (String envPattern : envNames) {
                if (Pattern.compile(RegexUtil.convertWildcardPatternToRegex(envPattern))
                        .matcher(env.getName())
                        .matches()) {
                    requestedEnvs.add(env);
                }
            }
        }
    }

    if (requestedEnvs.isEmpty()) {
        throw new IllegalArgumentException("No environment with name/s "
                + Lists.mutable.with(envNames).makeString("(", ",", ")") + " found");
    }

    return requestedEnvs.toImmutable();
}
 
Example #29
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicOrdering() {
    String sp1 = "sp1";
    String sp2 = "sp2";
    String sp3 = "sp3";
    String sp4 = "sp4";
    String sp5 = "sp5";

    Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);

    for (String vertex : Lists.mutable.with(sp1, sp2, sp3, sp4, sp5).toReversed()) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);
    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);

    ListIterable<String> sorted = sorter.sortChanges(graph);

    // First, compare the root topological order (i.e. ensure that the dependencies are respected)
    assertEquals(5, sorted.size());
    assertThat(sorted.indexOf(sp1), greaterThan(sorted.indexOf(sp2)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp1)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp3)));
    assertThat(sorted.indexOf(sp4), greaterThan(sorted.indexOf(sp5)));

    // Now check that we can achieve a consistent order too (for easier debuggability for clients)
    assertEquals(Lists.immutable.with(sp2, sp1, sp3, sp5, sp4), sorted);
}
 
Example #30
Source File: DbDataComparisonConfig.java    From obevo with Apache License 2.0 5 votes vote down vote up
public void init() {
    this.comparisonCommands = Lists.mutable.empty();
    MutableMap<String, DbDataSource> sourceMap = this.dbDataSources.groupByUniqueKey(new Function<DbDataSource, String>() {
        @Override
        public String valueOf(DbDataSource dbDataSource) {
            return dbDataSource.getName();
        }
    });
    for (Pair<String, String> comparisonCommandNamePair : this.comparisonCommandNamePairs) {
        this.comparisonCommands.add(new ComparisonCommand(
                sourceMap.get(comparisonCommandNamePair.getOne())
                , sourceMap.get(comparisonCommandNamePair.getTwo())
        ));
    }
}