forked from geldata/gel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelta.py
4414 lines (3742 loc) · 142 KB
/
delta.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
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# 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 __future__ import annotations
from typing import *
from typing import overload
import collections
import collections.abc
import contextlib
import functools
import itertools
import uuid
from edb import errors
from edb.common import adapter
from edb.common import checked
from edb.common import markup
from edb.common import ordered
from edb.common import parsing
from edb.common import struct
from edb.common import topological
from edb.common import typing_inspect
from edb.common import verutils
from edb.edgeql import ast as qlast
from edb.edgeql import compiler as qlcompiler
from . import expr as s_expr
from . import name as sn
from . import objects as so
from . import schema as s_schema
from . import utils
def delta_objects(
old_in: Iterable[so.Object_T],
new_in: Iterable[so.Object_T],
sclass: Type[so.Object_T],
*,
parent_confidence: Optional[float] = None,
context: so.ComparisonContext,
old_schema: s_schema.Schema,
new_schema: s_schema.Schema,
) -> DeltaRoot:
delta = DeltaRoot()
# TODO: Previously, we attempted to do an optimization based on
# computing a hash_criteria of each object, in order to discard
# unchanged objects. Because hash_criteria returns values that
# include schema objects, the optimization didn't work; it wasn't
# cheap, so I removed it. But the general idea is sound and should
# be revisited.
old = {o.get_name(old_schema): o for o in old_in}
new = {o.get_name(new_schema): o for o in new_in}
# If an object exists with the same name in both the old and the
# new schemas, we don't compare those objects to anything but
# each other. This makes our runtime linear in most common cases,
# though the worst case remains quadratic.
#
# This unfortunately means that we have trouble understanding
# "chain renames" (Foo -> Bar, Bar -> Baz), which may be worth
# addressing in the future, but we fail to understand that for
# other reasons also.
# Collect all the pairs of objects with the same name in both schemas.
pairs = [
(new[k], o) for k, o in old.items() if k in new
]
# Then collect the cross product of all the other objects.
pairs.extend(
itertools.product(
[o for k, o in new.items() if k not in old],
[o for k, o in old.items() if k not in new],
)
)
full_matrix: List[Tuple[so.Object_T, so.Object_T, float]] = []
# If there are any renames that are already decided on, honor those first
renames_x: Set[sn.Name] = set()
renames_y: Set[sn.Name] = set()
for y in old.values():
rename = context.renames.get((type(y), y.get_name(old_schema)))
if rename:
renames_x.add(rename.new_name)
renames_y.add(rename.classname)
if context.guidance is not None:
guidance = context.guidance
# In these functions, we need to look at the actual object to
# figure out the type instead of just using sclass because
# sclass might be an abstract parent like Pointer.
def can_create(obj: so.Object_T, name: sn.Name) -> bool:
return (type(obj), name) not in guidance.banned_creations
def can_alter(
obj: so.Object_T, old_name: sn.Name, new_name: sn.Name
) -> bool:
return (
(type(obj), (old_name, new_name))
not in guidance.banned_alters)
def can_delete(obj: so.Object_T, name: sn.Name) -> bool:
return (type(obj), name) not in guidance.banned_deletions
else:
def can_create(obj: so.Object_T, name: sn.Name) -> bool:
return True
def can_alter(
obj: so.Object_T, old_name: sn.Name, new_name: sn.Name
) -> bool:
return True
def can_delete(obj: so.Object_T, name: sn.Name) -> bool:
return True
for x, y in pairs:
x_name = x.get_name(new_schema)
y_name = y.get_name(old_schema)
similarity = y.compare(
x,
our_schema=old_schema,
their_schema=new_schema,
context=context,
)
# If similarity for an alter is 1.0, that means there is no
# actual change. We keep that, since otherwise we will generate
# extra drop/create pairs when we are already done.
if similarity < 1.0 and not can_alter(y, y_name, x_name):
similarity = 0.0
full_matrix.append((x, y, similarity))
full_matrix.sort(
key=lambda v: (
1.0 - v[2],
str(v[0].get_name(new_schema)),
str(v[1].get_name(old_schema)),
),
)
full_matrix_x = {}
full_matrix_y = {}
seen_x = set()
seen_y = set()
x_alter_variants: Dict[so.Object_T, int] = collections.defaultdict(int)
y_alter_variants: Dict[so.Object_T, int] = collections.defaultdict(int)
comparison_map: Dict[so.Object_T, Tuple[float, so.Object_T]] = {}
comparison_map_y: Dict[so.Object_T, Tuple[float, so.Object_T]] = {}
# Find the top similarity pairs
for x, y, similarity in full_matrix:
if x not in seen_x and y not in seen_y:
comparison_map[x] = (similarity, y)
comparison_map_y[y] = (similarity, x)
seen_x.add(x)
seen_y.add(y)
if x not in full_matrix_x:
full_matrix_x[x] = (similarity, y)
if y not in full_matrix_y:
full_matrix_y[y] = (similarity, x)
if (
can_alter(y, y.get_name(old_schema), x.get_name(new_schema))
and full_matrix_x[x][0] != 1.0
and full_matrix_y[y][0] != 1.0
):
x_alter_variants[x] += 1
y_alter_variants[y] += 1
alters = []
alter_pairs = []
if comparison_map:
if issubclass(sclass, so.InheritingObject):
# Generate the diff from the top of the inheritance
# hierarchy, since changes to parent objects may inform
# how the delta in child objects is treated.
order_x = cast(
Iterable[so.Object_T],
sort_by_inheritance(
new_schema,
cast(Iterable[so.InheritingObject], comparison_map),
),
)
else:
order_x = comparison_map
for x in order_x:
confidence, y = comparison_map[x]
x_name = x.get_name(new_schema)
y_name = y.get_name(old_schema)
already_has = x_name == y_name and x_name not in renames_x
if (
(0.6 < confidence < 1.0 and can_alter(y, y_name, x_name))
or (
(not can_create(x, x_name) or not can_delete(y, y_name))
and can_alter(y, y_name, x_name)
)
or x_name in renames_x
):
alter_pairs.append((x, y))
alter = y.as_alter_delta(
other=x,
context=context,
self_schema=old_schema,
other_schema=new_schema,
confidence=confidence,
)
# If we are basically certain about this alter,
# make the confidence 1.0, unless child steps
# are not confident.
if not (
(x_alter_variants[x] > 1 or (
not already_has and can_create(x, x_name)))
and parent_confidence != 1.0
):
cons = [
sub.get_annotation('confidence')
for sub in alter.get_subcommands(type=ObjectCommand)
]
confidence = min(
[1.0, *[c for c in cons if c is not None]])
alter.set_annotation('confidence', confidence)
alters.append(alter)
elif confidence == 1.0:
alter_pairs.append((x, y))
created = ordered.OrderedSet(new.values()) - {x for x, _ in alter_pairs}
for x in created:
x_name = x.get_name(new_schema)
if can_create(x, x_name) and x_name not in renames_x:
create = x.as_create_delta(schema=new_schema, context=context)
if x_alter_variants[x] > 0 and parent_confidence != 1.0:
confidence = full_matrix_x[x][0]
else:
confidence = 1.0
create.set_annotation('confidence', confidence)
delta.add(create)
delta.update(alters)
deleted_order: Iterable[so.Object_T]
deleted = ordered.OrderedSet(old.values()) - {y for _, y in alter_pairs}
if issubclass(sclass, so.InheritingObject):
deleted_order = sort_by_inheritance( # type: ignore[assignment]
old_schema,
cast(Iterable[so.InheritingObject], deleted),
)
else:
deleted_order = deleted
for y in deleted_order:
y_name = y.get_name(old_schema)
if can_delete(y, y_name) and y_name not in renames_y:
delete = y.as_delete_delta(schema=old_schema, context=context)
if y_alter_variants[y] > 0 and parent_confidence != 1.0:
confidence = full_matrix_y[y][0]
else:
confidence = 1.0
delete.set_annotation('confidence', confidence)
delta.add(delete)
return delta
def sort_by_inheritance(
schema: s_schema.Schema,
objs: Iterable[so.InheritingObjectT],
) -> Tuple[so.InheritingObjectT, ...]:
graph = {}
for x in objs:
graph[x] = topological.DepGraphEntry(
item=x,
deps=ordered.OrderedSet(x.get_ancestors(schema).objects(schema)),
extra=False,
)
return topological.sort(graph, allow_unresolved=True)
T = TypeVar("T")
def sort_by_cross_refs_key(
schema: s_schema.Schema,
objs: Iterable[T], *,
key: Callable[[T], so.Object],
) -> Tuple[T, ...]:
"""Sort an iterable of objects according to cross-references between them.
Return a toplogical ordering of a graph of objects joined by references.
It is assumed that the graph has no cycles.
"""
graph = {}
# We want to report longer cycles before trivial self references,
# since cycles with (for example) computed properties will *also*
# lead to self references (because the computed property gets
# inlined, essentially).
self_ref = None
for entry in objs:
x = key(entry)
referrers = schema.get_referrers(x)
if x in referrers:
self_ref = x
graph[x] = topological.DepGraphEntry(
item=entry,
deps={ref for ref in referrers
if not x.is_parent_ref(schema, ref) and x != ref},
extra=False,
)
res = topological.sort(graph, allow_unresolved=True)
if self_ref:
raise topological.CycleError(
f"{self_ref!r} refers to itself", item=self_ref)
return res
def sort_by_cross_refs(
schema: s_schema.Schema,
objs: Iterable[so.Object_T],
) -> Tuple[so.Object_T, ...]:
return sort_by_cross_refs_key(schema, objs, key=lambda x: x)
CommandMeta_T = TypeVar("CommandMeta_T", bound="CommandMeta")
class CommandMeta(
adapter.Adapter,
struct.MixedStructMeta,
):
_astnode_map: Dict[Type[qlast.DDLOperation], Type[Command]] = {}
def __new__(
mcls: Type[CommandMeta_T],
name: str,
bases: Tuple[type, ...],
dct: Dict[str, Any],
*,
context_class: Optional[Type[CommandContextToken[Command]]] = None,
**kwargs: Any,
) -> CommandMeta_T:
cls = super().__new__(mcls, name, bases, dct, **kwargs)
if context_class is not None:
cast(Command, cls)._context_class = context_class
return cls
def __init__(
cls,
name: str,
bases: Tuple[type, ...],
clsdict: Dict[str, Any],
*,
adapts: Optional[type] = None,
**kwargs: Any,
) -> None:
adapter.Adapter.__init__(cls, name, bases, clsdict, adapts=adapts)
struct.MixedStructMeta.__init__(cls, name, bases, clsdict)
astnodes = clsdict.get('astnode')
if astnodes and not isinstance(astnodes, (list, tuple)):
astnodes = [astnodes]
if astnodes:
cls.register_astnodes(astnodes)
def register_astnodes(
cls,
astnodes: Iterable[Type[qlast.DDLCommand]],
) -> None:
mapping = type(cls)._astnode_map
for astnode in astnodes:
existing = mapping.get(astnode)
if existing:
msg = ('duplicate EdgeQL AST node to command mapping: ' +
'{!r} is already declared for {!r}')
raise TypeError(msg.format(astnode, existing))
mapping[astnode] = cast(Type["Command"], cls)
# We use _DummyObject for contexts where an instance of an object is
# required by type signatures, and the actual reference will be quickly
# replaced by a real object.
_dummy_object = so.Object(
_private_id=uuid.UUID('C0FFEE00-C0DE-0000-0000-000000000000'),
)
Command_T = TypeVar("Command_T", bound="Command")
Command_T_co = TypeVar("Command_T_co", bound="Command", covariant=True)
class Command(
struct.MixedStruct,
markup.MarkupCapableMixin,
metaclass=CommandMeta,
):
source_context = struct.Field(parsing.ParserContext, default=None)
canonical = struct.Field(bool, default=False)
_context_class: Optional[Type[CommandContextToken[Command]]] = None
#: An optional list of commands that are prerequisites of this
#: command and must run before any of the operations in this
#: command or its subcommands in ops or caused_ops.
before_ops: List[Command]
#: An optional list of subcommands that are considered to be
#: integral part of this command.
ops: List[Command]
#: An optional list of commands that are _caused_ by this command,
#: such as any propagation to children or any other side-effects
#: that are not considered integral to this command.
caused_ops: List[Command]
#: AlterObjectProperty lookup table for get|set_attribute_value
_attrs: Dict[str, AlterObjectProperty]
#: AlterSpecialObjectField lookup table
_special_attrs: Dict[str, AlterSpecialObjectField[so.Object]]
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.ops = []
self.before_ops = []
self.caused_ops = []
self.qlast: qlast.DDLOperation
self._attrs = {}
self._special_attrs = {}
def dump(self) -> None:
markup.dump(self)
def copy(self: Command_T) -> Command_T:
result = super().copy()
result.before_ops = [op.copy() for op in self.before_ops]
result.ops = [op.copy() for op in self.ops]
result.caused_ops = [op.copy() for op in self.caused_ops]
return result
def get_verb(self) -> str:
"""Return a verb representing this command in infinitive form."""
raise NotImplementedError
def get_friendly_description(
self,
*,
parent_op: Optional[Command] = None,
schema: Optional[s_schema.Schema] = None,
object: Any = None,
object_desc: Optional[str] = None,
) -> str:
"""Return a friendly description of this command in imperative mood.
The result is used in error messages and other user-facing renderings
of the command.
"""
raise NotImplementedError
@classmethod
def adapt(cls: Type[Command_T], obj: Command) -> Command_T:
result = obj.copy_with_class(cls)
mcls = cast(CommandMeta, type(cls))
for op in obj.get_prerequisites():
result.add_prerequisite(mcls.adapt(op))
for op in obj.get_subcommands(
include_prerequisites=False,
include_caused=False,
):
result.add(mcls.adapt(op))
for op in obj.get_caused():
result.add_caused(mcls.adapt(op))
return result
def is_data_safe(self) -> bool:
return False
def get_required_user_input(self) -> list[dict[str, str]]:
return []
def record_diff_annotations(
self, *,
schema: s_schema.Schema,
orig_schema: Optional[s_schema.Schema],
context: so.ComparisonContext,
orig_object: Optional[so.Object],
object: Optional[so.Object],
) -> None:
"""Record extra information on a delta obtained by diffing schemas.
This provides an apportunity for a delta command to annotate itself
in schema diff schenarios (i.e. migrations).
Args:
schema:
Final schema of a migration.
orig_schema:
Original schema of a migration.
context:
Schema comparison context.
"""
pass
def resolve_obj_collection(
self,
value: Any,
schema: s_schema.Schema,
) -> Sequence[so.Object]:
sequence: Sequence[so.Object]
if isinstance(value, so.ObjectCollection):
sequence = value.objects(schema)
else:
sequence = []
for v in value:
if isinstance(v, so.Shell):
val = v.resolve(schema)
else:
val = v
sequence.append(val)
return sequence
def _resolve_attr_value(
self,
value: Any,
fname: str,
field: so.Field[Any],
schema: s_schema.Schema,
) -> Any:
ftype = field.type
if isinstance(value, so.Shell):
value = value.resolve(schema)
else:
if issubclass(ftype, so.ObjectDict):
if isinstance(value, so.ObjectDict):
items = dict(value.items(schema))
elif isinstance(value, collections.abc.Mapping):
items = {}
for k, v in value.items():
if isinstance(v, so.Shell):
val = v.resolve(schema)
else:
val = v
items[k] = val
value = ftype.create(schema, items)
elif issubclass(ftype, so.ObjectCollection):
sequence = self.resolve_obj_collection(value, schema)
value = ftype.create(schema, sequence)
else:
value = field.coerce_value(schema, value)
return value
def enumerate_attributes(self) -> Tuple[str, ...]:
return tuple(self._attrs)
def _enumerate_attribute_cmds(self) -> Tuple[AlterObjectProperty, ...]:
return tuple(self._attrs.values())
def has_attribute_value(self, attr_name: str) -> bool:
return attr_name in self._attrs or attr_name in self._special_attrs
def _get_simple_attribute_set_cmd(
self,
attr_name: str,
) -> Optional[AlterObjectProperty]:
return self._attrs.get(attr_name)
def _get_attribute_set_cmd(
self,
attr_name: str,
) -> Optional[AlterObjectProperty]:
cmd = self._get_simple_attribute_set_cmd(attr_name)
if cmd is None:
special_cmd = self._special_attrs.get(attr_name)
if special_cmd is not None:
cmd = special_cmd._get_attribute_set_cmd(attr_name)
return cmd
def get_attribute_value(
self,
attr_name: str,
) -> Any:
op = self._get_attribute_set_cmd(attr_name)
if op is not None:
return op.new_value
else:
return None
def get_local_attribute_value(
self,
attr_name: str,
) -> Any:
"""Return the new value of field, if not inherited."""
op = self._get_attribute_set_cmd(attr_name)
if op is not None and not op.new_inherited:
return op.new_value
else:
return None
def get_orig_attribute_value(
self,
attr_name: str,
) -> Any:
op = self._get_attribute_set_cmd(attr_name)
if op is not None:
return op.old_value
else:
return None
def is_attribute_inherited(
self,
attr_name: str,
) -> bool:
op = self._get_attribute_set_cmd(attr_name)
if op is not None:
return op.new_inherited
else:
return False
def is_attribute_computed(
self,
attr_name: str,
) -> bool:
op = self._get_attribute_set_cmd(attr_name)
if op is not None:
return op.new_computed
else:
return False
def get_attribute_source_context(
self,
attr_name: str,
) -> Optional[parsing.ParserContext]:
op = self._get_attribute_set_cmd(attr_name)
if op is not None:
return op.source_context
else:
return None
def set_attribute_value(
self,
attr_name: str,
value: Any,
*,
orig_value: Any = None,
inherited: bool = False,
orig_inherited: Optional[bool] = None,
computed: bool = False,
from_default: bool = False,
orig_computed: Optional[bool] = None,
source_context: Optional[parsing.ParserContext] = None,
) -> Command:
orig_op = op = self._get_simple_attribute_set_cmd(attr_name)
if op is None:
op = AlterObjectProperty(property=attr_name, new_value=value)
else:
op.new_value = value
if orig_inherited is None:
orig_inherited = inherited
op.new_inherited = inherited
op.old_inherited = orig_inherited
if orig_computed is None:
orig_computed = computed
op.new_computed = computed
op.old_computed = orig_computed
op.from_default = from_default
if source_context is not None:
op.source_context = source_context
if orig_value is not None:
op.old_value = orig_value
if orig_op is None:
self.add(op)
return op
def discard_attribute(self, attr_name: str) -> None:
op = self._get_attribute_set_cmd(attr_name)
if op is not None:
self.discard(op)
def __iter__(self) -> NoReturn:
raise TypeError(f'{type(self)} object is not iterable')
@overload
def get_subcommands(
self,
*,
type: Type[Command_T],
metaclass: Optional[Type[so.Object]] = None,
exclude: Union[Type[Command], Tuple[Type[Command], ...], None] = None,
include_prerequisites: bool = True,
include_caused: bool = True,
) -> Tuple[Command_T, ...]:
...
@overload
def get_subcommands(
self,
*,
type: None = None,
metaclass: Optional[Type[so.Object]] = None,
exclude: Union[Type[Command], Tuple[Type[Command], ...], None] = None,
include_prerequisites: bool = True,
include_caused: bool = True,
) -> Tuple[Command, ...]:
...
def get_subcommands(
self,
*,
type: Union[Type[Command_T], None] = None,
metaclass: Optional[Type[so.Object]] = None,
exclude: Union[Type[Command], Tuple[Type[Command], ...], None] = None,
include_prerequisites: bool = True,
include_caused: bool = True,
) -> Tuple[Command, ...]:
ops: Iterable[Command] = self.ops
if include_prerequisites:
ops = itertools.chain(self.before_ops, ops)
if include_caused:
ops = itertools.chain(ops, self.caused_ops)
filters = []
if type is not None:
t = type
filters.append(lambda i: isinstance(i, t))
if exclude is not None:
ex = exclude
filters.append(lambda i: not isinstance(i, ex))
if metaclass is not None:
mcls = metaclass
filters.append(
lambda i: (
isinstance(i, ObjectCommand)
and issubclass(i.get_schema_metaclass(), mcls)
)
)
if filters:
return tuple(filter(lambda i: all(f(i) for f in filters), ops))
else:
return tuple(ops)
@overload
def get_prerequisites(
self,
*,
type: Type[Command_T],
) -> Tuple[Command_T, ...]:
...
@overload
def get_prerequisites(
self,
*,
type: None = None,
) -> Tuple[Command, ...]:
...
def get_prerequisites(
self,
*,
type: Union[Type[Command_T], None] = None,
) -> Tuple[Command, ...]:
if type is not None:
t = type
return tuple(filter(lambda i: isinstance(i, t), self.before_ops))
else:
return tuple(self.before_ops)
@overload
def get_caused(
self,
*,
type: Type[Command_T],
) -> Tuple[Command_T, ...]:
...
@overload
def get_caused(
self,
*,
type: None = None,
) -> Tuple[Command, ...]:
...
def get_caused(
self,
*,
type: Union[Type[Command_T], None] = None,
) -> Tuple[Command, ...]:
if type is not None:
t = type
return tuple(filter(lambda i: isinstance(i, t), self.caused_ops))
else:
return tuple(self.caused_ops)
def has_subcommands(self) -> bool:
return bool(self.ops) or bool(self.before_ops) or bool(self.caused_ops)
def get_nonattr_subcommand_count(self) -> int:
attr_cmds = (AlterObjectProperty, AlterSpecialObjectField)
return len(self.get_subcommands(exclude=attr_cmds))
def get_nonattr_special_subcommand_count(self) -> int:
attr_cmds = (AlterObjectProperty,)
return len(self.get_subcommands(exclude=attr_cmds))
def prepend_prerequisite(self, command: Command) -> None:
if isinstance(command, CommandGroup):
for op in reversed(command.get_subcommands()):
self.prepend_prerequisite(op)
else:
self.before_ops.insert(0, command)
def add_prerequisite(self, command: Command) -> None:
if isinstance(command, CommandGroup):
self.before_ops.extend(command.get_subcommands())
else:
self.before_ops.append(command)
def prepend_caused(self, command: Command) -> None:
if isinstance(command, CommandGroup):
for op in reversed(command.get_subcommands()):
self.prepend_caused(op)
else:
self.caused_ops.insert(0, command)
def add_caused(self, command: Command) -> None:
if isinstance(command, CommandGroup):
self.caused_ops.extend(command.get_subcommands())
else:
self.caused_ops.append(command)
def prepend(self, command: Command) -> None:
if isinstance(command, CommandGroup):
for op in reversed(command.get_subcommands()):
self.prepend(op)
else:
if isinstance(command, AlterObjectProperty):
self._attrs[command.property] = command
elif isinstance(command, AlterSpecialObjectField):
self._special_attrs[command._field] = command
self.ops.insert(0, command)
def add(self, command: Command) -> None:
if isinstance(command, CommandGroup):
self.update(command.get_subcommands())
else:
if isinstance(command, AlterObjectProperty):
self._attrs[command.property] = command
elif isinstance(command, AlterSpecialObjectField):
self._special_attrs[command._field] = command
self.ops.append(command)
def update(self, commands: Iterable[Command]) -> None:
for command in commands:
self.add(command)
def replace(self, existing: Command, new: Command) -> None: # type: ignore
try:
i = self.ops.index(existing)
self.ops[i] = new
return
except ValueError:
pass
try:
i = self.before_ops.index(existing)
self.before_ops[i] = new
return
except ValueError:
pass
i = self.caused_ops.index(existing)
self.caused_ops[i] = new
def replace_all(self, commands: Iterable[Command]) -> None:
self.ops.clear()
self._attrs.clear()
self._special_attrs.clear()
self.update(commands)
def discard(self, command: Command) -> None:
try:
self.ops.remove(command)
except ValueError:
pass
try:
self.before_ops.remove(command)
except ValueError:
pass
try:
self.caused_ops.remove(command)
except ValueError:
pass
if isinstance(command, AlterObjectProperty):
self._attrs.pop(command.property)
elif isinstance(command, AlterSpecialObjectField):
self._special_attrs.pop(command._field)
def apply(
self,
schema: s_schema.Schema,
context: CommandContext,
) -> s_schema.Schema:
return schema
def apply_prerequisites(
self,
schema: s_schema.Schema,
context: CommandContext,
) -> s_schema.Schema:
for op in self.get_prerequisites():
schema = op.apply(schema, context)
return schema
def apply_subcommands(
self,
schema: s_schema.Schema,
context: CommandContext,
) -> s_schema.Schema:
for op in self.get_subcommands(
include_prerequisites=False,
include_caused=False,
):
if not isinstance(op, AlterObjectProperty):
schema = op.apply(schema, context=context)
return schema
def apply_caused(
self,
schema: s_schema.Schema,
context: CommandContext,
) -> s_schema.Schema:
for op in self.get_caused():
schema = op.apply(schema, context)
return schema
def get_ast(
self,
schema: s_schema.Schema,
context: CommandContext,
*,
parent_node: Optional[qlast.DDLOperation] = None,
) -> Optional[qlast.DDLOperation]:
context_class = type(self).get_context_class()
assert context_class is not None
with context(context_class(schema=schema, op=self)):
return self._get_ast(schema, context, parent_node=parent_node)
def _get_ast(