Automation Scripts

An automation script is a small program that does a task for you, such as adding the same column to many tables. DbSchema runs scripts in Groovy, a programming language similar to Java. A script can read and change your DbSchema design, run SQL in the database, and generate documentation.

A script can change the design in DbSchema: the tables, columns and diagrams of your project. It changes the database only when it runs SQL there. Database Terms explains the difference between the design and the database. The examples on this page use a PostgreSQL project with the schema shop and its tables customers and orders. Change these names to the names in your own project.

The Automation Scripts dialog: five scripts under My Scripts, the Examples folders with their counts, and the script List Columns with the columns of customers in its output

Open the Automation Scripts dialog

The dialog keeps your own scripts and the examples that come with DbSchema.

  1. Choose Query → Automation Scripts.
  2. Your scripts are under My Scripts.
  3. The examples are under Examples, in folders such as Basic, Design, Documentation and Export. The number at the right of a folder tells how many scripts it holds.
The Automation Scripts dialog with the Examples folders Basic and Design open, a short description under each script, and the About tab on the right

Below each script name, DbSchema shows the first sentence of its opening comment: the line that starts with // and explains the script. The read-only badge marks the Examples: you cannot change them. To change one, copy its text into a script under My Scripts. The About tab lists the variables that a script receives. DbSchema API at the bottom opens the API reference: the documentation of the classes and methods that a script can call.

Create and run a script

  1. Right-click My Scripts and choose Create Groovy Script.
  2. Type a file name and save. DbSchema creates the empty script and opens it in a tab.
  3. Type the script.
  4. Press Run.

The output shows under the script, after the message "Execution succeeded.". DbSchema saves the scripts of My Scripts when you close the dialog. They are files in the Automation Scripts Folder, which you can change in Edit → Settings → File Locations.

You can also run Groovy in the SQL Editor. In the SQL Editor toolbar, click the button labeled SQL and choose Java Groovy. A Groovy script in the SQL Editor gets the same variables, and sql is the connection of that SQL Editor.

What a script can use

A variable is a name that holds a value. A script in DbSchema receives these variables:

VariableWhat it holds
projectYour DbSchema design: its schemas, tables, columns and diagrams.
sqlThe connection to the database, as a Groovy Sql object. It is null, which means no value, while the project is not connected.
outThe output under the script. println writes there too.
argsThe values that you give after the script path on the command line. It is empty in the dialog.

The package com.wisecoders.dbschema.schema contains classes such as Project, Schema, Table and Column. The API reference describes each of them.

List the columns of a table

project.getSchema() finds a schema by its name, and getTable() finds a table in it.

// Prints the columns of the customers table, with their data types
def customers = project.getSchema('shop').getTable('customers')
for (column in customers.columns) {
    println "${column.name} ${column.typeString}"
}
The script List Columns and its output: customer_id integer, first_name varchar(60) and the other columns of customers

Run SQL from a script

sql runs statements in the database that the project is connected to. eachRow() reads the result of a query one row at a time.

// Counts the orders in the database, by status
sql.eachRow('SELECT status, count(*) AS orders FROM shop.orders GROUP BY status ORDER BY status') { row ->
    println "${row.status}: ${row.orders}"
}
The script Count Orders and its output: CANCELLED 130, DELIVERED 748, NEW 128, PAID 247, SHIPPED 247

Add a column to the design

createColumn() takes the column name and the data type. Use the data type name that your database uses, such as date or varchar(60).

// Adds the column birth_date to the customers table in the model
def customers = project.getSchema('shop').getTable('customers')
def birthDate = customers.createColumn('birth_date', 'date')
birthDate.comment = 'Used for birthday offers'
println "Added ${birthDate.name} ${birthDate.typeString} to ${customers.name}"
The script Add Column and its output: Added birth_date date to customers

This script changes the design only. The new column is created in the database when you apply the changes to the database.

Drop a column

To drop a column, the script first marks it with markForDeletion(). Then project.refresh() removes every marked column.

// Drops the column phone from the customers table in the model
def customers = project.getSchema('shop').getTable('customers')
def phone = customers.columns.getByName('phone')
phone.markForDeletion()
project.refresh()
println "Dropped ${phone.name} from ${customers.name}"
The script Drop Column and its output: Dropped phone from customers

This script drops the column from the design only. Database → Create or Upgrade Model in the Database adds the objects that are in the design but missing from the database. It does not drop the column from the database.

Drop the column from the database too

To drop the column from the database too, run the statement in the script:

sql.execute('ALTER TABLE shop.customers DROP COLUMN phone')
sql.commit()

The statement runs in a transaction: a group of changes that is not permanent until it is committed. The script tab does not commit changes by itself. Call sql.commit() to save the change in the database. You can also press Commit in the toolbar of the script tab. Some databases, such as MySQL, commit an ALTER TABLE statement automatically. In these databases, the column is dropped at once.

Build the design from a CSV file

A script can read any file with plain Groovy, such as a CSV file: a text file with values separated by commas. Each line of this file describes one database column, in the form table,column,data type:

suppliers,supplier_id,integer
suppliers,name,varchar
suppliers,email,varchar

The script reads the file. It creates each table that the design does not have yet, and adds the columns to it:

// Creates tables and columns in the model from a CSV file: table,column,data type
def shop = project.getSchema('shop')
new File('C:/data/columns.csv').eachLine { String line ->
    def (tableName, columnName, dataType) = line.split(',')
    def table = shop.getTable(tableName) ?: shop.createTable(tableName)
    table.createColumn(columnName, dataType)
    println "${tableName}.${columnName} ${dataType}"
}
The output of the CSV script: suppliers.supplier_id integer, suppliers.name varchar and suppliers.email varchar

The new table is in the design, but it does not appear on any diagram yet. Some CSV files contain quoted values, or values with commas inside them. Use the Import examples to read these files correctly.

Apply the changes to the database

  1. Choose Database → Create or Upgrade Model in the Database.
  2. In Commit Changes into the Database, keep the schemas ticked and press OK.
  3. The Execute Script In Database Dialog shows one statement at a time. Press Execute to run the statement, or Skip to leave it out. Press Execute All to run every statement, or Close to stop.
The Execute Script In Database Dialog at statement 3 of 3, CREATE TABLE shop.suppliers, which the CSV script created in the design

After the scripts above, the dialog lists three statements: ALTER TABLE shop.customers ADD birth_date date, the comment of birth_date, and CREATE TABLE shop.suppliers. There is no DROP for phone. Schema Synchronization explains this dialog and how to compare the design with the database.

Run a script from the command line

DbSchema can run a script without opening its window, for example in a scheduled task: a task that the operating system starts at a set time. In a terminal, start DbSchema.exe with -x and the full path of the script. The values after the script path are the arguments of the script.

"C:\Program Files\DbSchema\DbSchema.exe" -x C:/scripts/list-tables.groovy C:/models/shop.dbs > list-tables.log

When you run a script this way, no project is open. Both project and sql are null. The arguments are in args: here args[0] is C:/models/shop.dbs.

Use -x for scripts that work on a project file. To run SQL and Groovy on database connections from a terminal, use DbSchemaCLI.

Load a project file

To work with a design, the script loads the project file itself:

import com.wisecoders.dbschema.schema.store.ProjectLoader

def loader = new ProjectLoader()
new File(args[0]).withInputStream { input -> loader.parse(input) }
for (schema in loader.project.schemas) {
    for (table in schema.tables) {
        println "${schema.name}.${table.name}"
    }
}

The Import examples show how a script saves a project file that it changed.

Read the output and the exit code

DbSchema writes the output of the script to the standard output, the text that a program prints to the terminal. It writes its own log lines there too. The > list-tables.log at the end of the command saves all of it to a file. The lines of the script are marked STDOUT:

12:05:18.937 I {main} 「STDOUT」: Execute Script 'list-tables.groovy' as Java Groovy.
12:05:18.939 I {main} 「STDOUT」:
12:05:22.941 I {main} 「STDOUT」: shop.addresses
12:05:22.943 I {main} 「STDOUT」: shop.categories
12:05:22.945 I {main} 「STDOUT」: shop.countries
12:05:22.947 I {main} 「STDOUT」: shop.customers
...
12:05:22.962 I {main} 「STDOUT」: shop.wishlists

When DbSchema ends, it returns an exit code, a number that tells whether the run succeeded. It returns 0 if the script finishes, and 1 if the script fails. A scheduled task can check the exit code to find a failed script.

Run a script on macOS or Linux

The About tab of the dialog gives this command for macOS:

/Applications/DbSchema/DbSchema.app/Contents/MacOS/JavaApplicationStub -x /path/to/script.groovy

Give the full path of the script, and write its arguments right after the script path, as on Windows. Do not include -args, which the About tab shows before the arguments. Otherwise, DbSchema passes -args to the script as its first argument. On Linux, the About tab gives DbSchema -x <scriptFile>. On a computer without a screen, it says to set export DISPLAY=:0 first.

Common problems

The script fails with "Cannot invoke method ... on null object"

The script calls a method on something that does not exist.

  • If the method is called on sql, there is no database connection. Either the project is offline, or the script runs with -x, where sql is always null. Connect the project to the database, or open the connection in the script with groovy.sql.Sql.newInstance(...), as the example Create Database Connection shows.
  • If the method is called on a schema, a table or a column, its name is wrong. getSchema(), getTable() and getByName() return null for a name that the design does not have.

Next steps