-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
69 lines (52 loc) · 2.59 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
import sqlalchemy.exc
from sqlalchemy import create_engine, Column, Integer, String, Table, ForeignKey
from sqlalchemy.orm import declarative_base, sessionmaker, relationship, backref
Base = declarative_base()
engine = create_engine('sqlite:///test.sqlite3?check_same_thread=False',
echo=True) # TODO Что то придумать с проверкой потока для планировщика задач
course_tag = Table('course_tag', Base.metadata,
Column('user_id', Integer, ForeignKey('user.id'), primary_key=True),
Column('course_id', Integer, ForeignKey('course.id'), primary_key=True))
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
telegram_id = Column(Integer)
courses = relationship('Course', secondary=course_tag, backref=backref('course_tag'))
notification_mode = Column(Integer, default=1) # 0 - all notifications, 1 - important, 2 - very important
class Course(Base):
__tablename__ = 'course'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
description = Column(String)
user_id = Column(Integer, ForeignKey('user.id'))
user = relationship('User')
def get_course_by_name(session, name):
return session.query(Course).filter_by(name=name).first()
def get_all_courses(session=None):
if session is None:
session = sessionmaker(bind=engine)()
return session.query(Course).all()
def get_or_create(session=None, model=None, commit=True, create=True, **kwargs):
"""Получить модель model через сессию session. Если модель не найдена и указан флаг create, то создать ее и
вернуть ее. Если commit за обновить базу. """
if session is None:
session = sessionmaker(bind=engine)()
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance
elif create:
instance = model(**kwargs)
session.add(instance)
if commit:
session.commit()
return instance
raise sqlalchemy.exc.NoResultFound()
def get_courses_user_queued(session=None, telegram_id=None):
if session is None:
session = sessionmaker(bind=engine)()
if telegram_id is not None:
return session.query(Course).join(User).filter(User.telegram_id == telegram_id).all()
Base.metadata.create_all(engine)
if __name__ == "__main__":
for i in range(20):
course = get_or_create(model=Course, name=f'Test course {i}', description=f'Course description {i}')