-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
26 lines (22 loc) · 1008 Bytes
/
Copy pathdatabase.py
File metadata and controls
26 lines (22 loc) · 1008 Bytes
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
from models import conn, cursor
from schemas import ExpenseCreate, ExpenseOut
def create_expense(expense: ExpenseCreate) -> ExpenseOut:
cursor.execute(
"INSERT INTO expenses (amount, category, note, date) VALUES (?, ?, ?, ?)",
(expense.amount, expense.category, expense.note, expense.date)
)
conn.commit()
id = cursor.lastrowid
return ExpenseOut(id=id, **expense.dict())
def get_all_expenses():
cursor.execute("SELECT * FROM expenses")
rows = cursor.fetchall()
return [ExpenseOut(id=row[0], amount=row[1], category=row[2], note=row[3], date=row[4]) for row in rows]
def get_expenses_by_category(category):
cursor.execute("SELECT * FROM expenses WHERE category = ?", (category,))
rows = cursor.fetchall()
return [ExpenseOut(id=row[0], amount=row[1], category=row[2], note=row[3], date=row[4]) for row in rows]
def get_total_expense():
cursor.execute("SELECT SUM(amount) FROM expenses")
total = cursor.fetchone()[0]
return total or 0