Skip to content

Instantly share code, notes, and snippets.

@nobeans
Created February 25, 2011 18:34
Show Gist options
  • Save nobeans/844264 to your computer and use it in GitHub Desktop.
Save nobeans/844264 to your computer and use it in GitHub Desktop.
class DdlBuilder {
def writer
DdlBuilder(writer) { this.writer = writer }
def scheme(Closure cls) {
new NodeBuilder().scheme(cls).each { table ->
writer.println "CREATE TABLE ${table.name()} ("
writer.println table.collect { col ->
" ${col.name()} ${type(col.attribute('type'))}"
}.join(",\n")
writer.println ")"
}
}
private type(clazz) {
switch (clazz) {
case String: return "TEXT"
case int: return "INTEGER"
case Date: return "TIMESTAMP"
default:
throw new RuntimeException("unsupported type: $clazz")
}
}
}
def writer = new StringWriter()
new DdlBuilder(writer).scheme {
book {
id type:int
title type:String
published type:Date
author type:int
}
author {
id type:int
name type:String
}
}
println writer.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment