-
Notifications
You must be signed in to change notification settings - Fork 390
/
bootstrap.py
2560 lines (2178 loc) · 78.5 KB
/
bootstrap.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,
Callable,
Optional,
Tuple,
Type,
TypeVar,
Iterable,
Mapping,
Awaitable,
Dict,
List,
Set,
NamedTuple,
TYPE_CHECKING,
)
import dataclasses
import enum
import json
import logging
import os
import pathlib
import pickle
import re
import struct
import textwrap
from edb import buildmeta
from edb import errors
from edb import edgeql
from edb.ir import statypes
from edb.edgeql import ast as qlast
from edb.common import debug
from edb.common import devmode
from edb.common import retryloop
from edb.common import uuidgen
from edb.schema import ddl as s_ddl
from edb.schema import delta as sd
from edb.schema import extensions as s_exts
from edb.schema import functions as s_func
from edb.schema import modules as s_mod
from edb.schema import name as sn
from edb.schema import objects as s_obj
from edb.schema import properties as s_props
from edb.schema import reflection as s_refl
from edb.schema import schema as s_schema
from edb.schema import std as s_std
from edb.schema import types as s_types
from edb.server import args as edbargs
from edb.server import config
from edb.server import compiler as edbcompiler
from edb.server import defines as edbdef
from edb.server import pgcluster
from edb.server import pgcon
from edb.pgsql import common as pg_common
from edb.pgsql import dbops
from edb.pgsql import delta as delta_cmds
from edb.pgsql import metaschema
from edb.pgsql import params
from edb.pgsql import patches
from edb.pgsql.common import quote_ident as qi
from edb.pgsql.common import quote_literal as ql
from edgedb import scram
if TYPE_CHECKING:
import uuid
logger = logging.getLogger('edb.server')
STDLIB_CACHE_FILE_NAME = 'backend-stdlib.pickle'
class ClusterMode(enum.IntEnum):
pristine = 0
regular = 1
single_role = 2
single_database = 3
_T = TypeVar("_T")
# A simple connection proxy that reconnects and retries queries
# on connection errors. Helps defeat flaky connections and/or
# flaky Postgres servers (Digital Ocean managed instances are
# one example that has a weird setup that crashes a helper
# process when we bootstrap, breaking other connections).
class PGConnectionProxy:
def __init__(
self,
cluster: pgcluster.BaseCluster,
dbname: Optional[str] = None,
log_listener: Optional[Callable[[str, str], None]] = None,
):
self._conn: Optional[pgcon.PGConnection] = None
self._cluster = cluster
self._dbname = dbname
self._log_listener = log_listener or _pg_log_listener
async def connect(self) -> None:
if self._conn is not None:
self._conn.terminate()
if self._dbname:
self._conn = await self._cluster.connect(database=self._dbname)
else:
self._conn = await self._cluster.connect()
if self._log_listener is not None:
self._conn.add_log_listener(self._log_listener)
def _on_retry(self, exc: Optional[BaseException]) -> None:
logger.warning(
f'Retrying bootstrap SQL query due to connection error: '
f'{type(exc)}({exc})',
)
self.terminate()
async def _retry_conn_errors(
self,
task: Callable[[], Awaitable[_T]],
) -> _T:
rloop = retryloop.RetryLoop(
backoff=retryloop.exp_backoff(),
timeout=5.0,
ignore=(
ConnectionError,
pgcon.BackendConnectionError,
),
retry_cb=self._on_retry,
)
async for iteration in rloop:
async with iteration:
if self._conn is None:
await self.connect()
result = await task()
return result
async def sql_execute(self, sql: bytes | tuple[bytes, ...]) -> None:
async def _task() -> None:
assert self._conn is not None
await self._conn.sql_execute(sql)
return await self._retry_conn_errors(_task)
async def sql_fetch(
self,
sql: bytes | tuple[bytes, ...],
*,
args: tuple[bytes, ...] | list[bytes] = (),
) -> list[tuple[bytes, ...]]:
async def _task() -> list[tuple[bytes, ...]]:
assert self._conn is not None
return await self._conn.sql_fetch(sql, args=args)
return await self._retry_conn_errors(_task)
async def sql_fetch_val(
self,
sql: bytes,
*,
args: tuple[bytes, ...] | list[bytes] = (),
) -> bytes:
async def _task() -> bytes:
assert self._conn is not None
return await self._conn.sql_fetch_val(sql, args=args)
return await self._retry_conn_errors(_task)
async def sql_fetch_col(
self,
sql: bytes,
*,
args: tuple[bytes, ...] | list[bytes] = (),
) -> list[bytes]:
async def _task() -> list[bytes]:
assert self._conn is not None
return await self._conn.sql_fetch_col(sql, args=args)
return await self._retry_conn_errors(_task)
def terminate(self) -> None:
if self._conn is not None:
self._conn.terminate()
self._conn = None
@dataclasses.dataclass
class BootstrapContext:
cluster: pgcluster.BaseCluster
conn: PGConnectionProxy
args: edbargs.ServerConfig
mode: Optional[ClusterMode] = None
async def _execute(conn, query):
return await metaschema.execute_sql_script(conn, query)
async def _execute_block(conn, block: dbops.SQLBlock) -> None:
if not block.is_transactional():
stmts = block.get_statements()
else:
stmts = [block.to_string()]
for stmt in stmts:
await _execute(conn, stmt)
async def _execute_edgeql_ddl(
schema: s_schema.Schema_T,
ddltext: str,
stdmode: bool = True,
) -> s_schema.Schema_T:
context = sd.CommandContext(stdmode=stdmode)
for ddl_cmd in edgeql.parse_block(ddltext):
assert isinstance(ddl_cmd, qlast.DDLCommand)
delta_command = s_ddl.delta_from_ddl(
ddl_cmd, modaliases={}, schema=schema, stdmode=stdmode)
schema = delta_command.apply(schema, context) # type: ignore
return schema
async def _ensure_edgedb_supergroup(
ctx: BootstrapContext,
role_name: str,
*,
member_of: Iterable[str] = (),
members: Iterable[str] = (),
) -> None:
member_of = set(member_of)
backend_params = ctx.cluster.get_runtime_params()
superuser_role = backend_params.instance_params.base_superuser
if superuser_role:
# If the cluster is exposing an explicit superuser role,
# become a member of that instead of creating a superuser
# role directly.
member_of.add(superuser_role)
pg_role_name = ctx.cluster.get_role_name(role_name)
role = dbops.Role(
name=pg_role_name,
superuser=backend_params.has_superuser_access,
allow_login=False,
allow_createdb=True,
allow_createrole=True,
membership=member_of,
members=members,
)
create_role = dbops.CreateRole(
role,
neg_conditions=[dbops.RoleExists(pg_role_name)],
)
block = dbops.PLTopBlock()
create_role.generate(block)
await _execute_block(ctx.conn, block)
async def _ensure_edgedb_role(
ctx: BootstrapContext,
role_name: str,
*,
superuser: bool = False,
builtin: bool = False,
objid: Optional[uuid.UUID] = None,
) -> uuid.UUID:
member_of = set()
if superuser:
member_of.add(edbdef.EDGEDB_SUPERGROUP)
if objid is None:
objid = uuidgen.uuid1mc()
members = set()
login_role = ctx.cluster.get_connection_params().user
sup_role = ctx.cluster.get_role_name(edbdef.EDGEDB_SUPERUSER)
if login_role != sup_role:
members.add(login_role)
backend_params = ctx.cluster.get_runtime_params()
pg_role_name = ctx.cluster.get_role_name(role_name)
role = dbops.Role(
name=pg_role_name,
superuser=superuser and backend_params.has_superuser_access,
allow_login=True,
allow_createdb=True,
allow_createrole=True,
membership=[ctx.cluster.get_role_name(m) for m in member_of],
members=members,
metadata=dict(
id=str(objid),
name=role_name,
tenant_id=backend_params.tenant_id,
builtin=builtin,
),
)
create_role = dbops.CreateRole(
role,
neg_conditions=[dbops.RoleExists(pg_role_name)],
)
block = dbops.PLTopBlock()
create_role.generate(block)
await _execute_block(ctx.conn, block)
return objid
async def _get_cluster_mode(ctx: BootstrapContext) -> ClusterMode:
backend_params = ctx.cluster.get_runtime_params()
tenant_id = backend_params.tenant_id
# First, check the existence of EDGEDB_SUPERGROUP - the role which is
# usually created at the beginning of bootstrap.
is_default_tenant = tenant_id == buildmeta.get_default_tenant_id()
ignore_others = is_default_tenant and ctx.args.ignore_other_tenants
if is_default_tenant:
result = await ctx.conn.sql_fetch_col(
b"""
SELECT
r.rolname
FROM
pg_catalog.pg_roles AS r
WHERE
r.rolname LIKE ('%' || $1)
""",
args=[
edbdef.EDGEDB_SUPERGROUP.encode("utf-8"),
],
)
else:
result = await ctx.conn.sql_fetch_col(
b"""
SELECT
r.rolname
FROM
pg_catalog.pg_roles AS r
WHERE
r.rolname = $1
""",
args=[
ctx.cluster.get_role_name(
edbdef.EDGEDB_SUPERGROUP).encode("utf-8"),
],
)
if result:
if not ignore_others:
# Either our tenant slot is occupied, or there is
# a default tenant present.
return ClusterMode.regular
# We were explicitly asked to ignore the other default tenant,
# so check specifically if our tenant slot is occupied and ignore
# the others.
# This mode is used for in-place upgrade.
for rolname in result:
other_tenant_id = rolname[: -(len(edbdef.EDGEDB_SUPERGROUP) + 1)]
if other_tenant_id == tenant_id.encode("utf-8"):
return ClusterMode.regular
# Then, check if the current database was bootstrapped in single-db mode.
has_instdata = await ctx.conn.sql_fetch_val(
b'''
SELECT
tablename
FROM
pg_catalog.pg_tables
WHERE
schemaname = 'edgedbinstdata'
AND tablename = 'instdata'
''',
)
if has_instdata:
return ClusterMode.single_database
# At last, check for single-role-bootstrapped instance by trying to find
# the EdgeDB System DB with the assumption that we are not running in
# single-db mode. If not found, this is a pristine backend cluster.
if is_default_tenant:
result = await ctx.conn.sql_fetch_col(
b'''
SELECT datname
FROM pg_database
WHERE datname LIKE '%' || $1
''',
args=(
edbdef.EDGEDB_SYSTEM_DB.encode("utf-8"),
),
)
else:
result = await ctx.conn.sql_fetch_col(
b'''
SELECT datname
FROM pg_database
WHERE datname = $1
''',
args=(
ctx.cluster.get_db_name(
edbdef.EDGEDB_SYSTEM_DB).encode("utf-8"),
),
)
if result:
if not ignore_others:
# Either our tenant slot is occupied, or there is
# a default tenant present.
return ClusterMode.single_role
# We were explicitly asked to ignore the other default tenant,
# so check specifically if our tenant slot is occupied and ignore
# the others.
# This mode is used for in-place upgrade.
for dbname in result:
other_tenant_id = dbname[: -(len(edbdef.EDGEDB_SYSTEM_DB) + 1)]
if other_tenant_id == tenant_id.encode("utf-8"):
return ClusterMode.single_role
return ClusterMode.pristine
async def _create_edgedb_template_database(
ctx: BootstrapContext,
) -> uuid.UUID:
backend_params = ctx.cluster.get_runtime_params()
have_c_utf8 = backend_params.has_c_utf8_locale
logger.info('Creating template database...')
block = dbops.SQLBlock()
dbid = uuidgen.uuid1mc()
db = dbops.Database(
ctx.cluster.get_db_name(edbdef.EDGEDB_TEMPLATE_DB),
owner=ctx.cluster.get_role_name(edbdef.EDGEDB_SUPERUSER),
is_template=True,
lc_collate='C',
lc_ctype='C.UTF-8' if have_c_utf8 else 'en_US.UTF-8',
encoding='UTF8',
metadata=dict(
id=str(dbid),
tenant_id=backend_params.tenant_id,
name=edbdef.EDGEDB_TEMPLATE_DB,
builtin=True,
),
)
dbops.CreateDatabase(db, template='template0').generate(block)
await _execute_block(ctx.conn, block)
return dbid
async def _store_static_bin_cache_conn(
conn: metaschema.PGConnection,
key: str,
data: bytes,
) -> None:
text = f"""\
INSERT INTO edgedbinstdata.instdata (key, bin)
VALUES(
{pg_common.quote_literal(key)},
{pg_common.quote_bytea_literal(data)}::bytea
)
"""
await _execute(conn, text)
async def _store_static_bin_cache(
ctx: BootstrapContext,
key: str,
data: bytes,
) -> None:
await _store_static_bin_cache_conn(ctx.conn, key, data)
async def _store_static_text_cache(
ctx: BootstrapContext,
key: str,
data: str,
) -> None:
text = f"""\
INSERT INTO edgedbinstdata.instdata (key, text)
VALUES(
{pg_common.quote_literal(key)},
{pg_common.quote_literal(data)}::text
)
"""
await _execute(ctx.conn, text)
async def _store_static_json_cache(
ctx: BootstrapContext,
key: str,
data: str,
) -> None:
text = f"""\
INSERT INTO edgedbinstdata.instdata (key, json)
VALUES(
{pg_common.quote_literal(key)},
{pg_common.quote_literal(data)}::jsonb
)
"""
await _execute(ctx.conn, text)
def _process_delta_params(delta, schema, params):
"""Adapt and process the delta command."""
if debug.flags.delta_plan:
debug.header('Delta Plan')
debug.dump(delta, schema=schema)
context = sd.CommandContext(stdmode=True)
if not delta.canonical:
# Canonicalize
sd.apply(delta, schema=schema)
delta = delta_cmds.CommandMeta.adapt(delta)
context = sd.CommandContext(
stdmode=True,
backend_runtime_params=params,
)
schema = sd.apply(delta, schema=schema, context=context)
if debug.flags.delta_pgsql_plan:
debug.header('PgSQL Delta Plan')
debug.dump(delta, schema=schema)
return schema, delta
def _process_delta(ctx, delta, schema):
"""Adapt and process the delta command."""
return _process_delta_params(
delta, schema, ctx.cluster.get_runtime_params()
)
def compile_bootstrap_script(
compiler: edbcompiler.Compiler,
schema: s_schema.Schema,
eql: str,
*,
expected_cardinality_one: bool = False,
output_format: edbcompiler.OutputFormat = edbcompiler.OutputFormat.JSON,
) -> Tuple[s_schema.Schema, str]:
ctx = edbcompiler.new_compiler_context(
compiler_state=compiler.state,
user_schema=schema,
expected_cardinality_one=expected_cardinality_one,
json_parameters=True,
output_format=output_format,
bootstrap_mode=True,
)
return edbcompiler.compile_edgeql_script(ctx, eql)
def compile_single_query(
eql: str,
compilerctx: edbcompiler.CompileContext,
) -> str:
ql_source = edgeql.Source.from_string(eql)
units = edbcompiler.compile(ctx=compilerctx, source=ql_source).units
assert len(units) == 1 and len(units[0].sql) == 1
return units[0].sql[0].decode()
def _get_all_subcommands(
cmd: sd.Command, type: Optional[Type[sd.Command]] = None
) -> list[sd.Command]:
cmds = []
def go(cmd):
if not type or isinstance(cmd, type):
cmds.append(cmd)
for sub in cmd.get_subcommands():
go(sub)
go(cmd)
return cmds
def _get_schema_object_ids(
delta: sd.Command,
) -> Mapping[Tuple[sn.Name, Optional[str]], uuid.UUID]:
schema_object_ids = {}
for cmd in _get_all_subcommands(delta, sd.CreateObject):
assert isinstance(cmd, sd.CreateObject)
mcls = cmd.get_schema_metaclass()
if issubclass(mcls, s_obj.QualifiedObject):
qlclass = None
else:
qlclass = mcls.get_ql_class_or_die()
id = cmd.get_attribute_value('id')
schema_object_ids[cmd.classname, qlclass] = id
# backend_name in callables is a lot *like* an id, in that it gets
# randomly generated and needs to match between things.
if isinstance(cmd, s_func.CreateCallableObject):
backend_name = cmd.get_attribute_value('backend_name')
if backend_name:
schema_object_ids[
cmd.classname, f'{qlclass}-backend_name'] = backend_name
return schema_object_ids
def prepare_repair_patch(
stdschema: s_schema.Schema,
reflschema: s_schema.Schema,
userschema: s_schema.Schema,
globalschema: s_schema.Schema,
schema_class_layout: s_refl.SchemaClassLayout,
backend_params: params.BackendRuntimeParams,
config: Any,
) -> tuple[bytes, ...]:
compiler = edbcompiler.new_compiler(
std_schema=stdschema,
reflection_schema=reflschema,
schema_class_layout=schema_class_layout
)
compilerctx = edbcompiler.new_compiler_context(
compiler_state=compiler.state,
global_schema=globalschema,
user_schema=userschema,
)
res = edbcompiler.repair_schema(compilerctx)
if not res:
return ()
sql, _, _ = res
return sql
PatchEntry = tuple[tuple[str, ...], tuple[str, ...], dict[str, Any], bool]
async def gather_patch_info(
num: int,
kind: str,
patch: str,
conn: pgcon.PGConnection,
) -> Optional[dict[str, list[str]]]:
"""Fetch info for a patch that needs to use the connection.
Currently, the only thing we need is, for config updates, the
order that columns appear in the config views in SQL. We need this
because we need to preserve that order when we update the
view.
"""
if '+config' in kind:
# Find all the config views (they are pg_classes where
# there is also a table with the same name but "_dummy"
# at the end) and collect all their columns in order.
return json.loads(await conn.sql_fetch_val('''\
select json_object_agg(v.relname, (
select json_agg(a.attname order by a.attnum)
from pg_catalog.pg_attribute as a
where v.oid = a.attrelid
))
from pg_catalog.pg_class as v
inner join pg_catalog.pg_tables as t
on v.relname || '_dummy' = t.tablename
'''.encode('utf-8')))
else:
return None
def _generate_drop_views(
group: dbops.CommandGroup,
preblock: dbops.PLBlock,
) -> None:
for cv in reversed(list(group)):
dv: Any
if isinstance(cv, dbops.CreateView):
dv = dbops.DropView(
cv.view.name,
conditions=[dbops.ViewExists(cv.view.name)],
)
elif isinstance(cv, dbops.CreateFunction):
dv = dbops.DropFunction(
cv.function.name,
args=cv.function.args or (),
has_variadic=bool(cv.function.has_variadic),
if_exists=True,
)
else:
raise AssertionError(f'unsupported support view command {cv}')
dv.generate(preblock)
def prepare_patch(
num: int,
kind: str,
patch: str,
schema: s_schema.Schema,
reflschema: s_schema.Schema,
schema_class_layout: s_refl.SchemaClassLayout,
backend_params: params.BackendRuntimeParams,
patch_info: Optional[dict[str, list[str]]],
user_schema: Optional[s_schema.Schema]=None,
global_schema: Optional[s_schema.Schema]=None,
) -> PatchEntry:
val = f'{pg_common.quote_literal(json.dumps(num + 1))}::jsonb'
# TODO: This is an INSERT because 2.0 shipped without num_patches.
# We can just make this an UPDATE for 3.0
update = f"""\
INSERT INTO edgedbinstdata.instdata (key, json)
VALUES('num_patches', {val})
ON CONFLICT (key)
DO UPDATE SET json = {val};
"""
existing_view_columns = patch_info
# Pure SQL patches are simple
if kind == 'sql':
return (patch, update), (), {}, False
# metaschema-sql: just recreate a function from metaschema
if kind == 'metaschema-sql':
func = getattr(metaschema, patch)
create = dbops.CreateFunction(func(), or_replace=True)
block = dbops.PLTopBlock()
create.generate(block)
return (block.to_string(), update), (), {}, False
if kind == 'repair':
assert not patch
return (update,), (), {}, True
# EdgeQL and reflection schema patches need to be compiled.
current_block = dbops.PLTopBlock()
preblock = current_block.add_block()
subblock = current_block.add_block()
std_plans = []
updates: dict[str, Any] = {}
global_schema_update = kind == 'ext-pkg'
sys_update_only = global_schema_update or kind.endswith('+globalonly')
if kind == 'ext-pkg':
# N.B: We process this without actually having the global
# schema present, so we don't do any check for if it already
# exists. The backend code will overwrite an older version's
# JSON in the global metadata if it was already present.
patch = s_std.get_std_module_text(sn.UnqualName(f'ext/{patch}'))
if (
kind == 'edgeql'
or kind == 'ext-pkg'
or kind.startswith('edgeql+schema')
):
assert '+user_ext' not in kind
for ddl_cmd in edgeql.parse_block(patch):
assert isinstance(ddl_cmd, qlast.DDLCommand)
# First apply it to the regular schema, just so we can update
# stdschema
delta_command = s_ddl.delta_from_ddl(
ddl_cmd, modaliases={}, schema=schema, stdmode=True)
schema, _ = _process_delta_params(
delta_command, schema, backend_params)
# We need to extract all ids of new objects created when
# applying it to the regular schema, so that we can make sure
# to use the same ids in the reflschema.
schema_object_ids = _get_schema_object_ids(delta_command)
# Then apply it to the reflschema, which we will use to drive
# the actual table updating.
delta_command = s_ddl.delta_from_ddl(
ddl_cmd, modaliases={}, schema=reflschema,
schema_object_ids=schema_object_ids, stdmode=True)
reflschema, plan = _process_delta_params(
delta_command, reflschema, backend_params)
std_plans.append(delta_command)
plan.generate(subblock)
metadata_user_schema = reflschema
elif kind.startswith('edgeql+user_ext'):
assert '+schema' not in kind
# There isn't anything to do on the system database for
# userext updates.
if user_schema is None:
return (update,), (), dict(is_user_ext_update=True), False
# Only run a userext update if the extension we are trying to
# update is installed.
extension_name = kind.split('|')[-1]
extension = user_schema.get_global(
s_exts.Extension, extension_name, default=None)
if not extension:
return (update,), (), {}, False
assert global_schema
cschema = s_schema.ChainedSchema(
schema,
user_schema,
global_schema,
)
for ddl_cmd in edgeql.parse_block(patch):
assert isinstance(ddl_cmd, qlast.DDLCommand)
delta_command = s_ddl.delta_from_ddl(
ddl_cmd, modaliases={}, schema=cschema,
stdmode=False,
testmode=True,
)
cschema, plan = _process_delta_params(
delta_command, cschema, backend_params)
std_plans.append(delta_command)
plan.generate(subblock)
if '+config' in kind:
views = metaschema.get_config_views(cschema, existing_view_columns)
views.generate(subblock)
metadata_user_schema = cschema.get_top_schema()
elif kind == 'sql-introspection':
support_view_commands = dbops.CommandGroup()
support_view_commands.add_commands(
metaschema._generate_sql_information_schema())
support_view_commands.generate(subblock)
_generate_drop_views(support_view_commands, preblock)
metadata_user_schema = reflschema
else:
raise AssertionError(f'unknown patch type {kind}')
if kind.startswith('edgeql+schema'):
# If we are modifying the schema layout, we need to rerun
# generate_structure to collect schema changes not reflected
# in the public schema and to discover the new introspection
# query.
reflection = s_refl.generate_structure(
reflschema, make_funcs=False,
)
reflschema, plan = _process_delta_params(
reflection.intro_schema_delta, reflschema, backend_params)
plan.generate(subblock)
compiler = edbcompiler.new_compiler(
std_schema=schema,
reflection_schema=reflschema,
schema_class_layout=schema_class_layout
)
local_intro_sql, global_intro_sql = compile_intro_queries_stdlib(
compiler=compiler,
user_schema=reflschema,
reflection=reflection,
)
updates.update(dict(
classlayout=reflection.class_layout,
local_intro_query=local_intro_sql.encode('utf-8'),
global_intro_query=global_intro_sql.encode('utf-8'),
))
# This part is wildly hinky
# We need to delete all the support views and recreate them at the end
support_view_commands = dbops.CommandGroup()
support_view_commands.add_commands([
dbops.CreateView(view)
for view in metaschema._generate_schema_alias_views(
reflschema, sn.UnqualName('schema')
) + metaschema._generate_schema_alias_views(
reflschema, sn.UnqualName('sys')
)
])
support_view_commands.add_commands(
metaschema._generate_sql_information_schema())
_generate_drop_views(support_view_commands, preblock)
# We want to limit how much unconditional work we do, so only recreate
# extension views if requested.
if '+exts' in kind:
for extview in metaschema._generate_extension_views(reflschema):
support_view_commands.add_command(
dbops.CreateView(extview, or_replace=True))
# Similarly, only do config system updates if requested.
if '+config' in kind:
support_view_commands.add_command(
metaschema.get_config_views(schema, existing_view_columns))
# Though we always update the instdata for the config system,
# because it is currently the most convenient way to make sure
# all the versioned fields get updated.
config_spec = config.load_spec_from_schema(schema)
(
sysqueries,
report_configs_typedesc_1_0,
report_configs_typedesc_2_0,
) = compile_sys_queries(
reflschema,
compiler,
config_spec,
)
updates.update(dict(
sysqueries=json.dumps(sysqueries).encode('utf-8'),
report_configs_typedesc_1_0=report_configs_typedesc_1_0,
report_configs_typedesc_2_0=report_configs_typedesc_2_0,
configspec=config.spec_to_json(config_spec).encode('utf-8'),
))
support_view_commands.generate(subblock)
compiler = edbcompiler.new_compiler(
std_schema=schema,
reflection_schema=reflschema,
schema_class_layout=schema_class_layout
)
compilerctx = edbcompiler.new_compiler_context(
compiler_state=compiler.state,
user_schema=metadata_user_schema,
bootstrap_mode=user_schema is None,
)
for std_plan in std_plans:
edbcompiler.compile_schema_storage_in_delta(
ctx=compilerctx,
delta=std_plan,
block=subblock,
)
patch = current_block.to_string()
if debug.flags.delta_execute:
debug.header('Patch Script')
debug.dump_code(patch, lexer='sql')
if not global_schema_update:
updates.update(dict(
std_and_reflection_schema=(schema, reflschema),
))
bins = (
'std_and_reflection_schema', 'global_schema', 'classlayout',
'report_configs_typedesc_1_0', 'report_configs_typedesc_2_0',
)