forked from geldata/gel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.py
More file actions
2344 lines (1991 loc) · 78.2 KB
/
codegen.py
File metadata and controls
2344 lines (1991 loc) · 78.2 KB
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 *
import itertools
import re
from edb import errors
from edb.common.ast import codegen, base
from edb.common import typeutils
from . import ast as qlast
from . import quote as edgeql_quote
from . import qltypes
_module_name_re = re.compile(r'^(?!=\d)\w+(\.(?!=\d)\w+)*$')
_BYTES_ESCAPE_RE = re.compile(b'[\\\'\x00-\x1f\x7e-\xff]')
_NON_PRINTABLE_RE = re.compile(
r'[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F\u0080-\u009F\n]')
_ESCAPES = {
b'\\': b'\\\\',
b'\'': b'\\\'',
b'\t': b'\\t',
b'\n': b'\\n',
}
if TYPE_CHECKING:
import enum
Enum_T = TypeVar('Enum_T', bound=enum.Enum)
def _bytes_escape(match: Match[bytes]) -> bytes:
char = match.group(0)
try:
return _ESCAPES[char]
except KeyError:
return b'\\x%02x' % char[0]
def any_ident_to_str(ident: str) -> str:
if _module_name_re.match(ident):
return ident
else:
return ident_to_str(ident)
def ident_to_str(ident: str) -> str:
return edgeql_quote.quote_ident(ident)
def param_to_str(ident: str) -> str:
return '$' + edgeql_quote.quote_ident(
ident, allow_reserved=True)
def module_to_str(module: str) -> str:
return '.'.join([ident_to_str(part) for part in module.split('.')])
class EdgeQLSourceGeneratorError(errors.InternalServerError):
pass
class EdgeSchemaSourceGeneratorError(errors.InternalServerError):
pass
class EdgeQLSourceGenerator(codegen.SourceGenerator):
def __init__(
self, *args: Any,
sdlmode: bool = False,
descmode: bool = False,
# Uppercase keywords for backwards compatibility with older migrations.
uppercase: bool = False,
unsorted: bool = False,
limit_ref_classes:
Optional[AbstractSet[qltypes.SchemaObjectClass]] = None,
**kwargs: Any
) -> None:
super().__init__(*args, **kwargs)
self.sdlmode = sdlmode
self.descmode = descmode
self.uppercase = uppercase
self.unsorted = unsorted
self.limit_ref_classes = limit_ref_classes
def visit(
self,
node: Union[qlast.Base, List[qlast.Base]],
**kwargs: Any
) -> None:
if isinstance(node, list):
self.visit_list(node, terminator=';')
else:
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
visitor(node, **kwargs)
def _kw_case(self, *kws: str) -> str:
kwstring = ' '.join(kws)
if self.uppercase:
kwstring = kwstring.upper()
else:
kwstring = kwstring.lower()
return kwstring
def _write_keywords(self, *kws: str) -> None:
self.write(self._kw_case(*kws))
def _needs_parentheses(self, node) -> bool: # type: ignore
# The "parent" attribute is set by calling `_fix_parent_links`
# before traversing the AST. Since it's not an attribute that
# can be inferred by static typing we ignore typing for this
# function.
return (
node._parent is not None and (
not isinstance(node._parent, qlast.Base)
or not isinstance(node._parent, qlast.DDL)
)
)
def generic_visit(self, node: qlast.Base,
*args: Any, **kwargs: Any) -> None:
if isinstance(node, qlast.SDL):
raise EdgeQLSourceGeneratorError(
f'No method to generate code for {node.__class__.__name__}')
else:
raise EdgeQLSourceGeneratorError(
f'No method to generate code for {node.__class__.__name__}')
def _block_ws(self, change: int, newlines: bool = True) -> None:
if newlines:
self.indentation += change
self.new_lines = 1
else:
self.write(' ')
def _visit_aliases(self, node: qlast.Command) -> None:
if node.aliases:
self._write_keywords('WITH')
self._block_ws(1)
if node.aliases:
self.visit_list(node.aliases)
self._block_ws(-1)
def _visit_filter(self, node: qlast.FilterMixin,
newlines: bool = True) -> None:
if node.where:
self._write_keywords('FILTER')
self._block_ws(1, newlines)
self.visit(node.where)
self._block_ws(-1, newlines)
def _visit_order(self, node: qlast.OrderByMixin,
newlines: bool = True) -> None:
if node.orderby:
self._write_keywords('ORDER BY')
self._block_ws(1, newlines)
self.visit_list(
node.orderby,
separator=self._kw_case(' THEN'), newlines=newlines
)
self._block_ws(-1, newlines)
def _visit_offset_limit(self, node: qlast.OffsetLimitMixin,
newlines: bool = True) -> None:
if node.offset is not None:
self._write_keywords('OFFSET')
self._block_ws(1, newlines)
self.visit(node.offset)
self._block_ws(-1, newlines)
if node.limit is not None:
self._write_keywords('LIMIT')
self._block_ws(1, newlines)
self.visit(node.limit)
self._block_ws(-1, newlines)
def visit_OptionallyAliasedExpr(
self, node: qlast.OptionallyAliasedExpr) -> None:
if node.alias:
self.write(ident_to_str(node.alias))
self.write(' := ')
self._block_ws(1)
self.visit(node.expr)
if node.alias:
self._block_ws(-1)
def visit_AliasedExpr(self, node: qlast.AliasedExpr) -> None:
self.visit_OptionallyAliasedExpr(node)
def visit_InsertQuery(self, node: qlast.InsertQuery) -> None:
# need to parenthesise when INSERT appears as an expression
parenthesise = self._needs_parentheses(node)
if parenthesise:
self.write('(')
self._visit_aliases(node)
self._write_keywords('INSERT')
self._block_ws(1)
self.visit(node.subject)
self._block_ws(-1)
if node.shape:
self.indentation += 1
self._visit_shape(node.shape)
self.indentation -= 1
if node.unless_conflict:
on_expr, else_expr = node.unless_conflict
self._write_keywords('UNLESS CONFLICT')
if on_expr:
self._write_keywords(' ON ')
self.visit(on_expr)
if else_expr:
self._write_keywords(' ELSE ')
self.visit(else_expr)
if parenthesise:
self.write(')')
def visit_UpdateQuery(self, node: qlast.UpdateQuery) -> None:
# need to parenthesise when UPDATE appears as an expression
parenthesise = self._needs_parentheses(node)
if parenthesise:
self.write('(')
self._visit_aliases(node)
self._write_keywords('UPDATE')
self._block_ws(1)
self.visit(node.subject)
self._block_ws(-1)
self._visit_filter(node)
self.new_lines = 1
self._write_keywords('SET ')
self._visit_shape(node.shape)
if parenthesise:
self.write(')')
def visit_DeleteQuery(self, node: qlast.DeleteQuery) -> None:
# need to parenthesise when DELETE appears as an expression
parenthesise = self._needs_parentheses(node)
if parenthesise:
self.write('(')
self._visit_aliases(node)
self._write_keywords('DELETE')
self._block_ws(1)
self.visit(node.subject)
self._block_ws(-1)
self._visit_filter(node)
self._visit_order(node)
self._visit_offset_limit(node)
if parenthesise:
self.write(')')
def visit_SelectQuery(self, node: qlast.SelectQuery) -> None:
# XXX: need to parenthesise when SELECT appears as an expression,
# the actual passed value is ignored.
parenthesise = self._needs_parentheses(node)
if node.implicit:
parenthesise = parenthesise and bool(node.aliases)
if parenthesise:
self.write('(')
if not node.implicit or node.aliases:
self._visit_aliases(node)
self._write_keywords('SELECT')
self._block_ws(1)
if node.result_alias:
self.write(node.result_alias, ' := ')
self.visit(node.result)
if not node.implicit or node.aliases:
self._block_ws(-1)
else:
self.write(' ')
self._visit_filter(node)
self._visit_order(node)
self._visit_offset_limit(node)
if parenthesise:
self.write(')')
def visit_ForQuery(self, node: qlast.ForQuery) -> None:
# need to parenthesise when GROUP appears as an expression
parenthesise = self._needs_parentheses(node)
if parenthesise:
self.write('(')
self._visit_aliases(node)
self._write_keywords('FOR ')
self.write(ident_to_str(node.iterator_alias))
self._write_keywords(' IN ')
self.visit(node.iterator)
# guarantee an newline here
self.new_lines = 1
self._write_keywords('UNION ')
self._block_ws(1)
self.visit(node.result)
self.indentation -= 1
if parenthesise:
self.write(')')
def visit_GroupingIdentList(self, atom: qlast.GroupingIdentList) -> None:
self.write('(')
self.visit_list(atom.elements, newlines=False)
self.write(')')
def visit_GroupingSimple(self, node: qlast.GroupingSimple) -> None:
self.visit(node.element)
def visit_GroupingSets(self, node: qlast.GroupingSets) -> None:
self.write('{')
self.visit_list(node.sets, newlines=False)
self.write('}')
def visit_GroupingOperation(self, node: qlast.GroupingOperation) -> None:
self._write_keywords(node.oper)
self.write(' (')
self.visit_list(node.elements, newlines=False)
self.write(')')
def visit_GroupQuery(
self, node: qlast.GroupQuery, no_paren: bool=False) -> None:
# need to parenthesise when GROUP appears as an expression
parenthesise = self._needs_parentheses(node) and not no_paren
if parenthesise:
self.write('(')
self._visit_aliases(node)
if isinstance(node, qlast.InternalGroupQuery):
self._write_keywords('FOR ')
self._write_keywords('GROUP')
self._block_ws(1)
if node.subject_alias:
self.write(any_ident_to_str(node.subject_alias), ' := ')
self.visit(node.subject)
self._block_ws(-1)
if node.using is not None:
self._write_keywords('USING')
self._block_ws(1)
self.visit_list(node.using, newlines=False)
self._block_ws(-1)
self._write_keywords('BY ')
self.visit_list(node.by)
if parenthesise:
self.write(')')
def visit_InternalGroupQuery(self, node: qlast.InternalGroupQuery) -> None:
parenthesise = self._needs_parentheses(node)
if parenthesise:
self.write('(')
self.visit_GroupQuery(node, no_paren=True)
self._block_ws(0)
self._write_keywords('INTO ')
self.write(ident_to_str(node.group_alias))
if node.grouping_alias:
self.write(', ')
self.write(ident_to_str(node.grouping_alias))
self.write(' ')
self._block_ws(0)
self._write_keywords('UNION ')
self.visit(node.result)
if node.where:
self._write_keywords(' FILTER ')
self.visit(node.where)
if node.orderby:
self._write_keywords(' ORDER BY ')
self.visit_list(
node.orderby,
separator=self._kw_case(' THEN'), newlines=False
)
if parenthesise:
self.write(')')
def visit_ModuleAliasDecl(self, node: qlast.ModuleAliasDecl) -> None:
if node.alias:
self.write(ident_to_str(node.alias))
self._write_keywords(' AS ')
self._write_keywords('MODULE ')
self.write(any_ident_to_str(node.module))
def visit_SortExpr(self, node: qlast.SortExpr) -> None:
self.visit(node.path)
if node.direction:
self.write(' ')
self.write(node.direction)
if node.nones_order:
self._write_keywords(' EMPTY ')
self.write(node.nones_order.upper())
def visit_DetachedExpr(self, node: qlast.DetachedExpr) -> None:
self._write_keywords('DETACHED ')
self.visit(node.expr)
def visit_GlobalExpr(self, node: qlast.GlobalExpr) -> None:
self._write_keywords('GLOBAL ')
self.visit(node.name)
def visit_UnaryOp(self, node: qlast.UnaryOp) -> None:
op = str(node.op).upper()
self.write(op)
if op.isalnum():
self.write(' (')
self.visit(node.operand)
if op.isalnum():
self.write(')')
def visit_BinOp(self, node: qlast.BinOp) -> None:
self.write('(')
self.visit(node.left)
self.write(' ' + str(node.op).upper() + ' ')
self.visit(node.right)
self.write(')')
def visit_IsOp(self, node: qlast.IsOp) -> None:
self.write('(')
self.visit(node.left)
self.write(' ' + str(node.op).upper() + ' ')
self.visit(node.right)
self.write(')')
def visit_TypeOp(self, node: qlast.TypeOp) -> None:
self.write('(')
self.visit(node.left)
self.write(' ' + str(node.op).upper() + ' ')
self.visit(node.right)
self.write(')')
def visit_IfElse(self, node: qlast.IfElse) -> None:
self.write('(')
self.visit(node.if_expr)
self._write_keywords(' IF ')
self.visit(node.condition)
self._write_keywords(' ELSE ')
self.visit(node.else_expr)
self.write(')')
def visit_Tuple(self, node: qlast.Tuple) -> None:
self.write('(')
count = len(node.elements)
self.visit_list(node.elements, newlines=False)
if count == 1:
self.write(',')
self.write(')')
def visit_Set(self, node: qlast.Set) -> None:
self.write('{')
self.visit_list(node.elements, newlines=False)
self.write('}')
def visit_Array(self, node: qlast.Array) -> None:
self.write('[')
self.visit_list(node.elements, newlines=False)
self.write(']')
def visit_NamedTuple(self, node: qlast.NamedTuple) -> None:
self.write('(')
self._block_ws(1)
self.visit_list(node.elements, newlines=True, separator=',')
self._block_ws(-1)
self.write(')')
def visit_TupleElement(self, node: qlast.TupleElement) -> None:
self.visit(node.name)
self.write(' := ')
self.visit(node.val)
def visit_Path(self, node: qlast.Path) -> None:
for i, e in enumerate(node.steps):
if i > 0 or node.partial:
if (getattr(e, 'type', None) != 'property'
and not isinstance(e, qlast.TypeIntersection)):
self.write('.')
if i == 0:
if isinstance(e, qlast.ObjectRef):
self.visit(e)
elif isinstance(e, qlast.Anchor):
self.visit(e)
elif not isinstance(e, (qlast.Ptr,
qlast.Set,
qlast.Tuple,
qlast.NamedTuple,
qlast.TypeIntersection,
qlast.Parameter)):
self.write('(')
self.visit(e)
self.write(')')
else:
self.visit(e)
else:
self.visit(e)
def visit_Shape(self, node: qlast.Shape) -> None:
if node.expr is not None:
self.visit(node.expr)
self.write(' ')
self._visit_shape(node.elements)
def _visit_shape(self, shape: Sequence[qlast.ShapeElement]) -> None:
if shape:
self.write('{')
self._block_ws(1)
self.visit_list(shape)
self._block_ws(-1)
self.write('}')
def visit_Ptr(self, node: qlast.Ptr, *, quote: bool = True) -> None:
if node.type == 'property':
self.write('@')
elif node.direction and node.direction != '>':
self.write(node.direction)
self.visit(node.ptr)
def visit_TypeIntersection(self, node: qlast.TypeIntersection) -> None:
self._write_keywords('[IS ')
self.visit(node.type)
self.write(']')
def visit_ShapeElement(self, node: qlast.ShapeElement) -> None:
# PathSpec can only contain LinkExpr or LinkPropExpr,
# and must not be quoted.
quals = []
if node.required is not None:
if node.required:
quals.append('required')
else:
quals.append('optional')
if node.cardinality:
quals.append(node.cardinality.as_ptr_qual())
if quals:
self.write(*quals, delimiter=' ')
self.write(' ')
if len(node.expr.steps) == 1:
self.visit(node.expr)
else:
self.visit(node.expr.steps[0])
if not isinstance(node.expr.steps[1], qlast.TypeIntersection):
self.write('.')
self.visit(node.expr.steps[1])
if len(node.expr.steps) == 3:
self.visit(node.expr.steps[2])
if not node.compexpr and node.elements:
self.write(': ')
self._visit_shape(node.elements)
if node.where:
self._write_keywords(' FILTER ')
self.visit(node.where)
if node.orderby:
self._write_keywords(' ORDER BY ')
self.visit_list(
node.orderby,
separator=self._kw_case(' THEN'), newlines=False
)
if node.offset:
self._write_keywords(' OFFSET ')
self.visit(node.offset)
if node.limit:
self._write_keywords(' LIMIT ')
self.visit(node.limit)
if node.compexpr:
if node.operation is None:
raise AssertionError(
f'ShapeElement.operation is unexpectedly None'
)
if node.operation.op is qlast.ShapeOp.ASSIGN:
self.write(' := ')
elif node.operation.op is qlast.ShapeOp.APPEND:
self.write(' += ')
elif node.operation.op is qlast.ShapeOp.SUBTRACT:
self.write(' -= ')
else:
raise NotImplementedError(
f'unexpected shape operation: {node.operation.op!r}'
)
self.visit(node.compexpr)
def visit_Parameter(self, node: qlast.Parameter) -> None:
self.write(param_to_str(node.name))
def visit_Placeholder(self, node: qlast.Placeholder) -> None:
self.write('\\(')
self.write(node.name)
self.write(')')
def visit_StringConstant(self, node: qlast.StringConstant) -> None:
if not _NON_PRINTABLE_RE.search(node.value):
for d in ("'", '"', '$$'):
if d not in node.value:
if '\\' in node.value and d != '$$':
self.write('r', d, node.value, d)
else:
self.write(d, node.value, d)
return
self.write(edgeql_quote.dollar_quote_literal(node.value))
return
self.write(repr(node.value))
def visit_IntegerConstant(self, node: qlast.IntegerConstant) -> None:
if node.is_negative:
self.write('-')
self.write(node.value)
def visit_FloatConstant(self, node: qlast.FloatConstant) -> None:
if node.is_negative:
self.write('-')
self.write(node.value)
def visit_DecimalConstant(self, node: qlast.DecimalConstant) -> None:
if node.is_negative:
self.write('-')
self.write(node.value)
def visit_BigintConstant(self, node: qlast.BigintConstant) -> None:
if node.is_negative:
self.write('-')
self.write(node.value)
def visit_BooleanConstant(self, node: qlast.BooleanConstant) -> None:
self.write(node.value)
def visit_BytesConstant(self, node: qlast.BytesConstant) -> None:
val = _BYTES_ESCAPE_RE.sub(_bytes_escape, node.value)
self.write("b'", val.decode('utf-8', 'backslashreplace'), "'")
def visit_FunctionCall(self, node: qlast.FunctionCall) -> None:
if isinstance(node.func, tuple):
self.write(
f'{ident_to_str(node.func[0])}::{ident_to_str(node.func[1])}')
else:
self.write(ident_to_str(node.func))
self.write('(')
for i, arg in enumerate(node.args):
if i > 0:
self.write(', ')
self.visit(arg)
if node.kwargs:
if node.args:
self.write(', ')
for i, (name, arg) in enumerate(node.kwargs.items()):
if i > 0:
self.write(', ')
self.write(f'{edgeql_quote.quote_ident(name)} := ')
self.visit(arg)
self.write(')')
if node.window:
self._write_keywords(' OVER (')
self._block_ws(1)
if node.window.partition:
self._write_keywords('PARTITION BY ')
self.visit_list(node.window.partition, newlines=False)
self.new_lines = 1
if node.window.orderby:
self._write_keywords('ORDER BY ')
self.visit_list(
node.window.orderby, separator=self._kw_case(' THEN'))
self._block_ws(-1)
self.write(')')
def visit_AnyType(self, node: qlast.AnyType) -> None:
self.write('anytype')
def visit_AnyTuple(self, node: qlast.AnyTuple) -> None:
self.write('anytuple')
def visit_TypeCast(self, node: qlast.TypeCast) -> None:
self.write('<')
if node.cardinality_mod is qlast.CardinalityModifier.Optional:
self.write('optional ')
self.visit(node.type)
self.write('>')
self.visit(node.expr)
def visit_Indirection(self, node: qlast.Indirection) -> None:
self.write('(')
self.visit(node.arg)
self.write(')')
for indirection in node.indirection:
self.visit(indirection)
def visit_Slice(self, node: qlast.Slice) -> None:
self.write('[')
if node.start:
self.visit(node.start)
self.write(':')
if node.stop:
self.visit(node.stop)
self.write(']')
def visit_Index(self, node: qlast.Index) -> None:
self.write('[')
self.visit(node.index)
self.write(']')
def visit_ObjectRef(self, node: qlast.ObjectRef) -> None:
if node.itemclass:
self.write(node.itemclass)
self.write(' ')
if node.module:
self.write(ident_to_str(node.module))
self.write('::')
self.write(ident_to_str(node.name))
def visit_Anchor(self, node: qlast.Anchor) -> None:
self.write(node.name)
def visit_Subject(self, node: qlast.Subject) -> None:
self.write(node.name)
def visit_Source(self, node: qlast.Source) -> None:
self.write(node.name)
def visit_TypeExprLiteral(self, node: qlast.TypeExprLiteral) -> None:
self.visit(node.val)
def visit_TypeName(self, node: qlast.TypeName) -> None:
parenthesize = (
isinstance(node._parent, (qlast.IsOp, qlast.TypeOp, # type: ignore
qlast.Introspect)) and
node.subtypes is not None
)
if parenthesize:
self.write('(')
if node.name is not None:
self.write(ident_to_str(node.name), ': ')
if isinstance(node.maintype, qlast.Path):
self.visit(node.maintype)
else:
self.visit(node.maintype)
if node.subtypes is not None:
self.write('<')
self.visit_list(node.subtypes, newlines=False)
if node.dimensions is not None:
for dim in node.dimensions:
if dim is None:
self.write('[]')
else:
self.write('[', str(dim), ']')
self.write('>')
if parenthesize:
self.write(')')
def visit_Introspect(self, node: qlast.Introspect) -> None:
self.write('INTROSPECT ')
self.visit(node.type)
def visit_TypeOf(self, node: qlast.TypeOf) -> None:
self.write('TYPEOF ')
self.visit(node.expr)
# DDL nodes
def visit_Position(self, node: qlast.Position) -> None:
self.write(node.position)
if node.ref:
self.write(' ')
self.visit(node.ref)
def _ddl_visit_bases(self, node: qlast.BasesMixin) -> None:
if node.bases:
self._write_keywords(' EXTENDING ')
self.visit_list(node.bases, newlines=False)
def _ddl_clean_up_commands(
self,
commands: Sequence[qlast.Base],
) -> Sequence[qlast.Base]:
# Always omit orig_expr fields from output since we are
# using the original expression in TEXT output
# already.
return [
c for c in commands
if (
not isinstance(c, qlast.SetField)
or not c.name.startswith('orig_')
)
]
def _ddl_visit_body(
self,
commands: Sequence[qlast.Base],
group_by_system_comment: bool = False,
*,
allow_short: bool = False
) -> None:
if self.limit_ref_classes:
commands = [
c for c in commands
if (
not isinstance(c, qlast.ObjectDDL)
or c.name.itemclass in self.limit_ref_classes
)
]
commands = self._ddl_clean_up_commands(commands)
if len(commands) == 1 and allow_short and not (
isinstance(commands[0], qlast.ObjectDDL)
):
self.write(' ')
self.visit(commands[0])
elif len(commands) > 0:
self.write(' {')
self._block_ws(1)
if group_by_system_comment:
sort_key = lambda c: (
c.system_comment or '',
c.name.name if isinstance(c.name, qlast.ObjectRef)
else c.name
)
group_key = lambda c: c.system_comment or ''
if not self.unsorted:
commands = sorted(commands, key=sort_key)
groups = itertools.groupby(commands, group_key)
for i, (comment, items) in enumerate(groups):
if i > 0:
self.new_lines = 2
if comment:
self.write('#')
self.new_lines = 1
self.write(f'# {comment}')
self.new_lines = 1
self.write('#')
self.new_lines = 1
self.visit_list(list(items), terminator=';')
elif self.descmode or self.sdlmode:
sort_key = lambda c: (
(c.name.itemclass or '', c.name.name)
if isinstance(c, qlast.ObjectDDL)
else ('', c.name if isinstance(c, qlast.SetField) else '')
)
if not self.unsorted:
commands = sorted(commands, key=sort_key)
self.visit_list(list(commands), terminator=';')
else:
self.visit_list(list(commands), terminator=';')
self._block_ws(-1)
self.write('}')
def _visit_CreateObject(
self,
node: qlast.CreateObject,
*object_keywords: str,
after_name: Optional[Callable[[], None]] = None,
render_commands: bool = True,
unqualified: bool = False,
named: bool = True,
group_by_system_comment: bool = False
) -> None:
self._visit_aliases(node)
if self.sdlmode:
self.write(*[kw.lower() for kw in object_keywords], delimiter=' ')
else:
self._write_keywords('CREATE', *object_keywords)
if named:
self.write(' ')
if unqualified or not node.name.module:
self.write(ident_to_str(node.name.name))
else:
self.write(ident_to_str(node.name.module), '::',
ident_to_str(node.name.name))
if after_name:
after_name()
if node.create_if_not_exists and not self.sdlmode:
self._write_keywords(' IF NOT EXISTS')
commands = node.commands
if commands and render_commands:
self._ddl_visit_body(
commands,
group_by_system_comment=group_by_system_comment,
)
def _visit_AlterObject(
self,
node: qlast.AlterObject,
*object_keywords: str,
allow_short: bool = True,
after_name: Optional[Callable[[], None]] = None,
unqualified: bool = False,
named: bool = True,
ignored_cmds: Optional[AbstractSet[qlast.DDLOperation]] = None,
group_by_system_comment: bool = False,
ensure_endswith_block: bool = True
) -> None:
self._visit_aliases(node)
if self.sdlmode:
self.write(*[kw.lower() for kw in object_keywords], delimiter=' ')
else:
self._write_keywords('ALTER', *object_keywords)
if named:
self.write(' ')
if unqualified or not node.name.module:
self.write(ident_to_str(node.name.name))
else:
self.write(ident_to_str(node.name.module), '::',
ident_to_str(node.name.name))
if after_name:
after_name()
commands = node.commands
if ignored_cmds:
commands = [cmd for cmd in commands
if cmd not in ignored_cmds]
if commands:
self._ddl_visit_body(
commands,
group_by_system_comment=group_by_system_comment,
allow_short=allow_short,
)
else:
if ensure_endswith_block and not node.commands:
self._write_empty_block()
def _write_empty_block(self):
self.write(' {}')
def _visit_DropObject(
self,
node: qlast.DropObject,
*object_keywords: str,
unqualified: bool = False,
after_name: Optional[Callable[[], None]] = None,
named: bool = True
) -> None:
self._visit_aliases(node)
self._write_keywords('DROP', *object_keywords)
if named:
self.write(' ')
if unqualified or not node.name.module:
self.write(ident_to_str(node.name.name))
else:
self.write(ident_to_str(node.name.module), '::',
ident_to_str(node.name.name))