-
Notifications
You must be signed in to change notification settings - Fork 390
/
execute.pyx
960 lines (831 loc) · 32.6 KB
/
execute.pyx
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
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2019-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 typing import (
Any,
Mapping,
Optional,
)
from edgedb import scram
import asyncio
import base64
import decimal
import hashlib
import json
import logging
import immutables
from edb import errors
from edb.common import debug
from edb import edgeql
from edb.edgeql import qltypes
from edb.server import compiler
from edb.server import config
from edb.server import defines as edbdef
from edb.server.compiler import errormech
from edb.server.compiler cimport rpc
from edb.server.dbview cimport dbview
from edb.server.protocol cimport args_ser
from edb.server.protocol cimport frontend
from edb.server.pgcon cimport pgcon
from edb.server.pgcon import errors as pgerror
cdef object logger = logging.getLogger('edb.server')
cdef object FMT_NONE = compiler.OutputFormat.NONE
cdef WriteBuffer NO_ARGS = args_ser.combine_raw_args()
cdef class ExecutionGroup:
def __cinit__(self):
self.group = compiler.QueryUnitGroup()
self.bind_datas = []
cdef append(self, object query_unit, WriteBuffer bind_data=NO_ARGS):
self.group.append(query_unit, serialize=False)
self.bind_datas.append(bind_data)
async def execute(
self,
pgcon.PGConnection be_conn,
dbview.DatabaseConnectionView dbv,
fe_conn: frontend.AbstractFrontendConnection = None,
bytes state = None,
):
cdef int dbver
rv = None
async with be_conn.parse_execute_script_context():
dbver = dbv.dbver
parse_array = [False] * len(self.group)
be_conn.send_query_unit_group(
self.group,
True, # sync
self.bind_datas,
state,
0, # start
len(self.group), # end
dbver,
parse_array,
)
if state is not None:
await be_conn.wait_for_state_resp(state, state_sync=0)
for i, unit in enumerate(self.group):
if unit.output_format == FMT_NONE:
for sql in unit.sql:
await be_conn.wait_for_command(
unit, parse_array[i], dbver, ignore_data=True
)
rv = None
else:
for sql in unit.sql:
rv = await be_conn.wait_for_command(
unit, parse_array[i], dbver,
ignore_data=False,
fe_conn=fe_conn,
)
return rv
cdef ExecutionGroup build_cache_persistence_units(
pairs: list[tuple[rpc.CompilationRequest, compiler.QueryUnitGroup]],
ExecutionGroup group = None,
):
if group is None:
group = ExecutionGroup()
insert_sql = b'''
INSERT INTO "edgedb"."_query_cache"
("key", "schema_version", "input", "output", "evict")
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (key) DO UPDATE SET
"schema_version"=$2, "input"=$3, "output"=$4, "evict"=$5
'''
sql_hash = hashlib.sha1(insert_sql).hexdigest().encode('latin1')
for request, units in pairs:
# FIXME: this is temporary; drop this assertion when we support scripts
assert len(units) == 1
query_unit = units[0]
assert query_unit.cache_sql is not None
persist, evict = query_unit.cache_sql
serialized_result = units.maybe_get_serialized(0)
assert serialized_result is not None
if evict:
group.append(compiler.QueryUnit(sql=(evict,), status=b''))
if persist:
group.append(compiler.QueryUnit(sql=(persist,), status=b''))
group.append(
compiler.QueryUnit(
sql=(insert_sql,), sql_hash=sql_hash, status=b'',
),
args_ser.combine_raw_args((
query_unit.cache_key.bytes,
query_unit.user_schema_version.bytes,
request.serialize(),
serialized_result,
evict,
)),
)
return group
async def persist_cache(
be_conn: pgcon.PGConnection,
dbv: dbview.DatabaseConnectionView,
pairs: list[tuple[rpc.CompilationRequest, compiler.QueryUnitGroup]],
):
cdef group = build_cache_persistence_units(pairs)
try:
await group.execute(be_conn, dbv)
except Exception as ex:
if (
isinstance(ex, pgerror.BackendError)
and ex.code_is(pgerror.ERROR_SERIALIZATION_FAILURE)
# If we are in a transaction, we have to let the error
# propagate, since we can't do anything else after the error.
# Hopefully the client will retry, hit the cache, and
# everything will be fine.
and not dbv.in_tx()
):
# XXX: Is it OK to just ignore it? Can we rely on the conflict
# having set it to the same thing?
pass
else:
dbv.on_error()
raise
else:
signal_query_cache_changes(dbv)
# TODO: can we merge execute and execute_script?
async def execute(
be_conn: pgcon.PGConnection,
dbv: dbview.DatabaseConnectionView,
compiled: dbview.CompiledQuery,
bind_args: bytes,
*,
fe_conn: frontend.AbstractFrontendConnection = None,
use_prep_stmt: bint = False,
):
cdef:
bytes state = None, orig_state = None
WriteBuffer bound_args_buf
ExecutionGroup group
query_unit = compiled.query_unit_group[0]
if not dbv.in_tx():
orig_state = state = dbv.serialize_state()
new_types = None
server = dbv.server
tenant = dbv.tenant
data = None
try:
if be_conn.last_state == state:
# the current status in be_conn is in sync with dbview, skip the
# state restoring
state = None
dbv.start(query_unit)
if query_unit.create_db_template:
await tenant.on_before_create_db_from_template(
query_unit.create_db_template,
dbv.dbname,
)
if query_unit.drop_db:
await tenant.on_before_drop_db(
query_unit.drop_db,
dbv.dbname,
close_frontend_conns=query_unit.drop_db_reset_connections,
)
if query_unit.system_config:
await execute_system_config(be_conn, dbv, query_unit, state)
else:
config_ops = query_unit.config_ops
if query_unit.sql:
if query_unit.user_schema:
ddl_ret = await be_conn.run_ddl(query_unit, state)
if ddl_ret and ddl_ret['new_types']:
new_types = ddl_ret['new_types']
else:
bound_args_buf = args_ser.recode_bind_args(
dbv, compiled, bind_args)
assert not (query_unit.database_config
and query_unit.needs_readback), (
"needs_readback+database_config must use execute_script"
)
read_data = (
query_unit.needs_readback or query_unit.is_explain)
if compiled.request and query_unit.cache_sql:
group = build_cache_persistence_units(
[(compiled.request, compiled.query_unit_group)]
)
if not use_prep_stmt:
query_unit.sql_hash = b''
group.append(query_unit, bound_args_buf)
data = await group.execute(
be_conn,
dbv,
fe_conn=fe_conn if not read_data else None,
state=state,
)
else:
data = await be_conn.parse_execute(
query=query_unit,
fe_conn=fe_conn if not read_data else None,
bind_data=bound_args_buf,
use_prep_stmt=use_prep_stmt,
state=state,
dbver=dbv.dbver,
)
if query_unit.needs_readback and data:
config_ops = [
config.Operation.from_json(r[0][1:])
for r in data
]
if query_unit.is_explain:
# Go back to the compiler pool to analyze
# the explain output.
compiler_pool = server.get_compiler_pool()
r = await compiler_pool.analyze_explain_output(
query_unit.query_asts, data
)
buf = WriteBuffer.new_message(b'D')
buf.write_int16(1) # 1 column
buf.write_len_prefixed_bytes(r)
fe_conn.write(buf.end_message())
if state is not None:
# state is restored, clear orig_state so that we can
# set be_conn.last_state correctly later
orig_state = None
if query_unit.tx_savepoint_rollback:
dbv.rollback_tx_to_savepoint(query_unit.sp_name)
if query_unit.tx_savepoint_declare:
dbv.declare_savepoint(
query_unit.sp_name, query_unit.sp_id)
if query_unit.create_db_template:
try:
await tenant.on_after_create_db_from_template(
query_unit.create_db,
query_unit.create_db_template,
query_unit.create_db_mode,
)
except Exception:
# Clean up the database if we failed to restore into it.
# TODO: Is it worth having 'ready' flag that we set after
# the database is fully set up, and use that to clean up
# databases where a crash prevented doing this cleanup?
db_name = f'{tenant.tenant_id}_{query_unit.create_db}'
await be_conn.sql_execute(
b'drop database "%s"' % db_name.encode('utf-8')
)
raise
if query_unit.create_db:
await tenant.introspect_db(query_unit.create_db)
if query_unit.drop_db:
tenant.on_after_drop_db(query_unit.drop_db)
if config_ops:
await dbv.apply_config_ops(be_conn, config_ops)
except Exception as ex:
# If we made schema changes, include the new schema in the
# exception so that it can be used when interpreting.
if query_unit.user_schema:
if isinstance(ex, pgerror.BackendError):
ex._user_schema = query_unit.user_schema
dbv.on_error()
if query_unit.tx_commit and not be_conn.in_tx() and dbv.in_tx():
# The COMMIT command has failed. Our Postgres connection
# isn't in a transaction anymore. Abort the transaction
# in dbview.
dbv.abort_tx()
raise
else:
side_effects = dbv.on_success(query_unit, new_types)
state_serializer = compiled.query_unit_group.state_serializer
if state_serializer is not None:
dbv.set_state_serializer(state_serializer)
if side_effects:
signal_side_effects(dbv, side_effects)
if not dbv.in_tx() and not query_unit.tx_rollback and query_unit.sql:
state = dbv.serialize_state()
if state is not orig_state:
# In 3 cases the state is changed:
# 1. The non-tx query changed the state
# 2. The state is synced with dbview (orig_state is None)
# 3. We came out from a transaction (orig_state is None)
# Excluding two special case when the state is NOT changed:
# 1. An orphan ROLLBACK command without a paring start tx
# 2. There was no SQL, so the state can't have been synced.
be_conn.last_state = state
if (
not dbv.in_tx()
and not query_unit.tx_rollback
and query_unit.user_schema
and server.config_lookup(
"auto_rebuild_query_cache",
dbv.get_session_config(),
dbv.get_database_config(),
dbv.get_system_config(),
)
):
# TODO(fantix): recompile first and update cache in tx
if debug.flags.func_cache:
recompile_requests = await dbv.clear_cache_keys(be_conn)
else:
recompile_requests = [
req
for req, (grp, _) in dbv._db._eql_to_compiled.items()
if len(grp) == 1
]
await dbv.recompile_all(be_conn, recompile_requests)
finally:
if query_unit.drop_db:
tenant.allow_database_connections(query_unit.drop_db)
return data
async def execute_script(
conn: pgcon.PGConnection,
dbv: dbview.DatabaseConnectionView,
compiled: dbview.CompiledQuery,
bind_args: bytes,
*,
fe_conn: Optional[frontend.AbstractFrontendConnection],
):
cdef:
bytes state = None, orig_state = None
ssize_t sent = 0
bint in_tx, sync, no_sync
object user_schema, extensions, ext_config_settings, cached_reflection
object global_schema, roles
WriteBuffer bind_data
int dbver = dbv.dbver
bint parse
user_schema = extensions = ext_config_settings = cached_reflection = None
global_schema = roles = None
unit_group = compiled.query_unit_group
sync = False
no_sync = False
in_tx = dbv.in_tx()
if not in_tx:
orig_state = state = dbv.serialize_state()
data = None
try:
if conn.last_state == state:
# the current status in be_conn is in sync with dbview, skip the
# state restoring
state = None
async with conn.parse_execute_script_context():
parse_array = [False] * len(unit_group)
for idx, query_unit in enumerate(unit_group):
if fe_conn is not None and fe_conn.cancelled:
raise ConnectionAbortedError
assert not query_unit.is_explain
# XXX: pull out?
# We want to minimize the round trips we need to make, so
# ideally we buffer up everything, send it once, and then issue
# one SYNC. This gets messed up if there are commands where
# we need to read back information, though, such as SET GLOBAL.
#
# Because of that, we look for the next command that
# needs read back (probably there won't be one!), and
# execute everything up to that point at once,
# finished by a FLUSH.
if idx >= sent:
no_sync = False
for n in range(idx, len(unit_group)):
ng = unit_group[n]
if ng.ddl_stmt_id or ng.needs_readback:
sent = n + 1
if ng.needs_readback:
no_sync = True
break
else:
sent = len(unit_group)
sync = sent == len(unit_group) and not no_sync
bind_array = args_ser.recode_bind_args_for_script(
dbv, compiled, bind_args, idx, sent)
dbver = dbv.dbver
conn.send_query_unit_group(
unit_group,
sync,
bind_array,
state,
idx,
sent,
dbver,
parse_array,
)
if idx == 0 and state is not None:
await conn.wait_for_state_resp(state, state_sync=0)
# state is restored, clear orig_state so that we can
# set conn.last_state correctly later
orig_state = None
new_types = None
dbv.start_implicit(query_unit)
config_ops = query_unit.config_ops
if query_unit.user_schema:
user_schema = query_unit.user_schema
extensions = query_unit.extensions
ext_config_settings = query_unit.ext_config_settings
cached_reflection = query_unit.cached_reflection
if query_unit.global_schema:
global_schema = query_unit.global_schema
roles = query_unit.roles
if query_unit.sql:
parse = parse_array[idx]
if query_unit.ddl_stmt_id:
ddl_ret = await conn.handle_ddl_in_script(
query_unit, parse, dbver
)
if ddl_ret and ddl_ret['new_types']:
new_types = ddl_ret['new_types']
elif query_unit.needs_readback:
config_data = []
for sql in query_unit.sql:
config_data = await conn.wait_for_command(
query_unit, parse, dbver, ignore_data=False
)
if config_data:
config_ops = [
config.Operation.from_json(r[0][1:])
for r in config_data
]
elif query_unit.output_format == FMT_NONE:
for sql in query_unit.sql:
await conn.wait_for_command(
query_unit, parse, dbver, ignore_data=True
)
else:
for sql in query_unit.sql:
data = await conn.wait_for_command(
query_unit, parse, dbver,
ignore_data=False,
fe_conn=fe_conn,
)
if config_ops:
await dbv.apply_config_ops(conn, config_ops)
side_effects = dbv.on_success(query_unit, new_types)
if side_effects:
raise errors.InternalServerError(
"Side-effects in implicit transaction!"
)
except Exception as e:
dbv.on_error()
# Include the new schema in the exception so that it can be
# used when interpreting.
if isinstance(e, pgerror.BackendError):
e._user_schema = dbv.get_user_schema_pickle()
if not in_tx and dbv.in_tx():
# Abort the implicit transaction
dbv.abort_tx()
# If something went wrong that is *not* on the backend side, force
# an error to occur on the SQL side.
if not isinstance(e, pgerror.BackendError):
await conn.force_error()
raise
else:
if not in_tx:
side_effects = dbv.commit_implicit_tx(
user_schema,
extensions,
ext_config_settings,
global_schema,
roles,
cached_reflection,
)
if side_effects:
signal_side_effects(dbv, side_effects)
state = dbv.serialize_state()
if state is not orig_state:
conn.last_state = state
if unit_group.state_serializer is not None:
dbv.set_state_serializer(unit_group.state_serializer)
if (
not in_tx
and any(query_unit.user_schema for query_unit in unit_group)
and dbv.server.config_lookup(
"auto_rebuild_query_cache",
dbv.get_session_config(),
dbv.get_database_config(),
dbv.get_system_config(),
)
):
# TODO(fantix): recompile first and update cache in tx
if debug.flags.func_cache:
recompile_requests = await dbv.clear_cache_keys(conn)
else:
recompile_requests = [
req
for req, (grp, _) in dbv._db._eql_to_compiled.items()
if len(grp) == 1
]
await dbv.recompile_all(conn, recompile_requests)
finally:
if sent and not sync:
await conn.sync()
return data
async def execute_system_config(
conn: pgcon.PGConnection,
dbv: dbview.DatabaseConnectionView,
query_unit: compiler.QueryUnit,
state: bytes,
):
if query_unit.is_system_config:
dbv.server.before_alter_system_config()
# Sync state
await conn.sql_fetch(b'select 1', state=state)
if query_unit.sql:
if len(query_unit.sql) > 1:
raise errors.InternalServerError(
"unexpected multiple SQL statements in CONFIGURE INSTANCE "
"compilation product"
)
data = await conn.sql_fetch_col(query_unit.sql[0])
else:
data = None
if data:
# Prefer encoded op produced by the SQL command.
if data[0][0] != 0x01:
raise errors.InternalServerError(
f"unexpected JSONB version produced by SQL statement for "
f"CONFIGURE INSTANCE: {data[0][0]}"
)
config_ops = [config.Operation.from_json(r[1:]) for r in data]
else:
# Otherwise, fall back to staticly evaluated op.
config_ops = query_unit.config_ops
await dbv.apply_config_ops(conn, config_ops)
await conn.sql_execute(b'delete from _config_cache')
# If this is a backend configuration setting we also
# need to make sure it has been loaded.
if query_unit.backend_config:
await conn.sql_execute(b'SELECT pg_reload_conf()')
def signal_side_effects(dbv, side_effects):
tenant = dbv.tenant
if not tenant.accept_new_tasks:
return
if side_effects & dbview.SideEffects.SchemaChanges:
tenant.create_task(
tenant.signal_sysevent(
'schema-changes',
dbname=dbv.dbname,
),
interruptable=False,
)
if side_effects & dbview.SideEffects.GlobalSchemaChanges:
tenant.create_task(
tenant.signal_sysevent(
'global-schema-changes',
),
interruptable=False,
)
if side_effects & dbview.SideEffects.DatabaseConfigChanges:
tenant.create_task(
tenant.signal_sysevent(
'database-config-changes',
dbname=dbv.dbname,
),
interruptable=False,
)
if side_effects & dbview.SideEffects.DatabaseChanges:
tenant.create_task(
tenant.signal_sysevent(
'database-changes',
),
interruptable=False,
)
if side_effects & dbview.SideEffects.InstanceConfigChanges:
tenant.create_task(
tenant.signal_sysevent(
'system-config-changes',
),
interruptable=False,
)
def signal_query_cache_changes(dbv):
# FIXME: This is disabled because the increased sysevent traffic
# caused by doing this was causing test failures on aarch64 when
# sometimes the signals failed due to a failure to look up
# transactions. We need to figure out what is going on with that
# and restore it. We also probably want to rate limit
# query-cache-changes, or include a more detailed payload, since
# it can force pretty aggressive amounts of cache reloading work
# on the targets.
# dbv.tenant.create_task(
# dbv.tenant.signal_sysevent(
# 'query-cache-changes',
# dbname=dbv.dbname,
# ),
# interruptable=False,
# )
pass
async def parse_execute_json(
db: dbview.Database,
query: str,
*,
variables: Mapping[str, Any] = immutables.Map(),
globals_: Optional[Mapping[str, Any]] = None,
output_format: compiler.OutputFormat = compiler.OutputFormat.JSON,
query_cache_enabled: Optional[bool] = None,
cached_globally: bool = False,
use_metrics: bool = True,
) -> bytes:
# WARNING: only set cached_globally to True when the query is
# strictly referring to only shared stable objects in user schema
# or anything from std schema, for example:
# YES: select ext::auth::UIConfig { ... }
# NO: select default::User { ... }
if query_cache_enabled is None:
query_cache_enabled = not (
debug.flags.disable_qcache or debug.flags.edgeql_compile)
tenant = db.tenant
dbv = await tenant.new_dbview(
dbname=db.name,
query_cache=query_cache_enabled,
protocol_version=edbdef.CURRENT_PROTOCOL,
)
query_req = rpc.CompilationRequest(
db.server.compilation_config_serializer
).update(
edgeql.Source.from_string(query),
protocol_version=edbdef.CURRENT_PROTOCOL,
input_format=compiler.InputFormat.JSON,
output_format=output_format,
)
compiled = await dbv.parse(
query_req,
cached_globally=cached_globally,
use_metrics=use_metrics,
allow_capabilities=compiler.Capability.MODIFICATIONS,
)
pgcon = await tenant.acquire_pgcon(db.name)
try:
return await execute_json(
pgcon,
dbv,
compiled,
variables=variables,
globals_=globals_,
)
finally:
tenant.release_pgcon(db.name, pgcon)
async def execute_json(
be_conn: pgcon.PGConnection,
dbv: dbview.DatabaseConnectionView,
compiled: dbview.CompiledQuery,
variables: Mapping[str, Any] = immutables.Map(),
globals_: Optional[Mapping[str, Any]] = None,
*,
fe_conn: Optional[frontend.AbstractFrontendConnection] = None,
use_prep_stmt: bint = False,
) -> bytes:
dbv.set_globals(immutables.Map({
"__::__edb_json_globals__": config.SettingValue(
name="__::__edb_json_globals__",
value=_encode_json_value(globals_),
source='global',
scope=qltypes.ConfigScope.GLOBAL,
)
}))
qug = compiled.query_unit_group
args = []
if qug.in_type_args:
for param in qug.in_type_args:
value = variables.get(param.name)
args.append(value)
bind_args = _encode_args(args)
force_script = any(x.needs_readback for x in qug)
if len(qug) > 1 or force_script:
data = await execute_script(
be_conn,
dbv,
compiled,
bind_args,
fe_conn=fe_conn,
)
else:
data = await execute(
be_conn,
dbv,
compiled,
bind_args,
fe_conn=fe_conn,
)
if fe_conn is None:
if not data or len(data) > 1 or len(data[0]) != 1:
raise errors.InternalServerError(
f'received incorrect response data for a JSON query')
return data[0][0]
else:
return None
class DecimalEncoder(json.JSONEncoder):
def encode(self, obj):
if isinstance(obj, dict):
return '{' + ', '.join(
f'{self.encode(k)}: {self.encode(v)}'
for (k, v) in obj.items()
) + '}'
if isinstance(obj, list):
return '[' + ', '.join(map(self.encode, obj)) + ']'
if isinstance(obj, bytes):
return self.encode(base64.b64encode(obj).decode())
if isinstance(obj, decimal.Decimal):
return f'{obj:f}'
return super().encode(obj)
cdef bytes _encode_json_value(object val):
jarg = json.dumps(val, cls=DecimalEncoder)
return b'\x01' + jarg.encode('utf-8')
cdef bytes _encode_args(list args):
cdef:
WriteBuffer out_buf = WriteBuffer.new()
if args:
out_buf.write_int32(len(args))
for arg in args:
out_buf.write_int32(0) # reserved
if arg is None:
out_buf.write_int32(-1)
else:
jval = _encode_json_value(arg)
out_buf.write_int32(len(jval))
out_buf.write_bytes(jval)
return bytes(out_buf)
cdef _check_for_ise(exc):
# Unwrap ExceptionGroup that has only one Exception
if isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1:
exc = exc.exceptions[0]
if not isinstance(exc, errors.EdgeDBError):
nexc = errors.InternalServerError(
f'{type(exc).__name__}: {exc}',
hint=(
f'This is most likely a bug in EdgeDB. '
f'Please consider opening an issue ticket '
f'at https://github.com/edgedb/edgedb/issues/new'
f'?template=bug_report.md'
),
).with_traceback(exc.__traceback__)
formatted = getattr(exc, '__formatted_error__', None)
if formatted:
nexc.__formatted_error__ = formatted
if isinstance(exc, BaseExceptionGroup):
nexc.__cause__ = exc.with_traceback(None)
exc = nexc
return exc
async def interpret_error(
exc: Exception,
db: dbview.Database,
*,
global_schema_pickle: object=None,
user_schema_pickle: object=None,
from_graphql: bool=False,
) -> Exception:
if isinstance(exc, RecursionError):
exc = errors.UnsupportedFeatureError(
"The query caused the compiler "
"stack to overflow. It is likely too deeply nested.",
hint=(
"If the query does not contain deep nesting, "
"this may be a bug."
),
)
elif isinstance(exc, pgerror.BackendError):
try:
static_exc = errormech.static_interpret_backend_error(
exc.fields, from_graphql=from_graphql
)
# only use the backend if schema is required
if static_exc is errormech.SchemaRequired:
# Grab the schema from the exception first, if it is present.
user_schema_pickle = (
getattr(exc, '_user_schema', None)
or user_schema_pickle
or db.user_schema_pickle
)
global_schema_pickle = (
global_schema_pickle or db._index._global_schema_pickle
)
compiler_pool = db._index._server.get_compiler_pool()
exc = await compiler_pool.interpret_backend_error(
user_schema_pickle,
global_schema_pickle,
exc.fields,
from_graphql,
)
elif isinstance(static_exc, (
errors.DuplicateDatabaseDefinitionError,
errors.UnknownDatabaseError)):
tenant_id = db.tenant.tenant_id
message = static_exc.args[0].replace(f'{tenant_id}_', '')
exc = type(static_exc)(message)
else:
exc = static_exc
except Exception as e:
from edb.common import debug
if debug.flags.server:
debug.dump(e)
exc = RuntimeError(
'unhandled error while calling interpret_backend_error(); '
'run with EDGEDB_DEBUG_SERVER to debug.')
return _check_for_ise(exc)
def interpret_simple_error(
exc: Exception,
) -> Exception:
"""Intepret a protocol error not associated with a query or schema"""
if isinstance(exc, pgerror.BackendError):
static_exc = errormech.static_interpret_backend_error(exc.fields)
if static_exc is not errormech.SchemaRequired:
exc = static_exc
return _check_for_ise(exc)