Search in sources :

Example 6 with UnexpectedLiquibaseException

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

the class LoadDataChange method getCSVReader.

public CSVReader getCSVReader() throws IOException {
    ResourceAccessor resourceAccessor = getResourceAccessor();
    if (resourceAccessor == null) {
        throw new UnexpectedLiquibaseException("No file resourceAccessor specified for " + getFile());
    }
    InputStream stream = StreamUtil.openStream(file, isRelativeToChangelogFile(), getChangeSet(), resourceAccessor);
    if (stream == null) {
        return null;
    }
    Reader streamReader;
    if (getEncoding() == null) {
        streamReader = new UtfBomAwareReader(stream);
    } else {
        streamReader = new UtfBomAwareReader(stream, getEncoding());
    }
    char quotchar;
    if (StringUtils.trimToEmpty(this.quotchar).length() == 0) {
        // hope this is impossible to have a field surrounded with non ascii char 0x01
        quotchar = '\1';
    } else {
        quotchar = this.quotchar.charAt(0);
    }
    if (separator == null) {
        separator = liquibase.util.csv.CSVReader.DEFAULT_SEPARATOR + "";
    }
    return new CSVReader(streamReader, separator.charAt(0), quotchar);
}
Also used : ResourceAccessor(liquibase.resource.ResourceAccessor) CSVReader(liquibase.util.csv.CSVReader) EmptyLineAndCommentSkippingInputStream(liquibase.io.EmptyLineAndCommentSkippingInputStream) InputStream(java.io.InputStream) CSVReader(liquibase.util.csv.CSVReader) UtfBomAwareReader(liquibase.resource.UtfBomAwareReader) Reader(java.io.Reader) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) UtfBomAwareReader(liquibase.resource.UtfBomAwareReader)

Example 7 with UnexpectedLiquibaseException

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

the class LoadDataChange method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) {
    CSVReader reader = null;
    try {
        reader = getCSVReader();
        if (reader == null) {
            throw new UnexpectedLiquibaseException("Unable to read file " + this.getFile());
        }
        String[] headers = reader.readNext();
        if (headers == null) {
            throw new UnexpectedLiquibaseException("Data file " + getFile() + " was empty");
        }
        List<SqlStatement> statements = new ArrayList<SqlStatement>();
        boolean anyPreparedStatements = false;
        String[] line;
        // Start at '1' to take into account the header (already processed)
        int lineNumber = 1;
        boolean isCommentingEnabled = StringUtils.isNotEmpty(commentLineStartsWith);
        while ((line = reader.readNext()) != null) {
            lineNumber++;
            if (line.length == 0 || (line.length == 1 && StringUtils.trimToNull(line[0]) == null) || (isCommentingEnabled && isLineCommented(line))) {
                //nothing on this line
                continue;
            }
            // (Failure could indicate unquoted strings with commas, for example).
            if (line.length != headers.length) {
                throw new UnexpectedLiquibaseException("CSV file " + getFile() + " Line " + lineNumber + " has " + line.length + " values defined, Header has " + headers.length + ". Numbers MUST be equal (check for unquoted string with embedded commas)");
            }
            boolean needsPreparedStatement = false;
            List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
            for (int i = 0; i < headers.length; i++) {
                Object value = line[i];
                String columnName = headers[i].trim();
                ColumnConfig valueConfig = new ColumnConfig();
                ColumnConfig columnConfig = getColumnConfig(i, headers[i].trim());
                if (columnConfig != null) {
                    if ("skip".equalsIgnoreCase(columnConfig.getType())) {
                        continue;
                    }
                    // don't overwrite header name unless there is actually a value to override it with
                    if (columnConfig.getName() != null) {
                        columnName = columnConfig.getName();
                    }
                    valueConfig.setName(columnName);
                    if (columnConfig.getType() != null) {
                        if (columnConfig.getType().equalsIgnoreCase("BOOLEAN")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueBoolean(BooleanParser.parseBoolean(value.toString().toLowerCase()));
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("NUMERIC")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueNumeric(value.toString());
                            }
                        } else if (columnConfig.getType().toLowerCase().contains("date") || columnConfig.getType().toLowerCase().contains("time")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueDate(value.toString());
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("STRING")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValue(value.toString());
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("COMPUTED")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                liquibase.statement.DatabaseFunction function = new liquibase.statement.DatabaseFunction(value.toString());
                                valueConfig.setValueComputed(function);
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("SEQUENCE")) {
                            String sequenceName;
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                sequenceName = columnConfig.getDefaultValue();
                                if (sequenceName == null) {
                                    throw new UnexpectedLiquibaseException("Must set a sequence name in the loadData column defaultValue attribute");
                                }
                            } else {
                                sequenceName = value.toString();
                            }
                            liquibase.statement.SequenceNextValueFunction function = new liquibase.statement.SequenceNextValueFunction(sequenceName);
                            valueConfig.setValueComputed(function);
                        } else if (columnConfig.getType().equalsIgnoreCase("BLOB")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueBlobFile(value.toString());
                                needsPreparedStatement = true;
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("CLOB")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueClobFile(value.toString());
                                needsPreparedStatement = true;
                            }
                        } else {
                            throw new UnexpectedLiquibaseException("loadData type of " + columnConfig.getType() + " is not supported.  Please use BOOLEAN, NUMERIC, DATE, STRING, COMPUTED, SEQUENCE or SKIP");
                        }
                    }
                } else {
                    if (columnName.contains("(") || columnName.contains(")") && database instanceof AbstractJdbcDatabase) {
                        columnName = ((AbstractJdbcDatabase) database).quoteObject(columnName, Column.class);
                    }
                    valueConfig.setName(columnName);
                    if (value == null || value.toString().equalsIgnoreCase("NULL")) {
                        // value is always going to be a string unless overridden by ColumnConfig
                        valueConfig.setValue((String) value);
                    } else {
                        valueConfig.setValue(value.toString());
                    }
                }
                columns.add(valueConfig);
            }
            if (needsPreparedStatement) {
                anyPreparedStatements = true;
                statements.add(new InsertExecutablePreparedStatement(database, getCatalogName(), getSchemaName(), getTableName(), columns, getChangeSet(), getResourceAccessor()));
            } else {
                InsertStatement insertStatement = this.createStatement(getCatalogName(), getSchemaName(), getTableName());
                for (ColumnConfig column : columns) {
                    String columnName = column.getName();
                    Object value = column.getValueObject();
                    if (value == null) {
                        value = "NULL";
                    }
                    insertStatement.addColumnValue(columnName, value);
                }
                statements.add(insertStatement);
            }
        }
        if (anyPreparedStatements) {
            return statements.toArray(new SqlStatement[statements.size()]);
        } else {
            InsertSetStatement statementSet = this.createStatementSet(getCatalogName(), getSchemaName(), getTableName());
            for (SqlStatement stmt : statements) {
                statementSet.addInsertStatement((InsertStatement) stmt);
            }
            if (database instanceof MSSQLDatabase || database instanceof MySQLDatabase || database instanceof PostgresDatabase) {
                List<InsertStatement> innerStatements = statementSet.getStatements();
                if (innerStatements != null && innerStatements.size() > 0 && innerStatements.get(0) instanceof InsertOrUpdateStatement) {
                    //cannot do insert or update in a single statement
                    return statementSet.getStatementsArray();
                }
                // we only return a single "statement" - it's capable of emitting multiple sub-statements, should the need arise, on generation.
                return new SqlStatement[] { statementSet };
            } else {
                return statementSet.getStatementsArray();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (UnexpectedLiquibaseException ule) {
        if (getChangeSet() != null && getChangeSet().getFailOnError() != null && !getChangeSet().getFailOnError()) {
            Logger log = LogFactory.getLogger();
            log.info("Change set " + getChangeSet().toString(false) + " failed, but failOnError was false.  Error: " + ule.getMessage());
            return new SqlStatement[0];
        } else {
            throw ule;
        }
    } finally {
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException e) {
                ;
            }
        }
    }
}
Also used : InsertOrUpdateStatement(liquibase.statement.core.InsertOrUpdateStatement) ColumnConfig(liquibase.change.ColumnConfig) Logger(liquibase.logging.Logger) InsertStatement(liquibase.statement.core.InsertStatement) SqlStatement(liquibase.statement.SqlStatement) Column(liquibase.structure.core.Column) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) InsertExecutablePreparedStatement(liquibase.statement.InsertExecutablePreparedStatement) CSVReader(liquibase.util.csv.CSVReader) MySQLDatabase(liquibase.database.core.MySQLDatabase) IOException(java.io.IOException) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) PostgresDatabase(liquibase.database.core.PostgresDatabase) InsertSetStatement(liquibase.statement.core.InsertSetStatement) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 8 with UnexpectedLiquibaseException

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

the class ExecuteShellCommandChange method generateStatements.

@Override
public SqlStatement[] generateStatements(final Database database) {
    boolean shouldRun = true;
    if (os != null && os.size() > 0) {
        String currentOS = System.getProperty("os.name");
        if (!os.contains(currentOS)) {
            shouldRun = false;
            LogFactory.getLogger().info("Not executing on os " + currentOS + " when " + os + " was specified");
        }
    }
    // check if running under not-executed mode (logging output)
    boolean nonExecutedMode = false;
    Executor executor = ExecutorService.getInstance().getExecutor(database);
    if (executor instanceof LoggingExecutor) {
        nonExecutedMode = true;
    }
    this.finalCommandArray = createFinalCommandArray(database);
    if (shouldRun && !nonExecutedMode) {
        return new SqlStatement[] { new RuntimeStatement() {

            @Override
            public Sql[] generate(Database database) {
                try {
                    executeCommand(database);
                } catch (Exception e) {
                    throw new UnexpectedLiquibaseException("Error executing command: " + e.getLocalizedMessage(), e);
                }
                return null;
            }
        } };
    }
    if (nonExecutedMode) {
        try {
            return new SqlStatement[] { new CommentStatement(getCommandString()) };
        } finally {
            nonExecutedCleanup();
        }
    }
    return new SqlStatement[0];
}
Also used : SqlStatement(liquibase.statement.SqlStatement) Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) CommentStatement(liquibase.statement.core.CommentStatement) LoggingExecutor(liquibase.executor.LoggingExecutor) Database(liquibase.database.Database) RuntimeStatement(liquibase.statement.core.RuntimeStatement) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) ParsedNodeException(liquibase.parser.core.ParsedNodeException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) Sql(liquibase.sql.Sql)

Example 9 with UnexpectedLiquibaseException

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

the class LockServiceFactory method getLockService.

public LockService getLockService(Database database) {
    if (!openLockServices.containsKey(database)) {
        SortedSet<LockService> foundServices = new TreeSet<LockService>(new Comparator<LockService>() {

            @Override
            public int compare(LockService o1, LockService o2) {
                return -1 * Integer.valueOf(o1.getPriority()).compareTo(o2.getPriority());
            }
        });
        for (LockService lockService : registry) {
            if (lockService.supports(database)) {
                foundServices.add(lockService);
            }
        }
        if (foundServices.size() == 0) {
            throw new UnexpectedLiquibaseException("Cannot find LockService for " + database.getShortName());
        }
        try {
            LockService lockService = foundServices.iterator().next().getClass().newInstance();
            lockService.setDatabase(database);
            openLockServices.put(database, lockService);
        } catch (Exception e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }
    return openLockServices.get(database);
}
Also used : TreeSet(java.util.TreeSet) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 10 with UnexpectedLiquibaseException

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

the class StandardLockService method acquireLock.

@Override
public boolean acquireLock() throws LockException {
    if (hasChangeLogLock) {
        return true;
    }
    quotingStrategy = database.getObjectQuotingStrategy();
    Executor executor = ExecutorService.getInstance().getExecutor(database);
    try {
        database.rollback();
        this.init();
        Boolean locked = (Boolean) ExecutorService.getInstance().getExecutor(database).queryForObject(new SelectFromDatabaseChangeLogLockStatement("LOCKED"), Boolean.class);
        if (locked) {
            return false;
        } else {
            executor.comment("Lock Database");
            int rowsUpdated = executor.update(new LockDatabaseChangeLogStatement());
            if (rowsUpdated == -1 && database instanceof MSSQLDatabase) {
                LogFactory.getLogger().debug("Database did not return a proper row count (Might have NOCOUNT enabled)");
                database.rollback();
                Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(new LockDatabaseChangeLogStatement(), database);
                if (sql.length != 1) {
                    throw new UnexpectedLiquibaseException("Did not expect " + sql.length + " statements");
                }
                rowsUpdated = executor.update(new RawSqlStatement("EXEC sp_executesql N'SET NOCOUNT OFF " + sql[0].toSql().replace("'", "''") + "'"));
            }
            if (rowsUpdated > 1) {
                throw new LockException("Did not update change log lock correctly");
            }
            if (rowsUpdated == 0) {
                // another node was faster
                return false;
            }
            database.commit();
            LogFactory.getLogger().info("Successfully acquired change log lock");
            hasChangeLogLock = true;
            database.setCanCacheLiquibaseTableInfo(true);
            return true;
        }
    } catch (Exception e) {
        throw new LockException(e);
    } finally {
        try {
            database.rollback();
        } catch (DatabaseException e) {
            ;
        }
    }
}
Also used : LockException(liquibase.exception.LockException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseException(liquibase.exception.DatabaseException) LiquibaseException(liquibase.exception.LiquibaseException) Sql(liquibase.sql.Sql) Executor(liquibase.executor.Executor) LockException(liquibase.exception.LockException) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException)

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