forked from alexey-goloburdin/telegram-finance-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
63 lines (47 loc) · 1.58 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
import os
from typing import Dict, List, Tuple
import sqlite3
conn = sqlite3.connect(os.path.join("db", "finance.db"))
cursor = conn.cursor()
def insert(table: str, column_values: Dict):
columns = ', '.join( column_values.keys() )
values = [tuple(column_values.values())]
placeholders = ", ".join( "?" * len(column_values.keys()) )
cursor.executemany(
f"INSERT INTO {table} "
f"({columns}) "
f"VALUES ({placeholders})",
values)
conn.commit()
def fetchall(table: str, columns: List[str]) -> List[Tuple]:
columns_joined = ", ".join(columns)
cursor.execute(f"SELECT {columns_joined} FROM {table}")
rows = 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(table: str, row_id: int) -> None:
row_id = int(row_id)
cursor.execute(f"delete from {table} where id={row_id}")
conn.commit()
def get_cursor():
return cursor
def _init_db():
"""Инициализирует БД"""
with open("createdb.sql", "r") as f:
sql = f.read()
cursor.executescript(sql)
conn.commit()
def check_db_exists():
"""Проверяет, инициализирована ли БД, если нет — инициализирует"""
cursor.execute("SELECT name FROM sqlite_master "
"WHERE type='table' AND name='expense'")
table_exists = cursor.fetchall()
if table_exists:
return
_init_db()
check_db_exists()