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

Antonin Dvorak's avatar
Antonin Dvorak committed
21
22
    with conn:
        c = conn.cursor()
Domenico Giordano's avatar
Domenico Giordano committed
23
        for x in range(1, 11):
24
25
26
27
28
29
            try:
                if args:
                    c.execute(query, args)
                else:
                    c.execute(query)
            except:
Domenico Giordano's avatar
Domenico Giordano committed
30
31
                print("Sqlite3 execute unsuccessful, retrying after %s sec...." %x)
                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

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