sqlite3_backend.py 1.27 KB
Newer Older
1
2
import sqlite3
import time
Antonin Dvorak's avatar
Antonin Dvorak committed
3
4
5
6
7
8
9
10
11
12
13
14

def modify_db(conn,
              query,
              *args):
    """Wrapper for modifications (INSERT, UPDATE, DELETE or REPLACE) of Sqlite3 database.

    Executes given query and commits it - in case of lock it retries the commit

    Params
    ------
    connection: sqlite3 connection
        existing sqlite3 connection to use
15
    query: sql
Antonin Dvorak's avatar
Antonin Dvorak committed
16
17
18
19
        query to run
    args: array
        additional arguments for execute query, optional
    """
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

    with conn.cursor() as c:
        for x in range(0, 10):
            try:
                if args:
                    c.execute(query, args)
                else:
                    c.execute(query)
            except:
                print("Sqlite3 execute unsuccessful, retrying....")
                time.sleep(1)
                pass
            else:
                print("Sqlite3 execute successful, breaking the retry cycle.")
                break
Antonin Dvorak's avatar
Antonin Dvorak committed
35
36
37
38
39
40

    # retry commit - db might be locked by different process
    for x in range(0, 10):
        try:
            conn.commit()
        except:
41
            print("Sqlite3 commit unsuccessful, retrying....")
Antonin Dvorak's avatar
Antonin Dvorak committed
42
43
            time.sleep(1)
            pass
44
45
        else:
            print("Sqlite3 commit successful, breaking the retry cycle.")
Antonin Dvorak's avatar
Antonin Dvorak committed
46
            break