-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathestoult.py
executable file
·1239 lines (923 loc) · 33.2 KB
/
estoult.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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import io
from abc import ABC, abstractmethod
from importlib import import_module
from itertools import product
from enum import Enum
from copy import deepcopy
from collections import namedtuple
from contextlib import contextmanager
from typing import Any, Optional, Union, TYPE_CHECKING, Type
try:
import sqlite3
except ImportError:
sqlite3 = None
try:
import psycopg2 # type: ignore
except ImportError:
psycopg2 = None
try:
import MySQLdb as mysql # type: ignore
except ImportError:
mysql = None
try:
from importlib.metadata import version
__version__ = version("estoult")
except ImportError:
__version__ = "0.0.0.dev"
__all__ = [
"Association",
"Field",
"fn",
"MySQLDatabase",
"op",
"PostgreSQLDatabase",
"Schema",
"SQLiteDatabase",
"qf",
"Query",
]
class EstoultError(Exception):
pass
class ClauseError(EstoultError):
pass
class FieldError(EstoultError):
pass
class QueryError(EstoultError):
pass
class DatabaseError(EstoultError):
pass
class AssociationError(EstoultError):
pass
_sql_ops = {
"eq": "=",
"lt": "<",
"le": "<=",
"gt": ">",
"ge": ">=",
"ne": "<>",
"add": "+",
"sub": "-",
"mul": "*",
"truediv": "/",
"mod": "%",
}
def _parse_arg(arg):
if isinstance(arg, Clause):
return arg
elif isinstance(arg, Field):
return str(arg), ()
elif isinstance(arg, Query):
return arg._query, arg._params
elif isinstance(arg, list) or isinstance(arg, tuple):
placeholders = ", ".join(["%s"] * len(arg))
return placeholders, tuple(arg)
return "%s", (arg,)
def _parse_args(func):
def wrapper(*args):
return func(*[_parse_arg(a) for a in args])
return wrapper
def _strip(string):
string = string.rstrip(" ,")
if string.endswith(" and"):
string = string[:-3]
return string
def _make_op(operator):
@_parse_args
def wrapper(lhs, rhs):
return Clause(f"({lhs[0]}) {operator} ({rhs[0]})", tuple(lhs[1] + rhs[1]))
return wrapper
def _make_fn(name):
def wrapper(*args):
return Clause(f"{name}({str(', '.join([str(a) for a in args]))})", ())
return wrapper
class ClauseMetaclass(type):
def __new__(cls, clsname, bases, attrs):
# Add op overloading
for name, operator in _sql_ops.items():
attrs[f"__{name}__"] = staticmethod(_make_op(operator))
return super(ClauseMetaclass, cls).__new__(cls, clsname, bases, attrs)
class Clause(namedtuple("Clause", ["clause", "params"]), metaclass=ClauseMetaclass):
def __str__(self):
return self.clause
def __hash__(self):
return hash(str(self))
def __eq__(self, comp):
return str(self) == comp
class OperatorMetaclass(type):
def __new__(cls, clsname, bases, attrs):
for name, operator in _sql_ops.items():
attrs[name] = staticmethod(_make_op(operator))
c = super(OperatorMetaclass, cls).__new__(cls, clsname, bases, attrs)
c.add_op("or_", "or") # type: ignore
c.add_op("and_", "and") # type: ignore
c.add_op("in_", "in") # type: ignore
c.add_op("like", "like") # type: ignore
return c
class op(metaclass=OperatorMetaclass):
@staticmethod
def or_(lhs: Any, rhs: Any) -> Clause: ...
@staticmethod
def and_(lhs: Any, rhs: Any) -> Clause: ...
@staticmethod
def in_(lhs: Any, rhs: Any) -> Clause: ...
@staticmethod
def like(lhs: Any, rhs: Any) -> Clause: ...
@classmethod
def add_op(cls, name: str, op: str) -> None:
"""
Adds an operator to the module.
"""
def func(lhs, rhs):
fn = _make_op(op)
return fn(lhs, rhs)
setattr(cls, name, staticmethod(func))
@staticmethod
@_parse_args
def ilike(lhs, rhs):
# Does a case insensitive `like`. Only postgres has this operator,
# but we can hack it together for the others
if psycopg2:
return Clause(f"({lhs[0]}) ilike ({rhs[0]})", (lhs[1] + rhs[1]))
return Clause(f"lower({lhs[0]}) like lower({rhs[0]})", (lhs[1] + rhs[1]))
@staticmethod
@_parse_args
def not_(arg):
return Clause(f"not ({arg[0]})", (arg[1]))
@staticmethod
@_parse_args
def is_null(arg):
return Clause(f"({arg[0]}) is null", (arg[1]))
@staticmethod
@_parse_args
def not_null(arg):
return Clause(f"({arg[0]}) is not null", (arg[1]))
class FunctionMetaclass(type):
sql_fns = [
"count",
"sum",
"avg",
"ceil",
"distinct",
"concat",
"max",
"min",
]
def __new__(cls, clsname, bases, attrs):
for f in cls.sql_fns:
attrs[f] = staticmethod(_make_fn(f))
return super(FunctionMetaclass, cls).__new__(cls, clsname, bases, attrs)
class fn(metaclass=FunctionMetaclass):
@classmethod
def add_fn(cls, name, sql_fn):
"""
Adds an additional function to the module.
:param name: What the name of the function should be called.
:type name: str
:param sql_fn: The SQL function it is turned into.
:type sql_fn: str
"""
def func(*args):
fn = _make_fn(sql_fn)
return fn(*args)
setattr(cls, name, staticmethod(func))
@staticmethod
def alias(lhs, rhs):
s, p = _parse_arg(lhs)
return Clause(f"{s} as {rhs}", tuple(p))
@staticmethod
def cast(lhs, rhs):
s, p = _parse_arg(lhs)
return Clause(f"cast({s} as {rhs})", tuple(p))
@staticmethod
def wild(schema):
"""
Select a schema with wildcard.
:param schema: The schema.
:type schema: Schema
"""
if schema._allow_wildcard_select is False:
raise QueryError(
"Wildcard selects are disabled for schema: "
f"`{schema.__tablename__}`"
", please specify fields."
)
return Clause(f"{schema.__tablename__}.*", ())
class FieldMetaclass(type):
def __new__(cls, clsname, bases, attrs):
# Add op overloading
for name, operator in _sql_ops.items():
attrs[f"__{name}__"] = _make_op(operator)
return super(FieldMetaclass, cls).__new__(cls, clsname, bases, attrs)
class Field(metaclass=FieldMetaclass):
"""
A schema field, analogous to columns on a table.
:param type: Basic datatype of the field, used to cast values into the database.
:type type: type
:param name: The column name of the field, will default to the variable name of the
field.
:type name: str, optional
:param caster: A specified caster type/function for more extensive casting.
:type caster: callable, optional
:param null: Field allows nulls.
:type null: bool, optional
:param default: Default value.
:type default: optional
:param primary_key: Field is the primary key.
:type primary_key: bool, optional
"""
def __add__(self, other: Any) -> Clause: ...
def __sub__(self, other: Any) -> Clause: ...
def __mul__(self, other: Any) -> Clause: ...
def __truediv__(self, other: Any) -> Clause: ...
def __mod__(self, other: Any) -> Clause: ...
def __eq__(self, other: Any) -> Clause: ... # type: ignore
def __ne__(self, other: Any) -> Clause: ... # type: ignore
def __lt__(self, other: Any) -> Clause: ...
def __le__(self, other: Any) -> Clause: ...
def __gt__(self, other: Any) -> Clause: ...
def __ge__(self, other: Any) -> Clause: ...
def __init__(
self, type, name=None, caster=None, null=True, default=None, primary_key=False
):
self.schema: Optional[Schema] = None
self.type: str = type
self.name: Optional[str] = name
self.caster = caster
self.null = null
self.default = default
self.primary_key = primary_key
@property
def full_name(self):
if self.schema is None:
raise FieldError("Field does not have an associated schema")
if self.name is None:
raise FieldError("Field does not have a name")
return f"{self.schema.__tablename__}.{self.name}"
def __str__(self):
return self.full_name
def __hash__(self):
return hash(str(self))
def __repr__(self):
return (
f"<Field {self.type} name={self.name} caster={self.caster} "
f"null={self.null} default={self.default} "
f"primary_key={self.primary_key}>"
)
class qf(Field):
"""
Query field - an extra user defined field used for queries.
This is mainly needed for referencing aliases.
:param name: The name of the field.
:type name: str
"""
def __init__(self, name):
self.name = name
@property
def full_name(self):
return f"{self.name}"
def __repr__(self):
return f"<qf name={self.name}>"
class _Cardinals(Enum):
ONE_TO_ONE = 1
ONE_TO_MANY = 2
class _Association:
def __init__(self, cardinality, name, schema, owner, field):
self.cardinality = cardinality
self.name = name
self.owner = owner
self.field = field
self._lazy_schema = schema
@property
def schema(self):
if isinstance(self._lazy_schema, str):
[module, cls] = self._lazy_schema.rsplit(".", 1)
try:
self._lazy_schema = getattr(import_module(module), cls)
except (AttributeError, ModuleNotFoundError):
raise AssociationError(f"Could not import schema: {self._lazy_schema}")
return self._lazy_schema
class Association:
"""
One to One/Many associations to help translate between relational data and object
data.
Many to Many is currently not supported because it does not translate well into
an object structure.
"""
@staticmethod
def has_one(schema, on=[]):
return _Association(_Cardinals.ONE_TO_ONE, None, schema, on[0], on[1])
@staticmethod
def has_many(schema, on=[]):
return _Association(_Cardinals.ONE_TO_MANY, None, schema, on[0], on[1])
class SchemaMetaclass(type):
def __new__(cls, clsname, bases, attrs):
# Deepcopy inherited fields
for base in bases:
at = dir(base)
for a in at:
f = getattr(base, a)
if isinstance(f, Field):
attrs[a] = deepcopy(f)
c = super(SchemaMetaclass, cls).__new__(cls, clsname, bases, attrs)
for key in dir(c):
f = getattr(c, key)
if isinstance(f, Field):
# Reference schema in fields
f.schema = c # type: ignore
# Set name to var reference
if f.name is None:
f.name = key
if isinstance(f, _Association):
f.name = key
return c
@property
def fields(cls):
return [
getattr(cls, key)
for key in dir(cls)
if isinstance(getattr(cls, key), Field)
]
@property
def associations(cls):
return [
getattr(cls, key)
for key in dir(cls)
if isinstance(getattr(cls, key), _Association)
]
@property
def pk(cls):
pk = None
for field in cls.fields:
if field.primary_key is True:
return field
if field.name == "id":
pk = field
return pk
def __getitem__(cls, item):
return getattr(cls, item)
class Schema(metaclass=SchemaMetaclass):
"""
A schema representation of a database table.
:ivar _allow_wildcard_select: Determines if wildcards can be used when 'selecting'.
"""
_database_: Any = None
__tablename__ = None
_allow_wildcard_select = True
@classmethod
def _cast(cls, updating, row):
# Allow you to use a Field as key
for key, value in list(row.items()):
if isinstance(key, Field):
row[key.name] = value
else:
row[key] = value
changeset = {}
for field in cls.fields:
value = None
try:
# Try to get the value from the row
# In a try/catch so we can tell the difference between
# >>> row["field"] == None # Field is set to `None`
# >>> row.get("field") == None # Field is not set
value = row[field.name]
except KeyError:
if updating is True:
continue
if field.default is None:
continue
# Apply a default if we are inserting
if value is None and updating is False and field.default is not None:
if callable(field.default) is True:
value = field.default()
else:
value = field.default
# Cast the value
if value is not None:
value = (
field.type(value) if field.caster is None else field.caster(value)
)
changeset[field.name] = value
return changeset
@classmethod
def _validate(cls, updating, row):
changeset = {}
for field in cls.fields:
try:
value = row[field.name]
except KeyError:
continue
if field.null is False and value is None and updating is True:
raise FieldError(f"{str(field)} cannot be None")
changeset[field.name] = value
return changeset
@classmethod
def _casval(cls, row, updating):
changeset = cls._cast(updating, row)
changeset = cls._validate(updating, changeset)
# A user specified validation function
validate_func = getattr(cls, "validate", lambda _, x: x)
changeset = validate_func(updating, changeset)
return changeset
@classmethod
def _get_field_by_name(cls, name: Any):
# BIG HACK OH NO
if isinstance(name, Field):
name = name.name
return getattr(cls, name, None)
@classmethod
def _is_association(cls, name):
return isinstance(cls._get_field_by_name(name), _Association)
@classmethod
def _pop_associations(cls, obj):
return {
cls._get_field_by_name(k): obj.pop(k)
for k in [
key for key in obj.keys() if cls._is_association(key) and obj[key]
]
}
@classmethod
def insert(cls, obj):
associations = cls._pop_associations(obj)
changeset = cls._casval(obj, updating=False)
params = list(changeset.values())
fields = ", ".join(changeset.keys())
placeholders = ", ".join(["%s"] * len(changeset))
sql = f"insert into {cls.__tablename__} (%s) values (%s)" % (
fields,
placeholders,
)
if psycopg2 is not None and cls.pk:
sql += f" returning {cls.pk.name}"
pk = cls._database_.insert(_strip(sql), params)
if cls.pk:
changeset[cls.pk.name] = pk
if associations:
changeset_asos = {}
for aso, value in associations.items():
if not isinstance(aso, _Association):
raise AssociationError(f"Expected _Association, got {type(aso)}")
if aso.name is None:
raise AssociationError("Association name cannot be None")
changeset, changeset_asos[aso.name] = _do_association(
changeset, cls, aso, value
)
changeset = {**changeset, **changeset_asos}
return changeset
@classmethod
def update(cls, old, new):
obj = {**old, **new}
associations = cls._pop_associations(obj)
# Pop from old
old_ks = [k for k in old.keys()]
for k in old_ks:
if cls._is_association(k):
old.pop(k, None)
changeset = cls._casval(obj, updating=True)
sql = f"update {cls.__tablename__} set "
params = []
for key, value in changeset.items():
sql += f"{key} = %s, "
params.append(value)
sql = f"{_strip(sql)} where "
for key, value in old.items():
sql += f"{key} = %s and "
params.append(value)
cls._database_.sql(_strip(sql), params)
if associations:
changeset_asos = {}
for aso, value in associations.items():
if not isinstance(aso, _Association):
raise AssociationError(f"Expected _Association, got {type(aso)}")
if aso.name is None:
raise AssociationError("Association name cannot be None")
changeset, changeset_asos[aso.name] = _do_association(
changeset, cls, aso, value
)
changeset = {**changeset, **changeset_asos}
return changeset
@classmethod
def update_by_pk(cls, id, new):
if cls.pk is None:
raise FieldError(f"No primary key defined for {cls.__name__}")
if cls.pk.name is None:
raise FieldError(f"Primary key field has no name in {cls.__name__}")
return cls.update({cls.pk.name: id}, new)
@classmethod
def delete(cls, row):
# Deletes single row - look at `Query` for batch
sql = f"delete from {cls.__tablename__} where "
params = []
for key, value in row.items():
sql += f"{key} = %s and "
params.append(value)
return cls._database_.sql(_strip(sql), params)
@classmethod
def delete_by_pk(cls, id):
if cls.pk is None:
raise FieldError(f"No primary key defined for {cls.__name__}")
if cls.pk.name is None:
raise FieldError(f"Primary key field has no name in {cls.__name__}")
return cls.delete({cls.pk.name: id})
class QueryMetaclass(type):
sql_joins = [
"inner join",
"left join",
"left outer join",
"right join",
"right outer join",
"full join",
"full outer join",
]
@staticmethod
def make_join_fn(join_type):
def join_fn(self, schema, on):
q = f"{str(on[0])} = {str(on[1])}"
self._add_node(f"{join_type} {schema.__tablename__} on {q}", ())
return self
return join_fn
def __new__(cls, clsname, bases, attrs):
for join_type in cls.sql_joins:
attrs[join_type.replace(" ", "_")] = QueryMetaclass.make_join_fn(join_type)
return super(QueryMetaclass, cls).__new__(cls, clsname, bases, attrs)
Node = namedtuple("Node", ["node", "params"])
class Query(metaclass=QueryMetaclass):
def inner_join(self, schema: Type["Schema"], on: list[Any]) -> "Query": ...
def left_join(self, schema: Type["Schema"], on: list[Any]) -> "Query": ...
def left_outer_join(self, schema: Type["Schema"], on: list[Any]) -> "Query": ...
def right_join(self, schema: Type["Schema"], on: list[Any]) -> "Query": ...
def right_outer_join(self, schema: Type["Schema"], on: list[Any]) -> "Query": ...
def full_join(self, schema: Type["Schema"], on: list[Any]) -> "Query": ...
def full_outer_join(self, schema: Type["Schema"], on: list[Any]) -> "Query": ...
def __init__(self, schema):
self.schema = schema
self._method: Optional[str] = None
self._nodes = []
self._preloads = []
def _add_node(self, node, params):
self._nodes.append(Node(_strip(node), params))
@property
def _query(self):
return " ".join([x.node for x in self._nodes])
@property
def _params(self):
return tuple([p for x in self._nodes for p in x.params])
def select(self, *args):
self._method = "select"
query = ""
params = []
if len(args) < 1:
if self.schema._allow_wildcard_select is False:
raise QueryError(
"Wildcard selects are disabled for schema: "
f"`{self.schema.__tablename__}`"
", please specify fields."
)
query += "*"
else:
for arg in args:
if isinstance(arg, Clause):
string, p = arg
query += f"{string}, "
params.extend(p)
else:
query += f"{arg}, "
self._add_node(
f"select {_strip(query)} from {self.schema.__tablename__}", params
)
return self
def update(self, changeset):
self._method = "sql"
changeset = self.schema._casval(changeset, updating=True)
query = ""
params = []
for key, value in changeset.items():
query += f"{key} = %s, "
params.append(value)
self._add_node(f"update {self.schema.__tablename__} set {query}", params)
return self
def delete(self):
self._method = "sql"
self._add_node(f"delete from {self.schema.__tablename__}", ())
return self
def get(self, *args):
self.select(*args)
self._method = "get"
return self
def get_or_none(self, *args):
self.select(*args)
self._method = "get_or_none"
return self
def union(self, schema):
self._add_node("union", ())
self.schema = schema
return self
def where(self, *clauses):
query = ""
params = []
for clause in clauses:
string, p = clause
# We can always add an `and` to the end cus it get stripped off ;)
query += f"{string} and "
params.extend(p)
self._add_node(f"where {query}", params)
return self
def limit(self, *args):
# Example: .limit(1) or limit(1, 2)
if len(args) == 1:
self._add_node("limit %s", args)
elif len(args) == 2:
# `offset` works in mysql and postgres
self._add_node("limit %s offset %s", args)
else:
raise QueryError("`limit` has too many arguments")
return self
def order_by(self, *args):
# Example: .order_by(Frog.id, {Frog.name: "desc"})
query = "order by "
params = []
for a in args:
v = None
if isinstance(a, dict):
k, v = next(iter(a.items()))
if v != "asc" and v != "desc":
raise QueryError("Value must be 'asc' or 'desc'")
else:
k = a
if isinstance(k, Clause):
c, p = _parse_arg(k)
query += "%s " % c
params.extend(p)
elif isinstance(k, Field):
query += f"{k} "
else:
query += "%s "
params.append(str(k))
if v:
query += f"{v}, "
self._add_node(f"{query}", params)
return self
def preload(self, association):
self._preloads.append(association)
return self
def execute(self) -> Any:
if self._method is None:
raise QueryError("No method")
func = getattr(self.schema._database_, self._method)
data = func(self._query, self._params)
if data is None:
return data
for association, row in product(
self._preloads, data if isinstance(data, list) else [data]
):
key, new_row = _do_preload(self.schema._database_, association, row)
row[key] = new_row
return data
def copy(self):
return deepcopy(self)
def __str__(self):
return (
self.schema._database_.mogrify(self._query, self._params)
.decode("utf-8")
.strip()
)
def __repr__(self):
return f'<Query query="{self._query}" params={self._params}>'
def _do_association_update(row, schema, association, obj):
aso_schema = association.schema
pk_name = aso_schema.pk.name
updating = pk_name in obj.keys()
# Make sure association is always linked to our row
obj[association.field] = row.get(association.owner)
if updating is True:
# Update the association
obj = aso_schema.update({pk_name: obj[pk_name]}, obj)
id = obj[pk_name]
# If the schema is not associated with it, do it now
aso_on = row.get(association.owner)
row[association.owner] = id
if id != aso_on:
row = schema.update({schema.pk.name: row[schema.pk.name]}, row)
else:
# Insert the new association
obj = aso_schema.insert(obj)
# Update the previous schema to include the new association
row = schema.update(row, {association.owner: obj[association.field]})
return row, obj
def _do_association(row, schema, association, obj):
if association.cardinality == _Cardinals.ONE_TO_ONE:
return _do_association_update(row, schema, association, obj)
else:
# if association.cardinality == _Cardinals.ONE_TO_MANY:
new_objs = []
for o in obj:
row, new = _do_association_update(row, schema, association, o)
new_objs.append(new)
return row, new_objs
def _do_preload_query(db, cardinality, query, value):
if cardinality == _Cardinals.ONE_TO_ONE:
return db.get_or_none(query, (value,))
elif cardinality == _Cardinals.ONE_TO_MANY:
return db.select(query, (value,))
raise AssociationError("Association has unknown cardinality")
def _do_preload(db, association, row):
# If the association is just an association, then we can preload it without any
# issues
if isinstance(association, _Association):
if association.schema._allow_wildcard_select is False:
raise QueryError(
"Wildcard selects are disabled for schema: "
f"`{association.schema.__tablename__}`"
", please specify fields."
)
query = f"""
select * from {association.schema.__tablename__}
where {association.field} = %s
"""
return association.name, _do_preload_query(
db, association.cardinality, query, row[association.owner]
)
# Otherwise, associations can be dicts or lists and we need to recurse through them
aso, values = list(association.items())[0]
if row.get(aso.owner) is None:
return aso.name, None
associations = [
v for v in values if isinstance(v, _Association) or isinstance(v, dict)
]
fields = [v.name for v in values if isinstance(v, Field) and v.name is not None]
select = ", ".join(fields) if len(fields) > 0 else "*"