def debuginsert(tablename, seqname=None, **values): if values: print("INSERT INTO %s (%s) VALUES (%s)" % ( tablename, ", ".join(values.keys()), ', '.join([web.aparam() for x in values]) ), values.values()) else: print("INSERT INTO %s DEFAULT VALUES" % tablename)
def multiple_insert(tablename, values, seqname=None, _test=False): # multiple inserts are supported only in version 8.2+ if get_postgres_version() < (8, 2): result = [web.insert(tablename, seqname=seqname, **v) for v in values] if seqname: return result else: return None if not values: return [] keys = list(values[0]) #@@ make sure all keys are valid # make sure all rows have same keys. for v in values: if list(v) != keys: raise Exception('Bad data') q = web.SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))) data = [] for row in values: d = join([web.SQLQuery(web.aparam(), [row[k]]) for k in keys], ', ') data.append('(' + d + ')') q += join(data, ',') if seqname is not False: if seqname is None: seqname = tablename + "_id_seq" q += "; SELECT currval('%s')" % seqname if _test: return q db_cursor = web.ctx.db_cursor() web.ctx.db_execute(db_cursor, q) try: out = db_cursor.fetchone()[0] out = list(range(out - len(values) + 1, out + 1)) except Exception: out = None if not web.ctx.db_transaction: web.ctx.db.commit() return out
def multiple_insert(tablename, values, seqname=None, _test=False): # multiple inserts are supported only in version 8.2+ if get_postgres_version() < (8, 2): result = [web.insert(tablename, seqname=seqname, **v) for v in values] if seqname: return result else: return None if not values: return [] keys = values[0].keys() #@@ make sure all keys are valid # make sure all rows have same keys. for v in values: if v.keys() != keys: raise Exception, 'Bad data' q = web.SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))) data = [] for row in values: d = join([web.SQLQuery(web.aparam(), [row[k]]) for k in keys], ', ') data.append('(' + d + ')') q += join(data, ',') if seqname is not False: if seqname is None: seqname = tablename + "_id_seq" q += "; SELECT currval('%s')" % seqname if _test: return q db_cursor = web.ctx.db_cursor() web.ctx.db_execute(db_cursor, q) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out = None if not web.ctx.db_transaction: web.ctx.db.commit() return out