-
Notifications
You must be signed in to change notification settings - Fork 390
/
compiler.py
3358 lines (2885 loc) · 111 KB
/
compiler.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
from typing import (
Any,
Optional,
Tuple,
Union,
AbstractSet,
Iterable,
Mapping,
Sequence,
Dict,
List,
NamedTuple,
cast,
TYPE_CHECKING,
)
import dataclasses
import functools
import json
import hashlib
import pickle
import textwrap
import time
import uuid
import immutables
from edb import errors
from edb.common.typeutils import not_none
from edb.server import defines
from edb.server import config
from edb import edgeql
from edb.common import debug
from edb.common import verutils
from edb.common import uuidgen
from edb.edgeql import ast as qlast
from edb.edgeql import compiler as qlcompiler
from edb.edgeql import qltypes
from edb.ir import staeval as ireval
from edb.ir import ast as irast
from edb.schema import ddl as s_ddl
from edb.schema import delta as s_delta
from edb.schema import extensions as s_ext
from edb.schema import functions as s_func
from edb.schema import links as s_links
from edb.schema import properties as s_props
from edb.schema import modules as s_mod
from edb.schema import name as s_name
from edb.schema import objects as s_obj
from edb.schema import objtypes as s_objtypes
from edb.schema import pointers as s_pointers
from edb.schema import reflection as s_refl
from edb.schema import roles as s_role
from edb.schema import schema as s_schema
from edb.schema import types as s_types
from edb.schema import version as s_ver
from edb.pgsql import ast as pgast
from edb.pgsql import compiler as pg_compiler
from edb.pgsql import codegen as pg_codegen
from edb.pgsql import common as pg_common
from edb.pgsql import debug as pg_debug
from edb.pgsql import dbops as pg_dbops
from edb.pgsql import params as pg_params
from edb.pgsql import patches as pg_patches
from edb.pgsql import types as pg_types
from edb.pgsql import delta as pg_delta
from . import dbstate
from . import enums
from . import explain
from . import sertypes
from . import status
from . import ddl
from . import rpc
if TYPE_CHECKING:
from edb.pgsql import metaschema
EMPTY_MAP: immutables.Map[Any, Any] = immutables.Map()
@dataclasses.dataclass(frozen=True)
class CompilerDatabaseState:
user_schema: s_schema.Schema
global_schema: s_schema.Schema
cached_reflection: immutables.Map[str, Tuple[str, ...]]
@dataclasses.dataclass(frozen=True)
class CompileContext:
compiler_state: CompilerState
state: dbstate.CompilerConnectionState
output_format: enums.OutputFormat
expected_cardinality_one: bool
protocol_version: defines.ProtocolVersion
expect_rollback: bool = False
json_parameters: bool = False
schema_reflection_mode: bool = False
implicit_limit: int = 0
inline_typeids: bool = False
inline_typenames: bool = False
inline_objectids: bool = True
schema_object_ids: Optional[
Mapping[tuple[s_name.Name, Optional[str]], uuid.UUID]] = None
source: Optional[edgeql.Source] = None
backend_runtime_params: pg_params.BackendRuntimeParams = (
pg_params.get_default_runtime_params())
compat_ver: Optional[verutils.Version] = None
bootstrap_mode: bool = False
internal_schema_mode: bool = False
log_ddl_as_migrations: bool = True
dump_restore_mode: bool = False
notebook: bool = False
persistent_cache: bool = False
cache_key: Optional[uuid.UUID] = None
def _assert_not_in_migration_block(
self,
ql: qlast.Base
) -> None:
"""Check that a START MIGRATION block is *not* active."""
current_tx = self.state.current_tx()
mstate = current_tx.get_migration_state()
if mstate is not None:
stmt = status.get_status(ql).decode()
raise errors.QueryError(
f'cannot execute {stmt} in a migration block',
context=ql.context,
)
def _assert_in_migration_block(
self,
ql: qlast.Base
) -> dbstate.MigrationState:
"""Check that a START MIGRATION block *is* active."""
current_tx = self.state.current_tx()
mstate = current_tx.get_migration_state()
if mstate is None:
stmt = status.get_status(ql).decode()
raise errors.QueryError(
f'cannot execute {stmt} outside of a migration block',
context=ql.context,
)
return mstate
def _assert_not_in_migration_rewrite_block(
self,
ql: qlast.Base
) -> None:
"""Check that a START MIGRATION REWRITE block is *not* active."""
current_tx = self.state.current_tx()
mstate = current_tx.get_migration_rewrite_state()
if mstate is not None:
stmt = status.get_status(ql).decode()
raise errors.QueryError(
f'cannot execute {stmt} in a migration rewrite block',
context=ql.context,
)
def _assert_in_migration_rewrite_block(
self,
ql: qlast.Base
) -> dbstate.MigrationRewriteState:
"""Check that a START MIGRATION REWRITE block *is* active."""
current_tx = self.state.current_tx()
mstate = current_tx.get_migration_rewrite_state()
if mstate is None:
stmt = status.get_status(ql).decode()
raise errors.QueryError(
f'cannot execute {stmt} outside of a migration rewrite block',
context=ql.context,
)
return mstate
DEFAULT_MODULE_ALIASES_MAP: immutables.Map[Optional[str], str] = (
immutables.Map({None: defines.DEFAULT_MODULE_ALIAS}))
def compile_edgeql_script(
ctx: CompileContext,
eql: str,
) -> Tuple[s_schema.Schema, str]:
sql = _compile_ql_script(ctx, eql)
new_schema = ctx.state.current_tx().get_schema(
ctx.compiler_state.std_schema)
assert isinstance(new_schema, s_schema.ChainedSchema)
return new_schema.get_top_schema(), sql
def new_compiler(
std_schema: s_schema.Schema,
reflection_schema: s_schema.Schema,
schema_class_layout: s_refl.SchemaClassLayout,
*,
backend_runtime_params: Optional[pg_params.BackendRuntimeParams] = None,
local_intro_query: Optional[str] = None,
global_intro_query: Optional[str] = None,
config_spec: Optional[config.Spec] = None,
) -> Compiler:
"""Create and return a compiler instance."""
# XXX: THIS IS NOT GREAT
assert isinstance(std_schema, s_schema.FlatSchema)
assert isinstance(reflection_schema, s_schema.FlatSchema)
if not backend_runtime_params:
backend_runtime_params = pg_params.get_default_runtime_params()
if not config_spec:
config_spec = config.load_spec_from_schema(std_schema)
return Compiler(CompilerState(
std_schema=std_schema,
refl_schema=reflection_schema,
schema_class_layout=schema_class_layout,
backend_runtime_params=backend_runtime_params,
config_spec=config_spec,
local_intro_query=local_intro_query,
global_intro_query=global_intro_query,
))
async def new_compiler_from_pg(con: metaschema.PGConnection) -> Compiler:
num_patches = await get_patch_count(con)
std_schema, reflection_schema = await load_std_and_reflection_schema(
con, num_patches)
return new_compiler(
std_schema=std_schema,
reflection_schema=reflection_schema,
schema_class_layout=await load_schema_class_layout(
con, num_patches
),
local_intro_query=await load_schema_intro_query(
con, num_patches, 'local_intro_query'
),
global_intro_query=await load_schema_intro_query(
con, num_patches, 'global_intro_query'
),
config_spec=None,
)
def new_compiler_context(
*,
compiler_state: CompilerState,
user_schema: s_schema.Schema,
global_schema: s_schema.Schema=s_schema.EMPTY_SCHEMA,
modaliases: Optional[Mapping[Optional[str], str]] = None,
expected_cardinality_one: bool = False,
json_parameters: bool = False,
schema_reflection_mode: bool = False,
output_format: enums.OutputFormat = enums.OutputFormat.BINARY,
bootstrap_mode: bool = False,
internal_schema_mode: bool = False,
protocol_version: defines.ProtocolVersion = defines.CURRENT_PROTOCOL,
backend_runtime_params: pg_params.BackendRuntimeParams = (
pg_params.get_default_runtime_params()),
) -> CompileContext:
"""Create and return an ad-hoc compiler context."""
state = dbstate.CompilerConnectionState(
user_schema=user_schema,
global_schema=global_schema,
modaliases=immutables.Map(modaliases) if modaliases else EMPTY_MAP,
session_config=EMPTY_MAP,
database_config=EMPTY_MAP,
system_config=EMPTY_MAP,
cached_reflection=EMPTY_MAP,
)
ctx = CompileContext(
compiler_state=compiler_state,
state=state,
output_format=output_format,
expected_cardinality_one=expected_cardinality_one,
json_parameters=json_parameters,
schema_reflection_mode=schema_reflection_mode,
bootstrap_mode=bootstrap_mode,
internal_schema_mode=internal_schema_mode,
protocol_version=protocol_version,
backend_runtime_params=backend_runtime_params,
)
return ctx
async def get_patch_count(backend_conn: metaschema.PGConnection) -> int:
"""Get the number of applied patches."""
num_patches = await backend_conn.sql_fetch_val(
b'''
SELECT json::json from edgedbinstdata.instdata
WHERE key = 'num_patches';
''',
)
res: int = json.loads(num_patches) if num_patches else 0
return res
async def load_std_and_reflection_schema(
backend_conn: metaschema.PGConnection,
patches: int,
) -> tuple[s_schema.Schema, s_schema.Schema]:
vkey = pg_patches.get_version_key(patches)
# stdschema and reflschema are combined in one pickle to preserve sharing.
key = f"std_and_reflection_schema{vkey}"
data = await backend_conn.sql_fetch_val(
b"""
SELECT bin FROM edgedbinstdata.instdata
WHERE key = $1
""",
args=[key.encode("utf-8")],
)
try:
std_schema: s_schema.FlatSchema
refl_schema: s_schema.FlatSchema
std_schema, refl_schema = pickle.loads(data)
if vkey != pg_patches.get_version_key(len(pg_patches.PATCHES)):
std_schema = s_schema.upgrade_schema(std_schema)
refl_schema = s_schema.upgrade_schema(refl_schema)
return (std_schema, refl_schema)
except Exception as e:
raise RuntimeError(
'could not load std schema pickle') from e
async def load_schema_intro_query(
backend_conn: metaschema.PGConnection,
patches: int,
kind: str,
) -> str:
kind += pg_patches.get_version_key(patches)
return (await backend_conn.sql_fetch_val(
b"""
SELECT text FROM edgedbinstdata.instdata
WHERE key = $1::text;
""",
args=[kind.encode("utf-8")],
)).decode('utf-8')
async def load_schema_class_layout(
backend_conn: metaschema.PGConnection,
patches: int,
) -> s_refl.SchemaClassLayout:
key = f'classlayout{pg_patches.get_version_key(patches)}'
data = await backend_conn.sql_fetch_val(
b"""
SELECT bin FROM edgedbinstdata.instdata
WHERE key = $1::text;
""",
args=[key.encode("utf-8")],
)
try:
return cast(s_refl.SchemaClassLayout, pickle.loads(data))
except Exception as e:
raise RuntimeError(
'could not load schema class layout pickle') from e
@dataclasses.dataclass(frozen=True, kw_only=True)
class CompilerState:
std_schema: s_schema.FlatSchema
refl_schema: s_schema.FlatSchema
schema_class_layout: s_refl.SchemaClassLayout
backend_runtime_params: pg_params.BackendRuntimeParams
config_spec: config.Spec
local_intro_query: Optional[str]
global_intro_query: Optional[str]
@functools.cached_property
def state_serializer_factory(self) -> sertypes.StateSerializerFactory:
# TODO: This factory will probably need to become per-db once
# config spec differs between databases. See also #5836.
return sertypes.StateSerializerFactory(
self.std_schema, self.config_spec
)
@functools.cached_property
def compilation_config_serializer(self) -> sertypes.InputShapeSerializer:
return (
self.state_serializer_factory.make_compilation_config_serializer()
)
class Compiler:
state: CompilerState
def __init__(self, state: CompilerState):
self.state = state
@staticmethod
def _try_compile_rollback(eql: Union[edgeql.Source, bytes]) -> tuple[
dbstate.QueryUnitGroup, int
]:
source: Union[str, edgeql.Source]
if isinstance(eql, edgeql.Source):
source = eql
else:
source = eql.decode()
statements = edgeql.parse_block(source)
stmt = statements[0]
unit = None
if isinstance(stmt, qlast.RollbackTransaction):
sql = b'ROLLBACK;'
unit = dbstate.QueryUnit(
status=b'ROLLBACK',
sql=(sql,),
tx_rollback=True,
cacheable=False)
elif isinstance(stmt, qlast.RollbackToSavepoint):
sql = f'ROLLBACK TO {pg_common.quote_ident(stmt.name)};'.encode()
unit = dbstate.QueryUnit(
status=b'ROLLBACK TO SAVEPOINT',
sql=(sql,),
tx_savepoint_rollback=True,
sp_name=stmt.name,
cacheable=False)
if unit is not None:
rv = dbstate.QueryUnitGroup()
rv.append(unit)
return rv, len(statements) - 1
raise errors.TransactionError(
'expected a ROLLBACK or ROLLBACK TO SAVEPOINT command'
) # pragma: no cover
def compile_notebook(
self,
user_schema: s_schema.Schema,
global_schema: s_schema.Schema,
reflection_cache: immutables.Map[str, Tuple[str, ...]],
database_config: immutables.Map[str, config.SettingValue],
system_config: immutables.Map[str, config.SettingValue],
queries: List[str],
protocol_version: defines.ProtocolVersion,
implicit_limit: int = 0,
) -> List[
Tuple[
bool,
Union[dbstate.QueryUnit, Tuple[str, str, Dict[int, str]]]
]
]:
state = dbstate.CompilerConnectionState(
user_schema=user_schema,
global_schema=global_schema,
modaliases=DEFAULT_MODULE_ALIASES_MAP,
session_config=EMPTY_MAP,
database_config=database_config,
system_config=system_config,
cached_reflection=reflection_cache,
)
state.start_tx()
result: List[
Tuple[
bool,
Union[dbstate.QueryUnit, Tuple[str, str, Dict[int, str]]]
]
] = []
for query in queries:
try:
source = edgeql.Source.from_string(query)
ctx = CompileContext(
compiler_state=self.state,
state=state,
output_format=enums.OutputFormat.BINARY,
expected_cardinality_one=False,
implicit_limit=implicit_limit,
inline_typeids=False,
inline_typenames=True,
json_parameters=False,
source=source,
protocol_version=protocol_version,
notebook=True,
)
result.append(
(False, compile(ctx=ctx, source=source)[0]))
except Exception as ex:
fields = {}
typename = 'Error'
if (isinstance(ex, errors.EdgeDBError) and
type(ex) is not errors.EdgeDBError):
fields = ex._attrs
typename = type(ex).__name__
result.append(
(True, (typename, str(ex), fields)))
break
return result
def compile_sql(
self,
user_schema: s_schema.Schema,
global_schema: s_schema.Schema,
reflection_cache: immutables.Map[str, Tuple[str, ...]],
database_config: immutables.Map[str, config.SettingValue],
system_config: immutables.Map[str, config.SettingValue],
query_str: str,
tx_state: dbstate.SQLTransactionState,
prepared_stmt_map: Mapping[str, str],
current_database: str,
current_user: str,
) -> List[dbstate.SQLQueryUnit]:
state = dbstate.CompilerConnectionState(
user_schema=user_schema,
global_schema=global_schema,
modaliases=DEFAULT_MODULE_ALIASES_MAP,
session_config=EMPTY_MAP,
database_config=database_config,
system_config=system_config,
cached_reflection=reflection_cache,
)
schema = state.current_tx().get_schema(self.state.std_schema)
from edb.pgsql import parser as pg_parser
from edb.pgsql import resolver as pg_resolver
from edb.pgsql import codegen as pg_codegen
@functools.cache
def parse_search_path(search_path_str: str) -> list[str]:
search_path_stmt = pg_parser.parse(
f"SET search_path = {search_path_str}"
)[0]
assert isinstance(search_path_stmt, pgast.VariableSetStmt)
return [
arg.val for arg in search_path_stmt.args.args
if isinstance(arg, pgast.StringConstant)
]
def translate_query(stmt: pgast.Base) -> pg_codegen.SQLSource:
args = {}
try:
search_path = tx_state.get("search_path")
except KeyError:
search_path = None
if isinstance(search_path, str):
args['search_path'] = parse_search_path(search_path)
options = pg_resolver.Options(
current_user=current_user,
current_database=current_database,
current_query=query_str,
**args
)
resolved = pg_resolver.resolve(stmt, schema, options)
return pg_codegen.generate(
resolved, with_translation_data=True
)
def compute_stmt_name(text: str) -> str:
stmt_hash = hashlib.sha1(text.encode("utf-8"))
for setting_name in sorted(fe_settings_mutable):
try:
setting_value = tx_state.get(setting_name)
except KeyError:
pass
else:
stmt_hash.update(
f"{setting_name}:{setting_value}".encode("utf-8"))
return f"edb{stmt_hash.hexdigest()}"
pg_gen_source = functools.partial(
pg_codegen.generate_source, pretty=False)
# frontend-only settings (key) and their mutability (value)
fe_settings_mutable = {
'search_path': True,
'server_version': False,
'server_version_num': False,
}
stmts = pg_parser.parse(query_str)
sql_units = []
for stmt in stmts:
orig_text = pg_gen_source(stmt)
if debug.flags.sql_input:
debug.header('SQL Input')
debug.dump_code(
pg_codegen.generate_source(stmt, pretty=True), lexer='sql'
)
unit_ctor = functools.partial(
dbstate.SQLQueryUnit,
orig_query=orig_text,
fe_settings=tx_state.current_fe_settings(),
)
if isinstance(stmt, pgast.VariableSetStmt):
# GOTCHA: setting is frontend-only regardless of its mutability
fe_only = stmt.name in fe_settings_mutable
args = {
"query": orig_text,
"frontend_only": fe_only,
"command_tag": b"SET",
"is_local": stmt.scope == pgast.OptionsScope.TRANSACTION,
}
if fe_only:
if not fe_settings_mutable[stmt.name]:
raise errors.QueryError(
f'parameter "{stmt.name}" cannot be changed',
pgext_code='55P02', # cant_change_runtime_param
)
value = pg_codegen.generate_source(stmt.args)
args["set_vars"] = {stmt.name: value}
elif stmt.scope == pgast.OptionsScope.SESSION:
if len(stmt.args.args) == 1 and isinstance(
stmt.args.args[0], pgast.StringConstant
):
# this value is unquoted for restoring state in pgcon
value = stmt.args.args[0].val
else:
value = pg_gen_source(stmt.args)
args["set_vars"] = {stmt.name: value}
unit = unit_ctor(**args)
elif isinstance(stmt, pgast.VariableResetStmt):
fe_only = stmt.name in fe_settings_mutable
if (
fe_only and stmt.name
and not fe_settings_mutable[stmt.name]
):
raise errors.QueryError(
f'parameter "{stmt.name}" cannot be changed',
pgext_code='55P02', # cant_change_runtime_param
)
args = {
"query": orig_text,
"frontend_only": fe_only,
"command_tag": b"RESET",
"is_local": stmt.scope == pgast.OptionsScope.TRANSACTION,
}
if fe_only or stmt.scope == pgast.OptionsScope.SESSION:
args["set_vars"] = {stmt.name: None}
unit = unit_ctor(**args)
elif isinstance(stmt, pgast.VariableShowStmt):
unit = unit_ctor(
query=orig_text,
get_var=stmt.name,
frontend_only=stmt.name in fe_settings_mutable,
command_tag=b"SHOW",
)
elif isinstance(stmt, pgast.SetTransactionStmt):
args = {"query": orig_text}
if stmt.scope == pgast.OptionsScope.SESSION:
args["set_vars"] = {
f"default_{name}": value.val
if isinstance(value, pgast.StringConstant)
else pg_gen_source(value)
for name, value in stmt.options.options.items()
}
unit = unit_ctor(**args)
elif isinstance(stmt, (pgast.BeginStmt, pgast.StartStmt)):
unit = unit_ctor(
query=orig_text,
tx_action=dbstate.TxAction.START,
)
elif isinstance(stmt, pgast.CommitStmt):
unit = unit_ctor(
query=orig_text,
tx_action=dbstate.TxAction.COMMIT,
tx_chain=stmt.chain or False,
)
elif isinstance(stmt, pgast.RollbackStmt):
unit = unit_ctor(
query=orig_text,
tx_action=dbstate.TxAction.ROLLBACK,
tx_chain=stmt.chain or False,
)
elif isinstance(stmt, pgast.SavepointStmt):
unit = unit_ctor(
query=orig_text,
tx_action=dbstate.TxAction.DECLARE_SAVEPOINT,
sp_name=stmt.savepoint_name,
)
elif isinstance(stmt, pgast.ReleaseStmt):
unit = unit_ctor(
query=orig_text,
tx_action=dbstate.TxAction.RELEASE_SAVEPOINT,
sp_name=stmt.savepoint_name,
)
elif isinstance(stmt, pgast.RollbackToStmt):
unit = unit_ctor(
query=orig_text,
tx_action=dbstate.TxAction.ROLLBACK_TO_SAVEPOINT,
sp_name=stmt.savepoint_name,
)
elif isinstance(stmt, pgast.TwoPhaseTransactionStmt):
raise NotImplementedError(
"two-phase transactions are not supported"
)
elif isinstance(stmt, pgast.PrepareStmt):
# Translate the underlying query.
stmt_source = translate_query(stmt.query)
if stmt.argtypes:
param_types = []
for pt in stmt.argtypes:
param_types.append(pg_gen_source(pt))
param_text = f"({', '.join(param_types)})"
else:
param_text = ""
sql_trailer = f"{param_text} AS ({stmt_source.text})"
mangled_stmt_name = compute_stmt_name(
f"PREPARE {pg_common.quote_ident(stmt.name)}{sql_trailer}"
)
sql_text = (
f"PREPARE {pg_common.quote_ident(mangled_stmt_name)}"
f"{sql_trailer}"
)
unit = unit_ctor(
query=sql_text,
prepare=dbstate.PrepareData(
stmt_name=stmt.name,
be_stmt_name=mangled_stmt_name.encode("utf-8"),
query=stmt_source.text,
translation_data=stmt_source.translation_data,
),
command_tag=b"PREPARE",
)
elif isinstance(stmt, pgast.ExecuteStmt):
orig_name = stmt.name
mangled_name = prepared_stmt_map.get(orig_name)
if not mangled_name:
raise errors.QueryError(
f"prepared statement \"{orig_name}\" does "
f"not exist",
pgext_code='26000', # invalid_sql_statement_name
)
stmt.name = mangled_name
unit = unit_ctor(
query=pg_gen_source(stmt),
execute=dbstate.ExecuteData(
stmt_name=orig_name,
be_stmt_name=mangled_name.encode("utf-8"),
),
)
elif isinstance(stmt, pgast.DeallocateStmt):
orig_name = stmt.name
mangled_name = prepared_stmt_map.get(orig_name)
if not mangled_name:
raise errors.QueryError(
f"prepared statement \"{orig_name}\" does "
f"not exist",
pgext_code='26000', # invalid_sql_statement_name
)
stmt.name = mangled_name
unit = unit_ctor(
query=pg_gen_source(stmt),
deallocate=dbstate.DeallocateData(
stmt_name=orig_name,
be_stmt_name=mangled_name.encode("utf-8"),
),
command_tag=b"DEALLOCATE",
)
elif isinstance(stmt, pgast.LockStmt):
if stmt.mode not in ('ACCESS SHARE', 'ROW SHARE', 'SHARE'):
raise NotImplementedError(
"exclusive lock is not supported"
)
# just ignore
unit = unit_ctor(query="DO $$ BEGIN END $$;")
else:
source = translate_query(stmt)
unit = unit_ctor(
query=source.text,
translation_data=source.translation_data,
)
if debug.flags.sql_output:
debug.header('SQL Output')
debug.dump_code(unit.query, lexer='sql')
unit.stmt_name = compute_stmt_name(unit.query).encode("utf-8")
tx_state.apply(unit)
sql_units.append(unit)
if not sql_units:
# Cluvio will try to execute an empty query
sql_units.append(dbstate.SQLQueryUnit(
orig_query='',
query='',
fe_settings=tx_state.current_fe_settings()
))
return sql_units
def compile_request(
self,
user_schema: s_schema.Schema,
global_schema: s_schema.Schema,
reflection_cache: immutables.Map[str, Tuple[str, ...]],
database_config: Optional[immutables.Map[str, config.SettingValue]],
system_config: Optional[immutables.Map[str, config.SettingValue]],
serialized_request: bytes,
original_query: str,
) -> Tuple[
dbstate.QueryUnitGroup, Optional[dbstate.CompilerConnectionState]
]:
request = rpc.CompilationRequest(
self.state.compilation_config_serializer
)
request.deserialize(serialized_request, original_query)
units, cstate = self.compile(
user_schema,
global_schema,
reflection_cache,
database_config,
system_config,
request.source,
request.modaliases,
request.session_config,
request.output_format,
request.expect_one,
request.implicit_limit,
request.inline_typeids,
request.inline_typenames,
request.protocol_version,
request.inline_objectids,
request.json_parameters,
persistent_cache=True,
cache_key=request.get_cache_key(),
)
return units, cstate
def compile(
self,
user_schema: s_schema.Schema,
global_schema: s_schema.Schema,
reflection_cache: immutables.Map[str, Tuple[str, ...]],
database_config: Optional[immutables.Map[str, config.SettingValue]],
system_config: Optional[immutables.Map[str, config.SettingValue]],
source: edgeql.Source,
sess_modaliases: Optional[immutables.Map[Optional[str], str]],
sess_config: Optional[immutables.Map[str, config.SettingValue]],
output_format: enums.OutputFormat,
expect_one: bool,
implicit_limit: int,
inline_typeids: bool,
inline_typenames: bool,
protocol_version: defines.ProtocolVersion,
inline_objectids: bool = True,
json_parameters: bool = False,
persistent_cache: bool = False,
cache_key: Optional[uuid.UUID] = None,
) -> Tuple[dbstate.QueryUnitGroup,
Optional[dbstate.CompilerConnectionState]]:
if sess_config is None:
sess_config = EMPTY_MAP
if database_config is None:
database_config = EMPTY_MAP
if system_config is None:
system_config = EMPTY_MAP
if sess_modaliases is None:
sess_modaliases = DEFAULT_MODULE_ALIASES_MAP
state = dbstate.CompilerConnectionState(
user_schema=user_schema,
global_schema=global_schema,
modaliases=sess_modaliases,
session_config=sess_config,
database_config=database_config,
system_config=system_config,
cached_reflection=reflection_cache,
)
ctx = CompileContext(
compiler_state=self.state,
state=state,
output_format=output_format,
expected_cardinality_one=expect_one,
implicit_limit=implicit_limit,
inline_typeids=inline_typeids,
inline_typenames=inline_typenames,
inline_objectids=inline_objectids,
json_parameters=json_parameters,
source=source,
protocol_version=protocol_version,
persistent_cache=persistent_cache,
cache_key=cache_key,
)
unit_group = compile(ctx=ctx, source=source)
tx_started = False
for unit in unit_group:
if unit.tx_id:
tx_started = True
break
if tx_started:
return unit_group, ctx.state
else:
return unit_group, None
def compile_in_tx_request(
self,
state: dbstate.CompilerConnectionState,
txid: int,
serialized_request: bytes,
original_query: str,
expect_rollback: bool = False,
) -> Tuple[
dbstate.QueryUnitGroup, Optional[dbstate.CompilerConnectionState]
]:
request = rpc.CompilationRequest(
self.state.compilation_config_serializer
)
request.deserialize(serialized_request, original_query)
units, cstate = self.compile_in_tx(
state,
txid,
request.source,
request.output_format,
request.expect_one,
request.implicit_limit,
request.inline_typeids,
request.inline_typenames,
request.protocol_version,
request.inline_objectids,
request.json_parameters,
expect_rollback=expect_rollback,
persistent_cache=True,
cache_key=request.get_cache_key(),
)
return units, cstate
def compile_in_tx(
self,
state: dbstate.CompilerConnectionState,
txid: int,
source: edgeql.Source,
output_format: enums.OutputFormat,
expect_one: bool,
implicit_limit: int,
inline_typeids: bool,
inline_typenames: bool,
protocol_version: defines.ProtocolVersion,
inline_objectids: bool = True,
json_parameters: bool = False,
expect_rollback: bool = False,
persistent_cache: bool = False,
cache_key: Optional[uuid.UUID] = None,
) -> Tuple[dbstate.QueryUnitGroup, dbstate.CompilerConnectionState]:
if (