/*****************************************************************************
* Copyright 2012 celum Slovakia s r.o.
*
* 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 com.celum.dbtool.installer;
import com.celum.dbtool.resource.DbScriptsResource;
import com.celum.dbtool.script.DbScript;
import com.celum.dbtool.script.ScriptType;
import com.celum.dbtool.script.Version;
import com.celum.dbtool.script.VersionFactory;
import com.celum.dbtool.sql.*;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import java.io.Reader;
import java.sql.Connection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Doing installation of the DB from scripts that comes from resource.
* Installer do loading of all scripts. Each script is checked and executed
* depends on his type.
*
* The most important method is 'install' that take all DB scripts from
* {@link com.celum.dbtool.resource.DbScriptsResource} and executes them.
*
* @author Zdenko Vrabel (zdenko.vrabel@celum.com)
*/
public class DbInstaller
{
/** logger */
private static Logger LOG = Logger.getLogger(DbInstaller.class.getName());
/** determines entry point in groovy scripts */
public final static String GROOVY_DBMAIN = "dbmain";
/** event listener handles DbInstaller's events */
private DbEventListener eventListener;
/** version factory impl. which will parse the strings into versions */
private VersionFactory versionFactory;
/** holds all variables with values */
private final Map<String, Object> variables;
/** strategy how SQL will be executed */
private final SqlScriptStrategy scriptStrategy;
/** database connection */
private final Connection dbConnection;
/** groovy shell executes the groovy scripts */
private final GroovyShell shell;
/** this SQL is executed after each script and updates the DB version */
private String versionUpdateSqlScript;
/**
* Constructor
*/
private DbInstaller(Connection dbConnection, Map<String, Object> variables, SqlScriptStrategy scriptStrategy)
{
this.eventListener = new DummyEventListener();
this.versionFactory = VersionFactory.DEFAULT;
this.variables = variables;
this.dbConnection = dbConnection;
this.scriptStrategy = scriptStrategy;
this.shell = new GroovyShell();
}
/**
* Easy constructor when you need use it fast with default
* behaviour with Velocity support for placeholder values
*/
public DbInstaller(Connection con, Map<String, Object> variables)
{
this(con, variables, VelocityDecorator.decorate(LogDecorator.decorate(new SqlExecutionStrategy(con)), variables));
}
/**
* Easy constructor when you need use it fast with default
* behaviour without Velocity support
*/
public DbInstaller(Connection con)
{
this(con, new HashMap<String, Object>(), new SqlExecutionStrategy(con));
}
/**
* set the event listener, when your try to set 'null' listener
* then the original one stay as it is.
*/
public void setEventListener(DbEventListener eventListener)
{
if (eventListener != null) {
this.eventListener = eventListener;
}
}
/**
* set the version UPDATE SQL which is executed after each
* script where $version is replaced by script version.
*
* example of sql:
* <code>
* TRUNCATE TABLE VERSIONTABLE;
* INSERT INTO VERSIONTABLE(VERSIONCOL) VALUES ($version);
* </code>
*
* @param sqlScript version update sql script. If its null or empty, the version update is skipped.
*/
public void setVersionUpdateSql(String sqlScript)
{
this.versionUpdateSqlScript = sqlScript;
}
/**
* set the version factory. When you try to set 'null' value,
* the original one stay.
*/
public void setVersionFactory(VersionFactory versionFactory) {
if (versionFactory != null) {
this.versionFactory = versionFactory;
}
}
/**
* Executes all SQL scripts from given resource
*/
public void install(DbScriptsResource resource)
{
Collection<DbScript> scripts = resource.getSortedScripts(versionFactory);
for (DbScript script : scripts) {
executeScript(script);
}
}
/**
* method is invoked for each script that comes from resrouce and
* decide which execution method will be used (SQL or GROOVY)
*/
private void executeScript(DbScript script)
{
try {
script = eventListener.onProcessScript(script);
if (script != null) {
ScriptType type = script.getType();
switch (script.getType()) {
case SQL:
executeSqlScript(script);
break;
case GROOVY:
executeGroovyScript(script);
break;
}
updateDbVersion(script.getVersion());
}
} catch (Exception e) {
eventListener.onError(script, e);
}
}
/**
* method execute the SQL script
*/
private void executeSqlScript(DbScript sqlScript)
{
LOG.info("[SQL SCRIPT]:" + sqlScript.getName() + " (" + sqlScript.getVersion() + ")");
SqlScriptLoader
.loadScriptFromReader(sqlScript.getScriptReader())
.viaStrategy(scriptStrategy);
}
/**
* Method execute the GROOVY script
*/
private void executeGroovyScript(DbScript groovyScript)
{
LOG.info("[GROOVY SCRIPT]:" + groovyScript.getName() + " (" + groovyScript.getVersion() + ")");
Reader scriptReader = groovyScript.getScriptReader();
Script s = shell.parse(scriptReader);
s.invokeMethod(GROOVY_DBMAIN, new Object[] {dbConnection, variables} );
}
/**
* if versionUpdateSql is defined, it's executed after each script
* when $version is replaced by real script's version.
*/
private void updateDbVersion(Version v)
{
if (versionUpdateSqlScript == null || versionUpdateSqlScript.isEmpty()) {
return;
}
LOG.info("Update DB version to " + v.toString());
Map<String, Object> args = new HashMap<String, Object>();
args.put("version", v);
SqlScriptLoader
.loadScriptAsText(versionUpdateSqlScript)
.viaStrategy(VelocityDecorator.decorate(LogDecorator.decorate(new SqlExecutionStrategy(dbConnection)), args));
}
}