Search in sources :

Example 1 with Logger

use of liquibase.logging.Logger in project liquibase by liquibase.

the class DatabaseChangeLog method includeAll.

public void includeAll(String pathName, boolean isRelativeToChangelogFile, IncludeAllFilter resourceFilter, boolean errorIfMissingOrEmpty, Comparator<String> resourceComparator, ResourceAccessor resourceAccessor, ContextExpression includeContexts) throws SetupException {
    try {
        if (pathName == null) {
            throw new SetupException("No path attribute for includeAll");
        }
        pathName = pathName.replace('\\', '/');
        if (!(pathName.endsWith("/"))) {
            pathName = pathName + '/';
        }
        Logger log = LogFactory.getInstance().getLog();
        log.debug("includeAll for " + pathName);
        log.debug("Using file opener for includeAll: " + resourceAccessor.toString());
        String relativeTo = null;
        if (isRelativeToChangelogFile) {
            relativeTo = this.getPhysicalFilePath();
        }
        Set<String> unsortedResources = null;
        try {
            unsortedResources = resourceAccessor.list(relativeTo, pathName, true, false, true);
        } catch (FileNotFoundException e) {
            if (errorIfMissingOrEmpty) {
                throw e;
            }
        }
        SortedSet<String> resources = new TreeSet<String>(resourceComparator);
        if (unsortedResources != null) {
            for (String resourcePath : unsortedResources) {
                if (resourceFilter == null || resourceFilter.include(resourcePath)) {
                    resources.add(resourcePath);
                }
            }
        }
        if (resources.size() == 0 && errorIfMissingOrEmpty) {
            throw new SetupException("Could not find directory or directory was empty for includeAll '" + pathName + "'");
        }
        for (String path : resources) {
            include(path, false, resourceAccessor, includeContexts);
        }
    } catch (Exception e) {
        throw new SetupException(e);
    }
}
Also used : SetupException(liquibase.exception.SetupException) FileNotFoundException(java.io.FileNotFoundException) Logger(liquibase.logging.Logger) ParsedNodeException(liquibase.parser.core.ParsedNodeException) SetupException(liquibase.exception.SetupException) UnknownChangelogFormatException(liquibase.exception.UnknownChangelogFormatException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ValidationFailedException(liquibase.exception.ValidationFailedException) LiquibaseException(liquibase.exception.LiquibaseException)

Example 2 with Logger

use of liquibase.logging.Logger 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 3 with Logger

use of liquibase.logging.Logger in project liquibase by liquibase.

the class Main method configureClassLoader.

protected void configureClassLoader() throws CommandLineParsingException {
    final List<URL> urls = new ArrayList<URL>();
    if (this.classpath != null) {
        String[] classpath;
        if (isWindows()) {
            classpath = this.classpath.split(";");
        } else {
            classpath = this.classpath.split(":");
        }
        Logger logger = LogFactory.getInstance().getLog();
        for (String classpathEntry : classpath) {
            File classPathFile = new File(classpathEntry);
            if (!classPathFile.exists()) {
                throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist");
            }
            try {
                if (classpathEntry.endsWith(".war")) {
                    addWarFileClasspathEntries(classPathFile, urls);
                } else if (classpathEntry.endsWith(".ear")) {
                    JarFile earZip = new JarFile(classPathFile);
                    Enumeration<? extends JarEntry> entries = earZip.entries();
                    while (entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
                        if (entry.getName().toLowerCase().endsWith(".jar")) {
                            File jar = extract(earZip, entry);
                            URL newUrl = new URL("jar:" + jar.toURI().toURL() + "!/");
                            urls.add(newUrl);
                            logger.debug("Adding '" + newUrl + "' to classpath");
                            jar.deleteOnExit();
                        } else if (entry.getName().toLowerCase().endsWith("war")) {
                            File warFile = extract(earZip, entry);
                            addWarFileClasspathEntries(warFile, urls);
                        }
                    }
                } else {
                    URL newUrl = new File(classpathEntry).toURI().toURL();
                    logger.debug("Adding '" + newUrl + "' to classpath");
                    urls.add(newUrl);
                }
            } catch (Exception e) {
                throw new CommandLineParsingException(e);
            }
        }
    }
    if (includeSystemClasspath) {
        classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

            @Override
            public URLClassLoader run() {
                return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
            }
        });
    } else {
        classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

            @Override
            public URLClassLoader run() {
                return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
            }
        });
    }
    ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader));
    Thread.currentThread().setContextClassLoader(classLoader);
}
Also used : Logger(liquibase.logging.Logger) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) ParseException(java.text.ParseException) PrivilegedAction(java.security.PrivilegedAction) URLClassLoader(java.net.URLClassLoader) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) JarFile(java.util.jar.JarFile)

Example 4 with Logger

use of liquibase.logging.Logger in project liquibase by liquibase.

the class Main method addWarFileClasspathEntries.

private void addWarFileClasspathEntries(File classPathFile, List<URL> urls) throws IOException {
    Logger logger = LogFactory.getInstance().getLog();
    URL url = new URL("jar:" + classPathFile.toURI().toURL() + "!/WEB-INF/classes/");
    logger.info("adding '" + url + "' to classpath");
    urls.add(url);
    JarFile warZip = new JarFile(classPathFile);
    Enumeration<? extends JarEntry> entries = warZip.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().startsWith("WEB-INF/lib") && entry.getName().toLowerCase().endsWith(".jar")) {
            File jar = extract(warZip, entry);
            URL newUrl = new URL("jar:" + jar.toURI().toURL() + "!/");
            logger.info("adding '" + newUrl + "' to classpath");
            urls.add(newUrl);
            jar.deleteOnExit();
        }
    }
}
Also used : Logger(liquibase.logging.Logger) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) JarFile(java.util.jar.JarFile) URL(java.net.URL)

Example 5 with Logger

use of liquibase.logging.Logger in project liquibase by liquibase.

the class PostgresDatabase method setConnection.

@Override
public void setConnection(DatabaseConnection conn) {
    super.setConnection(conn);
    Logger log = LogFactory.getInstance().getLog();
    if (conn instanceof JdbcConnection) {
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            statement = ((JdbcConnection) conn).createStatement();
            resultSet = statement.executeQuery("select setting from pg_settings where name = 'edb_redwood_date'");
            if (resultSet.next()) {
                String setting = resultSet.getString(1);
                if (setting != null && setting.equals("on")) {
                    log.warning("EnterpriseDB " + conn.getURL() + " does not store DATE columns. Auto-converts them to TIMESTAMPs. (edb_redwood_date=true)");
                }
            }
        } catch (Exception e) {
            log.info("Cannot check pg_settings", e);
        } finally {
            JdbcUtils.close(resultSet, statement);
        }
    }
}
Also used : RawCallStatement(liquibase.statement.core.RawCallStatement) RawSqlStatement(liquibase.statement.core.RawSqlStatement) SqlStatement(liquibase.statement.SqlStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) JdbcConnection(liquibase.database.jvm.JdbcConnection) Logger(liquibase.logging.Logger) DatabaseException(liquibase.exception.DatabaseException) SQLException(java.sql.SQLException)

Aggregations

Logger (liquibase.logging.Logger)8 IOException (java.io.IOException)2 URL (java.net.URL)2 JarEntry (java.util.jar.JarEntry)2 JarFile (java.util.jar.JarFile)2 Database (liquibase.database.Database)2 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)2 SqlStatement (liquibase.statement.SqlStatement)2 FileNotFoundException (java.io.FileNotFoundException)1 URLClassLoader (java.net.URLClassLoader)1 PrivilegedAction (java.security.PrivilegedAction)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 Statement (java.sql.Statement)1 ParseException (java.text.ParseException)1 Properties (java.util.Properties)1 ColumnConfig (liquibase.change.ColumnConfig)1 ChangeLogIterator (liquibase.changelog.ChangeLogIterator)1 ChangeLogParameters (liquibase.changelog.ChangeLogParameters)1 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)1