forked from geldata/gel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypes.py
3554 lines (2892 loc) · 106 KB
/
types.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 2016-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
import collections
import collections.abc
import enum
import typing
import uuid
from edb import errors
from edb.common import checked
from edb.edgeql import ast as qlast
from edb.edgeql import qltypes
from edb.edgeql import compiler as qlcompiler
from . import abc as s_abc
from . import annos as s_anno
from . import casts as s_casts
from . import delta as sd
from . import expr as s_expr
from . import inheriting
from . import name as s_name
from . import objects as so
from . import schema as s_schema
from . import utils
if typing.TYPE_CHECKING:
# We cannot use `from typing import *` in this file due to name conflict
# with local Tuple and Type classes.
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional
from typing import AbstractSet, Sequence, Union, Callable
from edb.common import parsing
MAX_TYPE_DISTANCE = 1_000_000_000
class ExprType(enum.IntEnum):
"""Enumeration to identify the type of an expression in aliases."""
Select = enum.auto()
Insert = enum.auto()
Update = enum.auto()
Delete = enum.auto()
Group = enum.auto()
def is_update(self) -> bool:
return self == ExprType.Update
def is_insert(self) -> bool:
return self == ExprType.Insert
def is_mutation(self) -> bool:
return self != ExprType.Select and self != ExprType.Group
TypeT = typing.TypeVar('TypeT', bound='Type')
TypeT_co = typing.TypeVar('TypeT_co', bound='Type', covariant=True)
InheritingTypeT = typing.TypeVar('InheritingTypeT', bound='InheritingType')
CollectionTypeT = typing.TypeVar('CollectionTypeT', bound='Collection')
CollectionTypeT_co = typing.TypeVar(
'CollectionTypeT_co', bound='Collection', covariant=True)
CollectionExprAliasT = typing.TypeVar(
'CollectionExprAliasT', bound='CollectionExprAlias'
)
class Type(
so.SubclassableObject,
s_anno.AnnotationSubject,
s_abc.Type,
):
"""A schema item that is a valid *type*."""
# If this type is an alias, expr will contain an expression that
# defines it.
expr = so.SchemaField(
s_expr.Expression,
default=None, coerce=True, compcoef=0.909)
# For a type representing an expression alias, this would contain the
# expression type. Non-alias types have None here.
expr_type = so.SchemaField(
ExprType,
default=None, compcoef=0.909)
# True for views. This should always match the value of
# `bool(expr_type)`, but can be exported in the introspection
# schema without revealing weird internals.
from_alias = so.SchemaField(
bool,
default=False, compcoef=1.0)
# True when from a global. The purpose of this is to ensure that
# the types from globals and aliases can't be migrated between
# each other.
from_global = so.SchemaField(
bool,
default=False, compcoef=0.2)
# True for aliases defined by CREATE ALIAS, false for local
# aliases in queries.
alias_is_persistent = so.SchemaField(
bool,
default=False, compcoef=None)
# If this type is a view defined by a nested shape expression,
# and the nested shape contains references to link properties,
# rptr will contain the inbound pointer class.
rptr = so.SchemaField(
so.Object,
weak_ref=True,
default=None, compcoef=0.909)
# The OID by which the backend refers to the type.
backend_id = so.SchemaField(
int,
default=None, inheritable=False)
# True for types that cannot be persistently stored.
# See fts::document for an example.
transient = so.SchemaField(bool, default=False)
def compare(
self,
other: so.Object,
*,
our_schema: s_schema.Schema,
their_schema: s_schema.Schema,
context: so.ComparisonContext,
) -> float:
# We need to be able to compare objects and scalars, in some places
if (
isinstance(other, Type)
and not isinstance(other, self.__class__)
and not isinstance(self, other.__class__)
):
return 0.0
return super().compare(
other,
our_schema=our_schema, their_schema=their_schema, context=context)
def is_blocking_ref(
self, schema: s_schema.Schema, reference: so.Object
) -> bool:
return reference != self.get_rptr(schema)
def derive_subtype(
self: TypeT,
schema: s_schema.Schema,
*,
name: s_name.QualName,
mark_derived: bool = False,
attrs: Optional[Mapping[str, Any]] = None,
inheritance_merge: bool = True,
transient: bool = False,
inheritance_refdicts: Optional[AbstractSet[str]] = None,
**kwargs: Any,
) -> typing.Tuple[s_schema.Schema, TypeT]:
if self.get_name(schema) == name:
raise errors.SchemaError(
f'cannot derive {self!r}({name}) from itself')
derived_attrs: Dict[str, object] = {}
if attrs is not None:
derived_attrs.update(attrs)
derived_attrs['name'] = name
derived_attrs['bases'] = so.ObjectList.create(schema, [self])
derived_attrs['from_alias'] = bool(derived_attrs.get('expr_type'))
cmd = sd.get_object_delta_command(
objtype=type(self),
cmdtype=sd.CreateObject,
schema=schema,
name=name,
)
for k, v in derived_attrs.items():
cmd.set_attribute_value(k, v)
context = sd.CommandContext(
modaliases={},
schema=schema,
)
delta = sd.DeltaRoot()
with context(sd.DeltaRootContext(schema=schema, op=delta)):
if not inheritance_merge:
context.current().inheritance_merge = False
if inheritance_refdicts is not None:
context.current().inheritance_refdicts = inheritance_refdicts
if mark_derived:
context.current().mark_derived = True
if transient:
context.current().transient_derivation = True
delta.add(cmd)
schema = delta.apply(schema, context)
derived = typing.cast(TypeT, schema.get(name))
return schema, derived
def is_object_type(self) -> bool:
return False
def is_free_object_type(self, schema: s_schema.Schema) -> bool:
return False
def is_union_type(self, schema: s_schema.Schema) -> bool:
return False
def is_intersection_type(self, schema: s_schema.Schema) -> bool:
return False
def is_compound_type(self, schema: s_schema.Schema) -> bool:
return False
def is_polymorphic(self, schema: s_schema.Schema) -> bool:
return False
def is_any(self, schema: s_schema.Schema) -> bool:
return False
def is_anytuple(self, schema: s_schema.Schema) -> bool:
return False
def is_anyobject(self, schema: s_schema.Schema) -> bool:
return False
def is_scalar(self) -> bool:
return False
def is_collection(self) -> bool:
return False
def is_array(self) -> bool:
return False
def is_json(self, schema: s_schema.Schema) -> bool:
return False
def is_tuple(self, schema: s_schema.Schema) -> bool:
return False
def is_range(self) -> bool:
return False
def is_multirange(self) -> bool:
return False
def is_enum(self, schema: s_schema.Schema) -> bool:
return False
def is_sequence(self, schema: s_schema.Schema) -> bool:
return False
def is_array_of_tuples(self, schema: s_schema.Schema) -> bool:
return False
def find_predicate(
self,
pred: Callable[[Type], bool],
schema: s_schema.Schema,
) -> Optional[Type]:
if pred(self):
return self
else:
return None
def contains_predicate(
self,
pred: Callable[[Type], bool],
schema: s_schema.Schema,
) -> bool:
return bool(self.find_predicate(pred, schema))
def find_generic(self, schema: s_schema.Schema) -> Optional[Type]:
return self.find_predicate(
lambda x: x.is_any(schema) or x.is_anyobject(schema), schema
)
def contains_object(self, schema: s_schema.Schema) -> bool:
return self.contains_predicate(lambda x: x.is_object_type(), schema)
def contains_json(self, schema: s_schema.Schema) -> bool:
return self.contains_predicate(lambda x: x.is_json(schema), schema)
def find_array(self, schema: s_schema.Schema) -> Optional[Type]:
return self.find_predicate(lambda x: x.is_array(), schema)
def contains_array_of_tuples(self, schema: s_schema.Schema) -> bool:
return self.contains_predicate(
lambda x: x.is_array_of_tuples(schema), schema)
def test_polymorphic(self, schema: s_schema.Schema, poly: Type) -> bool:
"""Check if this type can be matched by a polymorphic type.
Examples:
- `array<anyscalar>`.test_polymorphic(`array<anytype>`) -> True
- `array<str>`.test_polymorphic(`array<anytype>`) -> True
- `array<int64>`.test_polymorphic(`anyscalar`) -> False
- `float32`.test_polymorphic(`anyint`) -> False
- `int32`.test_polymorphic(`anyint`) -> True
"""
if not poly.is_polymorphic(schema):
raise TypeError('expected a polymorphic type as a second argument')
if poly.is_any(schema):
return True
if poly.is_anyobject(schema) and self.is_object_type():
return True
return self._test_polymorphic(schema, poly)
def resolve_polymorphic(
self, schema: s_schema.Schema, other: Type
) -> Optional[Type]:
"""Resolve the polymorphic type component.
Examples:
- `array<anytype>`.resolve_polymorphic(`array<int>`) -> `int`
- `array<anytype>`.resolve_polymorphic(`tuple<int>`) -> None
"""
if not self.is_polymorphic(schema):
return None
return self._resolve_polymorphic(schema, other)
def to_nonpolymorphic(
self: TypeT, schema: s_schema.Schema, concrete_type: Type
) -> typing.Tuple[s_schema.Schema, Type]:
"""Produce an non-polymorphic version of self.
Example:
`array<anytype>`.to_nonpolymorphic(`int`) -> `array<int>`
`tuple<int, anytype>`.to_nonpolymorphic(`str`) -> `tuple<int, str>`
"""
if not self.is_polymorphic(schema):
raise TypeError('non-polymorphic type')
return self._to_nonpolymorphic(schema, concrete_type)
def _test_polymorphic(self, schema: s_schema.Schema, other: Type) -> bool:
return False
def _resolve_polymorphic(
self,
schema: s_schema.Schema,
concrete_type: Type,
) -> Optional[Type]:
raise NotImplementedError(
f'{type(self)} does not support resolve_polymorphic()')
def _to_nonpolymorphic(
self: TypeT,
schema: s_schema.Schema,
concrete_type: Type,
) -> typing.Tuple[s_schema.Schema, Type]:
raise NotImplementedError(
f'{type(self)} does not support to_nonpolymorphic()')
def is_view(self, schema: s_schema.Schema) -> bool:
return self.get_from_alias(schema)
def castable_to(
self,
other: Type,
schema: s_schema.Schema,
) -> bool:
if self.implicitly_castable_to(other, schema):
return True
elif self.assignment_castable_to(other, schema):
return True
else:
return False
def assignment_castable_to(
self, other: Type, schema: s_schema.Schema
) -> bool:
return self.implicitly_castable_to(other, schema)
def implicitly_castable_to(
self,
other: Type,
schema: s_schema.Schema,
) -> bool:
return False
def get_implicit_cast_distance(
self, other: Type, schema: s_schema.Schema
) -> int:
return -1
def find_common_implicitly_castable_type(
self,
other: Type,
schema: s_schema.Schema,
) -> typing.Tuple[s_schema.Schema, Optional[Type]]:
return schema, None
def get_union_of(
self: TypeT,
schema: s_schema.Schema,
) -> Optional[so.ObjectSet[TypeT]]:
return None
def get_is_opaque_union(self, schema: s_schema.Schema) -> bool:
return False
def get_intersection_of(
self: TypeT,
schema: s_schema.Schema,
) -> Optional[so.ObjectSet[TypeT]]:
return None
def material_type(
self: TypeT, schema: s_schema.Schema
) -> typing.Tuple[s_schema.Schema, TypeT]:
return schema, self
def peel_view(self, schema: s_schema.Schema) -> Type:
return self
def get_common_parent_type_distance(
self,
other: Type,
schema: s_schema.Schema,
) -> int:
raise NotImplementedError
def allow_ref_propagation(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
refdict: so.RefDict,
) -> bool:
return not self.is_view(schema)
def as_shell(
self: TypeT,
schema: s_schema.Schema,
) -> TypeShell[TypeT]:
name = typing.cast(s_name.QualName, self.get_name(schema))
if (
(union_of := self.get_union_of(schema))
and not self.is_view(schema)
):
assert isinstance(self, so.QualifiedObject)
return UnionTypeShell(
components=[
o.as_shell(schema) for o in union_of.objects(schema)
],
module=name.module,
opaque=self.get_is_opaque_union(schema),
schemaclass=type(self),
)
elif (
(intersection_of := self.get_intersection_of(schema))
and not self.is_view(schema)
):
assert isinstance(self, so.QualifiedObject)
return IntersectionTypeShell(
components=[
o.as_shell(schema) for o in intersection_of.objects(schema)
],
module=name.module,
schemaclass=type(self),
)
else:
return TypeShell(
name=name,
schemaclass=type(self),
)
def record_cmd_object_aux_data(
self,
schema: s_schema.Schema,
cmd: sd.ObjectCommand[Type],
) -> None:
super().record_cmd_object_aux_data(schema, cmd)
if self.is_compound_type(schema):
cmd.set_object_aux_data('is_compound_type', True)
def as_type_delete_if_dead(
self: TypeT,
schema: s_schema.Schema,
) -> Optional[sd.DeleteObject[TypeT]]:
"""If this is type is owned by other objects, delete it if unused.
For types that get created behind the scenes as part of
another object, such as collection types and union types, this
should generate an appropriate deletion. Otherwise, it should
return None.
"""
return None
class QualifiedType(so.QualifiedObject, Type):
@classmethod
def get_schema_class_displayname(cls) -> str:
return 'type'
class InheritingType(so.DerivableInheritingObject, QualifiedType):
def material_type(
self: InheritingTypeT,
schema: s_schema.Schema_T,
) -> typing.Tuple[s_schema.Schema_T, InheritingTypeT]:
return schema, self.get_nearest_non_derived_parent(schema)
def peel_view(self, schema: s_schema.Schema) -> Type:
# When self is a view, this returns the class the view
# is derived from (which may be another view). If no
# parent class is available, returns self.
if self.is_view(schema):
return typing.cast(Type, self.get_bases(schema).first(schema))
else:
return self
def get_common_parent_type_distance(
self,
other: Type,
schema: s_schema.Schema,
) -> int:
if other.is_any(schema) or self.is_any(schema):
return MAX_TYPE_DISTANCE
if not isinstance(other, type(self)):
return -1
if self == other:
return 0
ancestors = utils.get_class_nearest_common_ancestors(
schema, [self, other])
if not ancestors:
return -1
elif self in ancestors:
return 0
else:
all_ancestors = list(self.get_ancestors(schema).objects(schema))
return min(
all_ancestors.index(ancestor) + 1 for ancestor in ancestors)
class TypeShell(so.ObjectShell[TypeT_co]):
schemaclass: typing.Type[TypeT_co]
extra_args: tuple[qlast.Expr | qlast.TypeExpr, ...] | None
def __init__(
self,
*,
name: s_name.Name,
origname: Optional[s_name.Name] = None,
displayname: Optional[str] = None,
expr: Optional[str] = None,
schemaclass: typing.Type[TypeT_co],
sourcectx: Optional[parsing.ParserContext] = None,
extra_args: tuple[qlast.Expr] | None = None,
) -> None:
super().__init__(
name=name,
origname=origname,
displayname=displayname,
schemaclass=schemaclass,
sourcectx=sourcectx,
)
self.expr = expr
self.extra_args = extra_args
def resolve(self, schema: s_schema.Schema) -> TypeT_co:
return schema.get(
self.get_name(schema),
type=self.schemaclass,
sourcectx=self.sourcectx,
)
def is_polymorphic(self, schema: s_schema.Schema) -> bool:
return self.resolve(schema).is_polymorphic(schema)
def as_create_delta(
self,
schema: s_schema.Schema,
*,
view_name: Optional[s_name.QualName] = None,
attrs: Optional[Dict[str, Any]] = None,
) -> sd.Command:
raise errors.UnsupportedFeatureError(
f'unsupported type intersection in schema',
hint=f'Type intersections are currently '
f'unsupported as valid link targets.',
context=self.sourcectx,
)
class TypeExprShell(TypeShell[TypeT_co]):
components: typing.Tuple[TypeShell[TypeT_co], ...]
module: str
def __init__(
self,
*,
components: Iterable[TypeShell[TypeT_co]],
module: str,
schemaclass: typing.Type[TypeT_co],
sourcectx: Optional[parsing.ParserContext] = None,
) -> None:
super().__init__(
name=s_name.UnqualName('__unresolved__'),
schemaclass=schemaclass,
sourcectx=sourcectx,
)
self.components = tuple(components)
self.module = module
def resolve_components(
self,
schema: s_schema.Schema,
) -> typing.Tuple[TypeT_co, ...]:
return tuple(c.resolve(schema) for c in self.components)
def get_components(
self,
schema: s_schema.Schema,
) -> typing.Tuple[TypeShell[TypeT_co], ...]:
return self.components
class UnionTypeShell(TypeExprShell[TypeT_co]):
def __init__(
self,
*,
components: Iterable[TypeShell[TypeT_co]],
module: str,
opaque: bool = False,
schemaclass: typing.Type[TypeT_co],
sourcectx: Optional[parsing.ParserContext] = None,
) -> None:
super().__init__(
components=components,
module=module,
schemaclass=schemaclass,
sourcectx=sourcectx,
)
self.opaque = opaque
def get_name(
self,
schema: s_schema.Schema,
) -> s_name.Name:
return get_union_type_name(
(c.get_name(schema) for c in self.components),
opaque=self.opaque,
module=self.module,
)
def as_create_delta(
self,
schema: s_schema.Schema,
*,
view_name: Optional[s_name.QualName] = None,
attrs: Optional[Dict[str, Any]] = None,
) -> sd.Command:
name = get_union_type_name(
(c.get_name(schema) for c in self.components),
opaque=self.opaque,
module=self.module,
)
cmd = CreateUnionType(classname=name)
cmd.set_attribute_value('name', name)
cmd.set_attribute_value('components', tuple(self.components))
cmd.set_attribute_value('is_opaque_union', self.opaque)
return cmd
def __repr__(self) -> str:
dn = 'UnionType'
comps = ' | '.join(repr(c) for c in self.components)
return f'<{type(self).__name__} {dn}({comps}) at 0x{id(self):x}>'
class RenameType(sd.RenameObject[TypeT]):
def _canonicalize(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
scls: TypeT,
) -> None:
super()._canonicalize(schema, context, scls)
# Now, see if there are any compound or collection types using
# this type as a component. We must rename them, as they derive
# their names from the names of their component types.
# We must be careful about the order in which we consider the
# referrers, because they may reference each other as well, and
# so we must proceed with renames starting from the simplest type.
referrers = collections.defaultdict(set)
referrer_map = schema.get_referrers_ex(scls, scls_type=Type)
for (_, field_name), objs in referrer_map.items():
for obj in objs:
referrers[obj].add(field_name)
ref_order = sd.sort_by_cross_refs(schema, referrers)
for ref_type in ref_order:
field_names = referrers[ref_type]
for field_name in field_names:
if field_name == 'union_of' or field_name == 'intersection_of':
orig_ref_type_name = ref_type.get_name(schema)
assert isinstance(orig_ref_type_name, s_name.QualName)
components = ref_type.get_field_value(
schema, field_name)
assert components is not None
component_names = set(components.names(schema))
component_names.discard(self.classname)
component_names.add(self.new_name)
if field_name == 'union_of':
new_ref_type_name = get_union_type_name(
component_names,
module=orig_ref_type_name.module,
opaque=ref_type.get_is_opaque_union(schema),
)
else:
new_ref_type_name = get_intersection_type_name(
component_names,
module=orig_ref_type_name.module,
)
self.add(self.init_rename_branch(
ref_type,
new_ref_type_name,
schema=schema,
context=context,
))
elif (
isinstance(ref_type, Tuple)
and field_name == 'element_types'
):
subtypes = {
k: st.get_name(schema)
for k, st in (
ref_type.get_element_types(schema).items(schema)
)
}
new_tup_type_name = Tuple.generate_name(
subtypes,
named=ref_type.is_named(schema),
)
self.add(self.init_rename_branch(
ref_type,
new_tup_type_name,
schema=schema,
context=context,
))
elif (
isinstance(ref_type, Array)
and field_name == 'element_type'
):
new_arr_type_name = Array.generate_name(
ref_type.get_element_type(schema).get_name(schema)
)
self.add(self.init_rename_branch(
ref_type,
new_arr_type_name,
schema=schema,
context=context,
))
def _get_ast(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
*,
parent_node: Optional[qlast.DDLOperation] = None,
) -> Optional[qlast.DDLOperation]:
if (
self.maybe_get_object_aux_data('is_compound_type')
or self.scls.is_view(schema)
):
return None
else:
return super()._get_ast(schema, context, parent_node=parent_node)
class DeleteType(sd.DeleteObject[TypeT]):
def _get_ast(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
*,
parent_node: Optional[qlast.DDLOperation] = None,
) -> Optional[qlast.DDLOperation]:
if self.maybe_get_object_aux_data('is_compound_type'):
return None
else:
return super()._get_ast(schema, context, parent_node=parent_node)
class RenameInheritingType(
RenameType[InheritingTypeT],
inheriting.RenameInheritingObject[InheritingTypeT],
):
pass
class DeleteInheritingType(
DeleteType[InheritingTypeT],
inheriting.DeleteInheritingObject[InheritingTypeT],
):
pass
class CompoundTypeCommandContext(sd.ObjectCommandContext[InheritingType]):
pass
class CompoundTypeCommand(
sd.QualifiedObjectCommand[InheritingType],
context_class=CompoundTypeCommandContext,
):
pass
class CreateUnionType(sd.CreateObject[InheritingType], CompoundTypeCommand):
def apply(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
) -> s_schema.Schema:
if not context.canonical:
components = [
c.resolve(schema)
for c in self.get_attribute_value('components')
]
new_schema, union_type = utils.get_union_type(
schema,
components,
opaque=self.get_attribute_value('is_opaque_union') or False,
module=self.classname.module,
)
delta = union_type.as_create_delta(
schema=new_schema,
context=so.ComparisonContext(),
)
self.add(delta)
for cmd in self.get_subcommands():
schema = cmd.apply(schema, context)
return schema
class IntersectionTypeShell(TypeExprShell[TypeT_co]):
def get_name(
self,
schema: s_schema.Schema,
) -> s_name.Name:
return get_intersection_type_name(
(c.get_name(schema) for c in self.components),
module=self.module,
)
_collection_impls: Dict[str, typing.Type[Collection]] = {}
class Collection(Type, s_abc.Collection):
_schema_name: typing.ClassVar[typing.Optional[str]] = None
#: True for collection types that are stored in schema persistently
is_persistent = so.SchemaField(
bool,
default=False,
compcoef=None,
)
def __init_subclass__(
cls,
*,
schema_name: typing.Optional[str] = None,
) -> None:
super().__init_subclass__()
if schema_name is not None:
if existing := _collection_impls.get(schema_name):
raise TypeError(
f"{schema_name} is already implemented by {existing}")
_collection_impls[schema_name] = cls
cls._schema_name = schema_name
def as_create_delta(
self: CollectionTypeT,
schema: s_schema.Schema,
context: so.ComparisonContext,
) -> sd.ObjectCommand[CollectionTypeT]:
delta = super().as_create_delta(schema=schema, context=context)
assert isinstance(delta, sd.CreateObject)
if not isinstance(self, CollectionExprAlias):
delta.if_not_exists = True
return delta
def as_delete_delta(
self: CollectionTypeT,
*,
schema: s_schema.Schema,
context: so.ComparisonContext,
) -> sd.ObjectCommand[CollectionTypeT]:
delta = super().as_delete_delta(schema=schema, context=context)
assert isinstance(delta, sd.DeleteObject)
if not isinstance(self, CollectionExprAlias):
delta.if_exists = True
delta.if_unused = True
delta.canonical = False
return delta
@classmethod
def get_displayname_static(cls, name: s_name.Name) -> str:
if isinstance(name, s_name.QualName):
return str(name)
else:
return s_name.unmangle_name(str(name))
@classmethod
def get_schema_name(cls) -> str:
if cls._schema_name is None:
raise TypeError(
f"{cls.get_schema_class_displayname()} is not "
f"a concrete collection type"
)
return cls._schema_name
def get_generated_name(self, schema: s_schema.Schema) -> s_name.UnqualName:
"""Return collection type name generated from element types.
Unlike get_name(), which might return a custom name, this will always
return a name derived from the names of the collection element type(s).
"""
raise NotImplementedError
def is_polymorphic(self, schema: s_schema.Schema) -> bool:
return any(st.is_polymorphic(schema)
for st in self.get_subtypes(schema))
def find_predicate(
self,
pred: Callable[[Type], bool],
schema: s_schema.Schema,
) -> Optional[Type]:
if pred(self):
return self
for st in self.get_subtypes(schema):