HTTPS SSH

Gradle Database Plugin

This is a Database Plugin for Gradle. It makes it easy to re-initialise your database from your build. This is especially useful for testing.

Currently it is specific to MySQL and MariaDB.

This Database Plugin has been released under the Apache Licence (v2) in the hope someone else might find it useful.

It adds two new task types to your gradle build, DbInit and DbReset.

DbReset

Reset the specified database by issuing a drop database followed by a create database.

DbInit

Initialise a database. Requires the name of the already-created database, as well as a reference to a file containing sql statements. Typically this file will specify the schema, but seed data might also be included.

Installation

This plugin is available via the jcenter repository on Bintray. Using this repository is the easiest way to use this plugin. The example usage below uses jcenter.

Alternatively, you can download the source from https://bitbucket.org/coherentsoftware/gradle-databaseplugin and build your own jar.

Building

The build system uses the Gradle wrapper. Therefore the only requirement is Java 6 or later.

./gradlew

will build the plugin.

Usage

Common to all database tasks

import au.com.coherentsoftware.gradle.database.task.*

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath('au.com.coherentsoftware.gradle:Gradle-DatabasePlugin:VERSION')
    }
}

apply plugin: 'database'

database {
    username = 'mysqlUserName'
    password = 'mysqlUserPassword'
    driver = 'com.mysql.jdbc.Driver'  // the default value
    host = 'localhost'  // the default value
    port = '3306' // the default value
}

configurations {
    driver
}

dependencies {
    driver 'mysql:mysql-connector-java:5.1.23'
}

// Init jdbc so gradle can connect directly to db
URLClassLoader loader = GroovyObject.class.classLoader as URLClassLoader
configurations.driver.each { File file ->
    loader.addURL(file.toURI().toURL())
}
Class driver = loader.loadClass(project.database.driver)

DbReset Task

task cleanMyDb(type: DbReset) {
    database 'dbname'
}

DbInit Task

task initMyDb(type: DbInit) {
    database  'dbname'
    dataFile = 'data/initData.sql'
}

Licence

This software is released under the Apache License, Version 2.0. Please see the copy of the licence, included in this directory as LICENSE, for details.

Bugs, Wishlist

Current build config, plus usage, should be friendlier.

Is currently specific to MySql (and MariaDB). It would be nice if it also worked with (at least) PostgreSQL.

Documentation could be improved.

There are probably many ways the plugin could be made more robust.

There is too much initialisation code required in your project's build file. It would be better if the classloader and database driver could be managed transparently by the plugin.

Feel free to fork and send pull requests! Home page on BitBucket at https://bitbucket.org/coherentsoftware/gradle-databaseplugin