Seperti yang dikatakan @Machado, cara termudah untuk melakukannya adalah menghindarinya dan melakukan semua pemrosesan Anda di java utama Anda. Namun, masih mungkin untuk memiliki basis kode dengan kode yang sama tanpa mengulangi diri Anda dengan membuat kode untuk kedua basis kode.
Misalnya menggunakan roda gigi memungkinkan untuk menghasilkan tiga cuplikan dari definisi umum
cuplikan 1:
/*[[[cog
from generate import generate_sql_table
cog.outl(generate_sql_table("rectangle"))
]]]*/
CREATE TABLE rectangles (
width int,
height int
);
/*[[[end]]]*/
cuplikan 2:
public class Rectangle {
/*[[[cog
from generate import generate_domain_attributes,generate_domain_logic
cog.outl(generate_domain_attributes("rectangle"))
cog.outl(generate_domain_logic("rectangle"))
]]]*/
private int width;
private int height;
public int area {
return width * heigh;
}
/*[[[end]]]*/
}
cuplikan 3:
/*[[[cog
from generate import generate_sql
cog.outl(generate_sql("rectangle","""
SELECT sum({area})
FROM rectangles r"""))
]]]*/
SELECT sum((r.width * r.heigh))
FROM rectangles r
/*[[[end]]]*/
dari satu file referensi
import textwrap
import pprint
# the common definition
types = {"rectangle":
{"sql_table_name": "rectangles",
"sql_alias": "r",
"attributes": [
["width", "int"],
["height", "int"],
],
"methods": [
["area","int","this.width * this.heigh"],
]
}
}
# the utilities functions
def generate_sql_table(name):
type = types[name]
attributes =",\n ".join("{attr_name} {attr_type}".format(
attr_name=attr_name,
attr_type=attr_type)
for (attr_name,attr_type)
in type["attributes"])
return """
CREATE TABLE {table_name} (
{attributes}
);""".format(
table_name=type["sql_table_name"],
attributes = attributes
).lstrip("\n")
def generate_method(method_def):
name,type,value =method_def
value = value.replace("this.","")
return textwrap.dedent("""
public %(type)s %(name)s {
return %(value)s;
}""".lstrip("\n"))% {"name":name,"type":type,"value":value}
def generate_sql_method(type,method_def):
name,_,value =method_def
value = value.replace("this.",type["sql_alias"]+".")
return name,"""(%(value)s)"""% {"value":value}
def generate_domain_logic(name):
type = types[name]
attributes ="\n".join(generate_method(method_def)
for method_def
in type["methods"])
return attributes
def generate_domain_attributes(name):
type = types[name]
attributes ="\n".join("private {attr_type} {attr_name};".format(
attr_name=attr_name,
attr_type=attr_type)
for (attr_name,attr_type)
in type["attributes"])
return attributes
def generate_sql(name,sql):
type = types[name]
fields ={name:value
for name,value in
(generate_sql_method(type,method_def)
for method_def in type["methods"])}
sql=textwrap.dedent(sql.lstrip("\n"))
print (sql)
return sql.format(**fields)