forked from renceInbox/fastapi-todo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
73 lines (50 loc) · 1.69 KB
/
database.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
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from typing import Optional
engine = create_engine("sqlite:///app.db")
def get_db():
return Session(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class ToDo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
content = Column(String)
session_key = Column(String)
def __str__(self):
return self.content
def __repr__(self):
return f"ToDo(id={self.id}, content={self.content})"
Base.metadata.create_all(bind=engine)
def create_todo(db: Session, content: str, session_key: str):
todo = ToDo(content=content, session_key=session_key)
db.add(todo)
db.commit()
db.refresh(todo)
return todo
def get_todo(db: Session, item_id: int):
return db.query(ToDo).filter(ToDo.id == item_id).first()
def update_todo(db: Session, item_id: int, content: str):
todo = get_todo(db, item_id)
todo.content = content # type: ignore
db.commit()
db.refresh(todo)
return todo
def get_todos(db: Session, session_key: str, skip: int = 0, limit: int = 100):
return (
db.query(ToDo)
.filter(ToDo.session_key == session_key)
.offset(skip)
.limit(limit)
.all()
)
def delete_todo(db: Session, item_id: int):
todo = get_todo(db, item_id)
db.delete(todo)
db.commit()
def search_todos(db: Session, session_key: str, content: Optional[str] = None):
return (
db.query(ToDo)
.filter(ToDo.content.like(f"%{content}%"), ToDo.session_key == session_key)
.all()
)