Commit f92778e5 by zhoufensong

first commit

parents
* text eol=lf
*.ico binary
*.png binary
*.gif binary
*.jar binary
*.nofilter binary
*.kdbx binary
*.exe binary
*.dll binary
\ No newline at end of file
bin
build
target
*.iml
*.ipr
*.iws
*.ids
.project
.classpath
.settings
.metadata
.gradle
*.h2.db
.DS_Store
**/.idea/**
!**/.idea/runConfigurations/
!**/.idea/runConfigurations/*
!**/.idea/codeStyles/
!**/.idea/codeStyles/*
flyway-core/SPOOLEDCONTENTS.SQL
language: minimal
env:
matrix:
- JDK_VERSION=10
- JDK_VERSION=11
- JDK_VERSION=12
- JDK_VERSION=13
install: skip
script:
- docker run -it --rm -v "$PWD":/usr/src/flyway -w /usr/src/flyway maven:3-jdk-$JDK_VERSION mvn install -e
\ No newline at end of file
Contribute
==========
So you've got an awesome idea to throw into Flyway. Great! Please keep the following in mind:
* **Use http://stackoverflow.com/questions/tagged/flyway for Flyway questions that are not bugs.**
* **Contributions must include the necessary documentation updates.**
* **Make sure to read https://flywaydb.org/documentation/contribute/ first**
\ No newline at end of file
###### Which version and edition of Flyway are you using?
###### If this is not the latest version, can you reproduce the issue with the latest one as well?
(Many bugs are fixed in newer releases and upgrading will often resolve the issue)
###### Which client are you using? (Command-line, Java API, Maven plugin, Gradle plugin)
###### Which database are you using (type & version)?
###### Which operating system are you using?
###### What did you do?
(Please include the content causing the issue, any relevant configuration settings, the SQL statement that failed (if relevant) and the command you ran.)
###### What did you expect to see?
###### What did you see instead?
This diff is collapsed. Click to expand it.
Copyright 2010-2020 Redgate Software Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
# [Flyway](https://flywaydb.org) by [Redgate](https://www.red-gate.com/) [![Build Status](https://api.travis-ci.org/flyway/flyway.svg)](https://travis-ci.org/flyway/flyway) [![Maven Central](https://img.shields.io/maven-central/v/org.flywaydb/flyway-core.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.flywaydb.flyway-core%22) [![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0)
### Database Migrations Made Easy.
![Flyway](https://flywaydb.org/assets/logo/flyway-logo-tm.png "Flyway")
#### Evolve your database schema easily and reliably across all your instances.
Simple, focused and powerful.
#### Works on
Windows, macOS, Linux, Docker, Java and Android
#### Supported build tools
Maven and Gradle
#### Supported databases
Oracle, SQL Server, DB2, MySQL, Aurora MySQL, MariaDB, Percona XtraDB Cluster, PostgreSQL, Aurora PostgreSQL, Redshift, CockroachDB, SAP HANA, Sybase ASE, Informix, H2, HSQLDB, Derby, SQLite, Firebird
#### Third party plugins
SBT, Ant, Spring Boot, Grails, Play!, DropWizard, Grunt, Griffon, Ninja, ...
## Documentation
https://flywaydb.org
## About
Flyway is brought to you by [Redgate](https://www.red-gate.com/) with the help of [many contributors](https://flywaydb.org/documentation/contribute/hallOfFame.html).
## How to contribute
https://flywaydb.org/documentation/contribute
## License
Copyright (C) 2010-2020 [Boxfuse GmbH](https://boxfuse.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## Trademark
Flyway is a registered trademark of [Boxfuse GmbH](https://boxfuse.com), owned by [Redgate](https://www.red-gate.com/).
Welcome to Flyway.
------------------
Database Migrations Made Easy.
Documentation
-------------
You can find getting started guides and reference documentation at https://flywaydb.org
Contributing
------------
Here is the info on how you can contribute in various ways to the project: https://flywaydb.org/documentation/contribute/
License
-------
Copyright (C) 2010-2020 Boxfuse GmbH
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Flyway is a registered trademark of Boxfuse GmbH.
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
Welcome to Flyway
-----------------
Database Migrations Made Easy
Documentation
-------------
You can find getting started guides and reference documentation at https://flywaydb.org
Contributing
------------
Here is the info on how you can contribute in various ways to the project: https://flywaydb.org/documentation/contribute/
License
-------
Copyright (C) 2010-2020 Boxfuse GmbH
Flyway Community Edition : https://flywaydb.org/licenses/flyway-community
Flyway 30 day limited trial : https://flywaydb.org/licenses/flyway-trial
Flyway Pro Edition : https://flywaydb.org/licenses/flyway-pro
Flyway Enterprise Edition : https://flywaydb.org/licenses/flyway-enterprise
Flyway is a registered trademark of Boxfuse GmbH.
\ No newline at end of file
<!--
Copyright 2010-2020 Redgate Software Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<component xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/component/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/component/1.1.2 http://maven.apache.org/xsd/component-1.1.2.xsd">
<fileSets>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory></outputDirectory>
<includes>
<include>flyway.cmd</include>
</includes>
<fileMode>644</fileMode>
<filtered>true</filtered>
</fileSet>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory></outputDirectory>
<includes>
<include>flyway</include>
</includes>
<fileMode>744</fileMode>
<lineEnding>unix</lineEnding>
<filtered>true</filtered>
</fileSet>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory>drivers</outputDirectory>
<includes>
<include>put-your-jdbc-drivers-here.txt</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory>conf</outputDirectory>
<includes>
<include>flyway.conf</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory>sql</outputDirectory>
<includes>
<include>put-your-sql-migrations-here.txt</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory>jars</outputDirectory>
<includes>
<include>put-your-java-migration-jars-here.txt</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory>licenses</outputDirectory>
<includes>
<include>flyway-community.txt</include>
<include>LICENSES-THIRD-PARTY.txt</include>
<include>flyway-pro.txt</include>
<include>flyway-enterprise.txt</include>
</includes>
<fileMode>644</fileMode>
<filtered>true</filtered>
</fileSet>
<fileSet>
<directory>src/main/assembly</directory>
<outputDirectory></outputDirectory>
<includes>
<include>README.txt</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
<fileSet>
<directory>target/editions/pro</directory>
<outputDirectory>lib/pro</outputDirectory>
<includes>
<include>*</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
<fileSet>
<directory>target/editions/enterprise</directory>
<outputDirectory>lib/enterprise</outputDirectory>
<includes>
<include>*</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
<!-- Workaround for https://issues.apache.org/jira/browse/MASSEMBLY-864 -->
<useTransitiveDependencies>false</useTransitiveDependencies>
<includes>
<include>org.fusesource.jansi:jansi</include>
<include>com.google.code.gson:gson</include>
</includes>
</dependencySet>
<dependencySet>
<outputDirectory>lib/community</outputDirectory>
<!-- Workaround for https://issues.apache.org/jira/browse/MASSEMBLY-864 -->
<useTransitiveDependencies>false</useTransitiveDependencies>
<includes>
<include>org.flywaydb:flyway-core</include>
<include>org.flywaydb:flyway-commandline</include>
</includes>
</dependencySet>
<dependencySet>
<outputDirectory>drivers</outputDirectory>
<!-- Workaround for https://issues.apache.org/jira/browse/MASSEMBLY-864 -->
<useTransitiveDependencies>false</useTransitiveDependencies>
<includes>
<include>*</include>
</includes>
<excludes>
<exclude>org.flywaydb:flyway-*</exclude>
<exclude>org.fusesource.jansi:jansi</exclude>
<exclude>com.google.code.gson:gson</exclude>
</excludes>
</dependencySet>
</dependencySets>
</component>
\ No newline at end of file
#!/usr/bin/env bash
#
# Copyright 2010-2020 Boxfuse GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Detect Linux
linux=false
case "`uname`" in
Linux*) linux=true;;
esac
# Dereference softlinks
THIS="$0"
while [ -h "$THIS" ] ; do
ls=`ls -ld "$THIS"`
softlink=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$softlink" : '/.*' > /dev/null; then THIS="$softlink"; else THIS=`dirname "$THIS"`/"$softlink"; fi
done
# Detect the installation directory
INSTALLDIR=`dirname "$THIS"`
if [ -x "$INSTALLDIR/jre/bin/java" ]; then
JAVA_CMD=$INSTALLDIR/jre/bin/java
else
# Use JAVA_HOME if it is set
if [ -z "$JAVA_HOME" ]; then JAVA_CMD=java; else JAVA_CMD=$JAVA_HOME/bin/java; fi
fi
# Determine Flyway edition to use
POSITIONAL=()
while [[ $# -gt 0 ]]; do
POSITIONAL+=("$1")
flag="$1"
case $flag in
-community)
FLYWAY_EDITION=community
;;
-pro)
FLYWAY_EDITION=pro
;;
-enterprise)
FLYWAY_EDITION=enterprise
;;
esac
shift
done
set -- "${POSITIONAL[@]}"
if [ -z "$FLYWAY_EDITION" ]; then
FLYWAY_EDITION=community
fi
CP="$INSTALLDIR/lib/*:$INSTALLDIR/lib/$FLYWAY_EDITION/*:$INSTALLDIR/drivers/*"
EXTRA_ARGS=
if $linux; then
EXTRA_ARGS=-Djava.security.egd=file:/dev/../dev/urandom
fi
if `command -v cygpath > /dev/null`; then CP=`cygpath -pw "$CP"`; fi
"$JAVA_CMD" $JAVA_ARGS $EXTRA_ARGS -cp "$CP" org.flywaydb.commandline.Main "$@"
# Exit using the same code returned from Java
exit $?
\ No newline at end of file
@REM
@REM Copyright 2010-2020 Redgate Software Ltd
@REM
@REM Licensed under the Apache License, Version 2.0 (the "License");
@REM you may not use this file except in compliance with the License.
@REM You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing, software
@REM distributed under the License is distributed on an "AS IS" BASIS,
@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@REM See the License for the specific language governing permissions and
@REM limitations under the License.
@REM
@Echo off
setlocal
@REM Set the current directory to the installation directory
call :getCurrentBatch INSTALLDIR1
set INSTALLDIR=%INSTALLDIR1%
set INSTALLDIR=%INSTALLDIR:~0,-10%
if exist "%INSTALLDIR%\jre\bin\java.exe" (
set JAVA_CMD="%INSTALLDIR%\jre\bin\java.exe"
) else (
@REM Use JAVA_HOME if it is set
if "%JAVA_HOME%"=="" (
set JAVA_CMD=java
) else (
set JAVA_CMD="%JAVA_HOME%\bin\java.exe"
)
)
if "%JAVA_ARGS%"=="" (
set JAVA_ARGS=
)
@REM Determine Flyway edition to use
:loop
IF NOT [%1]==[] (
IF [%1]==[-community] (
SET FLYWAY_EDITION=community
GOTO :loop-end
)
IF [%1]==[-pro] (
SET FLYWAY_EDITION=pro
GOTO :loop-end
)
IF [%1]==[-enterprise] (
SET FLYWAY_EDITION=enterprise
GOTO :loop-end
)
SHIFT /1
GOTO :loop
)
:loop-end
if "%FLYWAY_EDITION%"=="" (
set FLYWAY_EDITION=community
)
%JAVA_CMD% %JAVA_ARGS% -cp "%CLASSPATH%;%INSTALLDIR%\lib\*;%INSTALLDIR%\lib\%FLYWAY_EDITION%\*;%INSTALLDIR%\drivers\*" org.flywaydb.commandline.Main %*
@REM Exit using the same code returned from Java
EXIT /B %ERRORLEVEL%
:getCurrentBatch
set "%~1=%~f0"
goto :eof
\ No newline at end of file
<!--
Copyright 2010-2020 Redgate Software Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>linux-x64</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>flyway-${project.version}</baseDirectory>
<componentDescriptors>
<componentDescriptor>src/main/assembly/component.xml</componentDescriptor>
</componentDescriptors>
<fileSets>
<fileSet>
<directory>target/dependency/jre-linux-x64-tar.gz/jdk-${version.jre}+9-jre</directory>
<outputDirectory>jre</outputDirectory>
<fileMode>755</fileMode>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
<!--
Copyright 2010-2020 Redgate Software Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>macosx-x64</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>flyway-${project.version}</baseDirectory>
<componentDescriptors>
<componentDescriptor>src/main/assembly/component.xml</componentDescriptor>
</componentDescriptors>
<fileSets>
<fileSet>
<directory>target/dependency/jre-macos-x64-tar.gz/jdk-${version.jre}+9-jre/Contents/Home</directory>
<outputDirectory>jre</outputDirectory>
<fileMode>755</fileMode>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
<!--
Copyright 2010-2020 Redgate Software Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>no-jre</id>
<formats>
<format>tar.gz</format>
<format>zip</format>
</formats>
<baseDirectory>flyway-${project.version}</baseDirectory>
<componentDescriptors>
<componentDescriptor>src/main/assembly/component.xml</componentDescriptor>
</componentDescriptors>
</assembly>
\ No newline at end of file
<!--
Copyright 2010-2020 Redgate Software Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>windows-x64</id>
<formats>
<format>zip</format>
</formats>
<baseDirectory>flyway-${project.version}</baseDirectory>
<componentDescriptors>
<componentDescriptor>src/main/assembly/component.xml</componentDescriptor>
</componentDescriptors>
<fileSets>
<fileSet>
<directory>target/dependency/jre-windows-x64-zip/jdk-${version.jre}+9-jre</directory>
<outputDirectory>jre</outputDirectory>
<fileMode>644</fileMode>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.core.api.logging.Log;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Color;
import org.fusesource.jansi.AnsiConsole;
import java.io.PrintStream;
/**
* Wrapper which adds color to a Console output.
*/
class ColorizedConsoleLog implements Log {
private final ConsoleLog log;
public static void install(boolean force) {
if (force) {
System.setProperty("jansi.force", "true");
}
AnsiConsole.systemInstall();
}
public ColorizedConsoleLog(ConsoleLog log) {
this.log = log;
}
@Override
public boolean isDebugEnabled() {
return this.log.isDebugEnabled();
}
@Override
public void debug(String message) {
colorizeBright(System.out, Color.BLACK);
this.log.debug(message);
reset(System.out);
}
@Override
public void info(String message) {
if (message.startsWith("Successfully")) {
colorize(System.out, Color.GREEN);
this.log.info(message);
reset(System.out);
} else {
this.log.info(message);
}
}
@Override
public void warn(String message) {
colorize(System.out, Color.YELLOW);
this.log.warn(message);
reset(System.out);
}
@Override
public void error(String message) {
colorize(System.err, Color.RED);
this.log.error(message);
reset(System.err);
}
@Override
public void error(String message, Exception e) {
colorize(System.err, Color.RED);
this.log.error(message, e);
reset(System.err);
}
private void colorize(PrintStream stream, Color color) {
stream.print(Ansi.ansi().fg(color));
}
private void colorizeBright(PrintStream stream, Color color) {
stream.print(Ansi.ansi().fgBright(color));
}
private void reset(PrintStream stream) {
stream.print(Ansi.ansi().reset());
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.commandline.ConsoleLog.Level;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.internal.util.StringUtils;
import java.util.*;
class CommandLineArguments {
enum Color {
ALWAYS("always"),
NEVER("never"),
AUTO("auto");
private final String value;
Color(String value) {
this.value = value;
}
public static Color fromString(String value) {
if (value.isEmpty()) {
return AUTO;
}
for (Color color : values()) {
if (color.value.equals(value)) {
return color;
}
}
return null;
}
public static boolean isValid(String value) {
return fromString(value) != null;
}
}
// Flags
private static String DEBUG_FLAG = "-X";
private static String QUIET_FLAG = "-q";
private static String SUPPRESS_PROMPT_FLAG = "-n";
private static String PRINT_VERSION_AND_EXIT_FLAG = "-v";
private static String JSON_FLAG = "-json";
private static String PRINT_USAGE_FLAG = "-?";
private static String COMMUNITY_FLAG = "-community";
private static String PRO_FLAG = "-pro";
private static String ENTERPRISE_FLAG = "-enterprise";
// Command line specific configuration options
private static String OUTPUT_FILE = "outputFile";
private static String LOG_FILE = "logFile";
private static String CONFIG_FILE_ENCODING = "configFileEncoding";
private static String CONFIG_FILES = "configFiles";
private static String COLOR = "color";
private static String WORKING_DIRECTORY = "workingDirectory";
private static List<String> VALID_OPERATIONS_AND_FLAGS = Arrays.asList(
DEBUG_FLAG,
QUIET_FLAG,
SUPPRESS_PROMPT_FLAG,
PRINT_VERSION_AND_EXIT_FLAG,
JSON_FLAG,
PRINT_USAGE_FLAG,
COMMUNITY_FLAG,
PRO_FLAG,
ENTERPRISE_FLAG,
"help",
"migrate",
"clean",
"info",
"validate",
"undo",
"baseline",
"repair"
);
private final String[] args;
CommandLineArguments(String[] args) {
this.args = args;
}
private static boolean isFlagSet(String[] args, String flag) {
for (String arg : args) {
if (flag.equals(arg)) {
return true;
}
}
return false;
}
private static String getArgumentValue(String argName, String[] allArgs) {
for (String arg : allArgs) {
if (arg.startsWith("-" + argName + "=")) {
return parseConfigurationOptionValueFromArg(arg);
}
}
return "";
}
private static String parseConfigurationOptionValueFromArg(String arg) {
int index = arg.indexOf("=");
if (index < 0 || index == arg.length()) {
return "";
}
return arg.substring(index + 1);
}
private static List<String> getOperationsFromArgs(String[] args) {
List<String> operations = new ArrayList<>();
for (String arg : args) {
if (!arg.startsWith("-")) {
operations.add(arg);
}
}
return operations;
}
private static List<String> getConfigFilesFromArgs(String[] args) {
String configFilesCommaSeparatedList = getArgumentValue(CONFIG_FILES, args);
return Arrays.asList(StringUtils.tokenizeToStringArray(configFilesCommaSeparatedList, ","));
}
private static Map<String, String> getConfigurationFromArgs(String[] args) {
Map<String, String> configuration = new HashMap<>();
for (String arg : args) {
if (isConfigurationArg(arg)) {
String configurationOptionName = getConfigurationOptionNameFromArg(arg);
if (!isConfigurationOptionIgnored(configurationOptionName)) {
configuration.put("flyway." + configurationOptionName, parseConfigurationOptionValueFromArg(arg));
}
}
}
return configuration;
}
private static boolean isConfigurationOptionIgnored(String configurationOptionName) {
return OUTPUT_FILE.equals(configurationOptionName) ||
LOG_FILE.equals(configurationOptionName) ||
COLOR.equals(configurationOptionName) ||
WORKING_DIRECTORY.equals(configurationOptionName);
}
private static String getConfigurationOptionNameFromArg(String arg) {
int index = arg.indexOf("=");
return arg.substring(1, index);
}
private static boolean isConfigurationArg(String arg) {
return arg.startsWith("-") && arg.contains("=");
}
void validate(Log log) {
for (String arg : args) {
if (!isConfigurationArg(arg) && !CommandLineArguments.VALID_OPERATIONS_AND_FLAGS.contains(arg)) {
throw new FlywayException("Invalid argument: " + arg);
}
}
if (isLogFilepathSet()) {
if (isOutputFileSet()) {
throw new FlywayException("-logFile and -outputFile are incompatible. -logFile is deprecated. Instead use -outputFile.");
}
if (shouldOutputJson()) {
throw new FlywayException("-logFile and -json are incompatible. -logFile is deprecated. Instead use -outputFile to print JSON to a file.");
}
log.warn("-logFile is deprecated. Instead use -outputFile.");
}
if (shouldOutputJson() && !hasOperation("info") ) {
throw new FlywayException("The -json flag is only supported by the info command.");
}
String colorArgumentValue = getArgumentValue(COLOR, args);
if (!Color.isValid(colorArgumentValue)) {
throw new FlywayException("'" + colorArgumentValue + "' is an invalid value for the -color option. Use 'always', 'never', or 'auto'.");
}
}
boolean shouldSuppressPrompt() {
return isFlagSet(args, SUPPRESS_PROMPT_FLAG);
}
boolean shouldPrintVersionAndExit() {
return isFlagSet(args, PRINT_VERSION_AND_EXIT_FLAG);
}
boolean shouldOutputJson() {
return isFlagSet(args, JSON_FLAG);
}
boolean shouldPrintUsage() {
return isFlagSet(args, PRINT_USAGE_FLAG) || getOperations().isEmpty();
}
Level getLogLevel() {
if (isFlagSet(args, QUIET_FLAG)) {
return Level.WARN;
}
if (isFlagSet(args, DEBUG_FLAG)) {
return Level.DEBUG;
}
return Level.INFO;
}
boolean hasOperation(String operation) {
return getOperations().contains(operation);
}
List<String> getOperations() {
return getOperationsFromArgs(args);
}
List<String> getConfigFiles() {
return getConfigFilesFromArgs(args);
}
String getOutputFile() {
return getArgumentValue(OUTPUT_FILE, args);
}
String getLogFilepath() {
return getArgumentValue(LOG_FILE, args);
}
String getWorkingDirectory() {
return getArgumentValue(WORKING_DIRECTORY, args);
}
boolean isOutputFileSet() {
return !getOutputFile().isEmpty();
}
boolean isLogFilepathSet() {
return !getLogFilepath().isEmpty();
}
boolean isWorkingDirectorySet() {
return !getWorkingDirectory().isEmpty();
}
String getConfigFileEncoding() {
return getArgumentValue(CONFIG_FILE_ENCODING, args);
}
boolean isConfigFileEncodingSet() {
return !getConfigFileEncoding().isEmpty();
}
Color getColor() {
return Color.fromString(getArgumentValue(COLOR, args));
}
Map<String, String> getConfiguration() {
return getConfigurationFromArgs(args);
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.core.api.logging.Log;
/**
* Console output for standard output and standard error.
*/
class ConsoleLog implements Log {
public enum Level {
DEBUG, INFO, WARN
}
private final Level level;
/**
* Creates a new PrintStream Log.
*
* @param level the log level.
*/
public ConsoleLog(Level level) {
this.level = level;
}
@Override
public boolean isDebugEnabled() {
return level == Level.DEBUG;
}
public void debug(String message) {
if (isDebugEnabled()) {
System.out.println("DEBUG: " + message);
}
}
public void info(String message) {
if (level.compareTo(Level.INFO) <= 0) {
System.out.println(message);
}
}
public void warn(String message) {
System.out.println("WARNING: " + message);
}
public void error(String message) {
System.err.println("ERROR: " + message);
}
public void error(String message, Exception e) {
System.err.println("ERROR: " + message);
e.printStackTrace(System.err);
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.commandline.CommandLineArguments.Color;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.api.logging.LogCreator;
/**
* Log Creator for the Command-Line console.
*/
class ConsoleLogCreator implements LogCreator {
private final CommandLineArguments commandLineArguments;
/**
* Creates a new Console Log Creator.
*
* @param commandLineArguments The command line arguments.
*/
ConsoleLogCreator(CommandLineArguments commandLineArguments) {
this.commandLineArguments = commandLineArguments;
}
public Log createLogger(Class<?> clazz) {
ConsoleLog log = new ConsoleLog(commandLineArguments.getLogLevel());
Color color = commandLineArguments.getColor();
if (Color.NEVER.equals(color) || (Color.AUTO.equals(color) && System.console() == null)) {
return log;
}
ColorizedConsoleLog.install(Color.ALWAYS.equals(color));
return new ColorizedConsoleLog(log);
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.commandline.ConsoleLog.Level;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.logging.Log;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
class FileLog implements Log {
private final Path path;
private final Level level;
public FileLog(Path path, Level level) {
this.path = path;
this.level = level;
}
@Override
public boolean isDebugEnabled() {
return level == Level.DEBUG;
}
@Override
public void debug(String message) {
if (isDebugEnabled()) {
writeLogMessage("DEBUG", message);
}
}
@Override
public void info(String message) {
if (level.compareTo(Level.INFO) <= 0) {
writeLogMessage(message);
}
}
@Override
public void warn(String message) {
writeLogMessage("WARNING", message);
}
@Override
public void error(String message) {
writeLogMessage("ERROR", message);
}
@Override
public void error(String message, Exception e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
String stackTrace = stringWriter.toString();
writeLogMessage("ERROR", message);
writeLogMessage(stackTrace);
}
private void writeLogMessage(String prefix, String message) {
String logMessage = prefix + ": " + message;
writeLogMessage(logMessage);
}
private void writeLogMessage(String logMessage) {
try {
Files.write(path, (logMessage + "\n").getBytes(), StandardOpenOption.APPEND, StandardOpenOption.WRITE);
} catch(IOException exception) {
throw new FlywayException("Could not write to file at " + path + ".", exception);
}
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.api.logging.LogCreator;
import org.flywaydb.commandline.ConsoleLog.Level;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* Log Creator for logging to a file
*/
class FileLogCreator implements LogCreator {
private final Level level;
private final Path path;
/**
* Creates a new file Log Creator.
*
* @param commandLineArguments The command line arguments
*/
FileLogCreator(CommandLineArguments commandLineArguments) {
String outputFilepath = "";
if (commandLineArguments.isOutputFileSet()) {
outputFilepath = commandLineArguments.getOutputFile();
} else if (commandLineArguments.isLogFilepathSet()) {
outputFilepath = commandLineArguments.getLogFilepath();
}
this.level = commandLineArguments.getLogLevel();
this.path = Paths.get(outputFilepath);
prepareOutputFile(path);
}
public Log createLogger(Class<?> clazz) {
return new FileLog(path, level);
}
private static void prepareOutputFile(Path path) {
try {
Files.write(path, "".getBytes(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
} catch(IOException exception) {
throw new FlywayException("Could not initialize log file at " + path + ".", exception);
}
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.api.logging.LogCreator;
import java.util.ArrayList;
import java.util.List;
/**
* Log creator for a MultiLog
*/
class MultiLogCreator implements LogCreator {
private final List<LogCreator> logCreators;
MultiLogCreator(List<LogCreator> logCreators) {
this.logCreators = logCreators;
}
@Override
public Log createLogger(Class<?> clazz) {
List<Log> logs = new ArrayList<>();
for (LogCreator logCreator : logCreators) {
logs.add(logCreator.createLogger(clazz));
}
return new MultiLogger(logs);
}
static MultiLogCreator empty() {
return new MultiLogCreator(new ArrayList<>());
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.commandline;
import org.flywaydb.core.api.logging.Log;
import java.util.List;
/**
* Log implementation that forwards method calls to multiple implementations
*/
class MultiLogger implements Log {
private final List<Log> logs;
public MultiLogger(List<Log> logs) {
this.logs = logs;
}
@Override
public boolean isDebugEnabled() {
for (Log log : logs) {
if (!log.isDebugEnabled()) {
return false;
}
}
return true;
}
@Override
public void debug(String message) {
for (Log log : logs) {
log.debug(message);
}
}
@Override
public void info(String message) {
for (Log log : logs) {
log.info(message);
}
}
@Override
public void warn(String message) {
for (Log log : logs) {
log.warn(message);
}
}
@Override
public void error(String message) {
for (Log log : logs) {
log.error(message);
}
}
@Override
public void error(String message, Exception e) {
for (Log log : logs) {
log.error(message, e);
}
}
}
\ No newline at end of file
<!--
Copyright 2010-2020 Redgate Software Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-parent</artifactId>
<version>0-SNAPSHOT</version>
</parent>
<artifactId>flyway-core</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jboss-vfs</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<optional>true</optional>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-license</id>
<goals>
<goal>copy-resources</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<resources>
<resource>
<directory>..</directory>
<includes>
<include>LICENSE.txt</include>
<include>README.txt</include>
</includes>
</resource>
</resources>
<outputDirectory>${project.build.outputDirectory}/META-INF</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Automatic-Module-Name>org.flywaydb.core</Automatic-Module-Name>
<Bundle-SymbolicName>org.flywaydb.core</Bundle-SymbolicName>
<Export-Package>
org.flywaydb.core;version=${project.version},
org.flywaydb.core.api.*;version=${project.version}
</Export-Package>
<Import-Package>
android.content;version="[4.0.1.2,9)";resolution:=optional,
android.content.pm;version="[4.0.1.2,9)";resolution:=optional,
android.content.res;version="[4.0.1.2,9)";resolution:=optional,
android.util;version="[4.0.1.2,9)";resolution:=optional,
dalvik.system;version="[4.0.1.2,9)";resolution:=optional,
javax.sql,
org.apache.commons.logging;version="[1.1,2)";resolution:=optional,
org.jboss.vfs;version="[3.1.0,4)";resolution:=optional,
org.postgresql.copy;version="[9.3.1102,100.0)";resolution:=optional,
org.postgresql.core;version="[9.3.1102,100.0)";resolution:=optional,
org.osgi.framework;version="1.3.0";resolution:=mandatory,
org.slf4j;version="[1.6,2)";resolution:=optional,
org.springframework.*;version="[2.5,6.0)";resolution:=optional
</Import-Package>
</instructions>
</configuration>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<sourceFileIncludes>
<sourceFileInclude>**/core/Flyway.java</sourceFileInclude>
<sourceFileInclude>**/core/api/**/*.java</sourceFileInclude>
</sourceFileIncludes>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<sourceFileIncludes>
<sourceFileInclude>**/core/Flyway.java</sourceFileInclude>
<sourceFileInclude>**/core/api/**/*.java</sourceFileInclude>
</sourceFileIncludes>
</configuration>
</plugin>
</plugins>
</reporting>
</project>
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
import java.util.Collection;
/**
* A facility to obtain classes.
*/
public interface ClassProvider<I> {
/**
* Retrieve all classes which implement the specified interface.
*
* @return The non-abstract classes that were found.
*/
Collection<Class<? extends I>> getClasses();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
public enum ErrorCode {
FAULT,
ERROR,
JDBC_DRIVER,
DB_CONNECTION,
DUPLICATE_VERSIONED_MIGRATION,
DUPLICATE_REPEATABLE_MIGRATION,
DUPLICATE_UNDO_MIGRATION,
CONFIGURATION;
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
/**
* Exception thrown when Flyway encounters a problem.
*/
public class FlywayException extends RuntimeException {
private ErrorCode errorCode = ErrorCode.ERROR;
/**
* Creates a new FlywayException with this message, cause, and error code.
*
* @param message The exception message.
* @param cause The exception cause.
* @param errorCode The error code.
*/
public FlywayException(String message, Throwable cause, ErrorCode errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
/**
* Creates a new FlywayException with this message and error code
*
* @param message The exception message.
* @param errorCode The error code.
*/
public FlywayException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
}
/**
* Creates a new FlywayException with this message and this cause.
*
* @param message The exception message.
* @param cause The exception cause.
*/
public FlywayException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a new FlywayException with this cause. For use in subclasses that override getMessage().
*
* @param cause The exception cause.
*/
public FlywayException(Throwable cause) {
super(cause);
}
/**
* Creates a new FlywayException with this message.
*
* @param message The exception message.
*/
public FlywayException(String message) {
super(message);
}
/**
* Creates a new FlywayException. For use in subclasses that override getMessage().
*/
public FlywayException() {
super();
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
import org.flywaydb.core.internal.output.InfoOutput;
interface InfoOutputProvider {
InfoOutput getInfoOutput();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
import java.util.Date;
/**
* Info about a migration.
*/
public interface MigrationInfo extends Comparable<MigrationInfo> {
/**
* @return The type of migration (BASELINE, SQL, JDBC, ...)
*/
MigrationType getType();
/**
* @return The target version of this migration.
*/
Integer getChecksum();
/**
* @return The schema version after the migration is complete.
*/
MigrationVersion getVersion();
/**
* @return The description of the migration.
*/
String getDescription();
/**
* @return The name of the script to execute for this migration, relative to its classpath or filesystem location.
*/
String getScript();
/**
* @return The state of the migration (PENDING, SUCCESS, ...)
*/
MigrationState getState();
/**
* @return The timestamp when this migration was installed. (Only for applied migrations)
*/
Date getInstalledOn();
/**
* @return The user that installed this migration. (Only for applied migrations)
*/
String getInstalledBy();
/**
* @return The rank of this installed migration. This is the most precise way to sort applied migrations by installation order.
* Migrations that were applied later have a higher rank. (Only for applied migrations)
*/
Integer getInstalledRank();
/**
* @return The execution time (in millis) of this migration. (Only for applied migrations)
*/
Integer getExecutionTime();
/**
* @return The physical location of the migration on disk.
*/
String getPhysicalLocation();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
/**
* Info about all migrations, including applied, current and pending with details and status.
*/
public interface MigrationInfoService extends InfoOutputProvider {
/**
* Retrieves the full set of infos about applied, current and future migrations.
*
* @return The full set of infos. An empty array if none.
*/
MigrationInfo[] all();
/**
* Retrieves the information of the current applied migration, if any.
*
* @return The info. {@code null} if no migrations have been applied yet.
*/
MigrationInfo current();
/**
* Retrieves the full set of infos about pending migrations, available locally, but not yet applied to the DB.
*
* @return The pending migrations. An empty array if none.
*/
MigrationInfo[] pending();
/**
* Retrieves the full set of infos about the migrations applied to the DB.
*
* @return The applied migrations. An empty array if none.
*/
MigrationInfo[] applied();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
/**
* The state of a migration.
*/
public enum MigrationState {
/**
* This migration has not been applied yet.
*/
PENDING("Pending", true, false, false),
/**
* This migration has not been applied yet, and won't be applied because target is set to a lower version.
*/
ABOVE_TARGET("Above Target", true, false, false),
/**
* This migration was not applied against this DB, because the schema history table was baselined with a higher version.
*/
BELOW_BASELINE("Below Baseline", true, false, false),
/**
* This migration has baselined this DB.
*/
BASELINE("Baseline", true, true, false),
/**
* <p>This usually indicates a problem.</p>
* <p>
* This migration was not applied against this DB, because a migration with a higher version has already been
* applied. This probably means some checkins happened out of order.
* </p>
* <p>Fix by increasing the version number, run clean and migrate again or rerun migration with outOfOrder enabled.</p>
*/
IGNORED("Ignored", true, false, false),
/**
* <p>This migration succeeded.</p>
* <p>
* This migration was applied against this DB, but it is not available locally.
* This usually results from multiple older migration files being consolidated into a single one.
* </p>
*/
MISSING_SUCCESS("Missing", false, true, false),
/**
* <p>This migration failed.</p>
* <p>
* This migration was applied against this DB, but it is not available locally.
* This usually results from multiple older migration files being consolidated into a single one.
* </p>
* <p>This should rarely, if ever, occur in practice.</p>
*/
MISSING_FAILED("Failed (Missing)", false, true, true),
/**
* This migration succeeded.
*/
SUCCESS("Success", true, true, false),
/**
* This versioned migration succeeded, but has since been undone.
*/
UNDONE("Undone", true, true, false),
/**
* This undo migration is ready to be applied if desired.
*/
AVAILABLE("Available", true, false, false),
/**
* This migration failed.
*/
FAILED("Failed", true, true, true),
/**
* <p>This migration succeeded.</p>
* <p>
* This migration succeeded, but it was applied out of order.
* Rerunning the entire migration history might produce different results!
* </p>
*/
OUT_OF_ORDER("Out of Order", true, true, false),
/**
* <p>This migration succeeded.</p>
* <p>
* This migration has been applied against the DB, but it is not available locally.
* Its version is higher than the highest version available locally.
* It was most likely successfully installed by a future version of this deployable.
* </p>
*/
FUTURE_SUCCESS("Future", false, true, false),
/**
* <p>This migration failed.</p>
* <p>
* This migration has been applied against the DB, but it is not available locally.
* Its version is higher than the highest version available locally.
* It most likely failed during the installation of a future version of this deployable.
* </p>
*/
FUTURE_FAILED("Failed (Future)", false, true, true),
/**
* This is a repeatable migration that is outdated and should be re-applied.
*/
OUTDATED("Outdated", true, true, false),
/**
* This is a repeatable migration that is outdated and has already been superseded by a newer run.
*/
SUPERSEDED("Superseded", true, true, false);
/**
* The name suitable for display to the end-user.
*/
private final String displayName;
/**
* Flag indicating if this migration is available on the classpath or not.
*/
private final boolean resolved;
/**
* Flag indicating if this migration has been applied or not.
*/
private final boolean applied;
/**
* Flag indicating if this migration has failed when it was applied or not.
*/
private final boolean failed;
/**
* Creates a new MigrationState.
*
* @param displayName The name suitable for display to the end-user.
* @param resolved Flag indicating if this migration is available on the classpath or not.
* @param applied Flag indicating if this migration has been applied or not.
* @param failed Flag indicating if this migration has failed when it was applied or not.
*/
MigrationState(String displayName, boolean resolved, boolean applied, boolean failed) {
this.displayName = displayName;
this.resolved = resolved;
this.applied = applied;
this.failed = failed;
}
/**
* @return The name suitable for display to the end-user.
*/
public String getDisplayName() {
return displayName;
}
/**
* @return Flag indicating if this migration has been applied or not.
*/
public boolean isApplied() {
return applied;
}
/**
* @return Flag indicating if this migration has been resolved or not.
*/
public boolean isResolved() {
return resolved;
}
/**
* @return Flag indicating if this migration has failed or not.
*/
public boolean isFailed() {
return failed;
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
/**
* Type of migration.
*/
public enum MigrationType {
/**
* Schema creation migration.
*/
SCHEMA(true, false),
/**
* Baseline migration.
*/
BASELINE(true, false),
/**
* SQL migrations.
*/
SQL(false, false),
/**
* Undo SQL migrations.
*/
UNDO_SQL(false, true),
/**
* JDBC Java-based migrations.
*/
JDBC(false, false),
/**
* Undo JDBC java-based migrations.
*/
UNDO_JDBC(false, true),
/**
* Spring JDBC Java-based migrations.
*
* @deprecated Will be removed in Flyway 7.0. Use JDBC instead.
*/
@Deprecated
SPRING_JDBC(false, false),
/**
* Undo Spring JDBC java-based migrations.
*
* @deprecated Will be removed in Flyway 7.0. Use UNDO_JDBC instead.
*/
@Deprecated
UNDO_SPRING_JDBC(false, true),
/**
* Migrations using custom MigrationResolvers.
*/
CUSTOM(false, false),
/**
* Undo migrations using custom MigrationResolvers.
*/
UNDO_CUSTOM(false, true);
private final boolean synthetic;
private final boolean undo;
MigrationType(boolean synthetic, boolean undo) {
this.synthetic = synthetic;
this.undo = undo;
}
/**
* @return Whether this is a synthetic migration type, which is only ever present in the schema history table,
* but never discovered by migration resolvers.
*/
public boolean isSynthetic() {
return synthetic;
}
/**
* @return Whether this is an undo migration, which has undone an earlier migration present in the schema history table.
*/
public boolean isUndo() {
return undo;
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* A version of a migration.
*
* @author Axel Fontaine
*/
public final class MigrationVersion implements Comparable<MigrationVersion> {
/**
* Version for an empty schema.
*/
public static final MigrationVersion EMPTY = new MigrationVersion(null, "<< Empty Schema >>");
/**
* Latest version.
*/
public static final MigrationVersion LATEST = new MigrationVersion(BigInteger.valueOf(-1), "<< Latest Version >>");
/**
* Current version. Only a marker. For the real version use Flyway.info().current() instead.
*/
public static final MigrationVersion CURRENT = new MigrationVersion(BigInteger.valueOf(-2), "<< Current Version >>");
/**
* Regex for matching proper version format
*/
private static final Pattern SPLIT_REGEX = Pattern.compile("\\.(?=\\d)");
/**
* The individual parts this version string is composed of. Ex. 1.2.3.4.0 -> [1, 2, 3, 4, 0]
*/
private final List<BigInteger> versionParts;
/**
* The printable text to represent the version.
*/
private final String displayText;
/**
* Create a MigrationVersion from a version String.
*
* @param version The version String. The value {@code current} will be interpreted as MigrationVersion.CURRENT,
* a marker for the latest version that has been applied to the database.
* @return The MigrationVersion
*/
@SuppressWarnings("ConstantConditions")
public static MigrationVersion fromVersion(String version) {
if ("current".equalsIgnoreCase(version)) return CURRENT;
if ("latest".equalsIgnoreCase(version) || LATEST.getVersion().equals(version)) return LATEST;
if (version == null) return EMPTY;
return new MigrationVersion(version);
}
/**
* Creates a Version using this version string.
*
* @param version The version in one of the following formats: 6, 6.0, 005, 1.2.3.4, 201004200021. <br/>{@code null}
* means that this version refers to an empty schema.
*/
private MigrationVersion(String version) {
String normalizedVersion = version.replace('_', '.');
this.versionParts = tokenize(normalizedVersion);
this.displayText = normalizedVersion;
}
/**
* Creates a Version using this version string.
*
* @param version The version in one of the following formats: 6, 6.0, 005, 1.2.3.4, 201004200021. <br/>{@code null}
* means that this version refers to an empty schema.
* @param displayText The alternative text to display instead of the version number.
*/
private MigrationVersion(BigInteger version, String displayText) {
this.versionParts = new ArrayList<>();
this.versionParts.add(version);
this.displayText = displayText;
}
/**
* @return The textual representation of the version.
*/
@Override
public String toString() {
return displayText;
}
/**
* @return Numeric version as String
*/
public String getVersion() {
if (this.equals(EMPTY)) return null;
if (this.equals(LATEST)) return Long.toString(Long.MAX_VALUE);
return displayText;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MigrationVersion version1 = (MigrationVersion) o;
return compareTo(version1) == 0;
}
@Override
public int hashCode() {
return versionParts == null ? 0 : versionParts.hashCode();
}
/**
* Convenience method for quickly checking whether this version is at least as new as this other version.
*
* @param otherVersion The other version.
* @return {@code true} if this version is equal or newer, {@code false} if it is older.
*/
public boolean isAtLeast(String otherVersion) {
return compareTo(MigrationVersion.fromVersion(otherVersion)) >= 0;
}
/**
* Convenience method for quickly checking whether this version is newer than this other version.
*
* @param otherVersion The other version.
* @return {@code true} if this version is newer, {@code false} if it is not.
*/
public boolean isNewerThan(String otherVersion) {
return compareTo(MigrationVersion.fromVersion(otherVersion)) > 0;
}
/**
* Convenience method for quickly checking whether this major version is newer than this other major version.
*
* @param otherVersion The other version.
* @return {@code true} if this major version is newer, {@code false} if it is not.
*/
public boolean isMajorNewerThan(String otherVersion) {
return getMajor().compareTo(MigrationVersion.fromVersion(otherVersion).getMajor()) > 0;
}
/**
* @return The major version.
*/
public BigInteger getMajor() {
return versionParts.get(0);
}
/**
* @return The major version as a string.
*/
public String getMajorAsString() {
return versionParts.get(0).toString();
}
/**
* @return The minor version as a string.
*/
public String getMinorAsString() {
if (versionParts.size() == 1) {
return "0";
}
return versionParts.get(1).toString();
}
@Override
public int compareTo(MigrationVersion o) {
if (o == null) {
return 1;
}
if (this == EMPTY) {
if (o == EMPTY) return 0;
else return -1;
}
if (this == CURRENT) {
return o == CURRENT ? 0 : -1;
}
if (this == LATEST) {
if (o == LATEST) return 0;
else return 1;
}
if (o == EMPTY) {
return 1;
}
if (o == CURRENT) {
return 1;
}
if (o == LATEST) {
return -1;
}
final List<BigInteger> parts1 = versionParts;
final List<BigInteger> parts2 = o.versionParts;
int largestNumberOfParts = Math.max(parts1.size(), parts2.size());
for (int i = 0; i < largestNumberOfParts; i++) {
final int compared = getOrZero(parts1, i).compareTo(getOrZero(parts2, i));
if (compared != 0) {
return compared;
}
}
return 0;
}
private BigInteger getOrZero(List<BigInteger> elements, int i) {
return i < elements.size() ? elements.get(i) : BigInteger.ZERO;
}
/**
* Splits this string into list of Long
*
* @param versionStr The string to split.
* @return The resulting array.
*/
private List<BigInteger> tokenize(String versionStr) {
List<BigInteger> parts = new ArrayList<>();
for (String part : SPLIT_REGEX.split(versionStr)) {
parts.add(toBigInteger(versionStr, part));
}
for (int i = parts.size() - 1; i > 0; i--) {
if (!parts.get(i).equals(BigInteger.ZERO)) {
break;
}
parts.remove(i);
}
return parts;
}
private BigInteger toBigInteger(String versionStr, String part) {
try {
return new BigInteger(part);
} catch (NumberFormatException e) {
throw new FlywayException("Version may only contain 0..9 and . (dot). Invalid version: " + versionStr);
}
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api;
import org.flywaydb.core.internal.resource.LoadableResource;
import java.util.Collection;
/**
* A facility to obtain loadable resources.
*/
public interface ResourceProvider {
/**
* Retrieves the resource with this name.
*
* @param name The name of the resource.
* @return The resource or {@code null} if not found.
*/
LoadableResource getResource(String name);
/**
* Retrieve all resources whose name begins with this prefix and ends with any of these suffixes.
*
* @param prefix The prefix.
* @param suffixes The suffixes.
* @return The matching resources.
*/
Collection<LoadableResource> getResources(String prefix, String[] suffixes);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.android;
import android.content.Context;
/**
* Holds an Android context. The context must be set for Flyway to be able to scan assets and classes for migrations.
*
* <p>
* You can set this within an activity using ContextHolder.setContext(this);
* </p>
*/
public class ContextHolder {
private ContextHolder() {}
/**
* The Android context to use.
*/
private static Context context;
/**
* @return The Android context to use to be able to scan assets and classes for migrations.
*/
public static Context getContext() {
return context;
}
/**
* @param context The Android context to use to be able to scan assets and classes for migrations.
*/
public static void setContext(Context context) {
ContextHolder.context = context;
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Android-specific helper classes.
*/
package org.flywaydb.core.api.android;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.callback;
/**
* Base implementation of Callback from which one can inherit. This is a convenience class that assumes by default that
* all events are handled and all handlers can run within a transaction.
*/
public abstract class BaseCallback implements Callback {
@Override
public boolean supports(Event event, Context context) {
return true;
}
@Override
public boolean canHandleInTransaction(Event event, Context context) {
return true;
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.callback;
/**
* This is the main callback interface that should be implemented to handle Flyway lifecycle events.
*/
public interface Callback {
/**
* Whether this callback supports this event or not. This is primarily meant as a way to optimize event handling
* by avoiding unnecessary connection state setups for events that will not be handled anyway.
*
* @param event The event to check.
* @param context The context for this event.
* @return {@code true} if it can be handled, {@code false} if not.
*/
boolean supports(Event event, Context context);
/**
* Whether this event can be handled in a transaction or whether it must be handled outside a transaction instead.
* In the vast majority of the cases the answer will be
* {@code true}. Only in the rare cases where non-transactional statements are executed should this return {@code false}.
* This method is called before {@link #handle(Event, Context)} in order to determine in advance whether a transaction
* can be used or not.
*
* @param event The event to check.
* @param context The context for this event.
* @return {@code true} if it can be handled within a transaction (almost all cases). {@code false} if it must be
* handled outside a transaction instead (very rare).
*/
boolean canHandleInTransaction(Event event, Context context);
/**
* Handles this Flyway lifecycle event.
*
* @param event The event to handle.
* @param context The context for this event.
*/
void handle(Event event, Context context);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.callback;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.configuration.Configuration;
import java.sql.Connection;
/**
* The context relevant to an event.
*/
public interface Context {
/**
* @return The configuration currently in use.
*/
Configuration getConfiguration();
/**
* @return The JDBC connection being used. Transaction are managed by Flyway.
* When the context is passed to the {@link Callback#handle(Event, Context)} method, a transaction will already have
* been started if required and will be automatically committed or rolled back afterwards.
*/
Connection getConnection();
/**
* @return The info about the migration being handled. Only relevant for the BEFORE_EACH_* and AFTER_EACH_* events.
* {@code null} in all other cases.
*/
MigrationInfo getMigrationInfo();
/**
* @return The info about the statement being handled. Only relevant for the statement-level events.
* {@code null} in all other cases.
* <p><i>Flyway Pro and Flyway Enterprise only</i></p>
*/
Statement getStatement();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.callback;
/**
* An error that occurred while executing a statement.
* <p><i>Flyway Pro and Flyway Enterprise only</i></p>
*/
public interface Error {
/**
* @return The error code.
*/
int getCode();
/**
* @return The error state.
*/
String getState();
/**
* @return The error message.
*/
String getMessage();
/**
* Checks whether this error has already been handled.
*
* @return {@code true} {@code true} if this error has already be handled or {@code false} if it should flow
* via the default error handler.
*/
boolean isHandled();
/**
* Sets whether this error has already been handled.
*
* @param handled {@code true} if this error has already be handled or {@code false} if it should flow via the
* default error handler.
*/
void setHandled(boolean handled);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.callback;
/**
* The Flyway lifecycle events that can be handled in callbacks.
*/
public enum Event {
/**
* Fired before clean is executed. This event will be fired in a separate transaction from the actual clean operation.
*/
BEFORE_CLEAN("beforeClean"),
/**
* Fired after clean has succeeded. This event will be fired in a separate transaction from the actual clean operation.
*/
AFTER_CLEAN("afterClean"),
/**
* Fired after clean has failed. This event will be fired in a separate transaction from the actual clean operation.
*/
AFTER_CLEAN_ERROR("afterCleanError"),
/**
* Fired before migrate is executed. This event will be fired in a separate transaction from the actual migrate operation.
*/
BEFORE_MIGRATE("beforeMigrate"),
/**
* Fired before each individual migration is executed. This event will be fired within the same transaction (if any)
* as the migration and can be used for things like setting up connection parameters that are required by migrations.
*/
BEFORE_EACH_MIGRATE("beforeEachMigrate"),
/**
* Fired before each individual statement in a migration is executed. This event will be fired within the same transaction (if any)
* as the migration and can be used for things like asserting a statement complies with policy (for example: no grant statements allowed).
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
BEFORE_EACH_MIGRATE_STATEMENT("beforeEachMigrateStatement"),
/**
* Fired after each individual statement in a migration that succeeded. This event will be fired within the same transaction (if any)
* as the migration.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_EACH_MIGRATE_STATEMENT("afterEachMigrateStatement"),
/**
* Fired after each individual statement in a migration that failed. This event will be fired within the same transaction (if any)
* as the migration.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_EACH_MIGRATE_STATEMENT_ERROR("afterEachMigrateStatementError"),
/**
* Fired after each individual migration that succeeded. This event will be fired within the same transaction (if any)
* as the migration.
*/
AFTER_EACH_MIGRATE("afterEachMigrate"),
/**
* Fired after each individual migration that failed. This event will be fired within the same transaction (if any)
* as the migration.
*/
AFTER_EACH_MIGRATE_ERROR("afterEachMigrateError"),
/**
* Fired after migrate has succeeded. This event will be fired in a separate transaction from the actual migrate operation.
*/
AFTER_MIGRATE("afterMigrate"),
/**
* Fired after migrate has failed. This event will be fired in a separate transaction from the actual migrate operation.
*/
AFTER_MIGRATE_ERROR("afterMigrateError"),
/**
* Fired before undo is executed. This event will be fired in a separate transaction from the actual undo operation.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
BEFORE_UNDO("beforeUndo"),
/**
* Fired before each individual undo is executed. This event will be fired within the same transaction (if any)
* as the undo and can be used for things like setting up connection parameters that are required by undo.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
BEFORE_EACH_UNDO("beforeEachUndo"),
/**
* Fired before each individual statement in an undo migration is executed. This event will be fired within the same transaction (if any)
* as the migration and can be used for things like asserting a statement complies with policy (for example: no grant statements allowed).
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
BEFORE_EACH_UNDO_STATEMENT("beforeEachUndoStatement"),
/**
* Fired after each individual statement in an undo migration that succeeded. This event will be fired within the same transaction (if any)
* as the migration.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_EACH_UNDO_STATEMENT("afterEachUndoStatement"),
/**
* Fired after each individual statement in an undo migration that failed. This event will be fired within the same transaction (if any)
* as the migration.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_EACH_UNDO_STATEMENT_ERROR("afterEachUndoStatementError"),
/**
* Fired after each individual undo that succeeded. This event will be fired within the same transaction (if any)
* as the undo.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_EACH_UNDO("afterEachUndo"),
/**
* Fired after each individual undo that failed. This event will be fired within the same transaction (if any)
* as the undo.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_EACH_UNDO_ERROR("afterEachUndoError"),
/**
* Fired after undo has succeeded. This event will be fired in a separate transaction from the actual undo operation.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_UNDO("afterUndo"),
/**
* Fired after undo has failed. This event will be fired in a separate transaction from the actual undo operation.
* <p><i>Flyway Pro and Enterprise Edition only</i></p>
*/
AFTER_UNDO_ERROR("afterUndoError"),
/**
* Fired before validate is executed. This event will be fired in a separate transaction from the actual validate operation.
*/
BEFORE_VALIDATE("beforeValidate"),
/**
* Fired after validate has succeeded. This event will be fired in a separate transaction from the actual validate operation.
*/
AFTER_VALIDATE("afterValidate"),
/**
* Fired after validate has failed. This event will be fired in a separate transaction from the actual validate operation.
*/
AFTER_VALIDATE_ERROR("afterValidateError"),
/**
* Fired before baseline is executed. This event will be fired in a separate transaction from the actual baseline operation.
*/
BEFORE_BASELINE("beforeBaseline"),
/**
* Fired after baseline has succeeded. This event will be fired in a separate transaction from the actual baseline operation.
*/
AFTER_BASELINE("afterBaseline"),
/**
* Fired after baseline has failed. This event will be fired in a separate transaction from the actual baseline operation.
*/
AFTER_BASELINE_ERROR("afterBaselineError"),
/**
* Fired before repair is executed. This event will be fired in a separate transaction from the actual repair operation.
*/
BEFORE_REPAIR("beforeRepair"),
/**
* Fired after repair has succeeded. This event will be fired in a separate transaction from the actual repair operation.
*/
AFTER_REPAIR("afterRepair"),
/**
* Fired after repair has failed. This event will be fired in a separate transaction from the actual repair operation.
*/
AFTER_REPAIR_ERROR("afterRepairError"),
/**
* Fired before info is executed. This event will be fired in a separate transaction from the actual info operation.
*/
BEFORE_INFO("beforeInfo"),
/**
* Fired after info has succeeded. This event will be fired in a separate transaction from the actual info operation.
*/
AFTER_INFO("afterInfo"),
/**
* Fired after info has failed. This event will be fired in a separate transaction from the actual info operation.
*/
AFTER_INFO_ERROR("afterInfoError");
private final String id;
Event(String id) {
this.id = id;
}
/**
* @return The id of an event. Examples: {@code beforeClean}, {@code afterEachMigrate}, ...
*/
public String getId() {
return id;
}
/**
* Retrieves the event with this id.
* @param id The id.
* @return The event. {@code null} if not found.
*/
public static Event fromId(String id) {
for (Event event : values()) {
if (event.id.equals(id)) {
return event;
}
}
return null;
}
@Override
public String toString() {
return id;
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.callback;
import java.util.List;
/**
* The statement relevant to an event.
* <p><i>Flyway Pro and Flyway Enterprise only</i></p>
*/
public interface Statement {
/**
* @return The SQL statement.
*/
String getSql();
/**
* @return The warnings that were raised during the execution of the statement.
* {@code null} if the statement hasn't been executed yet.
*/
List<Warning> getWarnings();
/**
* @return The errors that were thrown during the execution of the statement.
* {@code null} if the statement hasn't been executed yet.
*/
List<Error> getErrors();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.callback;
/**
* A warning that occurred while executing a statement.
* <p><i>Flyway Pro and Flyway Enterprise only</i></p>
*/
public interface Warning {
/**
* @return The warning code.
*/
int getCode();
/**
* @return The warning state.
*/
String getState();
/**
* @return The warning message.
*/
String getMessage();
/**
* Checks whether this warning has already been handled.
*
* @return {@code true} {@code true} if this warning has already be handled or {@code false} if it should flow
* via the default warning handler.
*/
boolean isHandled();
/**
* Sets whether this warning has already been handled.
*
* @param handled {@code true} if this warning has already be handled or {@code false} if it should flow via the
* default warning handler.
*/
void setHandled(boolean handled);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interfaces for Flyway lifecycle callbacks.
*/
package org.flywaydb.core.api.callback;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interfaces for Flyway configuration injection.
*/
package org.flywaydb.core.api.configuration;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.executor;
import org.flywaydb.core.api.configuration.Configuration;
import java.sql.Connection;
/**
* The context relevant to a migration executor.
*/
public interface Context {
/**
* @return The configuration currently in use.
*/
Configuration getConfiguration();
/**
* @return The JDBC connection being used. Transaction are managed by Flyway.
* When the context is passed to the migrate method, a transaction will already have
* been started if required and will be automatically committed or rolled back afterwards, unless the
* canExecuteInTransaction method has been implemented to return false.
*/
Connection getConnection();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.executor;
import java.sql.SQLException;
/**
* Executes a migration.
*/
public interface MigrationExecutor {
/**
* Executes the migration this executor is associated with.
*
* @param context The context to use to execute the migration against the DB.
* @throws SQLException when the execution of a statement failed.
*/
void execute(Context context) throws SQLException;
/**
* Whether the execution can take place inside a transaction. Almost all implementation should return {@code true}.
* This however makes it possible to execute certain migrations outside a transaction. This is useful for databases
* like PostgreSQL and SQL Server where certain statement can only execute outside a transaction.
*
* @return {@code true} if a transaction should be used (highly recommended), or {@code false} if not.
*/
boolean canExecuteInTransaction();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interfaces for Migration executors.
*/
package org.flywaydb.core.api.executor;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.logging;
/**
* A logger.
*/
public interface Log {
/**
* @return Whether debug logging is enabled.
*/
boolean isDebugEnabled();
/**
* Logs a debug message.
*
* @param message The message to log.
*/
void debug(String message);
/**
* Logs an info message.
*
* @param message The message to log.
*/
void info(String message);
/**
* Logs a warning message.
*
* @param message The message to log.
*/
void warn(String message);
/**
* Logs an error message.
*
* @param message The message to log.
*/
void error(String message);
/**
* Logs an error message and the exception that caused it.
*
* @param message The message to log.
* @param e The exception that caused the error.
*/
void error(String message, Exception e);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.logging;
/**
* Factory for implementation-specific loggers.
*/
public interface LogCreator {
/**
* Creates an implementation-specific logger for this class.
*
* @param clazz The class to create the logger for.
* @return The logger.
*/
Log createLogger(Class<?> clazz);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.logging;
import org.flywaydb.core.internal.logging.LogCreatorFactory;
/**
* Factory for loggers. Custom MigrationResolver, MigrationExecutor, Callback and JavaMigration
* implementations should use this to obtain a logger that will work with any logging framework across all environments
* (API, Maven, Gradle, CLI, etc).
*/
public class LogFactory {
/**
* Factory for implementation-specific loggers.
*/
private static volatile LogCreator logCreator;
/**
* The factory for implementation-specific loggers to be used as a fallback when no other suitable loggers were found.
*/
private static LogCreator fallbackLogCreator;
/**
* Prevent instantiation.
*/
private LogFactory() {
// Do nothing
}
/**
* Sets the LogCreator that will be used. This will effectively override Flyway's default LogCreator auto-detection
* logic and force Flyway to always use this LogCreator regardless of which log libraries are present on the
* classpath.
*
* <p>This is primarily meant for integrating Flyway into environments with their own logging system (like Ant,
* Gradle, Maven, ...). This ensures Flyway is a good citizen in those environments and sends its logs through the
* expected pipeline.</p>
*
* @param logCreator The factory for implementation-specific loggers.
*/
public static void setLogCreator(LogCreator logCreator) {
LogFactory.logCreator = logCreator;
}
/**
* Sets the fallback LogCreator. This LogCreator will be used as a fallback solution when the default LogCreator
* auto-detection logic fails to detect a suitable LogCreator based on the log libraries present on the classpath.
*
* @param fallbackLogCreator The factory for implementation-specific loggers to be used as a fallback when no other
* suitable loggers were found.
*/
public static void setFallbackLogCreator(LogCreator fallbackLogCreator) {
LogFactory.fallbackLogCreator = fallbackLogCreator;
}
/**
* Retrieves the matching logger for this class.
*
* @param clazz The class to get the logger for.
* @return The logger.
*/
public static Log getLog(Class<?> clazz) {
if (logCreator == null) {
logCreator = LogCreatorFactory.getLogCreator(LogFactory.class.getClassLoader(), fallbackLogCreator);
}
return logCreator.createLogger(clazz);
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interfaces for Flyway's log abstraction. Custom MigrationResolver, MigrationExecutor, FlywayCallback, ErrorHandler and JdbcMigration
* implementations should use this to obtain a logger that will work with any logging framework across all environments
* (API, Maven, Gradle, CLI, etc).
*/
package org.flywaydb.core.api.logging;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.migration;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.internal.resolver.MigrationInfoHelper;
import org.flywaydb.core.internal.util.Pair;
/**
* <p>This is the recommended class to extend for implementing Java-based Migrations.</p>
* <p>Subclasses should follow the default Flyway naming convention of having a class name with the following structure:</p>
* <ul>
* <li><strong>Versioned Migrations:</strong> V2__Add_new_table</li>
* <li><strong>Undo Migrations:</strong> U2__Add_new_table</li>
* <li><strong>Repeatable Migrations:</strong> R__Add_new_table</li>
* </ul>
*
* <p>The file name consists of the following parts:</p>
* <ul>
* <li><strong>Prefix:</strong> V for versioned migrations, U for undo migrations, R for repeatable migrations</li>
* <li><strong>Version:</strong> Underscores (automatically replaced by dots at runtime) separate as many parts as you like (Not for repeatable migrations)</li>
* <li><strong>Separator:</strong> __ (two underscores)</li>
* <li><strong>Description:</strong> Underscores (automatically replaced by spaces at runtime) separate the words</li>
* </ul>
* <p>If you need more control over the class name, you can override the default convention by implementing the
* JavaMigration interface directly. This will allow you to name your class as you wish. Version, description and
* migration category are provided by implementing the respective methods.</p>
*/
public abstract class BaseJavaMigration implements JavaMigration {
private final MigrationVersion version;
private final String description;
/**
* Creates a new instance of a Java-based migration following Flyway's default naming convention.
*/
public BaseJavaMigration() {
String shortName = getClass().getSimpleName();
String prefix;
boolean repeatable = shortName.startsWith("R");
if (shortName.startsWith("V") || repeatable
) {
prefix = shortName.substring(0, 1);
} else {
throw new FlywayException("Invalid Java-based migration class name: " + getClass().getName()
+ " => ensure it starts with V" +
" or R," +
" or implement org.flywaydb.core.api.migration.JavaMigration directly for non-default naming");
}
Pair<MigrationVersion, String> info =
MigrationInfoHelper.extractVersionAndDescription(shortName, prefix, "__", new String[]{""}, repeatable);
version = info.getLeft();
description = info.getRight();
}
@Override
public MigrationVersion getVersion() {
return version;
}
@Override
public String getDescription() {
return description;
}
@Override
public Integer getChecksum() {
return null;
}
@Override
public boolean isUndo() {
return false;
}
@Override
public boolean canExecuteInTransaction() {
return true;
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.migration;
import org.flywaydb.core.api.configuration.Configuration;
import java.sql.Connection;
/**
* The context relevant to a Java-based migration.
*/
public interface Context {
/**
* @return The configuration currently in use.
*/
Configuration getConfiguration();
/**
* @return The JDBC connection being used. Transaction are managed by Flyway.
* When the context is passed to the migrate method, a transaction will already have
* been started if required and will be automatically committed or rolled back afterwards, unless the
* canExecuteInTransaction method has been implemented to return false.
*/
Connection getConnection();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.migration;
import org.flywaydb.core.api.MigrationVersion;
/**
* Interface to be implemented by Java-based Migrations.
*
* <p>Java-based migrations are a great fit for all changes that can not easily be expressed using SQL.</p>
*
* <p>These would typically be things like</p>
* <ul>
* <li>BLOB &amp; CLOB changes</li>
* <li>Advanced bulk data changes (Recalculations, advanced format changes, …)</li>
* </ul>
*
* <p>Migration classes implementing this interface will be
* automatically discovered when placed in a location on the classpath.</p>
*
* <p>Most users will be better served by subclassing subclass {@link BaseJavaMigration} instead of implementing this
* interface directly, as {@link BaseJavaMigration} encourages the use of Flyway's default naming convention and
* comes with sensible default implementations of all methods (except migrate of course) while at the same time also
* providing better isolation against future additions to this interface.</p>
*/
public interface JavaMigration {
/**
* @return The version of the schema after the migration is complete. {@code null} for repeatable migrations.
*/
MigrationVersion getVersion();
/**
* @return The description of this migration for the migration history. Never {@code null}.
*/
String getDescription();
/**
* Computes the checksum of the migration.
*
* @return The checksum of the migration.
*/
Integer getChecksum();
/**
* Whether this is an undo migration for a previously applied versioned migration.
*
* @return {@code true} if it is, {@code false} if not. Always {@code false} for repeatable migrations.
*/
boolean isUndo();
/**
* Whether the execution should take place inside a transaction. Almost all implementation should return {@code true}.
* This however makes it possible to execute certain migrations outside a transaction. This is useful for databases
* like PostgreSQL and SQL Server where certain statement can only execute outside a transaction.
*
* @return {@code true} if a transaction should be used (highly recommended), or {@code false} if not.
*/
boolean canExecuteInTransaction();
/**
* Executes this migration. The execution will automatically take place within a transaction, when the underlying
* database supports it and the canExecuteInTransaction returns {@code true}.
*
* @param context The context relevant for this migration, containing things like the JDBC connection to use and the
* current Flyway configuration.
* @throws Exception when the migration failed.
*/
void migrate(Context context) throws Exception;
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interfaces for Migration implementors.
*/
package org.flywaydb.core.api.migration;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* FlywayException, MigrationInfo and related classes.
*/
package org.flywaydb.core.api;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.resolver;
interface ChecksumMatcher {
boolean checksumMatches(Integer checksum);
boolean checksumMatchesWithoutBeingIdentical(Integer checksum);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.resolver;
import org.flywaydb.core.api.configuration.Configuration;
import java.sql.Connection;
/**
* The context relevant to a migration resolver.
*/
public interface Context {
/**
* @return The configuration currently in use.
*/
Configuration getConfiguration();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.resolver;
import java.util.Collection;
/**
* Resolves available migrations. This interface can be implemented to create custom resolvers. A custom resolver
* can be used to create additional types of migrations not covered by the standard resolvers (jdbc, sql, spring-jdbc).
* Using the skipDefaultResolvers configuration property, the built-in resolvers can also be completely replaced.
*/
public interface MigrationResolver {
/**
* Resolves the available migrations.
*
* @return The available migrations.
*/
Collection<ResolvedMigration> resolveMigrations(Context context);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.api.resolver;
import org.flywaydb.core.api.MigrationType;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.executor.MigrationExecutor;
/**
* Migration resolved through a MigrationResolver. Can be applied against a database.
*/
public interface ResolvedMigration extends ChecksumMatcher {
/**
* @return The version of the database after applying this migration. {@code null} for repeatable migrations.
*/
MigrationVersion getVersion();
/**
* @return The description of the migration.
*/
String getDescription();
/**
* @return The name of the script to execute for this migration, relative to its base (classpath/filesystem) location.
*/
String getScript();
/**
* @return The checksum of the migration. Optional. Can be {@code null} if not unique checksum is computable.
*/
Integer getChecksum();
/**
* @return The type of migration (INIT, SQL, ...)
*/
MigrationType getType();
/**
* @return The physical location of the migration on disk. Used for more precise error reporting in case of conflict.
*/
String getPhysicalLocation();
/**
* @return The executor to run this migration.
*/
MigrationExecutor getExecutor();
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interfaces for Migration resolvers.
*/
package org.flywaydb.core.api.resolver;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.callback;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.callback.Event;
import org.flywaydb.core.api.callback.Warning;
import org.flywaydb.core.api.callback.Error;
import java.util.List;
/**
* Executes the callbacks for a specific event.
*/
public interface CallbackExecutor {
/**
* Executes the callbacks for this event on the main connection, within a separate transaction per callback if possible.
*
* @param event The vent to handle.
*/
void onEvent(Event event);
/**
* Executes the callbacks for this event on the migration connection, within a separate transaction per callback if possible.
*
* @param event The vent to handle.
*/
void onMigrateOrUndoEvent(Event event);
/**
* Sets the current migration info.
*
* @param migrationInfo The current migration.
*/
void setMigrationInfo(MigrationInfo migrationInfo);
/**
* Executes the callbacks for an "each" event within the same transaction (if any) as the main operation.
*
* @param event The event to handle.
*/
void onEachMigrateOrUndoEvent(Event event);
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.callback;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.callback.Callback;
import org.flywaydb.core.api.callback.Context;
import org.flywaydb.core.api.callback.Error;
import org.flywaydb.core.api.callback.Event;
import org.flywaydb.core.api.callback.Warning;
import org.flywaydb.core.api.configuration.Configuration;
import org.flywaydb.core.internal.database.base.Connection;
import org.flywaydb.core.internal.database.base.Database;
import org.flywaydb.core.internal.database.base.Schema;
import org.flywaydb.core.internal.jdbc.ExecutionTemplateFactory;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Executes the callbacks for a specific event.
*/
public class DefaultCallbackExecutor implements CallbackExecutor {
private final Configuration configuration;
private final Database database;
private final Schema schema;
private final Collection<Callback> callbacks;
private MigrationInfo migrationInfo;
/**
* Creates a new callback executor.
*
* @param configuration The configuration.
* @param database The database.
* @param schema The current schema to use for the connection.
* @param callbacks The callbacks to execute.
*/
public DefaultCallbackExecutor(Configuration configuration, Database database, Schema schema, Collection<Callback> callbacks) {
this.configuration = configuration;
this.database = database;
this.schema = schema;
this.callbacks = callbacks;
}
@Override
public void onEvent(final Event event) {
execute(event, database.getMainConnection());
}
@Override
public void onMigrateOrUndoEvent(final Event event) {
execute(event, database.getMigrationConnection());
}
@Override
public void setMigrationInfo(MigrationInfo migrationInfo) {
this.migrationInfo = migrationInfo;
}
@Override
public void onEachMigrateOrUndoEvent(Event event) {
final Context context = new SimpleContext(configuration, database.getMigrationConnection(), migrationInfo);
for (Callback callback : callbacks) {
if (callback.supports(event, context)) {
callback.handle(event, context);
}
}
}
private void execute(final Event event, final Connection connection) {
final Context context = new SimpleContext(configuration, connection, null);
for (final Callback callback : callbacks) {
if (callback.supports(event, context)) {
if (callback.canHandleInTransaction(event, context)) {
ExecutionTemplateFactory.createExecutionTemplate(connection.getJdbcConnection(),
database).execute(new Callable<Void>() {
@Override
public Void call() {
DefaultCallbackExecutor.this.execute(connection, callback, event, context);
return null;
}
});
} else {
execute(connection, callback, event, context);
}
}
}
}
private void execute(Connection connection, Callback callback, Event event, Context context) {
connection.restoreOriginalState();
connection.changeCurrentSchemaTo(schema);
handleEvent(callback, event, context);
}
private void handleEvent(Callback callback, Event event, Context context) {
try {
callback.handle(event, context);
} catch (RuntimeException e) {
throw new FlywayException("Error while executing " + event.getId() + " callback: " + e.getMessage(), e);
}
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.callback;
import org.flywaydb.core.api.callback.Callback;
import org.flywaydb.core.api.callback.Context;
import org.flywaydb.core.api.callback.Event;
/**
* Callback that does nothing.
*/
public enum NoopCallback implements Callback {
INSTANCE;
@Override
public boolean supports(Event event, Context context) {
return false;
}
@Override
public boolean canHandleInTransaction(Event event, Context context) {
return true;
}
@Override
public void handle(Event event, Context context) {
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.callback;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.callback.Error;
import org.flywaydb.core.api.callback.Event;
import org.flywaydb.core.api.callback.Warning;
import java.util.List;
/**
* A callback executor that does nothing.
*/
public enum NoopCallbackExecutor implements CallbackExecutor {
INSTANCE;
@Override
public void onEvent(Event event) {
}
@Override
public void onMigrateOrUndoEvent(Event event) {
}
@Override
public void setMigrationInfo(MigrationInfo migrationInfo) {
}
@Override
public void onEachMigrateOrUndoEvent(Event event) {
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.callback;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.callback.Context;
import org.flywaydb.core.api.callback.Error;
import org.flywaydb.core.api.callback.Statement;
import org.flywaydb.core.api.callback.Warning;
import org.flywaydb.core.api.configuration.Configuration;
import org.flywaydb.core.internal.database.base.Connection;
import java.util.List;
public class SimpleContext implements Context {
private final Configuration configuration;
private final Connection connection;
private final MigrationInfo migrationInfo;
private final Statement statement;
SimpleContext(Configuration configuration, Connection connection, MigrationInfo migrationInfo) {
this.configuration = configuration;
this.connection = connection;
this.migrationInfo = migrationInfo;
this.statement = null;
}
public SimpleContext(Configuration configuration, Connection connection, MigrationInfo migrationInfo,
String sql, List<Warning> warnings, List<Error> errors) {
this.configuration = configuration;
this.connection = connection;
this.migrationInfo = migrationInfo;
this.statement = new SimpleStatement(sql, warnings, errors);
}
@Override
public Configuration getConfiguration() {
return configuration;
}
@Override
public java.sql.Connection getConnection() {
return connection.getJdbcConnection();
}
@Override
public MigrationInfo getMigrationInfo() {
return migrationInfo;
}
@Override
public Statement getStatement() {
return statement;
}
private static class SimpleStatement implements Statement {
private final String sql;
private final List<Warning> warnings;
private final List<Error> errors;
private SimpleStatement(String sql, List<Warning> warnings, List<Error> errors) {
this.sql = sql;
this.warnings = warnings;
this.errors = errors;
}
@Override
public String getSql() {
return sql;
}
@Override
public List<Warning> getWarnings() {
return warnings;
}
@Override
public List<Error> getErrors() {
return errors;
}
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.callback;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.callback.Callback;
import org.flywaydb.core.api.callback.Context;
import org.flywaydb.core.api.callback.Event;
import org.flywaydb.core.api.configuration.Configuration;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.api.logging.LogFactory;
import org.flywaydb.core.internal.resource.LoadableResource;
import org.flywaydb.core.internal.resource.ResourceName;
import org.flywaydb.core.internal.resource.ResourceNameParser;
import org.flywaydb.core.api.ResourceProvider;
import org.flywaydb.core.internal.sqlscript.SqlScript;
import org.flywaydb.core.internal.sqlscript.SqlScriptExecutorFactory;
import org.flywaydb.core.internal.sqlscript.SqlScriptFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Callback factory, looking for SQL scripts (named like on the callback methods) inside the configured locations.
*/
public class SqlScriptCallbackFactory {
private static final Log LOG = LogFactory.getLog(SqlScriptCallbackFactory.class);
private final List<SqlScriptCallback> callbacks = new ArrayList<>();
/**
* Creates a new instance.
*
* @param resourceProvider The resource provider.
* @param sqlScriptFactory The SQL statement factory.
* @param configuration The Flyway configuration.
*/
public SqlScriptCallbackFactory(ResourceProvider resourceProvider,
SqlScriptExecutorFactory sqlScriptExecutorFactory,
SqlScriptFactory sqlScriptFactory,
Configuration configuration) {
Map<String, SqlScript> callbacksFound = new HashMap<>();
LOG.debug("Scanning for SQL callbacks ...");
Collection<LoadableResource> resources = resourceProvider.getResources("", configuration.getSqlMigrationSuffixes());
ResourceNameParser resourceNameParser = new ResourceNameParser(configuration);
for (LoadableResource resource : resources) {
ResourceName parsedName = resourceNameParser.parse(resource.getFilename());
if (!parsedName.isValid()) {
continue;
}
String name = parsedName.getFilenameWithoutSuffix();
Event event = Event.fromId(parsedName.getPrefix());
if (event != null) {
SqlScript existing = callbacksFound.get(name);
if (existing != null) {
throw new FlywayException("Found more than 1 SQL callback script called " + name + "!\n" +
"Offenders:\n" +
"-> " + existing.getResource().getAbsolutePathOnDisk() + "\n" +
"-> " + resource.getAbsolutePathOnDisk());
}
SqlScript sqlScript = sqlScriptFactory.createSqlScript(resource, configuration.isMixed(), resourceProvider);
callbacksFound.put(name, sqlScript);
callbacks.add(new SqlScriptCallback(event, parsedName.getDescription(), sqlScriptExecutorFactory, sqlScript
));
}
}
Collections.sort(callbacks);
}
public List<Callback> getCallbacks() {
return new ArrayList<>(callbacks);
}
private static class SqlScriptCallback implements Callback, Comparable<SqlScriptCallback> {
private final Event event;
private final String description;
private final SqlScriptExecutorFactory sqlScriptExecutorFactory;
private final SqlScript sqlScript;
private SqlScriptCallback(Event event, String description, SqlScriptExecutorFactory sqlScriptExecutorFactory, SqlScript sqlScript
) {
this.event = event;
this.description = description;
this.sqlScriptExecutorFactory = sqlScriptExecutorFactory;
this.sqlScript = sqlScript;
}
@Override
public boolean supports(Event event, Context context) {
return this.event == event;
}
@Override
public boolean canHandleInTransaction(Event event, Context context) {
return sqlScript.executeInTransaction();
}
@Override
public void handle(Event event, Context context) {
LOG.info("Executing SQL callback: " + event.getId()
+ (description == null ? "" : " - " + description)
+ (sqlScript.executeInTransaction() ? "" : " [non-transactional]"));
sqlScriptExecutorFactory.createSqlScriptExecutor(context.getConnection()
).execute(sqlScript);
}
@Override
public int compareTo(SqlScriptCallback o) {
int result = event.compareTo(o.event);
if (result == 0) {
if (description == null) {
return -1;
}
if (o.description == null) {
return 1;
}
result = description.compareTo(o.description);
}
return result;
}
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* FlywayException, MigrationInfo and related classes.
*/
package org.flywaydb.core.internal.callback;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.clazz;
import org.flywaydb.core.api.ClassProvider;
import java.util.Collection;
import java.util.Collections;
/**
* ClassProvider that does nothing.
*/
public enum NoopClassProvider implements ClassProvider {
INSTANCE;
@Override
public Collection<Class<?>> getClasses() {
return Collections.emptyList();
}
}
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Private API. No compatibility guarantees provided.
*/
package org.flywaydb.core.internal.clazz;
\ No newline at end of file
/*
* Copyright 2010-2020 Redgate Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.command;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.callback.Event;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.api.logging.LogFactory;
import org.flywaydb.core.internal.callback.CallbackExecutor;
import org.flywaydb.core.internal.schemahistory.AppliedMigration;
import org.flywaydb.core.internal.schemahistory.SchemaHistory;
/**
* Handles Flyway's baseline command.
*/
public class DbBaseline {
private static final Log LOG = LogFactory.getLog(DbBaseline.class);
/**
* The schema history table.
*/
private final SchemaHistory schemaHistory;
/**
* The version to tag an existing schema with when executing baseline.
*/
private final MigrationVersion baselineVersion;
/**
* The description to tag an existing schema with when executing baseline.
*/
private final String baselineDescription;
/**
* The callback executor.
*/
private final CallbackExecutor callbackExecutor;
/**
* Creates a new DbBaseline.
*
* @param schemaHistory The database schema history table.
* @param baselineVersion The version to tag an existing schema with when executing baseline.
* @param baselineDescription The description to tag an existing schema with when executing baseline.
* @param callbackExecutor The callback executor.
*/
public DbBaseline(SchemaHistory schemaHistory, MigrationVersion baselineVersion,
String baselineDescription, CallbackExecutor callbackExecutor) {
this.schemaHistory = schemaHistory;
this.baselineVersion = baselineVersion;
this.baselineDescription = baselineDescription;
this.callbackExecutor = callbackExecutor;
}
/**
* Baselines the database.
*/
public void baseline() {
callbackExecutor.onEvent(Event.BEFORE_BASELINE);
try {
if (!schemaHistory.exists()) {
schemaHistory.create(true);
LOG.info("Successfully baselined schema with version: " + baselineVersion);
} else {
AppliedMigration baselineMarker = schemaHistory.getBaselineMarker();
if (baselineMarker != null) {
if (baselineVersion.equals(baselineMarker.getVersion())
&& baselineDescription.equals(baselineMarker.getDescription())) {
LOG.info("Schema history table " + schemaHistory + " already initialized with ("
+ baselineVersion + "," + baselineDescription + "). Skipping.");
} else {
throw new FlywayException("Unable to baseline schema history table " + schemaHistory + " with ("
+ baselineVersion + "," + baselineDescription
+ ") as it has already been baselined with ("
+ baselineMarker.getVersion() + "," + baselineMarker.getDescription() + ")");
}
} else {
if (schemaHistory.hasSchemasMarker() && baselineVersion.equals(MigrationVersion.fromVersion("0"))) {
throw new FlywayException("Unable to baseline schema history table " + schemaHistory + " with version 0 as this version was used for schema creation");
}
if (schemaHistory.hasNonSyntheticAppliedMigrations()) {
throw new FlywayException("Unable to baseline schema history table " + schemaHistory + " as it already contains migrations");
}
if (schemaHistory.allAppliedMigrations().isEmpty()) {
throw new FlywayException("Unable to baseline schema history table " + schemaHistory + " as it already exists, and is empty.\n" +
"Delete the schema history table with the clean command, and run baseline again.");
}
throw new FlywayException("Unable to baseline schema history table " + schemaHistory + " as it already contains migrations.\n" +
"Delete the schema history table with the clean command, and run baseline again.");
}
}
} catch (FlywayException e) {
callbackExecutor.onEvent(Event.AFTER_BASELINE_ERROR);
throw e;
}
callbackExecutor.onEvent(Event.AFTER_BASELINE);
}
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment