sqlite3_backend.py 1.78 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
    """
Antonin Dvorak's avatar
Antonin Dvorak committed
18
    upperbound = 11
19

Antonin Dvorak's avatar
Antonin Dvorak committed
20
21
    with conn:
        c = conn.cursor()
Antonin Dvorak's avatar
Antonin Dvorak committed
22
23
        # retry db execute
        for x in range(1, upperbound):
24
25
            try:
                if args:
Antonin Dvorak's avatar
Antonin Dvorak committed
26
                    c.execute(query, *args)
27
28
                else:
                    c.execute(query)
Antonin Dvorak's avatar
Antonin Dvorak committed
29
30
            except Exception as e:
                print("Sqlite3 execute unsuccessful, reason: \"%s\" \nRetrying after %s sec...." % (str(e), x))
Domenico Giordano's avatar
Domenico Giordano committed
31
                time.sleep(x)
32
33
34
35
                pass
            else:
                print("Sqlite3 execute successful, breaking the retry cycle.")
                break
Antonin Dvorak's avatar
Antonin Dvorak committed
36
37
38
            # 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
39

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