-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathmodels.py
More file actions
193 lines (144 loc) · 5.68 KB
/
models.py
File metadata and controls
193 lines (144 loc) · 5.68 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
from __future__ import annotations
from datetime import datetime
from typing import Dict, Any
from sqlalchemy import (DDL, Boolean, Column, DateTime, ForeignKey, Index,
Integer, String, event, UniqueConstraint)
from sqlalchemy.dialects.postgresql import TSVECTOR
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import relationship, Session
from app.config import PSQL_ENVIRONMENT
from app.database.database import Base
from app.dependencies import logger
class UserEvent(Base):
__tablename__ = "user_event"
id = Column(Integer, primary_key=True, index=True)
user_id = Column('user_id', Integer, ForeignKey('users.id'))
event_id = Column('event_id', Integer, ForeignKey('events.id'))
events = relationship("Event", back_populates="participants")
participants = relationship("User", back_populates="events")
def __repr__(self):
return f'<UserEvent ({self.participants}, {self.events})>'
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, nullable=False)
email = Column(String, unique=True, nullable=False)
password = Column(String, nullable=False)
full_name = Column(String)
language = Column(String)
description = Column(String, default="Happy new user!")
avatar = Column(String, default="profile.png")
telegram_id = Column(String, unique=True)
is_active = Column(Boolean, default=False)
events = relationship("UserEvent", back_populates="participants")
weekly_tasks = relationship(
"WeeklyTask", cascade="all, delete", back_populates="owner")
tasks = relationship(
"Task", cascade="all, delete", back_populates="owner")
def __repr__(self):
return f'<User {self.id}>'
class Event(Base):
__tablename__ = "events"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=False)
start = Column(DateTime, nullable=False)
end = Column(DateTime, nullable=False)
content = Column(String)
location = Column(String)
color = Column(String, nullable=True)
owner_id = Column(Integer, ForeignKey("users.id"))
category_id = Column(Integer, ForeignKey("categories.id"))
owner = relationship("User")
participants = relationship("UserEvent", back_populates="events")
# PostgreSQL
if PSQL_ENVIRONMENT:
events_tsv = Column(TSVECTOR)
__table_args__ = (Index(
'events_tsv_idx',
'events_tsv',
postgresql_using='gin'),
)
def __repr__(self):
return f'<Event {self.id}>'
class Category(Base):
__tablename__ = "categories"
__table_args__ = (
UniqueConstraint('user_id', 'name', 'color'),
)
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
color = Column(String, nullable=False)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
@staticmethod
def create(db_session: Session, name: str, color: str,
user_id: int) -> Category:
try:
category = Category(name=name, color=color, user_id=user_id)
db_session.add(category)
db_session.flush()
db_session.commit()
db_session.refresh(category)
except (SQLAlchemyError, IntegrityError) as e:
logger.error(f"Failed to create category: {e}")
raise e
else:
return category
def to_dict(self) -> Dict[str, Any]:
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
def __repr__(self) -> str:
return f'<Category {self.id} {self.name} {self.color}>'
class PSQLEnvironmentError(Exception):
pass
# PostgreSQL
if PSQL_ENVIRONMENT:
trigger_snippet = DDL("""
CREATE TRIGGER ix_events_tsv_update BEFORE INSERT OR UPDATE
ON events
FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(events_tsv,'pg_catalog.english','title','content')
""")
event.listen(
Event.__table__,
'after_create',
trigger_snippet.execute_if(dialect='postgresql')
)
class Invitation(Base):
__tablename__ = "invitations"
id = Column(Integer, primary_key=True, index=True)
status = Column(String, nullable=False, default="unread")
recipient_id = Column(Integer, ForeignKey("users.id"))
event_id = Column(Integer, ForeignKey("events.id"))
creation = Column(DateTime, default=datetime.now)
recipient = relationship("User")
event = relationship("Event")
def __repr__(self):
return (
f'<Invitation '
f'({self.event.owner}'
f'to {self.recipient})>'
)
class Task(Base):
__tablename__ = "tasks"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
content = Column(String)
is_done = Column(Boolean, nullable=False)
is_important = Column(Boolean, nullable=False)
date_time = Column(DateTime, nullable=False)
owner_id = Column(Integer, ForeignKey("users.id"))
owner = relationship("User", back_populates="tasks")
class WeeklyTask(Base):
__tablename__ = "weekly_task"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
days = Column(String, nullable=False)
content = Column(String)
is_important = Column(Boolean, nullable=False)
the_time = Column(String, nullable=False)
owner_id = Column(Integer, ForeignKey("users.id"))
owner = relationship("User", back_populates="weekly_tasks")
class Quote(Base):
__tablename__ = "quotes"
id = Column(Integer, primary_key=True, index=True)
text = Column(String, nullable=False)
author = Column(String)