You may have heard about the versioned migration of the database structure. About it wrote on Habré . DBDeploy is one of the simplest and most well-known tools that makes it easy to install all the latest changes in the database on any instance and any developer machine. And Gradle is now a fashionable tool for building a project (like Ant and Maven, only better). About him, too, have already written .
The question is how to run DBDeploy from the Gradle script? DBDeploy has Tasks for Ant and a plugin for Maven, but for now there is no plug-in for DBdeploy (more precisely, it is in its infancy). Having poked around a bit, I came to the conclusion that the easiest way is to use the same Ant task DBDeploy from the Gradle script ( it describes how to use any Ant task from the gradle script). Consider an example.
Suppose our project has the following structure. The db folder contains the following SQL scripts:
project.ext { dbDriver = 'com.mysql.jdbc.Driver' dbUrl = 'jdbc:mysql:///habrahabr' dbUsername = 'habra' dbPassword = 'habr' }
task updateDatabase << { ant.taskdef(name: 'dbdeploy', classname: 'com.dbdeploy.AntTarget', classpath: configurations.compile.asPath) ant.dbdeploy(driver: dbDriver, url: dbUrl, userid: dbUsername, password: dbPassword, dir: 'db', dbms: 'mysql', undooutputfile: 'db/undo_last_change.sql') }
<b>task createChangelogTable</b> << { ant.sql(driver: dbDriver, url: dbUrl, userid: dbUsername, password: dbPassword, encoding: 'UTF-8', classpath: configurations.compile.asPath) { fileset(file: 'db/create_changelog_table.sql') } }
<b>task undoLastChange</b> << { ant.sql(driver: dbDriver, url: dbUrl, userid: dbUsername, password: dbPassword, encoding: 'UTF-8', classpath: configurations.compile.asPath) { fileset(file: 'db/undo_last_change.sql') } }
Thus, we got 3 tasks:
: createChangelogTable BUILD SUCCESSFUL
[ant: dbdeploy] dbdeploy 3.0M3 [ant: dbdeploy] Reading change scripts from directory / tmp / habr / gradle-dbdeploy / db ... [ant: dbdeploy] Changes currently applied to database: [ant: dbdeploy] 1..61 [ant: dbdeploy] Scripts available: [ant: dbdeploy] 62..62 [ant: dbdeploy] To be applied: [ant: dbdeploy] 62..62 [ant: dbdeploy] Applying # 62: 062_migrate_currency_to_eur.sql ... [ant: dbdeploy] -> statement 1 of 5 ... [ant: dbdeploy] -> statement 2 of 5 ... [ant: dbdeploy] -> statement 3 of 5 ... [ant: dbdeploy] -> statement 4 of 5 ... [ant: dbdeploy] -> statement 5 of 5 ... [ant: dbdeploy] Generating undo scripts ... BUILD SUCCESSFUL
: undoLastChange BUILD SUCCESSFUL
Now you can, once running “gradle createChangelogTable”, run “gradle updateDatabase” every time after each script change, and to undo the latest changes, use “gradle undoLastChange”.
Gradle provides a very concise and readable syntax for build scripts, DBDeploy offers a simple and reliable way to put changes in the database. And they worked great.
Have a great Vision!
Source: https://habr.com/ru/post/152765/
All Articles