Revision 2063
Added by Aaron Marcuse-Kubitza over 12 years ago
lib/sql.py | ||
---|---|---|
341 | 341 |
|
342 | 342 |
default = object() # tells insert() to use the default value for a column |
343 | 343 |
|
344 |
def insert(db, table, row, returning=None, recover=None, cacheable=True,
|
|
345 |
table_is_esc=False): |
|
344 |
def insert_select(db, table, select_query=None, cols=None, params=None,
|
|
345 |
returning=None, recover=None, cacheable=True, table_is_esc=False):
|
|
346 | 346 |
''' |
347 | 347 |
@param returning str|None An inserted column (such as pkey) to return |
348 | 348 |
@param table_is_esc Whether the table name has already been escaped |
349 | 349 |
''' |
350 |
if select_query == None: select_query = 'DEFAULT VALUES' |
|
351 |
if cols == []: cols = None # no cols (all defaults) = unknown col names |
|
350 | 352 |
if not table_is_esc: check_name(table) |
353 |
|
|
354 |
# Build query |
|
355 |
query = 'INSERT INTO '+table |
|
356 |
if cols != None: |
|
357 |
map(check_name, cols) |
|
358 |
query += ' ('+', '.join(cols)+')' |
|
359 |
query += ' '+select_query |
|
360 |
|
|
361 |
if returning != None: |
|
362 |
check_name(returning) |
|
363 |
query += ' RETURNING '+returning |
|
364 |
|
|
365 |
return run_query(db, query, params, recover, cacheable) |
|
366 |
|
|
367 |
def insert(db, table, row, *args, **kw_args): |
|
368 |
'''For args, see insert_select()''' |
|
351 | 369 |
if lists.is_seq(row): cols = None |
352 | 370 |
else: |
353 | 371 |
cols = row.keys() |
354 | 372 |
row = row.values() |
355 |
map(check_name, cols) |
|
356 | 373 |
row = list(row) # ensure that "!= []" works |
357 | 374 |
|
358 | 375 |
# Check for special values |
... | ... | |
365 | 382 |
values.append(value) |
366 | 383 |
|
367 | 384 |
# Build query |
368 |
query = 'INSERT INTO '+table |
|
369 |
if values != []: |
|
370 |
if cols != None: query += ' ('+', '.join(cols)+')' |
|
371 |
query += ' VALUES ('+(', '.join(labels))+')' |
|
372 |
else: query += ' DEFAULT VALUES' |
|
385 |
if values != []: query = ' VALUES ('+(', '.join(labels))+')' |
|
386 |
else: query = None |
|
373 | 387 |
|
374 |
if returning != None: |
|
375 |
check_name(returning) |
|
376 |
query += ' RETURNING '+returning |
|
377 |
|
|
378 |
return run_query(db, query, values, recover, cacheable) |
|
388 |
return insert_select(db, table, query, cols, values, *args, **kw_args) |
|
379 | 389 |
|
380 | 390 |
def last_insert_id(db): |
381 | 391 |
module = util.root_module(db.db) |
Also available in: Unified diff
sql.py: Added insert_select() and use it in insert()