Jak powiedział @Machado, najprostszym sposobem na to jest uniknięcie tego i wykonanie całego przetwarzania w głównej Javie. Jednak nadal możliwe jest kodowanie kodu bazowego za pomocą podobnego kodu bez powtarzania się przez wygenerowanie kodu dla obu baz kodu.
Na przykład za pomocą zębatki enable można wygenerować trzy fragmenty ze wspólnej definicji
fragment 1:
/*[[[cog
from generate import generate_sql_table
cog.outl(generate_sql_table("rectangle"))
]]]*/
CREATE TABLE rectangles (
width int,
height int
);
/*[[[end]]]*/
fragment 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]]]*/
}
fragment 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]]]*/
z jednego pliku referencyjnego
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)