Revision 2121
Added by Aaron Marcuse-Kubitza over 12 years ago
lib/sql.py | ||
---|---|---|
306 | 306 |
|
307 | 307 |
order_by_pkey = object() # tells mk_select() to order by the pkey |
308 | 308 |
|
309 |
def mk_select(db, table, fields=None, conds=None, limit=None, start=None, |
|
309 |
def mk_select(db, tables, fields=None, conds=None, limit=None, start=None,
|
|
310 | 310 |
order_by=order_by_pkey, table_is_esc=False): |
311 | 311 |
''' |
312 |
@param tables The single table to select from, or a list of tables to join |
|
313 |
together, in the form: [table0, (table1, joins_dict), ...] |
|
312 | 314 |
@param fields Use None to select all fields in the table |
313 | 315 |
@param table_is_esc Whether the table name has already been escaped |
314 | 316 |
@return tuple(query, params) |
315 | 317 |
''' |
316 | 318 |
def esc_name_(name): return esc_name(db, name) |
317 | 319 |
|
320 |
if not lists.is_seq(tables): tables = [tables] |
|
321 |
tables = tables[:] # don't modify input! |
|
322 |
table0 = tables.pop(0) # first table is separate |
|
323 |
|
|
318 | 324 |
if conds == None: conds = {} |
319 | 325 |
assert limit == None or type(limit) == int |
320 | 326 |
assert start == None or type(start) == int |
321 | 327 |
if order_by == order_by_pkey: |
322 |
order_by = pkey(db, table, recover=True, table_is_esc=table_is_esc) |
|
323 |
if not table_is_esc: table = esc_name_(table)
|
|
328 |
order_by = pkey(db, table0, recover=True, table_is_esc=table_is_esc)
|
|
329 |
if not table_is_esc: table0 = esc_name_(table0)
|
|
324 | 330 |
|
325 | 331 |
params = [] |
326 | 332 |
|
327 | 333 |
def parse_col(field): |
328 | 334 |
'''Parses fields''' |
329 |
if isinstance(field, tuple): # field is literal values
|
|
335 |
if isinstance(field, tuple): # field is literal value |
|
330 | 336 |
value, col = field |
331 | 337 |
sql_ = '%s' |
332 | 338 |
params.append(value) |
... | ... | |
345 | 351 |
query = 'SELECT ' |
346 | 352 |
if fields == None: query += '*' |
347 | 353 |
else: query += ', '.join(map(parse_col, fields)) |
348 |
query += ' FROM '+table |
|
354 |
query += ' FROM '+table0
|
|
349 | 355 |
|
350 | 356 |
missing = True |
351 | 357 |
if conds != {}: |
Also available in: Unified diff
sql.py: mk_select(): Accept a list of tables to join together (initial implementation just uses the first table)