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 sqlands(left, lst): """Similar to webpy sqlors but for ands""" if isinstance(lst, web.utils.iters): lst = list(lst) ln = len(lst) if ln == 0: return web.SQLQuery("1!=2") if ln == 1: lst = lst[0] if isinstance(lst, web.utils.iters): return web.SQLQuery(['('] + sum([[left, web.sqlparam(x), ' AND '] for x in lst], []) + ['1!=2)']) else: return left + web.sqlparam(lst)
def join(items, sep): q = web.SQLQuery('') for i, item in enumerate(items): if i: q += sep q += item return q
def create(self, sitename): if self.sitestore is None: self.sitestore = DBSiteStore(self.db, self.schema) if not self.has_initialized(): q = str(self.schema.sql()) self.db.query(web.SQLQuery([q])) self.sitestore.initialize() return self.sitestore