-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathmodel.py
222 lines (182 loc) · 7.03 KB
/
model.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
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
""" Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from sqlalchemy import Column, Integer, String, Boolean, LargeBinary, Float, \
Numeric, DateTime, Date, FetchedValue, ForeignKey, ColumnDefault
from sqlalchemy.orm import registry, relationship
from sqlalchemy.dialects.postgresql import JSONB, ARRAY
from datetime import timezone, datetime
mapper_registry = registry()
Base = mapper_registry.generate_base()
def format_timestamp(timestamp: datetime) -> str:
return timestamp.astimezone(timezone.utc).isoformat() if timestamp else None
"""
BaseMixin contains properties that are common to all models in this sample.
The created_at and updated_at properties are automatically filled with the
current client system time when a model is created or updated.
"""
class BaseMixin(object):
__prepare_statements__ = None
version_id = Column(Integer, nullable=False)
created_at = Column(DateTime(timezone=True),
# We need to explicitly format the timestamps with a
# timezone to ensure that SQLAlchemy uses a
# timestamptz instead of just timestamp.
ColumnDefault(datetime.utcnow().astimezone(timezone.utc)))
updated_at = Column(DateTime(timezone=True),
ColumnDefault(
datetime.utcnow().astimezone(timezone.utc),
for_update=True))
__mapper_args__ = {"version_id_col": version_id}
"""
BaseUuidMixin is the base class for all tables that use a client-side
generated UUID as the primary key.
"""
class BaseUuidMixin(BaseMixin):
id = Column(String, primary_key=True)
"""
BaseInt64Mixin is the base class for all tables that use an auto-generated
INT64 as the primary key. The value is generated by a bit-reversed sequence
in the database.
"""
class BaseInt64Mixin(BaseMixin):
id = Column(Integer, primary_key=True)
class Singer(BaseUuidMixin, Base):
__tablename__ = "singers"
first_name = Column(String(100))
last_name = Column(String(200))
full_name = Column(String,
server_default=FetchedValue(),
server_onupdate=FetchedValue())
active = Column(Boolean)
albums = relationship("Album", back_populates="singer")
__mapper_args__ = {
"eager_defaults": True,
"version_id_col": BaseMixin.version_id
}
def __repr__(self):
return (
f"singers("
f"id={self.id!r},"
f"first_name={self.first_name!r},"
f"last_name={self.last_name!r},"
f"active={self.active!r},"
f"created_at={format_timestamp(self.created_at)!r},"
f"updated_at={format_timestamp(self.updated_at)!r}"
f")"
)
class Album(BaseUuidMixin, Base):
__tablename__ = "albums"
title = Column(String(200))
marketing_budget = Column(Numeric)
release_date = Column(Date)
cover_picture = Column(LargeBinary)
singer_id = Column(String, ForeignKey("singers.id"))
singer = relationship("Singer", back_populates="albums")
# The `tracks` relationship uses passive_deletes=True, because `tracks` is
# interleaved in `albums` with `ON DELETE CASCADE`. This prevents SQLAlchemy
# from deleting the related tracks when an album is deleted, and lets the
# database handle it.
tracks = relationship("Track", back_populates="album", passive_deletes=True)
def __repr__(self):
return (
f"albums("
f"id={self.id!r},"
f"title={self.title!r},"
f"marketing_budget={self.marketing_budget!r},"
f"release_date={self.release_date!r},"
f"cover_picture={self.cover_picture!r},"
f"singer={self.singer_id!r},"
f"created_at={format_timestamp(self.created_at)!r},"
f"updated_at={format_timestamp(self.updated_at)!r}"
f")"
)
class Track(BaseUuidMixin, Base):
__tablename__ = "tracks"
id = Column(String, ForeignKey("albums.id"), primary_key=True)
track_number = Column(Integer, primary_key=True)
title = Column(String)
sample_rate = Column(Float)
album = relationship("Album", back_populates="tracks")
def __repr__(self):
return (
f"tracks("
f"id={self.id!r},"
f"track_number={self.track_number!r},"
f"title={self.title!r},"
f"sample_rate={self.sample_rate!r},"
f"created_at={format_timestamp(self.created_at)!r},"
f"updated_at={format_timestamp(self.updated_at)!r}"
f")"
)
class Venue(BaseUuidMixin, Base):
__tablename__ = "venues"
name = Column(String(200))
description = Column(JSONB)
def __repr__(self):
return (
f"venues("
f"id={self.id!r},"
f"name={self.name!r},"
f"description={self.description!r},"
f"created_at={format_timestamp(self.created_at)!r},"
f"updated_at={format_timestamp(self.updated_at)!r}"
f")"
)
class Concert(BaseUuidMixin, Base):
__tablename__ = "concerts"
name = Column(String(200))
venue_id = Column(String, ForeignKey("venues.id"))
venue = relationship("Venue")
singer_id = Column(String, ForeignKey("singers.id"))
singer = relationship("Singer")
start_time = Column(DateTime(timezone=True))
end_time = Column(DateTime(timezone=True))
ticket_sales = relationship("TicketSale", back_populates="concert")
def __repr__(self):
return (
f"concerts("
f"id={self.id!r},"
f"name={self.name!r},"
f"venue={self.venue!r},"
f"singer={self.singer!r},"
f"start_time={self.start_time!r},"
f"end_time={self.end_time!r},"
f"created_at={format_timestamp(self.created_at)!r},"
f"updated_at={format_timestamp(self.updated_at)!r}"
f")"
)
class TicketSale(BaseInt64Mixin, Base):
__tablename__ = "ticket_sales"
concert_id = Column(String, ForeignKey("concerts.id"))
concert = relationship("Concert")
customer_name = Column(String)
price = Column(Numeric)
# "seats" has type text[] in the database. By not specifying any type here,
# we ensure that SQLAlchemy just sends an untyped string value to the
# database. If we were to configure the type to be ARRAY(String) here, then
# we would get an error 'Array casting / coercion is not supported', as
# SQLAlchemy would try to cast the value to a VARCHAR[].
# TODO: Use this mapping when array casting/coercion is supported.
# seats = Column(ARRAY(String))
seats = Column()
def __repr__(self):
return (
f"ticket_sales("
f"id={self.id!r},"
f"concert={self.concert!r},"
f"customer_name={self.customer_name!r},"
f"price={self.price!r},"
f"seats={self.seats!r},"
f"created_at={format_timestamp(self.created_at)!r},"
f"updated_at={format_timestamp(self.updated_at)!r}"
f")"
)