-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
63 lines (53 loc) · 2.08 KB
/
model.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
import os
from typing import List, Tuple
import sqlite3
class Model:
def __init__(self):
self.conn = sqlite3.connect(os.path.join("db", "drugs.db"))
self.cursor = self.conn.cursor()
self.check_db_exists()
def insert(self, table: str, columns: List, values: List[Tuple]):
cnt = len(columns)
columns = ', '.join( columns )
placeholders = ", ".join( "?" * cnt)
self.cursor.executemany(
f"INSERT INTO {table} "
f"({columns}) "
f"VALUES ({placeholders})",
values)
self.conn.commit()
def fetchall(self, table: str, columns: List[str]) -> List[Tuple]:
columns_joined = ", ".join(columns)
self.cursor.execute(f"SELECT {columns_joined} FROM {table}")
rows = self.cursor.fetchall()
result = []
for row in rows:
dict_row = {}
for index, column in enumerate(columns):
dict_row[column] = row[index]
result.append(dict_row)
return result
def delete(self, table: str, row_id: int) -> None:
row_id = int(row_id)
self.cursor.execute(f"delete from {table} where id={row_id}")
self.conn.commit()
def clear_table(self, table: str) -> None:
self.cursor.execute(f"delete from {table}")
self.cursor.execute(f"UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='{table}';")
self.conn.commit()
def get_cursor(self):
return self.cursor
def _init_db(self) -> None:
"""Инициализирует БД"""
with open("createdb.sql", "r") as f:
sql = f.read()
self.cursor.executescript(sql)
self.conn.commit()
def check_db_exists(self) -> None:
"""Проверяет, инициализирована ли БД, если нет — инициализирует"""
self.cursor.execute("SELECT name FROM sqlite_master "
"WHERE type='table' AND name='prices'")
table_exists = self.cursor.fetchall()
if table_exists:
return
self._init_db()