Search in sources :

Example 41 with UnexpectedLiquibaseException

use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.

the class DataTypeFactory method fromDescription.

//    public Map<String, SortedSet<Class<? extends LiquibaseDataType>>> getRegistry() {
//        return registry;
//    }
//    public LiquibaseDataType fromDescription(String dataTypeDefinition) {
//        return fromDescription(dataTypeDefinition, null);
//    }
public LiquibaseDataType fromDescription(String dataTypeDefinition, Database database) {
    String dataTypeName = dataTypeDefinition;
    if (dataTypeName.matches(".+\\(.*\\).*")) {
        dataTypeName = dataTypeName.replaceFirst("\\s*\\(.*\\)", "");
    }
    if (dataTypeName.matches(".+\\{.*")) {
        dataTypeName = dataTypeName.replaceFirst("\\s*\\{.*", "");
    }
    boolean autoIncrement = false;
    if (dataTypeName.endsWith(" identity")) {
        dataTypeName = dataTypeName.replaceFirst(" identity$", "");
        autoIncrement = true;
    }
    // unquote delimited identifiers
    final String[][] quotePairs = new String[][] { // double quotes
    { "\"", "\"" }, // square brackets (a la mssql)
    { "[", "]" }, // backticks (a la mysql)
    { "`", "`" }, // single quotes
    { "'", "'" } };
    for (String[] quotePair : quotePairs) {
        String openQuote = quotePair[0];
        String closeQuote = quotePair[1];
        if (dataTypeName.startsWith(openQuote)) {
            int indexOfCloseQuote = dataTypeName.indexOf(closeQuote, openQuote.length());
            if (indexOfCloseQuote != -1 && dataTypeName.indexOf(closeQuote, indexOfCloseQuote + closeQuote.length()) == -1) {
                dataTypeName = dataTypeName.substring(openQuote.length(), indexOfCloseQuote) + dataTypeName.substring(indexOfCloseQuote + closeQuote.length(), dataTypeName.length());
                break;
            }
        }
    }
    String additionalInfo = null;
    if (dataTypeName.toLowerCase().startsWith("bit varying") || dataTypeName.toLowerCase().startsWith("character varying")) {
    //not going to do anything. Special case for postgres in our tests, need to better support handling these types of differences
    } else {
        String[] splitTypeName = dataTypeName.split("\\s+", 2);
        dataTypeName = splitTypeName[0];
        if (splitTypeName.length > 1) {
            additionalInfo = splitTypeName[1];
        }
    }
    Collection<Class<? extends LiquibaseDataType>> classes = registry.get(dataTypeName.toLowerCase());
    LiquibaseDataType liquibaseDataType = null;
    if (classes == null) {
        if (dataTypeName.toUpperCase().startsWith("INTERVAL")) {
            liquibaseDataType = new UnknownType(dataTypeDefinition);
        } else {
            liquibaseDataType = new UnknownType(dataTypeName);
        }
    } else {
        Iterator<Class<? extends LiquibaseDataType>> iterator = classes.iterator();
        do {
            try {
                liquibaseDataType = iterator.next().newInstance();
            } catch (Exception e) {
                throw new UnexpectedLiquibaseException(e);
            }
        } while ((database != null) && !liquibaseDataType.supports(database) && iterator.hasNext());
    }
    if ((database != null) && !liquibaseDataType.supports(database)) {
        throw new UnexpectedLiquibaseException("Could not find type for " + liquibaseDataType.toString() + " for databaes " + database.getShortName());
    }
    if (liquibaseDataType == null) {
        liquibaseDataType = new UnknownType(dataTypeName);
    }
    liquibaseDataType.setAdditionalInformation(additionalInfo);
    if (dataTypeDefinition.matches(".+\\s*\\(.*")) {
        String paramStrings = dataTypeDefinition.replaceFirst(".*?\\(", "").replaceFirst("\\).*", "");
        String[] params = paramStrings.split(",");
        for (String param : params) {
            param = StringUtils.trimToNull(param);
            if (param != null) {
                if (liquibaseDataType instanceof CharType && !(database instanceof OracleDatabase)) {
                    //only use byte types on oracle, not sure what else supports it
                    param = param.replaceFirst(" BYTE", "");
                }
                liquibaseDataType.addParameter(param);
            }
        }
    }
    if (dataTypeDefinition.matches(".*\\{.*")) {
        String paramStrings = dataTypeDefinition.replaceFirst(".*?\\{", "").replaceFirst("\\}.*", "");
        String[] params = paramStrings.split(",");
        for (String param : params) {
            param = StringUtils.trimToNull(param);
            if (param != null) {
                String[] paramAndValue = param.split(":", 2);
                try {
                    ObjectUtil.setProperty(liquibaseDataType, paramAndValue[0], paramAndValue[1]);
                } catch (Exception e) {
                    throw new RuntimeException("Unknown property " + paramAndValue[0] + " for " + liquibaseDataType.getClass().getName() + " " + liquibaseDataType.toString());
                }
            }
        }
    }
    if (autoIncrement && liquibaseDataType instanceof IntType) {
        ((IntType) liquibaseDataType).setAutoIncrement(true);
    }
    if (autoIncrement && liquibaseDataType instanceof BigIntType) {
        ((BigIntType) liquibaseDataType).setAutoIncrement(true);
    }
    liquibaseDataType.finishInitialization(dataTypeDefinition);
    return liquibaseDataType;
}
Also used : BigIntType(liquibase.datatype.core.BigIntType) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) IntType(liquibase.datatype.core.IntType) BigIntType(liquibase.datatype.core.BigIntType) UnknownType(liquibase.datatype.core.UnknownType) OracleDatabase(liquibase.database.core.OracleDatabase) CharType(liquibase.datatype.core.CharType) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 42 with UnexpectedLiquibaseException

use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.

the class SQLiteDatabase method getAlterTableStatements.

public static List<SqlStatement> getAlterTableStatements(AlterTableVisitor alterTableVisitor, Database database, String catalogName, String schemaName, String tableName) throws DatabaseException {
    List<SqlStatement> statements = new ArrayList<SqlStatement>();
    Table table = null;
    try {
        table = SnapshotGeneratorFactory.getInstance().createSnapshot((Table) new Table().setName(tableName).setSchema(new Schema(new Catalog(null), null)), database);
        List<ColumnConfig> createColumns = new ArrayList<ColumnConfig>();
        List<ColumnConfig> copyColumns = new ArrayList<ColumnConfig>();
        if (table != null) {
            for (Column column : table.getColumns()) {
                ColumnConfig new_column = new ColumnConfig(column);
                if (alterTableVisitor.createThisColumn(new_column)) {
                    createColumns.add(new_column);
                }
                ColumnConfig copy_column = new ColumnConfig(column);
                if (alterTableVisitor.copyThisColumn(copy_column)) {
                    copyColumns.add(copy_column);
                }
            }
        }
        for (ColumnConfig column : alterTableVisitor.getColumnsToAdd()) {
            if (alterTableVisitor.createThisColumn(column)) {
                createColumns.add(column);
            }
            if (alterTableVisitor.copyThisColumn(column)) {
                copyColumns.add(column);
            }
        }
        List<Index> newIndices = new ArrayList<Index>();
        for (Index index : SnapshotGeneratorFactory.getInstance().createSnapshot(new CatalogAndSchema(catalogName, schemaName), database, new SnapshotControl(database, Index.class)).get(Index.class)) {
            if (index.getTable().getName().equalsIgnoreCase(tableName)) {
                if (alterTableVisitor.createThisIndex(index)) {
                    newIndices.add(index);
                }
            }
        }
        // rename table
        String temp_table_name = tableName + "_temporary";
        statements.addAll(Arrays.asList(new RenameTableStatement(catalogName, schemaName, tableName, temp_table_name)));
        // create temporary table
        CreateTableChange ct_change_tmp = new CreateTableChange();
        ct_change_tmp.setSchemaName(schemaName);
        ct_change_tmp.setTableName(tableName);
        for (ColumnConfig column : createColumns) {
            ct_change_tmp.addColumn(column);
        }
        statements.addAll(Arrays.asList(ct_change_tmp.generateStatements(database)));
        // copy rows to temporary table
        statements.addAll(Arrays.asList(new CopyRowsStatement(temp_table_name, tableName, copyColumns)));
        // delete original table
        statements.addAll(Arrays.asList(new DropTableStatement(catalogName, schemaName, temp_table_name, false)));
        // validate indices
        statements.addAll(Arrays.asList(new ReindexStatement(catalogName, schemaName, tableName)));
        // add remaining indices
        for (Index index_config : newIndices) {
            AddColumnConfig[] columns = new AddColumnConfig[index_config.getColumns().size()];
            for (int i = 0; i < index_config.getColumns().size(); i++) {
                columns[i] = new AddColumnConfig(index_config.getColumns().get(i));
            }
            statements.addAll(Arrays.asList(new CreateIndexStatement(index_config.getName(), catalogName, schemaName, tableName, index_config.isUnique(), index_config.getAssociatedWithAsString(), columns)));
        }
        return statements;
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) AddColumnConfig(liquibase.change.AddColumnConfig) CatalogAndSchema(liquibase.CatalogAndSchema) SqlStatement(liquibase.statement.SqlStatement) InvalidExampleException(liquibase.snapshot.InvalidExampleException) SnapshotControl(liquibase.snapshot.SnapshotControl) CatalogAndSchema(liquibase.CatalogAndSchema) CreateTableChange(liquibase.change.core.CreateTableChange) AddColumnConfig(liquibase.change.AddColumnConfig) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 43 with UnexpectedLiquibaseException

use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.

the class ConfigurationProperty method init.

/**
     * Initialize this property with values in the given ConfigurationProvers. If the configurationValueProviders do not contain
     * a default value, the property is initialized with the value set by {@link #setDefaultValue(Object)}.
     * If multiple configurationValueProviders contain values, the first in the list wins.
     */
protected void init(ConfigurationValueProvider[] configurationValueProviders) {
    Object containerValue = null;
    for (ConfigurationValueProvider container : configurationValueProviders) {
        containerValue = container.getValue(namespace, name);
        for (String alias : aliases) {
            if (containerValue != null) {
                break;
            }
            containerValue = container.getValue(namespace, alias);
        }
    }
    if (containerValue == null) {
        value = defaultValue;
    } else {
        try {
            value = valueOf(containerValue);
            wasOverridden = true;
        } catch (NumberFormatException e) {
            throw new UnexpectedLiquibaseException("Error parsing " + containerValue + " as a " + type.getSimpleName());
        }
    }
}
Also used : UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 44 with UnexpectedLiquibaseException

use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.

the class ChangeParameterMetaData method getExampleValue.

public Object getExampleValue(Database database) {
    if (exampleValues != null) {
        Object exampleValue = null;
        for (Map.Entry<String, Object> entry : exampleValues.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("all")) {
                exampleValue = entry.getValue();
            } else if (DatabaseList.definitionMatches(entry.getKey(), database, false)) {
                return entry.getValue();
            }
        }
        if (exampleValue != null) {
            return exampleValue;
        }
    }
    Map standardExamples = new HashMap();
    standardExamples.put("tableName", "person");
    standardExamples.put("schemaName", "public");
    standardExamples.put("tableSchemaName", "public");
    standardExamples.put("catalogName", "cat");
    standardExamples.put("tableCatalogName", "cat");
    standardExamples.put("columnName", "id");
    standardExamples.put("columnNames", "id, name");
    standardExamples.put("indexName", "idx_address");
    standardExamples.put("columnDataType", "int");
    standardExamples.put("dataType", "int");
    standardExamples.put("sequenceName", "seq_id");
    standardExamples.put("viewName", "v_person");
    standardExamples.put("constraintName", "const_name");
    standardExamples.put("primaryKey", "pk_id");
    if (standardExamples.containsKey(parameterName)) {
        return standardExamples.get(parameterName);
    }
    for (String prefix : new String[] { "base", "referenced", "new", "old" }) {
        if (parameterName.startsWith(prefix)) {
            String mainName = StringUtils.lowerCaseFirst(parameterName.replaceFirst("^" + prefix, ""));
            if (standardExamples.containsKey(mainName)) {
                return standardExamples.get(mainName);
            }
        }
    }
    if (dataType.equals("string")) {
        return "A String";
    } else if (dataType.equals("integer")) {
        return 3;
    } else if (dataType.equals("boolean")) {
        return true;
    } else if (dataType.equals("bigInteger")) {
        return new BigInteger("371717");
    } else if (dataType.equals("list")) {
        //"TODO";
        return null;
    } else if (dataType.equals("sequenceNextValueFunction")) {
        return new SequenceNextValueFunction("seq_name");
    } else if (dataType.equals("databaseFunction")) {
        return new DatabaseFunction("now");
    } else if (dataType.equals("list of columnConfig")) {
        ArrayList<ColumnConfig> list = new ArrayList<ColumnConfig>();
        list.add(new ColumnConfig().setName("id").setType("int"));
        return list;
    } else if (dataType.equals("list of addColumnConfig")) {
        ArrayList<ColumnConfig> list = new ArrayList<ColumnConfig>();
        list.add(new AddColumnConfig().setName("id").setType("int"));
        return list;
    } else if (dataType.equals("list of loadDataColumnConfig")) {
        ArrayList<ColumnConfig> list = new ArrayList<ColumnConfig>();
        list.add(new LoadDataColumnConfig().setName("id").setType("int"));
        return list;
    } else {
        throw new UnexpectedLiquibaseException("Unknown dataType " + dataType + " for " + getParameterName());
    }
}
Also used : DatabaseFunction(liquibase.statement.DatabaseFunction) LoadDataColumnConfig(liquibase.change.core.LoadDataColumnConfig) LoadDataColumnConfig(liquibase.change.core.LoadDataColumnConfig) BigInteger(java.math.BigInteger) SequenceNextValueFunction(liquibase.statement.SequenceNextValueFunction) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 45 with UnexpectedLiquibaseException

use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.

the class ChangeLogHistoryServiceFactory method getChangeLogService.

public ChangeLogHistoryService getChangeLogService(Database database) {
    if (services.containsKey(database)) {
        return services.get(database);
    }
    SortedSet<ChangeLogHistoryService> foundServices = new TreeSet<ChangeLogHistoryService>(new Comparator<ChangeLogHistoryService>() {

        @Override
        public int compare(ChangeLogHistoryService o1, ChangeLogHistoryService o2) {
            return -1 * Integer.valueOf(o1.getPriority()).compareTo(o2.getPriority());
        }
    });
    for (ChangeLogHistoryService service : registry) {
        if (service.supports(database)) {
            foundServices.add(service);
        }
    }
    if (foundServices.size() == 0) {
        throw new UnexpectedLiquibaseException("Cannot find ChangeLogHistoryService for " + database.getShortName());
    }
    try {
        ChangeLogHistoryService exampleService = foundServices.iterator().next();
        Class<? extends ChangeLogHistoryService> aClass = exampleService.getClass();
        ChangeLogHistoryService service;
        try {
            aClass.getConstructor();
            service = aClass.newInstance();
            service.setDatabase(database);
        } catch (NoSuchMethodException e) {
            // must have been manually added to the registry and so already configured.
            service = exampleService;
        }
        services.put(database, service);
        return service;
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Aggregations

UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)75 DatabaseException (liquibase.exception.DatabaseException)12 IOException (java.io.IOException)10 Database (liquibase.database.Database)10 DatabaseObject (liquibase.structure.DatabaseObject)10 LiquibaseException (liquibase.exception.LiquibaseException)9 InvalidExampleException (liquibase.snapshot.InvalidExampleException)9 CatalogAndSchema (liquibase.CatalogAndSchema)8 InputStream (java.io.InputStream)7 ParsedNodeException (liquibase.parser.core.ParsedNodeException)7 SQLException (java.sql.SQLException)6 DatabaseFunction (liquibase.statement.DatabaseFunction)6 SqlStatement (liquibase.statement.SqlStatement)6 ArrayList (java.util.ArrayList)5 Matcher (java.util.regex.Matcher)5 Change (liquibase.change.Change)5 ColumnConfig (liquibase.change.ColumnConfig)5 Executor (liquibase.executor.Executor)5 Sql (liquibase.sql.Sql)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4