8.6.2. Initializing and Updating a Database from The Command Line

Database create and update scripts can be run from the command line using the com.haulmont.cuba.core.sys.utils.DbUpdaterUtil class included in the platform’s Middleware block. At startup, the following arguments should be specified:

  • dbTypeDBMS type, possible values: postgres, mssql, oracle, mysql.

  • dbVersionDBMS version (optional argument).

  • dbDriver - JDBC driver class name (optional argument). If not provided, the driver class name will be derived from dbType.

  • dbUser – database user name.

  • dbPassword – database user password.

  • dbUrl – database connection URL. For primary initialization, the specified database should be empty; the database is not cleared automatically in advance.

  • scriptsDir – absolute path to the folder containing scripts in the standard structure. Typically, this is the database scripts directory supplied with the application.

  • one of the possible commands:

    • create – initialize the database.

    • check – show all unexecuted update scripts.

    • update – update the database.

An example of a script for Linux running DbUpdaterUtil:

#!/bin/sh

DB_URL="jdbc:postgresql://localhost/mydb"

APP_CORE_DIR="./../webapps/app-core"
WEBLIB="$APP_CORE_DIR/WEB-INF/lib"
SCRIPTS="$APP_CORE_DIR/WEB-INF/db"
TOMCAT="./../lib"
SHARED="./../shared/lib"

CLASSPATH=""
for jar in `ls "$TOMCAT/"`
do
  CLASSPATH="$TOMCAT/$jar:$CLASSPATH"
done

for jar in `ls "$WEBLIB/"`
do
  CLASSPATH="$WEBLIB/$jar:$CLASSPATH"
done

for jar in `ls "$SHARED/"`
do
  CLASSPATH="$SHARED/$jar:$CLASSPATH"
done

java -cp $CLASSPATH com.haulmont.cuba.core.sys.utils.DbUpdaterUtil \
 -dbType postgres -dbUrl $DB_URL \
 -dbUser $1 -dbPassword $2 \
 -scriptsDir $SCRIPTS \
 -$3

This script is designed to work with the database named mydb running on the local PostgreSQL server. The script should be located in the bin folder of the Tomcat server and should be started with {username}, {password} and {command}, for example:

./dbupdate.sh cuba cuba123 update

Script execution progress is displayed in the console. If any error occurs, same actions as described in the previous section for the automatic update mechanism should be performed.

Warning

When updating the database from the command line, the existing Groovy scripts are started, but only their main part gets executed. Due to the lack of the server context, the script’s PostUpdate part is ignored with the corresponding message written to the console.