Namespaces/introspection: collecting sql strings for validation

Martin Drautzburg Martin.Drautzburg at web.de
Sun Apr 22 14:26:26 EDT 2007


Peter Otten wrote:

> Martin Drautzburg wrote:
> 
>> I would like to validate sql strings, which are spread all over the
>> code, i.e. I run ("prepare") them against a database to see if it
>> happy with the statements. Spelling errors in sql have been a major
>> pain for me.

> 
> def validateSQL(filename=None):
>     if filename is None:
>         # by default operate on the calling module
>         filename = sys._getframe(1).f_globals["__file__"]
>     for s in strings(filename):
>         print "validating", repr(s)

This involves parsing the file. I can see that it would even work on a
pyc file and it actually does solve the problem. Still (for the glory
of the human mind) I would like to do this without parsing a file, but
just the python internal memory. 

> Another option would be to mark SQL statements similar to gettext by
> enclosing them in a function call
> 
> sql = SQL("select * from...")
> 
> and then defining SQL() as either a no-op in production or an actual
> validation while you are debugging. Even simpler and safer would be to
> always validate once:
> 
> def SQL(sql, checked=set()):
>     if sql in checked:
>         return True
>     if not valid_sql(sql): raise ValueError
>     checked.add(sql)
>     return sql

No this does not do the trick. I will not be able to validate an sql
statement bofore I run over the piece of code that uses it. Or I would
have to define all my sql = SQL stuff on module level, isn't id. I
mean, the problem is: when are those sql = SQL statement really
ececuted?




More information about the Python-list mailing list