-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathddl.py
More file actions
1800 lines (1554 loc) · 58.4 KB
/
ddl.py
File metadata and controls
1800 lines (1554 loc) · 58.4 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 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, Dict, List, FrozenSet
import dataclasses
import json
import textwrap
from edb import errors
from edb import edgeql
from edb.common import debug
from edb.common import ast
from edb.common import uuidgen
from edb.edgeql import ast as qlast
from edb.edgeql import codegen as qlcodegen
from edb.edgeql import compiler as qlcompiler
from edb.edgeql import qltypes
from edb.edgeql import quote as qlquote
from edb.schema import annos as s_annos
from edb.schema import constraints as s_constraints
from edb.schema import database as s_db
from edb.schema import ddl as s_ddl
from edb.schema import delta as s_delta
from edb.schema import expraliases as s_expraliases
from edb.schema import functions as s_func
from edb.schema import globals as s_globals
from edb.schema import indexes as s_indexes
from edb.schema import links as s_links
from edb.schema import migrations as s_migrations
from edb.schema import objects as s_obj
from edb.schema import objtypes as s_objtypes
from edb.schema import policies as s_policies
from edb.schema import pointers as s_pointers
from edb.schema import properties as s_properties
from edb.schema import rewrites as s_rewrites
from edb.schema import scalars as s_scalars
from edb.schema import schema as s_schema
from edb.schema import triggers as s_triggers
from edb.schema import utils as s_utils
from edb.schema import version as s_ver
from edb.pgsql import common as pg_common
from edb.pgsql import delta as pg_delta
from edb.pgsql import dbops as pg_dbops
from . import dbstate
from . import compiler
NIL_QUERY = b"SELECT LIMIT 0"
def compile_and_apply_ddl_stmt(
ctx: compiler.CompileContext,
stmt: qlast.DDLCommand,
source: Optional[edgeql.Source] = None,
) -> dbstate.DDLQuery:
query, _ = _compile_and_apply_ddl_stmt(ctx, stmt, source)
return query
def _compile_and_apply_ddl_stmt(
ctx: compiler.CompileContext,
stmt: qlast.DDLCommand,
source: Optional[edgeql.Source] = None,
) -> tuple[dbstate.DDLQuery, Optional[pg_dbops.SQLBlock]]:
if isinstance(stmt, qlast.GlobalObjectCommand):
ctx._assert_not_in_migration_block(stmt)
current_tx = ctx.state.current_tx()
schema = current_tx.get_schema(ctx.compiler_state.std_schema)
mstate = current_tx.get_migration_state()
if (
mstate is None
and not ctx.bootstrap_mode
and ctx.log_ddl_as_migrations
and not isinstance(
stmt,
(
qlast.CreateMigration,
qlast.GlobalObjectCommand,
qlast.DropMigration,
),
)
):
allow_bare_ddl = compiler._get_config_val(ctx, 'allow_bare_ddl')
if allow_bare_ddl != "AlwaysAllow":
raise errors.QueryError(
"bare DDL statements are not allowed on this database branch",
hint="Use the migration commands instead.",
details=(
f"The `allow_bare_ddl` configuration variable "
f"is set to {str(allow_bare_ddl)!r}. The "
f"`edgedb migrate` command normally sets this "
f"to avoid accidental schema changes outside of "
f"the migration flow."
),
span=stmt.span,
)
cm = qlast.CreateMigration( # type: ignore
body=qlast.NestedQLBlock(
commands=[stmt],
),
commands=[
qlast.SetField(
name='generated_by',
value=qlast.Path(
steps=[
qlast.ObjectRef(
name='MigrationGeneratedBy', module='schema'
),
qlast.Ptr(name='DDLStatement'),
]
),
)
],
)
return _compile_and_apply_ddl_stmt(ctx, cm)
assert isinstance(stmt, qlast.DDLCommand)
new_schema, delta = s_ddl.delta_and_schema_from_ddl(
stmt,
schema=schema,
modaliases=current_tx.get_modaliases(),
**_get_delta_context_args(ctx),
)
if debug.flags.delta_plan:
debug.header('Canonical Delta Plan')
debug.dump(delta, schema=schema)
if mstate := current_tx.get_migration_state():
mstate = mstate._replace(
accepted_cmds=mstate.accepted_cmds + (stmt,),
)
last_proposed = mstate.last_proposed
if last_proposed:
if last_proposed[0].required_user_input or last_proposed[
0
].prompt_id.startswith("Rename"):
# Cannot auto-apply the proposed DDL
# if user input is required.
# Also skip auto-applying for renames, since
# renames often force a bunch of rethinking.
mstate = mstate._replace(last_proposed=None)
else:
proposed_stmts = last_proposed[0].statements
ddl_script = '\n'.join(proposed_stmts)
if source and source.text() == ddl_script:
# The client has confirmed the proposed migration step,
# advance the proposed script.
mstate = mstate._replace(
last_proposed=last_proposed[1:],
)
else:
# The client replied with a statement that does not
# match what was proposed, reset the proposed script
# to force script regeneration on next DESCRIBE.
mstate = mstate._replace(last_proposed=None)
current_tx.update_migration_state(mstate)
current_tx.update_schema(new_schema)
query = dbstate.DDLQuery(
sql=NIL_QUERY,
user_schema=current_tx.get_user_schema(),
is_transactional=True,
warnings=tuple(delta.warnings),
feature_used_metrics=None,
)
return query, None
store_migration_sdl = compiler._get_config_val(ctx, 'store_migration_sdl')
if (
isinstance(stmt, qlast.CreateMigration)
and store_migration_sdl == 'AlwaysStore'
):
stmt.target_sdl = s_ddl.sdl_text_from_schema(new_schema)
# If we are in a migration rewrite, we also don't actually
# apply the DDL, just record it. (The DDL also needs to be a
# CreateMigration.)
if mrstate := current_tx.get_migration_rewrite_state():
if not isinstance(stmt, qlast.CreateMigration):
# This will always fail, and gives us the error we need
ctx._assert_not_in_migration_rewrite_block(stmt)
# Tell this to the type checker
raise AssertionError()
mrstate = mrstate._replace(
accepted_migrations=(mrstate.accepted_migrations + (stmt,))
)
current_tx.update_migration_rewrite_state(mrstate)
current_tx.update_schema(new_schema)
query = dbstate.DDLQuery(
sql=NIL_QUERY,
user_schema=current_tx.get_user_schema(),
is_transactional=True,
warnings=tuple(delta.warnings),
feature_used_metrics=None,
)
return query, None
# Apply and adapt delta, build native delta plan, which
# will also update the schema.
block, new_types, config_ops = _process_delta(ctx, delta)
ddl_stmt_id: Optional[str] = None
is_transactional = block.is_transactional()
if not is_transactional:
if not isinstance(stmt, qlast.DatabaseCommand):
raise AssertionError(
f"unexpected non-transaction DDL command type: {stmt}")
sql_stmts = block.get_statements()
sql = sql_stmts[0].encode("utf-8")
db_op_trailer = tuple(stmt.encode("utf-8") for stmt in sql_stmts[1:])
else:
if new_types:
# Inject a query returning backend OIDs for the newly
# created types.
ddl_stmt_id = str(uuidgen.uuid1mc())
new_type_ids = [
f'{pg_common.quote_literal(tid)}::uuid' for tid in new_types
]
# Return newly-added type id mapping via the indirect
# return channel (see PGConnection.last_indirect_return)
new_types_sql = textwrap.dedent(f"""\
PERFORM edgedb.indirect_return(
json_build_object(
'ddl_stmt_id',
{pg_common.quote_literal(ddl_stmt_id)},
'new_types',
(SELECT
json_object_agg(
"id"::text,
json_build_array("backend_id", "name")
)
FROM
edgedb_VER."_SchemaType"
WHERE
"id" = any(ARRAY[
{', '.join(new_type_ids)}
])
)
)::text
)"""
)
block.add_command(pg_dbops.Query(text=new_types_sql).code())
sql = block.to_string().encode('utf-8')
db_op_trailer = ()
create_db = None
drop_db = None
drop_db_reset_connections = False
create_db_template = None
create_db_mode = None
if isinstance(stmt, qlast.DropDatabase):
drop_db = stmt.name.name
drop_db_reset_connections = stmt.force
elif isinstance(stmt, qlast.CreateDatabase):
create_db = stmt.name.name
create_db_template = stmt.template.name if stmt.template else None
create_db_mode = stmt.branch_type
elif isinstance(stmt, qlast.AlterDatabase):
for cmd in stmt.commands:
if isinstance(cmd, qlast.Rename):
drop_db = stmt.name.name
create_db = cmd.new_name.name
drop_db_reset_connections = stmt.force
if debug.flags.delta_execute_ddl:
debug.header('Delta Script (DDL Only)')
# The schema updates are always the last statement, so grab
# everything but
code = '\n\n'.join(block.get_statements()[:-1])
debug.dump_code(code, lexer='sql')
if debug.flags.delta_execute:
debug.header('Delta Script')
debug.dump_code(sql + b"\n".join(db_op_trailer), lexer='sql')
new_user_schema = current_tx.get_user_schema_if_updated()
query = dbstate.DDLQuery(
sql=sql,
is_transactional=is_transactional,
create_db=create_db,
drop_db=drop_db,
drop_db_reset_connections=drop_db_reset_connections,
create_db_template=create_db_template,
create_db_mode=create_db_mode,
db_op_trailer=db_op_trailer,
ddl_stmt_id=ddl_stmt_id,
user_schema=new_user_schema,
cached_reflection=current_tx.get_cached_reflection_if_updated(),
global_schema=current_tx.get_global_schema_if_updated(),
config_ops=config_ops,
warnings=tuple(delta.warnings),
feature_used_metrics=(
produce_feature_used_metrics(ctx.compiler_state, new_user_schema)
if new_user_schema else None
),
)
return query, block
def _new_delta_context(
ctx: compiler.CompileContext, args: Any = None
) -> s_delta.CommandContext:
return s_delta.CommandContext(
backend_runtime_params=ctx.compiler_state.backend_runtime_params,
internal_schema_mode=ctx.internal_schema_mode,
**(_get_delta_context_args(ctx) if args is None else args),
)
def _get_delta_context_args(ctx: compiler.CompileContext) -> dict[str, Any]:
"""Get the args needed for delta_and_schema_from_ddl"""
return dict(
stdmode=ctx.bootstrap_mode,
testmode=ctx.is_testmode(),
store_migration_sdl=(
compiler._get_config_val(ctx, 'store_migration_sdl')
) == 'AlwaysStore',
schema_object_ids=ctx.schema_object_ids,
compat_ver=ctx.compat_ver,
)
def _process_delta(
ctx: compiler.CompileContext, delta: s_delta.DeltaRoot
) -> tuple[pg_dbops.SQLBlock, FrozenSet[str], Any]:
"""Adapt and process the delta command."""
current_tx = ctx.state.current_tx()
schema = current_tx.get_schema(ctx.compiler_state.std_schema)
pgdelta = pg_delta.CommandMeta.adapt(delta)
assert isinstance(pgdelta, pg_delta.DeltaRoot)
context = _new_delta_context(ctx)
schema = pgdelta.apply(schema, context)
current_tx.update_schema(schema)
if debug.flags.delta_pgsql_plan:
debug.header('PgSQL Delta Plan')
debug.dump(pgdelta, schema=schema)
db_cmd = any(
isinstance(c, s_db.BranchCommand) for c in pgdelta.get_subcommands()
)
if db_cmd:
block = pg_dbops.SQLBlock()
new_types: FrozenSet[str] = frozenset()
else:
block = pg_dbops.PLTopBlock()
new_types = frozenset(str(tid) for tid in pgdelta.new_types)
# Generate SQL DDL for the delta.
pgdelta.generate(block) # type: ignore
# XXX: We would prefer for there to not be trampolines ever after bootstrap
pgdelta.create_trampolines.generate(block) # type: ignore
# Generate schema storage SQL (DML into schema storage tables).
subblock = block.add_block()
compiler.compile_schema_storage_in_delta(
ctx, pgdelta, subblock, context=context
)
# Performance hack; we really want trivial migration commands
# (that only mutate the migration log) to not trigger a pg_catalog
# view refresh, since many get issued as part of MIGRATION
# REWRITEs.
all_migration_tweaks = all(
isinstance(
cmd, (s_ver.AlterSchemaVersion, s_migrations.MigrationCommand)
)
and not cmd.get_subcommands(type=s_delta.ObjectCommand)
for cmd in delta.get_subcommands()
)
if not ctx.bootstrap_mode and not all_migration_tweaks:
from edb.pgsql import metaschema
refresh = metaschema.generate_sql_information_schema_refresh(
ctx.compiler_state.backend_runtime_params.instance_params.version
)
refresh.generate(subblock)
return block, new_types, pgdelta.config_ops
def compile_dispatch_ql_migration(
ctx: compiler.CompileContext,
ql: qlast.MigrationCommand,
*,
in_script: bool,
) -> dbstate.BaseQuery:
if ctx.expect_rollback and not isinstance(
ql, (qlast.AbortMigration, qlast.AbortMigrationRewrite)
):
# Only allow ABORT MIGRATION to pass when expecting a rollback
if ctx.state.current_tx().get_migration_state() is None:
raise errors.TransactionError(
'expected a ROLLBACK or ROLLBACK TO SAVEPOINT command'
)
else:
raise errors.TransactionError(
'expected a ROLLBACK or ABORT MIGRATION command'
)
match ql:
case qlast.CreateMigration():
ctx._assert_not_in_migration_block(ql)
return compile_and_apply_ddl_stmt(ctx, ql)
case qlast.StartMigration():
return _start_migration(ctx, ql, in_script)
case qlast.PopulateMigration():
return _populate_migration(ctx, ql)
case qlast.DescribeCurrentMigration():
return _describe_current_migration(ctx, ql)
case qlast.AlterCurrentMigrationRejectProposed():
return _alter_current_migration_reject_proposed(ctx, ql)
case qlast.CommitMigration():
return _commit_migration(ctx, ql)
case qlast.AbortMigration():
return _abort_migration(ctx, ql)
case qlast.DropMigration():
ctx._assert_not_in_migration_block(ql)
return compile_and_apply_ddl_stmt(ctx, ql)
case qlast.StartMigrationRewrite():
return _start_migration_rewrite(ctx, ql, in_script)
case qlast.CommitMigrationRewrite():
return _commit_migration_rewrite(ctx, ql)
case qlast.AbortMigrationRewrite():
return _abort_migration_rewrite(ctx, ql)
case qlast.ResetSchema():
return _reset_schema(ctx, ql)
case _:
raise AssertionError(f'unexpected migration command: {ql}')
def _start_migration(
ctx: compiler.CompileContext,
ql: qlast.StartMigration,
in_script: bool,
) -> dbstate.BaseQuery:
ctx._assert_not_in_migration_block(ql)
current_tx = ctx.state.current_tx()
schema = current_tx.get_schema(ctx.compiler_state.std_schema)
if current_tx.is_implicit() and not in_script:
savepoint_name = None
tx_cmd = qlast.StartTransaction()
tx_query = compiler._compile_ql_transaction(ctx, tx_cmd)
query = dbstate.MigrationControlQuery(
sql=tx_query.sql,
action=dbstate.MigrationAction.START,
tx_action=tx_query.action,
cacheable=False,
modaliases=None,
)
else:
savepoint_name = current_tx.start_migration()
query = dbstate.MigrationControlQuery(
sql=NIL_QUERY,
action=dbstate.MigrationAction.START,
tx_action=None,
cacheable=False,
modaliases=None,
)
if isinstance(ql.target, qlast.CommittedSchema):
mrstate = ctx._assert_in_migration_rewrite_block(ql)
target_schema = mrstate.target_schema
else:
assert ctx.compiler_state.std_schema is not None
base_schema = s_schema.ChainedSchema(
ctx.compiler_state.std_schema,
s_schema.EMPTY_SCHEMA,
current_tx.get_global_schema(),
)
target_schema, warnings = s_ddl.apply_sdl(
ql.target,
base_schema=base_schema,
current_schema=schema,
testmode=ctx.is_testmode(),
)
query = dataclasses.replace(query, warnings=tuple(warnings))
current_tx.update_migration_state(
dbstate.MigrationState(
parent_migration=schema.get_last_migration(),
initial_schema=schema,
initial_savepoint=savepoint_name,
guidance=s_obj.DeltaGuidance(),
target_schema=target_schema,
accepted_cmds=tuple(),
last_proposed=None,
),
)
return query
def _populate_migration(
ctx: compiler.CompileContext,
ql: qlast.PopulateMigration,
) -> dbstate.BaseQuery:
mstate = ctx._assert_in_migration_block(ql)
current_tx = ctx.state.current_tx()
schema = current_tx.get_schema(ctx.compiler_state.std_schema)
diff = s_ddl.delta_schemas(
schema,
mstate.target_schema,
guidance=mstate.guidance,
)
if debug.flags.delta_plan:
debug.header('Populate Migration Diff')
debug.dump(diff, schema=schema)
new_ddl: Tuple[qlast.DDLCommand, ...] = tuple(
s_ddl.ddlast_from_delta( # type: ignore
schema,
mstate.target_schema,
diff,
testmode=ctx.is_testmode(),
),
)
all_ddl = mstate.accepted_cmds + new_ddl
mstate = mstate._replace(
accepted_cmds=all_ddl,
last_proposed=None,
)
if debug.flags.delta_plan:
debug.header('Populate Migration DDL AST')
text = []
for cmd in new_ddl:
debug.dump(cmd)
text.append(qlcodegen.generate_source(cmd, pretty=True))
debug.header('Populate Migration DDL Text')
debug.dump_code(';\n'.join(text) + ';')
current_tx.update_migration_state(mstate)
delta_context = _new_delta_context(ctx)
# We want to make *certain* that the DDL we generate
# produces the correct schema when applied, so we reload
# the diff from the AST instead of just relying on the
# delta tree. We do this check because it is *very
# important* that we not emit DDL that moves the schema
# into the wrong state.
#
# The actual check for whether the schema matches is done
# by DESCRIBE CURRENT MIGRATION AS JSON, to populate the
# 'complete' flag.
if debug.flags.delta_plan:
debug.header('Populate Migration Applied Diff')
for cmd in new_ddl:
reloaded_diff = s_ddl.delta_from_ddl(
cmd,
schema=schema,
modaliases=current_tx.get_modaliases(),
**_get_delta_context_args(ctx),
)
schema = reloaded_diff.apply(schema, delta_context)
if debug.flags.delta_plan:
debug.dump(reloaded_diff, schema=schema)
current_tx.update_schema(schema)
return dbstate.MigrationControlQuery(
sql=NIL_QUERY,
tx_action=None,
action=dbstate.MigrationAction.POPULATE,
cacheable=False,
modaliases=None,
)
def _describe_current_migration(
ctx: compiler.CompileContext,
ql: qlast.DescribeCurrentMigration,
) -> dbstate.BaseQuery:
mstate = ctx._assert_in_migration_block(ql)
current_tx = ctx.state.current_tx()
schema = current_tx.get_schema(ctx.compiler_state.std_schema)
if ql.language is qltypes.DescribeLanguage.DDL:
text = []
for stmt in mstate.accepted_cmds:
# Generate uppercase DDL commands for backwards
# compatibility with older migration text.
text.append(
qlcodegen.generate_source(stmt, pretty=True, uppercase=True)
)
if text:
description = ';\n'.join(text) + ';'
else:
description = ''
desc_ql = edgeql.parse_query(
f'SELECT {qlquote.quote_literal(description)}')
return compiler._compile_ql_query(
ctx,
desc_ql,
cacheable=False,
migration_block_query=True,
)
if ql.language is qltypes.DescribeLanguage.JSON:
confirmed = []
for stmt in mstate.accepted_cmds:
confirmed.append(
# Add a terminating semicolon to match
# "proposed", which is created by
# s_ddl.statements_from_delta.
#
# Also generate uppercase DDL commands for
# backwards compatibility with older migration
# text.
qlcodegen.generate_source(stmt, pretty=True, uppercase=True)
+ ';',
)
if mstate.last_proposed is None:
guided_diff = s_ddl.delta_schemas(
schema,
mstate.target_schema,
generate_prompts=True,
guidance=mstate.guidance,
)
if debug.flags.delta_plan:
debug.header('DESCRIBE CURRENT MIGRATION AS JSON delta')
debug.dump(guided_diff)
proposed_ddl = s_ddl.statements_from_delta(
schema, mstate.target_schema, guided_diff, uppercase=True
)
proposed_steps = []
if proposed_ddl:
for ddl_text, ddl_ast, top_op in proposed_ddl:
assert isinstance(top_op, s_delta.ObjectCommand)
# get_ast has a lot of logic for figuring
# out when an op is implicit in a parent
# op. get_user_prompt does not have any of
# that sort of logic, which makes it
# susceptible to producing overly broad
# messages. To avoid duplicating that sort
# of logic, we recreate the delta from the
# AST, and extract a user prompt from
# *that*.
# This is stupid, and it is slow.
top_op2 = s_ddl.cmd_from_ddl(
ddl_ast,
schema=schema,
modaliases=current_tx.get_modaliases(),
)
assert isinstance(top_op2, s_delta.ObjectCommand)
prompt_key2, prompt_text = top_op2.get_user_prompt()
# Similarly, some placeholders may not have made
# it into the actual query, so filter them out.
used_placeholders = {
p.name
for p in ast.find_children(ddl_ast, qlast.Placeholder)
}
required_user_input = tuple(
inp
for inp in top_op.get_required_user_input()
if inp['placeholder'] in used_placeholders
)
# The prompt_id still needs to come from
# the original op, though, since
# orig_cmd_class is lost in ddl.
prompt_key, _ = top_op.get_user_prompt()
prompt_id = s_delta.get_object_command_id(prompt_key)
confidence = top_op.get_annotation('confidence')
assert confidence is not None
step = dbstate.ProposedMigrationStep(
statements=(ddl_text,),
confidence=confidence,
prompt=prompt_text,
prompt_id=prompt_id,
data_safe=top_op.is_data_safe(),
required_user_input=required_user_input,
operation_key=prompt_key2,
)
proposed_steps.append(step)
proposed_desc = proposed_steps[0].to_json()
else:
proposed_desc = None
mstate = mstate._replace(
last_proposed=tuple(proposed_steps),
)
current_tx.update_migration_state(mstate)
else:
if mstate.last_proposed:
proposed_desc = mstate.last_proposed[0].to_json()
else:
proposed_desc = None
extra = {}
complete = False
if proposed_desc is None:
diff = s_ddl.delta_schemas(schema, mstate.target_schema)
complete = not bool(diff.get_subcommands())
if debug.flags.delta_plan and not complete:
debug.header('DESCRIBE CURRENT MIGRATION AS JSON mismatch')
debug.dump(diff)
if not complete:
extra['debug_diff'] = debug.dumps(diff)
desc = (
json.dumps(
{
'parent': (
str(mstate.parent_migration.get_name(schema))
if mstate.parent_migration is not None
else 'initial'
),
'complete': complete,
'confirmed': confirmed,
'proposed': proposed_desc,
**extra,
}
)
)
desc_ql = edgeql.parse_query(
f'SELECT to_json({qlquote.quote_literal(desc)})'
)
return compiler._compile_ql_query(
ctx,
desc_ql,
cacheable=False,
migration_block_query=True,
)
raise AssertionError(
f'DESCRIBE CURRENT MIGRATION AS {ql.language}' f' is not implemented'
)
def _alter_current_migration_reject_proposed(
ctx: compiler.CompileContext,
ql: qlast.AlterCurrentMigrationRejectProposed,
) -> dbstate.BaseQuery:
mstate = ctx._assert_in_migration_block(ql)
current_tx = ctx.state.current_tx()
if not mstate.last_proposed:
# XXX: Or should we compute what the proposal would be?
new_guidance = mstate.guidance
else:
last = mstate.last_proposed[0]
cmdclass_name, mcls, classname, new_name = last.operation_key
if new_name is None:
new_name = classname
if cmdclass_name.startswith('Create'):
new_guidance = mstate.guidance._replace(
banned_creations=mstate.guidance.banned_creations
| {
(mcls, classname),
}
)
elif cmdclass_name.startswith('Delete'):
new_guidance = mstate.guidance._replace(
banned_deletions=mstate.guidance.banned_deletions
| {
(mcls, classname),
}
)
else:
new_guidance = mstate.guidance._replace(
banned_alters=mstate.guidance.banned_alters
| {
(mcls, (classname, new_name)),
}
)
mstate = mstate._replace(
guidance=new_guidance,
last_proposed=None,
)
current_tx.update_migration_state(mstate)
return dbstate.MigrationControlQuery(
sql=NIL_QUERY,
tx_action=None,
action=dbstate.MigrationAction.REJECT_PROPOSED,
cacheable=False,
modaliases=None,
)
def _commit_migration(
ctx: compiler.CompileContext,
ql: qlast.CommitMigration,
) -> dbstate.BaseQuery:
mstate = ctx._assert_in_migration_block(ql)
current_tx = ctx.state.current_tx()
schema = current_tx.get_schema(ctx.compiler_state.std_schema)
diff = s_ddl.delta_schemas(schema, mstate.target_schema)
if list(diff.get_subcommands()):
raise errors.QueryError(
'cannot commit incomplete migration',
hint=(
'Please finish the migration by specifying the'
' remaining DDL operations or run POPULATE MIGRATION'
' to let the system populate the outstanding DDL'
' automatically.'
),
span=ql.span,
)
if debug.flags.delta_plan:
debug.header('Commit Migration DDL AST')
text = []
for cmd in mstate.accepted_cmds:
debug.dump(cmd)
text.append(qlcodegen.generate_source(cmd, pretty=True))
debug.header('Commit Migration DDL Text')
debug.dump_code(';\n'.join(text) + ';')
last_migration = schema.get_last_migration()
if last_migration:
last_migration_ref = s_utils.name_to_ast_ref(
last_migration.get_name(schema),
)
else:
last_migration_ref = None
target_sdl: Optional[str] = None
store_migration_sdl = compiler._get_config_val(ctx, 'store_migration_sdl')
if store_migration_sdl == 'AlwaysStore':
target_sdl = s_ddl.sdl_text_from_schema(schema)
create_migration = qlast.CreateMigration( # type: ignore
body=qlast.NestedQLBlock(
commands=mstate.accepted_cmds # type: ignore
),
parent=last_migration_ref,
target_sdl=target_sdl,
)
current_tx.update_schema(mstate.initial_schema)
current_tx.update_migration_state(None)
# If we are in a migration rewrite, don't actually apply
# the change, just record it.
if mrstate := current_tx.get_migration_rewrite_state():
current_tx.update_schema(mstate.target_schema)
mrstate = mrstate._replace(
accepted_migrations=(
mrstate.accepted_migrations + (create_migration,)
)
)
current_tx.update_migration_rewrite_state(mrstate)
return dbstate.MigrationControlQuery(
sql=NIL_QUERY,
action=dbstate.MigrationAction.COMMIT,
tx_action=None,
cacheable=False,
modaliases=None,
)
current_tx.update_schema(mstate.initial_schema)
current_tx.update_migration_state(None)
ddl_query = compile_and_apply_ddl_stmt(
ctx,
create_migration,
)
if mstate.initial_savepoint:
current_tx.commit_migration(mstate.initial_savepoint)
tx_action = None
else:
tx_action = dbstate.TxAction.COMMIT
return dbstate.MigrationControlQuery(
sql=ddl_query.sql,
ddl_stmt_id=ddl_query.ddl_stmt_id,
action=dbstate.MigrationAction.COMMIT,
tx_action=tx_action,
cacheable=False,
modaliases=None,
user_schema=ctx.state.current_tx().get_user_schema(),
cached_reflection=(current_tx.get_cached_reflection_if_updated()),
)
def _abort_migration(
ctx: compiler.CompileContext,
ql: qlast.AbortMigration,
) -> dbstate.BaseQuery:
mstate = ctx._assert_in_migration_block(ql)
current_tx = ctx.state.current_tx()
if mstate.initial_savepoint:
current_tx.abort_migration(mstate.initial_savepoint)
sql = NIL_QUERY
tx_action = None
else:
tx_cmd = qlast.RollbackTransaction()
tx_query = compiler._compile_ql_transaction(ctx, tx_cmd)
sql = tx_query.sql
tx_action = tx_query.action
current_tx.update_migration_state(None)
return dbstate.MigrationControlQuery(
sql=sql,
action=dbstate.MigrationAction.ABORT,
tx_action=tx_action,
cacheable=False,
modaliases=None,
)
def _start_migration_rewrite(
ctx: compiler.CompileContext,
ql: qlast.StartMigrationRewrite,
in_script: bool,
) -> dbstate.BaseQuery:
ctx._assert_not_in_migration_block(ql)
ctx._assert_not_in_migration_rewrite_block(ql)
current_tx = ctx.state.current_tx()
schema = current_tx.get_schema(ctx.compiler_state.std_schema)
# Start a transaction if we aren't in one already
if current_tx.is_implicit() and not in_script:
savepoint_name = None
tx_cmd = qlast.StartTransaction()
tx_query = compiler._compile_ql_transaction(ctx, tx_cmd)
query = dbstate.MigrationControlQuery(
sql=tx_query.sql,