def parse(typebychar, connection, text, *args, **kvargs):
i = iter(text)
index = 0
result = ''
try:
while True:
try: c = next(i)
except StopIteration: break
if c == '%':
c = next(i)
if c == '(':
field = ''
while True:
c = next(i)
if c == ')': break
field += c
c = next(i)
result += typebychar[c].to_db(connection, kvargs[field])
elif c == '%':
result += '%'
else:
result += typebychar[c].to_db(connection, args[index])
index += 1
else:
result += c
except StopIteration:
raise Exception('unexpeted end of sql template')
return result