-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
108 lines (92 loc) · 2.84 KB
/
db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import logging
from collections.abc import Iterable
from sqlite3 import (
connect,
Connection,
Error,
Row
)
log = logging.getLogger(__name__)
def create_connection(
db_file: str = "db.sqlite3"
) -> Connection | None: # Instead of Optional
try:
conn = connect(db_file)
conn.row_factory = Row
return conn
except Error as SqliteErr:
log.error(
f"Can not connect to {db_file}. {SqliteErr}"
)
return None
def insert_data(
conn: Connection,
table_name: str,
query: dict[str, tuple | list],
) -> None:
try:
cur = conn.cursor()
columns_str = ', '.join(query.keys())
placeholders = ', '.join(['?' for _ in range(len(query.keys()))])
query_string = f"INSERT OR IGNORE INTO {table_name} ({columns_str}) VALUES ({placeholders})"
cur.execute(query_string, list(query.values()))
conn.commit()
except Error as SqliteErr:
log.error(
f"Can not insert to table {table_name}. {SqliteErr}"
)
def update_data_by_id(
conn: Connection,
table_name: str,
query: dict[str, tuple | list],
row_id: int | str
) -> None:
try:
cur = conn.cursor()
set_values = ', '.join([f"{col} = ?" for col in query.keys()])
values = (*query.values(), row_id)
query_string = f"UPDATE {table_name} SET {set_values} WHERE id = ?"
cur.execute(query_string, values)
conn.commit()
except Error as SqliteErr:
log.error(
f"Can not update data in table {table_name} by {row_id}. {SqliteErr}"
)
def find_id_by_params(
conn: Connection,
table_name: str,
search_query: dict[str, tuple | list],
) -> int | None:
try:
cur = conn.cursor()
search_conditions = ' AND '.join([f"{col} = ?" for col in search_query.keys()])
query = f"SELECT id FROM {table_name} WHERE {search_conditions}"
cur.execute(query, list(search_query.values()))
row = cur.fetchone()
return row['id'] if row else None
except Error as SqliteErr:
log.error(
f"Can not find data in table {table_name}"\
f"by values {search_query.values()}. {SqliteErr}"
)
def execute_query(
conn: Connection,
query: str,
values: tuple = (),
is_return: bool = True,
is_one: bool = False
) -> None:
try:
cur = conn.cursor()
if is_return:
executed = cur.execute(query, values)
table_values = executed.fetchone() if is_one else executed.fetchall()
return table_values
else:
cur.execute(query, values)
conn.commit()
return
except Error as SqliteErr:
log.error(
f"Can not execute query {query}. {SqliteErr}"
)