-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathmodels.py
485 lines (352 loc) · 12.3 KB
/
models.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
from __future__ import absolute_import
import datetime
import enum
import uuid
from decimal import Decimal
from typing import List, Optional
# fmt: off
from sqlalchemy import (
Column,
Date,
Enum,
ForeignKey,
Integer,
Numeric,
String,
Table,
func,
)
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref, column_property, composite, mapper, relationship
from sqlalchemy.sql.type_api import TypeEngine
from graphene_sqlalchemy.tests.utils import wrap_select_func
from graphene_sqlalchemy.utils import (
SQL_VERSION_HIGHER_EQUAL_THAN_1_4,
SQL_VERSION_HIGHER_EQUAL_THAN_2,
)
# fmt: off
if SQL_VERSION_HIGHER_EQUAL_THAN_2:
from sqlalchemy.sql.sqltypes import HasExpressionLookup # noqa # isort:skip
else:
from sqlalchemy.sql.sqltypes import _LookupExpressionAdapter as HasExpressionLookup # noqa # isort:skip
# fmt: on
PetKind = Enum("cat", "dog", name="pet_kind")
class HairKind(enum.Enum):
LONG = "long"
SHORT = "short"
Base = declarative_base()
association_table = Table(
"association",
Base.metadata,
Column("pet_id", Integer, ForeignKey("pets.id")),
Column("reporter_id", Integer, ForeignKey("reporters.id")),
)
class Editor(Base):
__tablename__ = "editors"
editor_id = Column(Integer(), primary_key=True)
name = Column(String(100))
class Pet(Base):
__tablename__ = "pets"
id = Column(Integer(), primary_key=True)
name = Column(String(30))
pet_kind = Column(PetKind, nullable=False)
hair_kind = Column(Enum(HairKind, name="hair_kind"), nullable=False)
reporter_id = Column(Integer(), ForeignKey("reporters.id"))
legs = Column(Integer(), default=4)
class CompositeFullName(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def __composite_values__(self):
return self.first_name, self.last_name
def __repr__(self):
return "{} {}".format(self.first_name, self.last_name)
class ProxiedReporter(Base):
__tablename__ = "reporters_error"
id = Column(Integer(), primary_key=True)
first_name = Column(String(30), doc="First name")
last_name = Column(String(30), doc="Last name")
reporter_id = Column(Integer(), ForeignKey("reporters.id"))
reporter = relationship("Reporter", uselist=False)
# This is a hybrid property, we don't support proxies on hybrids yet
composite_prop = association_proxy("reporter", "composite_prop")
class Reporter(Base):
__tablename__ = "reporters"
id = Column(Integer(), primary_key=True)
first_name = Column(String(30), doc="First name")
last_name = Column(String(30), doc="Last name")
email = Column(String(), doc="Email")
favorite_pet_kind = Column(PetKind)
pets = relationship(
"Pet",
secondary=association_table,
backref="reporters",
order_by="Pet.id",
lazy="selectin",
)
articles = relationship(
"Article", backref=backref("reporter", lazy="selectin"), lazy="selectin"
)
favorite_article = relationship("Article", uselist=False, lazy="selectin")
@hybrid_property
def hybrid_prop_with_doc(self) -> str:
"""Docstring test"""
return self.first_name
@hybrid_property
def hybrid_prop(self) -> str:
return self.first_name
@hybrid_property
def hybrid_prop_str(self) -> str:
return self.first_name
@hybrid_property
def hybrid_prop_int(self) -> int:
return 42
@hybrid_property
def hybrid_prop_float(self) -> float:
return 42.3
@hybrid_property
def hybrid_prop_bool(self) -> bool:
return True
@hybrid_property
def hybrid_prop_list(self) -> List[int]:
return [1, 2, 3]
column_prop = column_property(
wrap_select_func(func.cast(func.count(id), Integer)), doc="Column property"
)
composite_prop = composite(
CompositeFullName, first_name, last_name, doc="Composite"
)
headlines = association_proxy("articles", "headline")
articles_tags_table = Table(
"articles_tags",
Base.metadata,
Column("article_id", ForeignKey("articles.id")),
Column("tag_id", ForeignKey("tags.id")),
)
class Image(Base):
__tablename__ = "images"
id = Column(Integer(), primary_key=True)
external_id = Column(Integer())
description = Column(String(30))
class Tag(Base):
__tablename__ = "tags"
id = Column(Integer(), primary_key=True)
name = Column(String(30))
class Article(Base):
__tablename__ = "articles"
id = Column(Integer(), primary_key=True)
headline = Column(String(100))
pub_date = Column(Date())
reporter_id = Column(Integer(), ForeignKey("reporters.id"))
readers = relationship(
"Reader", secondary="articles_readers", back_populates="articles"
)
recommended_reads = association_proxy("reporter", "articles")
# one-to-one relationship with image
image_id = Column(Integer(), ForeignKey("images.id"), unique=True)
image = relationship("Image", backref=backref("articles", uselist=False))
# many-to-many relationship with tags
tags = relationship("Tag", secondary=articles_tags_table, backref="articles")
class Reader(Base):
__tablename__ = "readers"
id = Column(Integer(), primary_key=True)
name = Column(String(100))
articles = relationship(
"Article", secondary="articles_readers", back_populates="readers"
)
class ArticleReader(Base):
__tablename__ = "articles_readers"
article_id = Column(Integer(), ForeignKey("articles.id"), primary_key=True)
reader_id = Column(Integer(), ForeignKey("readers.id"), primary_key=True)
class ReflectedEditor(type):
"""Same as Editor, but using reflected table."""
@classmethod
def __subclasses__(cls):
return []
editor_table = Table("editors", Base.metadata, autoload=True)
# TODO Remove when switching min sqlalchemy version to SQLAlchemy 1.4
if SQL_VERSION_HIGHER_EQUAL_THAN_1_4:
Base.registry.map_imperatively(ReflectedEditor, editor_table)
else:
mapper(ReflectedEditor, editor_table)
############################################
# The models below are mainly used in the
# @hybrid_property type inference scenarios
############################################
class ShoppingCartItem(Base):
__tablename__ = "shopping_cart_items"
id = Column(Integer(), primary_key=True)
@hybrid_property
def hybrid_prop_shopping_cart(self) -> List["ShoppingCart"]:
return [ShoppingCart(id=1)]
class ShoppingCart(Base):
__tablename__ = "shopping_carts"
id = Column(Integer(), primary_key=True)
# Standard Library types
@hybrid_property
def hybrid_prop_str(self) -> str:
return self.first_name
@hybrid_property
def hybrid_prop_int(self) -> int:
return 42
@hybrid_property
def hybrid_prop_float(self) -> float:
return 42.3
@hybrid_property
def hybrid_prop_bool(self) -> bool:
return True
@hybrid_property
def hybrid_prop_decimal(self) -> Decimal:
return Decimal("3.14")
@hybrid_property
def hybrid_prop_date(self) -> datetime.date:
return datetime.datetime.now().date()
@hybrid_property
def hybrid_prop_time(self) -> datetime.time:
return datetime.datetime.now().time()
@hybrid_property
def hybrid_prop_datetime(self) -> datetime.datetime:
return datetime.datetime.now()
# Lists and Nested Lists
@hybrid_property
def hybrid_prop_list_int(self) -> List[int]:
return [1, 2, 3]
@hybrid_property
def hybrid_prop_list_date(self) -> List[datetime.date]:
return [self.hybrid_prop_date, self.hybrid_prop_date, self.hybrid_prop_date]
@hybrid_property
def hybrid_prop_nested_list_int(self) -> List[List[int]]:
return [
self.hybrid_prop_list_int,
]
@hybrid_property
def hybrid_prop_deeply_nested_list_int(self) -> List[List[List[int]]]:
return [
[
self.hybrid_prop_list_int,
],
]
# Other SQLAlchemy Instance
@hybrid_property
def hybrid_prop_first_shopping_cart_item(self) -> ShoppingCartItem:
return ShoppingCartItem(id=1)
# Other SQLAlchemy Instance with expression
@hybrid_property
def hybrid_prop_first_shopping_cart_item_expression(self) -> ShoppingCartItem:
return ShoppingCartItem(id=1)
@hybrid_prop_first_shopping_cart_item_expression.expression
def hybrid_prop_first_shopping_cart_item_expression(cls):
return ShoppingCartItem
# Other SQLAlchemy Instances
@hybrid_property
def hybrid_prop_shopping_cart_item_list(self) -> List[ShoppingCartItem]:
return [ShoppingCartItem(id=1), ShoppingCartItem(id=2)]
# Self-references
@hybrid_property
def hybrid_prop_self_referential(self) -> "ShoppingCart":
return ShoppingCart(id=1)
@hybrid_property
def hybrid_prop_self_referential_list(self) -> List["ShoppingCart"]:
return [ShoppingCart(id=1)]
# Optional[T]
@hybrid_property
def hybrid_prop_optional_self_referential(self) -> Optional["ShoppingCart"]:
return None
# UUIDS
@hybrid_property
def hybrid_prop_uuid(self) -> uuid.UUID:
return uuid.uuid4()
@hybrid_property
def hybrid_prop_uuid_list(self) -> List[uuid.UUID]:
return [
uuid.uuid4(),
]
@hybrid_property
def hybrid_prop_optional_uuid(self) -> Optional[uuid.UUID]:
return None
class KeyedModel(Base):
__tablename__ = "test330"
id = Column(Integer(), primary_key=True)
reporter_number = Column("% reporter_number", Numeric, key="reporter_number")
############################################
# For interfaces
############################################
class Person(Base):
id = Column(Integer(), primary_key=True)
type = Column(String())
name = Column(String())
birth_date = Column(Date())
__tablename__ = "person"
__mapper_args__ = {
"polymorphic_on": type,
"with_polymorphic": "*", # needed for eager loading in async session
}
class NonAbstractPerson(Base):
id = Column(Integer(), primary_key=True)
type = Column(String())
name = Column(String())
birth_date = Column(Date())
__tablename__ = "non_abstract_person"
__mapper_args__ = {
"polymorphic_on": type,
"polymorphic_identity": "person",
}
class Employee(Person):
hire_date = Column(Date())
__mapper_args__ = {
"polymorphic_identity": "employee",
}
class Owner(Base):
id = Column(Integer(), primary_key=True)
name = Column(String())
accounts = relationship(lambda: Account, back_populates="owner", lazy="selectin")
__tablename__ = "owner"
class Account(Base):
id = Column(Integer(), primary_key=True)
type = Column(String())
owner_id = Column(Integer(), ForeignKey(Owner.__table__.c.id))
owner = relationship(Owner, back_populates="accounts")
balance = Column(Integer())
__tablename__ = "account"
__mapper_args__ = {
"polymorphic_on": type,
}
class CurrentAccount(Account):
overdraft = Column(Integer())
__mapper_args__ = {
"polymorphic_identity": "current",
}
class SavingsAccount(Account):
interest_rate = Column(Integer())
__mapper_args__ = {
"polymorphic_identity": "savings",
}
############################################
# Custom Test Models
############################################
class CustomIntegerColumn(HasExpressionLookup, TypeEngine):
"""
Custom Column Type that our converters don't recognize
Adapted from sqlalchemy.Integer
"""
"""A type for ``int`` integers."""
__visit_name__ = "integer"
def get_dbapi_type(self, dbapi):
return dbapi.NUMBER
@property
def python_type(self):
return int
def literal_processor(self, dialect):
def process(value):
return str(int(value))
return process
class CustomColumnModel(Base):
__tablename__ = "customcolumnmodel"
id = Column(Integer(), primary_key=True)
custom_col = Column(CustomIntegerColumn)
class CompositePrimaryKeyTestModel(Base):
__tablename__ = "compositekeytestmodel"
first_name = Column(String(30), primary_key=True)
last_name = Column(String(30), primary_key=True)