lib/db.py
changeset 26 81d6679d50d0
parent 24 001f52cd057e
equal deleted inserted replaced
25:4b3cf12848c2 26:81d6679d50d0
    32     c = conn.cursor()
    32     c = conn.cursor()
    33     c.executemany(expr, iter)
    33     c.executemany(expr, iter)
    34 
    34 
    35     return c
    35     return c
    36 
    36 
       
    37 def insert (expr, *args) :
       
    38     return execute_commit(expr, *args).lastrowid
       
    39 
       
    40 def insert_many (cb, expr, iter) :
       
    41     """
       
    42         Perform an executemany with the given iterator (which must yield (cb_val, args) tuples), calling the given callback with the args (cb_val, row_id)
       
    43     """
       
    44 
       
    45     c = conn.cursor()
       
    46 
       
    47     c.executemany(expr, _lastrowid_adapter(c, iter, cb))
       
    48 
       
    49     return commit(c)
       
    50 
       
    51 def _lastrowid_adapter (c, iter, cb) :
       
    52     for val, args in iter :
       
    53         yield args
       
    54 
       
    55         cb(val, c.lastrowid)
       
    56 
    37 def commit (cursor) :
    57 def commit (cursor) :
    38     try :
    58     try :
    39         cursor.execute("COMMIT")
    59         cursor.execute("COMMIT")
    40     except sqlite3.OperationalError :
    60     except sqlite3.OperationalError :
    41         pass    # ffs. INSERT just doesn't do anything otherwise
    61         pass    # ffs. INSERT just doesn't do anything otherwise
    42 
    62 
    43     return cursor.rowcount
    63     return cursor
    44 
    64 
    45 def execute_commit (expr, *args) :
    65 def execute_commit (expr, *args) :
    46     return commit(execute(expr, *args))
    66     return commit(execute(expr, *args))
    47 
    67 
    48 def execute_commit_many (expr, iter) :
    68 def execute_commit_many (expr, iter) :
    49     return commit(execute_many(expr, iter))
    69     return commit(execute_many(expr, iter))
    50 
    70 
    51 select = execute
    71 select = execute
    52 
    72 
    53 delete = execute_commit
    73 delete = execute_commit
    54 insert = execute_commit
       
    55 
    74 
    56 delete_many = execute_commit_many
    75 delete_many = execute_commit_many
    57 insert_many = execute_commit_many
       
    58 
    76 
    59 cursor = conn.cursor
    77 cursor = conn.cursor
    60 
    78