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

    with conn.cursor() as c:
Domenico Giordano's avatar
Domenico Giordano committed
22
        for x in range(1, 11):
23
24
25
26
27
28
            try:
                if args:
                    c.execute(query, args)
                else:
                    c.execute(query)
            except:
Domenico Giordano's avatar
Domenico Giordano committed
29
30
                print("Sqlite3 execute unsuccessful, retrying after %s sec...." %x)
                time.sleep(x)
31
32
33
34
                pass
            else:
                print("Sqlite3 execute successful, breaking the retry cycle.")
                break
Antonin Dvorak's avatar
Antonin Dvorak committed
35
36

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