Skip to content

Instantly share code, notes, and snippets.

@pgaertig
Last active June 15, 2019 04:09
Show Gist options
  • Save pgaertig/9502960 to your computer and use it in GitHub Desktop.
Save pgaertig/9502960 to your computer and use it in GitHub Desktop.
FactoryGrill - db population made easy - a-la FactoryGirl
import groovy.sql.Sql
import org.codehaus.groovy.control.CompilerConfiguration
import java.sql.Connection
class FactoryGrill extends Script {
private Connection connection;
private Sql sql;
void setConnection(Connection conn) {
connection = conn;
sql = new Sql(conn);
}
void prepare() {
if(connection == null) {
setConnection(getBinding().getVariable("connection") as Connection);
}
}
void load(String groovySource) {
def config = new CompilerConfiguration();
config.setScriptBaseClass(this.getClass().getName());
def binding = new Binding();
binding.setVariable("connection", connection);
GroovyShell shell = new GroovyShell(this.class.classLoader, binding, config);
shell.evaluate(groovySource);
}
void insert(LinkedHashMap row, String table) {
prepare();
def columns = row.keySet().join(', ');
def paramPlaceholders = ('?,' * row.size())[0..-2];
def query = "INSERT INTO ${table} (${columns}) VALUES (${paramPlaceholders})"
println "FactoryGrill: \"${query}\" with ${row.values()}"
sql.executeInsert(
"INSERT INTO ${table} (${columns}) VALUES (${paramPlaceholders})", row.values().asList()
);
}
@Override
Object run() {
return null;
}
}
insert('MyTable', ID: 1, CREATED_AT: new Date(), NAME: 'Example text')
//above is equivalent to:
// INSERT INTO MyTable(ID, CREATED_AT, NAME) VALUES (1, ..current date here.., 'Example text')
//You can do more with Groovy:
import org.apache.commons.lang3.RandomStringUtils;
for ( i in 0..9 ) {
insert('USERS', CREATED_AT: new Date(), EMAIL: "test${i}@mydomain.com",
SALT: RandomStringUtils.randomAlphanumeric(32));
}
FactoryGrill fg = new FactoryGrill();
fg.setConnection(connection); //this should be java.sql.Connection
fg.load(new File('seeddata.groovy').text);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment