diff init.gradle @ 174:e949e86b570e

add databaseDrop|Create tasks for managing environment psql databases
author smith@nwoca.org
date Wed, 17 Sep 2014 22:05:37 +0100
parents 50db7a832af5
children c3b7af90d1e4
line wrap: on
line diff
--- a/init.gradle	Fri Sep 05 22:59:30 2014 +0100
+++ b/init.gradle	Wed Sep 17 22:05:37 2014 +0100
@@ -1,3 +1,4 @@
+import groovy.sql.*
 
 gradle.ext.ssdtDevelkitLocation = gradle.ext.has('ssdtDevelkitLocation') ? gradle.ssdtDevelkitLocation : 'http://hg.ssdt-ohio.org/browse/public/develkit'
 
@@ -240,6 +241,49 @@
         }
     }
 
+	if (gradle.hasProperty('environmentDatabase')) {
+		tasks.addRule("Pattern: database{Drop|Create}...: drops or creates the environment's database") { String taskName ->
+			if(taskName.startsWith('database') && (taskName.contains('Drop') || taskName.contains('Create')) ) {
+			   task(taskName) {
+					doLast {
+						def dropIt = taskName.contains("Drop")
+						def createIt = taskName.contains("Create")
+						def driverName = gradle.environmentDatabase.jdbc.driverClassName
+						def databaseUrl = gradle.environmentDatabase.jdbc.url
+						if (driverName != "org.postgresql.Driver") {
+							logger.info "skipping database operation for non-postgresql driver"
+							throw new StopActionException("driver $driverName not supported by $taskName")
+						}
+						if (!configurations.hasProperty('jdbcdriver')) {
+							throw new GradleException("databaseDrop requires a 'jdbcdriver' configuration with a postgresql (or other) driver" )
+						} 
+						configurations.jdbcdriver.each {File file ->
+							GroovyObject.class.classLoader.addURL(file.toURL())
+						}						
+						Class.forName(driverName)
+						def url = new URI(databaseUrl.substring(5))
+						def jdbcBaseUrl = databaseUrl - url.path
+						def databaseName = url.path - "/"
+						def adminUrl = jdbcBaseUrl + "/postgres"
+						def sql =  Sql.newInstance(adminUrl,
+											gradle.environmentDatabase.jdbc.username,
+											gradle.environmentDatabase.jdbc.password,
+											driverName)
+						if (dropIt) {
+							logger.info "dropping $databaseName (if exists) from $adminUrl"
+							sql.execute 'DROP DATABASE IF EXISTS "' + databaseName + '";' 
+						}
+
+						if (createIt) {
+							logger.info  "Creating database $databaseName at $adminUrl"
+							sql.execute 'CREATE DATABASE "' + databaseName + '";' 
+						}						
+					}
+			   }
+			
+			}
+		}
+	}
     
 }