sqlstring -- a library to build a SELECT statement

Pierre Quentel quentel.pierre at wanadoo.fr
Thu Oct 20 15:54:35 EDT 2005


grunar at gmail.com a écrit :
> 
> 
> My solution is sqlstring. A single-purpose library: to create SQL
> statement objects. These objects (such as sqlstring.Select), represent
> complex SQL Statements, but as Python objects. The benefit is that you
> can, at run-time, "build" the statement pythonically, without
> getting bogged down in String Manipulation. The theory is that once in
> use, things that were complex (string magic) become simpler, and allow
> the program to worry about higher-level issues.
> 
With the same starting point - I don't like writing SQL strings inside 
Python code either - I have tested a different approach : use the Python 
list comprehension / generator expression syntax for the select requests

I have published a recipe on the Python Cookbook : 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442447

For instance :

s = query(r.name for r in planes if r.speed > 500)
for item in s:
	print s

query is a class whose instances are created with the generator 
expression as argument. The matching SQL request is built in the 
__init__ method, here :

SELECT r.name FROM planes AS r WHERE r.speed > 500

On two tables :

s=query(r.name for r in planes for c in countries if r.country ==
     c.country and c.continent == 'Europe')

is translated into :

SELECT r.name FROM countries AS c ,plane AS r WHERE (r.country =
     c.country AND c.continent = 'Europe')

For the moment the implementation is not very elegant, especially for 
getting the source code of the generator expression (it would be nice if 
they had an attribute for that !), and I'm not sure if it could work for 
all the forms of the SELECT syntax. But it should cover at least the 
most usual kinds of requests, with a Pythonic syntax

Regards,
Pierre



More information about the Python-list mailing list