Skip to content

Add before/after-new hooks. #126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/main/java/org/apache/ibatis/migration/Environment.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2010-2017 the original author or authors.
* Copyright 2010-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -52,7 +52,9 @@ private enum SETTING_KEY {
hook_before_down,
hook_before_each_down,
hook_after_each_down,
hook_after_down
hook_after_down,
hook_before_new,
hook_after_new
}

private static final List<String> SETTING_KEYS;
Expand Down Expand Up @@ -89,6 +91,9 @@ private enum SETTING_KEY {
private final String hookAfterEachDown;
private final String hookAfterDown;

private final String hookBeforeNew;
private final String hookAfterNew;

private final Properties variables = new Properties();

public Environment(File file) {
Expand Down Expand Up @@ -122,6 +127,9 @@ public Environment(File file) {
this.hookAfterEachDown = prop.getProperty(SETTING_KEY.hook_after_each_down.name());
this.hookAfterDown = prop.getProperty(SETTING_KEY.hook_after_down.name());

this.hookBeforeNew = prop.getProperty(SETTING_KEY.hook_before_new.name());
this.hookAfterNew = prop.getProperty(SETTING_KEY.hook_after_new.name());

// User defined variables.
Set<Entry<Object, Object>> entries = prop.entrySet();
for (Entry<Object, Object> entry : entries) {
Expand Down Expand Up @@ -229,6 +237,14 @@ public String getHookAfterDown() {
return hookAfterDown;
}

public String getHookBeforeNew() {
return hookBeforeNew;
}

public String getHookAfterNew() {
return hookAfterNew;
}

public Properties getVariables() {
return variables;
}
Expand Down
24 changes: 24 additions & 0 deletions src/main/java/org/apache/ibatis/migration/commands/NewCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,13 @@
package org.apache.ibatis.migration.commands;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.migration.MigrationException;
import org.apache.ibatis.migration.hook.MigrationHook;
import org.apache.ibatis.migration.hook.NewHookContext;
import org.apache.ibatis.migration.options.SelectedOptions;
import org.apache.ibatis.migration.utils.Util;

Expand All @@ -41,6 +45,13 @@ public void execute(String... params) {
existingEnvironmentFile();
String filename = getNextIDAsString() + "_" + description.replace(' ', '_') + ".sql";

Map<String, Object> hookBindings = new HashMap<String, Object>();
MigrationHook hook = createNewHook();
if (hook != null) {
hookBindings.put(MigrationHook.HOOK_CONTEXT, new NewHookContext(description, filename));
hook.before(hookBindings);
}

if (options.getTemplate() != null) {
copyExternalResourceTo(options.getTemplate(), Util.file(paths.getScriptPath(), filename), variables);
} else {
Expand All @@ -53,6 +64,10 @@ public void execute(String... params) {
.append("Your migrations configuration did not find your custom template. Using the default template.");
copyDefaultTemplate(variables, filename);
}
if (hook != null) {
hookBindings.put(MigrationHook.HOOK_CONTEXT, new NewHookContext(description, filename));
hook.after(hookBindings);
}
}
printStream.println("Done!");
printStream.println();
Expand All @@ -62,4 +77,13 @@ private void copyDefaultTemplate(Properties variables, String filename) {
copyResourceTo("org/apache/ibatis/migration/template_migration.sql", Util.file(paths.getScriptPath(), filename),
variables);
}

private MigrationHook createNewHook() {
String before = environment().getHookBeforeNew();
String after = environment().getHookAfterNew();
if (before == null && after == null) {
return null;
}
return createFileMigrationHook(before, null, null, after);
}
}
45 changes: 45 additions & 0 deletions src/main/java/org/apache/ibatis/migration/hook/NewHookContext.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Copyright 2010-2018 the original author or authors.
*
* 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.apache.ibatis.migration.hook;

/**
* Hook context object that is available to <code>before_new</code> and <code>after_new</code> hooks.
*/
public class NewHookContext {
private String description;
private String filename;

public NewHookContext(String description, String filename) {
super();
this.description = description;
this.filename = filename;
}

/**
* @return The specified description.
*/
public String getDescription() {
return description;
}

/**
* @return The name of the file that is created by new command.<br>
* In <code>before_new</code> hook, the file is not created yet.
*/
public String getFilename() {
return filename;
}
}
24 changes: 23 additions & 1 deletion src/site/xdoc/hooks.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

Copyright 2010-2016 the original author or authors.
Copyright 2010-2018 the original author or authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -127,6 +127,8 @@ Hello, World!]]></source>
<li>hook_before_each_down</li>
<li>hook_after_each_down</li>
<li>hook_after_down</li>
<li>hook_before_new (since 3.3.5)</li>
<li>hook_after_new (since 3.3.5)</li>
</ul>

<h4>Minimum setting : language and file name</h4>
Expand Down Expand Up @@ -200,6 +202,17 @@ print(migrationPaths.getScriptPath());
print(migrationPaths.getDriverPath());
print(migrationPaths.getHookPath());]]></source>

<h4>About <i>hookContext</i></h4>

<p>
A global variable <code>hookContext</code> is passed to each hook script, but the object bound to this variable depends on the hook.
</p>

<ul>
<li>For hooks except before_new and after_new, it is an instance of <a href="/migrations/apidocs/org/apache/ibatis/migration/hook/HookContext.html" target="_blank">HookContext</a>.</li>
<li>For before_new and after_new hooks, it will be <a href="/migrations/apidocs/org/apache/ibatis/migration/hook/NewHookContext.html" target="_blank">NewHookContext</a>.</li>
</ul>

<h4>Accessing <i>Change</i> object (in each hook only)</h4>

<p>
Expand All @@ -214,6 +227,11 @@ print(hookContext.getChange().getFilename());]]></source>
The Change instance is a clone and will be discarded after each exection, so modifying it would be meaningless.
</p>

<p>
<span class="label important">NOTE</span>
Change is not available to before_new and after_new hooks.
</p>

<h4>Execute SQL statement</h4>

<p>
Expand All @@ -240,6 +258,10 @@ try {
stmt = null;
}]]></source>

<p>
<span class="label important">NOTE</span>
These methods are not available to before_new and after_new hooks.
</p>

<h4>Invoking function</h4>

Expand Down
26 changes: 8 additions & 18 deletions src/test/java/org/apache/ibatis/migration/MigratorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ public void checkAssertion() {

@Test
public void shouldInitTempDirectory() throws Exception {
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "init"));
assertNotNull(basePath.list());
assertEquals(4, basePath.list().length);
Expand All @@ -310,7 +310,7 @@ public void shouldInitTempDirectory() throws Exception {
@Test
public void shouldRespectIdPattern() throws Exception {
String idPattern = "000";
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "--idpattern=" + idPattern, "init"));
File changelog = new File(
basePath.getCanonicalPath() + File.separator + "scripts" + File.separator + "001_create_changelog.sql");
Expand All @@ -325,7 +325,7 @@ public void shouldRespectIdPattern() throws Exception {
@Test
public void useCustomTemplate() throws Exception {
String desc = "test new migration";
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "init"));
assertNotNull(basePath.list());
assertEquals(4, basePath.list().length);
Expand All @@ -351,7 +351,7 @@ public void useCustomTemplate() throws Exception {

@Test
public void useCustomTemplateWithNoValue() throws Exception {
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "init"));
assertNotNull(basePath.list());
assertEquals(4, basePath.list().length);
Expand All @@ -368,7 +368,7 @@ public void useCustomTemplateWithNoValue() throws Exception {
@Test
public void useCustomTemplateWithBadPath() throws Exception {
System.setProperty("migrationsHome", "/tmp");
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "init"));
assertNotNull(basePath.list());
assertEquals(4, basePath.list().length);
Expand All @@ -386,7 +386,7 @@ public void useCustomTemplateWithBadPath() throws Exception {
@Test
public void shouldSuppressOutputIfQuietOptionEnabled() throws Throwable {
System.setProperty("migrationsHome", "/tmp");
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
out.clearLog();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "--quiet", "init"));
String output = out.getLog();
Expand All @@ -397,7 +397,7 @@ public void shouldSuppressOutputIfQuietOptionEnabled() throws Throwable {
@Test
public void shouldColorizeSuccessOutputIfColorOptionEnabled() throws Throwable {
System.setProperty("migrationsHome", "/tmp");
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
out.clearLog();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "--color", "init"));
String output = out.getLog();
Expand All @@ -415,18 +415,8 @@ public void checkAssertion() {
}
});
System.setProperty("migrationsHome", "/tmp");
File basePath = getTempDir();
File basePath = TestUtil.getTempDir();
out.clearLog();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "--color", "new"));
}

private File getTempDir() throws IOException {
File f = File.createTempFile("migration", "test");
assertTrue(f.delete());
assertTrue(f.mkdir());
assertTrue(f.exists());
assertTrue(f.isDirectory());
f.deleteOnExit();
return f;
}
}
105 changes: 105 additions & 0 deletions src/test/java/org/apache/ibatis/migration/hook/NewHookTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* Copyright 2010-2018 the original author or authors.
*
* 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.apache.ibatis.migration.hook;

import static org.junit.Assert.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.migration.Migrator;
import org.apache.ibatis.migration.utils.TestUtil;
import org.apache.ibatis.migration.utils.Util;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.Assertion;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
import org.junit.contrib.java.lang.system.SystemOutRule;

public class NewHookTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();

@Rule
public final SystemOutRule out = new SystemOutRule().enableLog();

@Test
public void shouldRunNewHooks() throws Throwable {
File basePath = initBaseDir();
File scriptPath = new File(basePath.getCanonicalPath() + File.separator + "scripts");
Migrator
.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "--idpattern=00", "new", "create table1 JIRA-123"));
String[] scripts = scriptPath.list();
assertEquals(4, scripts.length);
String output = out.getLog();
assertTrue(output.contains("SUCCESS"));
assertTrue(output.contains("Description is valid."));
assertTrue(output.contains("Renamed 03_create_table1_JIRA-123.sql to 03_create_table1_JIRA123.sql"));
assertTrue(new File(scriptPath, "03_create_table1_JIRA123.sql").exists());
}

@Test
public void shouldNotCreateFileWhenBeforeHookThrowsException() throws Throwable {
exit.expectSystemExitWithStatus(1);
exit.checkAssertionAfterwards(new Assertion() {
public void checkAssertion() {
String output = out.getLog();
assertTrue(output.contains("FAILURE"));
}
});
File basePath = initBaseDir();
File scriptPath = new File(basePath.getCanonicalPath() + File.separator + "scripts");
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "new", "create table1"));
assertEquals(3, scriptPath.list().length);
}

protected File initBaseDir() throws IOException {
File basePath = TestUtil.getTempDir();
Migrator.main(TestUtil.args("--path=" + basePath.getAbsolutePath(), "--idpattern=00", "init"));
// Copy hook script
File hooksDir = new File(basePath, "hooks");
hooksDir.mkdir();
FileInputStream srcStream = new FileInputStream(
Resources.getResourceAsFile("org/apache/ibatis/migration/hook/testdir/hooks/NewHook.js"));
FileOutputStream destStream = new FileOutputStream(Util.file(hooksDir, "NewHook.js"));
try {
FileChannel srcChannel = srcStream.getChannel();
FileChannel destChannel = destStream.getChannel();
srcChannel.transferTo(0, srcChannel.size(), destChannel);
} finally {
srcStream.close();
destStream.close();
}
// Add hook settings
File envFile = new File(basePath.getCanonicalPath() + File.separator + "environments", "development.properties");
PrintWriter writer = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(envFile, true), "utf-8")));
try {
writer.println("hook_before_new=js:NewHook.js:_function=validateDesc");
writer.println("hook_after_new=js:NewHook.js:_function=renameFile");
} finally {
writer.close();
}
return basePath;
}
}
Loading