sqlite3_backend.py 1.69 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

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
13
    query: sql
Antonin Dvorak's avatar
Antonin Dvorak committed
14
15
16
17
        query to run
    args: array
        additional arguments for execute query, optional
    """
18
    upperbound = 11
19

20
    c = conn.cursor()
21
22
    # retry db execute
    for x in range(1, upperbound):
23
24
        try:
            if args:
25
                c.execute(query, *args)
26
            else:
27
                c.execute(query)
28
29
        except Exception as e:
            print("Sqlite3 execute unsuccessful, reason: \"%s\" \nRetrying after %s sec...." % (str(e), x))
30
31
32
33
34
            time.sleep(x)
            pass
        else:
            print("Sqlite3 execute successful, breaking the retry cycle.")
            break
35
36
37
        # max attempts achieved, quit
        if x == upperbound - 1:
            raise Exception("Sqlite3 - achieved max retries to execute with no success, giving up...")
Antonin Dvorak's avatar
Antonin Dvorak committed
38

39
40
    # retry db commit
    for x in range(1, upperbound):
Antonin Dvorak's avatar
Antonin Dvorak committed
41
42
        try:
            conn.commit()
43
44
        except Exception as e:
            print("Sqlite3 commit unsuccessful, reason: \"%s\" \nRetrying after %s sec...." % (str(e), x))
Domenico Giordano's avatar
Domenico Giordano committed
45
            time.sleep(x)
Antonin Dvorak's avatar
Antonin Dvorak committed
46
            pass
47
48
        else:
            print("Sqlite3 commit successful, breaking the retry cycle.")
Antonin Dvorak's avatar
Antonin Dvorak committed
49
            break
50
51
52
        # max attempts achieved, quit            
        if x == upperbound - 1:
            raise Exception("Sqlite3 - achieved max retries to commit with no success, giving up...")