-
Notifications
You must be signed in to change notification settings - Fork 45
/
schema_updater.cc
4848 lines (4474 loc) · 201 KB
/
schema_updater.cc
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
//
// Copyright 2020 Google LLC
//
// 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.
//
#include "backend/schema/updater/schema_updater.h"
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <optional>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include "zetasql/base/logging.h"
#include "google/spanner/admin/database/v1/common.pb.h"
#include "zetasql/public/analyzer_options.h"
#include "zetasql/public/function.h"
#include "zetasql/public/function.pb.h"
#include "zetasql/public/function_signature.h"
#include "zetasql/public/options.pb.h"
#include "zetasql/public/simple_catalog.h"
#include "zetasql/public/type.h"
#include "zetasql/resolved_ast/resolved_node_kind.pb.h"
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/flags/flag.h"
#include "absl/functional/function_ref.h"
#include "absl/log/log.h"
#include "absl/meta/type_traits.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "absl/strings/substitute.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "backend/common/case.h"
#include "backend/common/ids.h"
#include "backend/common/utils.h"
#include "backend/database/pg_oid_assigner/pg_oid_assigner.h"
#include "backend/query/analyzer_options.h"
#include "backend/query/catalog.h"
#include "backend/query/function_catalog.h"
#include "backend/schema/backfills/change_stream_backfill.h"
#include "backend/schema/backfills/column_value_backfill.h"
#include "backend/schema/backfills/index_backfill.h"
#include "backend/schema/builders/change_stream_builder.h"
#include "backend/schema/builders/check_constraint_builder.h"
#include "backend/schema/builders/column_builder.h"
#include "backend/schema/builders/database_options_builder.h"
#include "backend/schema/builders/foreign_key_builder.h"
#include "backend/schema/builders/index_builder.h"
#include "backend/schema/builders/model_builder.h"
#include "backend/schema/builders/named_schema_builder.h"
#include "backend/schema/builders/sequence_builder.h"
#include "backend/schema/builders/table_builder.h"
#include "backend/schema/builders/udf_builder.h"
#include "backend/schema/builders/view_builder.h"
#include "backend/schema/catalog/change_stream.h"
#include "backend/schema/catalog/check_constraint.h"
#include "backend/schema/catalog/column.h"
#include "backend/schema/catalog/database_options.h"
#include "backend/schema/catalog/foreign_key.h"
#include "backend/schema/catalog/index.h"
#include "backend/schema/catalog/model.h"
#include "backend/schema/catalog/named_schema.h"
#include "backend/schema/catalog/proto_bundle.h"
#include "backend/schema/catalog/schema.h"
#include "backend/schema/catalog/sequence.h"
#include "backend/schema/catalog/table.h"
#include "backend/schema/catalog/udf.h"
#include "backend/schema/catalog/view.h"
#include "backend/schema/ddl/operations.pb.h"
#include "backend/schema/graph/schema_graph.h"
#include "backend/schema/graph/schema_graph_editor.h"
#include "backend/schema/graph/schema_node.h"
#include "backend/schema/parser/ddl_parser.h"
#include "backend/schema/updater/ddl_type_conversion.h"
#include "backend/schema/updater/global_schema_names.h"
#include "backend/schema/updater/schema_validation_context.h"
#include "backend/schema/updater/sql_expression_validators.h"
#include "backend/schema/verifiers/check_constraint_verifiers.h"
#include "backend/schema/verifiers/foreign_key_verifiers.h"
#include "backend/storage/storage.h"
#include "common/constants.h"
#include "common/errors.h"
#include "common/feature_flags.h"
#include "common/limits.h"
#include "third_party/spanner_pg/ddl/ddl_translator.h"
#include "third_party/spanner_pg/ddl/pg_to_spanner_ddl_translator.h"
#include "third_party/spanner_pg/interface/emulator_parser.h"
#include "third_party/spanner_pg/interface/parser_output.h"
#include "third_party/spanner_pg/interface/pg_arena.h"
#include "third_party/spanner_pg/interface/spangres_translator_interface.h"
#include "third_party/spanner_pg/shims/error_shim.h"
#include "third_party/spanner_pg/shims/memory_context_pg_arena.h"
#include "google/protobuf/repeated_ptr_field.h"
#include "zetasql/base/ret_check.h"
#include "zetasql/base/status_macros.h"
ABSL_FLAG(bool, cloud_spanner_emulator_disable_cs_retention_check, false,
"whether we want to check the retention limit when altering a change "
"stream's retention period.");
namespace google {
namespace spanner {
namespace emulator {
namespace backend {
namespace {
namespace database_api = ::google::spanner::admin::database::v1;
using ::postgres_translator::interfaces::ExpressionTranslateResult;
// A struct that defines the columns used by an index.
struct ColumnsUsedByIndex {
std::vector<const KeyColumn*> index_key_columns;
std::vector<const Column*> stored_columns;
std::vector<const Column*> null_filtered_columns;
std::vector<const Column*> partition_by_columns;
std::vector<const Column*> order_by_columns;
};
// Get all the names of objects in a vector of objects. Useful for creating
// error messages with multiple objects, i.e. getting all the names of tables in
// a schema.
template <typename T>
std::vector<std::string> GetObjectNames(absl::Span<const T* const> objects) {
std::vector<std::string> names;
for (const auto* object : objects) {
names.push_back(object->Name());
}
return names;
}
// A class that processes a set of Cloud Spanner DDL statements, and applies
// them to an existing (or empty) `Schema` to obtain the updated `Schema`.
//
// The effects of the DDL statements are checked for semantic validity during
// the process and appropriate errors returned on any violations.
//
// Implementation note:
// Semantic violation checks other than existence checks (required to build
// proper reference relationships in the schema graph) should be avoided in this
// class and should instead be encoded in the `Validate()` and
// `ValidateUpdate()` implementations of `SchemaNode`(s) so that they are
// executed during both database schema creation and update.
class SchemaUpdaterImpl {
public:
SchemaUpdaterImpl() = delete; // Private construction only.
~SchemaUpdaterImpl() = default;
// Disallow copies but enable moves.
SchemaUpdaterImpl(const SchemaUpdaterImpl&) = delete;
SchemaUpdaterImpl& operator=(const SchemaUpdaterImpl&) = delete;
SchemaUpdaterImpl(SchemaUpdaterImpl&&) = default;
// Assignment move is not supported by absl::Time.
SchemaUpdaterImpl& operator=(SchemaUpdaterImpl&&) = delete;
absl::StatusOr<SchemaUpdaterImpl> static Build(
zetasql::TypeFactory* type_factory,
TableIDGenerator* table_id_generator,
ColumnIDGenerator* column_id_generator, Storage* storage,
absl::Time schema_change_ts, PgOidAssigner* pg_oid_assigner,
const Schema* existing_schema) {
SchemaUpdaterImpl impl(type_factory, table_id_generator,
column_id_generator, storage, schema_change_ts,
pg_oid_assigner, existing_schema);
ZETASQL_RETURN_IF_ERROR(impl.Init());
return impl;
}
// Apply DDL statements returning the SchemaValidationContext containing
// the schema change actions resulting from each statement. Please note that
// it can return an empty vector when all statements are no-op and no changes
// are made.
absl::StatusOr<std::vector<SchemaValidationContext>> ApplyDDLStatements(
const SchemaChangeOperation& schema_change_operation);
std::vector<std::unique_ptr<const Schema>> GetIntermediateSchemas() {
return std::move(intermediate_schemas_);
}
private:
SchemaUpdaterImpl(zetasql::TypeFactory* type_factory,
TableIDGenerator* table_id_generator,
ColumnIDGenerator* column_id_generator, Storage* storage,
absl::Time schema_change_ts, PgOidAssigner* pg_oid_assigner,
const Schema* existing_schema)
: type_factory_(type_factory),
table_id_generator_(table_id_generator),
column_id_generator_(column_id_generator),
storage_(storage),
schema_change_timestamp_(schema_change_ts),
latest_schema_(existing_schema),
editor_(nullptr),
pg_oid_assigner_(pg_oid_assigner) {}
// Initializes potentially failing components after construction.
absl::Status Init();
// Applies the given `statement` on to `latest_schema_`. Please note that
// it can return a nullptr if the statement is a no-op and no changes are
// made.
absl::StatusOr<std::unique_ptr<const Schema>> ApplyDDLStatement(
absl::string_view statement, absl::string_view proto_descriptor_bytes,
const database_api::DatabaseDialect& dialect);
// Run any pending schema actions resulting from the schema change statements.
absl::Status RunPendingActions(
const std::vector<SchemaValidationContext>& pending_work,
int* num_succesful);
absl::Status InitColumnNameAndTypesFromTable(
const Table* table, const ddl::CreateTable* ddl_create_table,
std::vector<zetasql::SimpleTable::NameAndType>* name_and_types);
absl::Status AnalyzeGeneratedColumn(
absl::string_view expression, const std::string& column_name,
const zetasql::Type* column_type, const Table* table,
const ddl::CreateTable* ddl_create_table,
absl::flat_hash_set<std::string>* dependent_column_names,
absl::flat_hash_set<const SchemaNode*>* udf_dependencies);
absl::Status AnalyzeColumnDefaultValue(
absl::string_view expression, const std::string& column_name,
const zetasql::Type* column_type, const Table* table,
const ddl::CreateTable* ddl_create_table,
absl::flat_hash_set<const SchemaNode*>* dependent_sequences,
absl::flat_hash_set<const SchemaNode*>* udf_dependencies);
absl::Status AnalyzeCheckConstraint(
absl::string_view expression, const Table* table,
const ddl::CreateTable* ddl_create_table,
absl::flat_hash_set<std::string>* dependent_column_names,
CheckConstraint::Builder* builder,
absl::flat_hash_set<const SchemaNode*>* udf_dependencies);
template <typename ColumnModifier>
absl::Status SetColumnOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
const database_api::DatabaseDialect& dialect, ColumnModifier* modifier);
template <typename ColumnDef, typename ColumnDefModifer>
absl::StatusOr<std::string> TranslatePGExpression(
const ColumnDef& ddl_column, const Table* table,
const ddl::CreateTable* ddl_create_table, ColumnDefModifer& modifier);
template <typename ColumnDefModifier>
absl::Status SetColumnDefinition(const ddl::ColumnDefinition& ddl_column,
const Table* table,
const ddl::CreateTable* ddl_create_table,
const database_api::DatabaseDialect& dialect,
ColumnDefModifier* modifier);
absl::Status AlterColumnDefinition(
const ddl::ColumnDefinition& ddl_column, const Table* table,
const database_api::DatabaseDialect& dialect, Column::Editor* editor);
absl::Status AlterColumnSetDropDefault(
const ddl::AlterTable::AlterColumn& alter_column, const Table* table,
const Column* column, const database_api::DatabaseDialect& dialect,
Column::Editor* editor);
absl::StatusOr<const Column*> CreateColumn(
const ddl::ColumnDefinition& ddl_column, const Table* table,
const ddl::CreateTable* ddl_table,
const database_api::DatabaseDialect& dialect);
absl::StatusOr<const KeyColumn*> CreatePrimaryKeyColumn(
const ddl::KeyPartClause& ddl_key_part, const Table* table,
KeyColumn::Builder* builder);
absl::Status CreatePrimaryKeyConstraint(
const ddl::KeyPartClause& ddl_key_part, Table::Builder* builder,
bool with_oid = true);
absl::Status CreateInterleaveConstraint(
const ddl::InterleaveClause& interleave, Table::Builder* builder);
absl::Status CreateInterleaveConstraint(const Table* parent,
Table::OnDeleteAction on_delete,
Table::Builder* builder);
absl::Status ValidateChangeStreamForClause(
const ddl::ChangeStreamForClause& change_stream_for_clause,
absl::string_view change_stream_name);
absl::Status ValidateChangeStreamLimits(
const ddl::ChangeStreamForClause& change_stream_for_clause,
absl::string_view change_stream_name);
absl::Status ValidateLimitsForTrackedObjects(
const ddl::ChangeStreamForClause& change_stream_for_clause,
absl::FunctionRef<absl::Status(const Table*)> table_cb,
absl::FunctionRef<absl::Status(const Column*)> column_cb);
absl::Status RegisterTrackedObjects(
const ddl::ChangeStreamForClause& change_stream_for_clause,
const ChangeStream* change_stream);
absl::Status UnregisterChangeStreamFromTrackedObjects(
const ChangeStream* change_stream);
absl::Status BuildChangeStreamTrackedObjects(
const ddl::ChangeStreamForClause& change_stream_for_clause,
const ChangeStream* change_stream, ChangeStream::Builder* builder);
absl::Status EditChangeStreamTrackedObjects(
const ddl::ChangeStreamForClause& change_stream_for_clause,
const ChangeStream* change_stream);
absl::Status UnregisterChangeStreamFromTrackedObjects(
const ChangeStream* change_stream,
absl::FunctionRef<absl::Status(Table::Editor*)> table_cb,
absl::FunctionRef<absl::Status(Column::Editor*)> column_cb);
absl::Status RegisterTrackedObjects(
const ChangeStream* change_stream,
const ddl::ChangeStreamForClause& change_stream_for_clause,
absl::FunctionRef<absl::Status(Table::Editor*)> table_cb,
absl::FunctionRef<absl::Status(Column::Editor*)> column_cb);
template <typename ChangeStreamModifier>
absl::Status SetChangeStreamOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
ChangeStreamModifier* modifier);
template <typename Modifier>
absl::Status SetDatabaseOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
Modifier* modifier);
absl::Status ValidateChangeStreamOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options);
static std::string MakeChangeStreamTvfName(
std::string change_stream_name,
const database_api::DatabaseDialect& dialect);
absl::StatusOr<const Table*> GetInterleaveConstraintTable(
const std::string& interleave_in_table_name,
const Table::Builder& builder) const;
static Table::OnDeleteAction GetInterleaveConstraintOnDelete(
const ddl::InterleaveClause& interleave);
absl::Status CreateForeignKeyConstraint(
const ddl::ForeignKey& ddl_foreign_key, const Table* referencing_table);
absl::StatusOr<const ForeignKey*> BuildForeignKeyConstraint(
const ddl::ForeignKey& ddl_foreign_key, const Table* referencing_table);
absl::Status EvaluateForeignKeyReferencedPrimaryKey(
const Table* table,
const google::protobuf::RepeatedPtrField<std::string>& column_names,
std::vector<int>* column_order, bool* index_required) const;
absl::Status EvaluateForeignKeyReferencingPrimaryKey(
const Table* table,
const google::protobuf::RepeatedPtrField<std::string>& column_names,
const std::vector<int>& column_order, bool* index_required) const;
absl::StatusOr<const Index*> CreateForeignKeyIndex(
const ForeignKey* foreign_key, const Table* table,
const std::vector<std::string>& column_names, bool unique);
bool CanInterleaveForeignKeyIndex(
const Table* table, const std::vector<std::string>& column_names) const;
absl::StatusOr<ExpressionTranslateResult> TranslatePostgreSqlExpression(
const Table* table, const ddl::CreateTable* ddl_create_table,
absl::string_view expression);
absl::StatusOr<ExpressionTranslateResult> TranslatePostgreSqlQueryInView(
absl::string_view query);
absl::Status CreateCheckConstraint(
const ddl::CheckConstraint& ddl_check_constraint, const Table* table,
const ddl::CreateTable* ddl_create_table);
absl::Status CreateRowDeletionPolicy(
const ddl::RowDeletionPolicy& row_deletion_policy,
Table::Builder* builder);
absl::StatusOr<std::shared_ptr<const ProtoBundle>> CreateProtoBundle(
const ddl::CreateProtoBundle& ddl_proto_bundle,
absl::string_view proto_descriptor_bytes);
absl::Status CreateTable(const ddl::CreateTable& ddl_table,
const database_api::DatabaseDialect& dialect);
absl::StatusOr<const Column*> CreateIndexDataTableColumn(
const Table* indexed_table, const std::string& source_column_name,
const Table* index_data_table, bool is_null_filtered);
absl::Status AddIndexColumnsByName(const std::string& column_name,
const Table* indexed_table,
bool is_null_filtered,
std::vector<const Column*>& columns,
Table::Builder& builder);
absl::Status AddSearchIndexColumns(
const ::google::protobuf::RepeatedPtrField<ddl::KeyPartClause>& key_parts,
const Table* indexed_table, bool is_null_filtered,
std::vector<const Column*>& columns, Table::Builder& builder);
absl::StatusOr<std::unique_ptr<const Table>> CreateIndexDataTable(
absl::string_view index_name,
const std::vector<ddl::KeyPartClause>& index_pk,
const std::string* interleave_in_table,
const ::google::protobuf::RepeatedPtrField<ddl::StoredColumnDefinition>&
stored_columns,
const ::google::protobuf::RepeatedPtrField<ddl::KeyPartClause>* partition_by,
const ::google::protobuf::RepeatedPtrField<ddl::KeyPartClause>* order_by,
const ::google::protobuf::RepeatedPtrField<std::string>* null_filtered_columns,
const Index* index, const Table* indexed_table,
ColumnsUsedByIndex* columns_used_by_index);
absl::StatusOr<std::unique_ptr<const Table>> CreateChangeStreamDataTable(
const ChangeStream* change_stream,
const Table* change_stream_partition_table);
absl::StatusOr<std::unique_ptr<const Table>> CreateChangeStreamPartitionTable(
const ChangeStream* change_stream);
absl::StatusOr<const Column*> CreateChangeStreamTableColumn(
const std::string& column_name, const Table* change_stream_table,
const zetasql::Type* type);
absl::StatusOr<const KeyColumn*> CreateChangeStreamTablePKColumn(
const std::string& pk_column_name, const Table* change_stream_table);
absl::Status CreateChangeStreamTablePKConstraint(
const std::string& pk_column_name, Table::Builder* builder);
absl::StatusOr<const Index*> CreateIndex(
const ddl::CreateIndex& ddl_index, const Table* indexed_table = nullptr);
absl::StatusOr<const Index*> CreateSearchIndex(
const ddl::CreateSearchIndex& ddl_index,
const Table* indexed_table = nullptr);
absl::StatusOr<const ChangeStream*> CreateChangeStream(
const ddl::CreateChangeStream& ddl_change_stream,
const database_api::DatabaseDialect& dialect);
absl::StatusOr<const Index*> CreateIndexHelper(
const std::string& index_name, const std::string& index_base_name,
bool is_unique, bool is_null_filtered,
const std::string* interleave_in_table,
const std::vector<ddl::KeyPartClause>& table_pk,
const ::google::protobuf::RepeatedPtrField<ddl::StoredColumnDefinition>&
stored_columns,
bool is_search_index,
const ::google::protobuf::RepeatedPtrField<ddl::KeyPartClause>* partition_by,
const ::google::protobuf::RepeatedPtrField<ddl::KeyPartClause>* order_by,
const ::google::protobuf::RepeatedPtrField<std::string>* null_filtered_columns,
const Table* indexed_table);
absl::flat_hash_set<const SchemaNode*>
GatherTransitiveDependenciesForSchemaNode(
const absl::flat_hash_set<const SchemaNode*>& initial_set);
bool IsBuiltInFunction(const std::string& function_name);
bool CanFunctionReplaceTakenName(const ddl::CreateFunction& ddl_function);
std::string GetFunctionKindAsString(const ddl::CreateFunction& ddl_function);
absl::Status AnalyzeFunctionDefinition(
const ddl::CreateFunction& ddl_function, bool replace,
absl::flat_hash_set<const SchemaNode*>* dependencies,
std::unique_ptr<zetasql::FunctionSignature>* function_signature,
Udf::Determinism* determinism_level);
absl::Status AnalyzeFunctionDefinition(
const ddl::CreateFunction& ddl_function, bool replace,
std::vector<View::Column>* output_columns,
absl::flat_hash_set<const SchemaNode*>* dependencies);
absl::StatusOr<Udf::Builder> CreateFunctionBuilder(
const ddl::CreateFunction& ddl_function,
std::unique_ptr<zetasql::FunctionSignature> function_signature,
Udf::Determinism determinism_level,
absl::flat_hash_set<const SchemaNode*> dependencies);
absl::StatusOr<View::Builder> CreateFunctionBuilder(
const ddl::CreateFunction& ddl_function,
std::vector<View::Column> output_columns,
absl::flat_hash_set<const SchemaNode*> dependencies);
absl::Status CreateFunction(const ddl::CreateFunction& ddl_function);
template <typename SequenceModifier>
absl::Status SetSequenceOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
SequenceModifier* modifier);
absl::Status ValidateSequenceOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
const Sequence* current_sequence);
absl::StatusOr<const Sequence*> CreateSequence(
const ddl::CreateSequence& create_sequence
);
absl::Status CreateNamedSchema(const ddl::CreateSchema& create_schema);
absl::Status AlterRowDeletionPolicy(
std::optional<ddl::RowDeletionPolicy> row_deletion_policy,
const Table* table);
absl::Status ValidateAlterDatabaseOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options);
absl::Status AlterDatabase(const ddl::AlterDatabase& alter_database);
absl::Status AlterTable(const ddl::AlterTable& alter_table,
const database_api::DatabaseDialect& dialect);
absl::Status AlterChangeStream(
const ddl::AlterChangeStream& alter_change_stream);
absl::Status AlterChangeStreamForClause(
const ddl::ChangeStreamForClause& ddl_change_stream_for_clause,
const ChangeStream* change_stream);
absl::Status AlterIndex(const ddl::AlterIndex& alter_index);
absl::Status AlterInterleaveAction(
const ddl::InterleaveClause::Action& ddl_interleave_action,
const Table* table);
absl::Status AlterSequence(const ddl::AlterSequence& alter_sequence,
const Sequence* current_sequence);
absl::Status AlterNamedSchema(const ddl::AlterSchema& alter_schema);
absl::StatusOr<std::shared_ptr<const ProtoBundle>> AlterProtoBundle(
const ddl::AlterProtoBundle& ddl_alter_proto_bundle,
absl::string_view proto_descriptor_bytes);
absl::Status AlterProtoColumnTypes(
const ProtoBundle* proto_bundle,
const ddl::AlterProtoBundle& ddl_alter_proto_bundle);
absl::Status AlterProtoColumnType(const Column* column,
const ProtoBundle* proto_bundle,
Column::Editor* editor);
absl::StatusOr<const zetasql::Type*> GetProtoTypeFromBundle(
const zetasql::Type* type, const ProtoBundle* proto_bundle);
absl::Status AddCheckConstraint(
const ddl::CheckConstraint& ddl_check_constraint, const Table* table);
absl::Status AddForeignKey(const ddl::ForeignKey& ddl_foreign_key,
const Table* table);
absl::Status DropConstraint(const std::string& constraint_name,
const Table* table);
absl::Status AddSynonym(const ddl::AlterTable::AddSynonym& add_synonym,
const Table* table);
absl::Status DropSynonym(const ddl::AlterTable::DropSynonym& drop_synonym,
const Table* table);
absl::Status DropTable(const ddl::DropTable& drop_table);
absl::Status DropIndex(const ddl::DropIndex& drop_index);
absl::Status DropChangeStream(
const ddl::DropChangeStream& drop_change_stream);
absl::Status DropSequence(const ddl::DropSequence& drop_sequence,
const Sequence* current_sequence);
absl::Status DropNamedSchema(const ddl::DropSchema& drop_schema);
absl::Status ApplyImplSetColumnOptions(
const ddl::SetColumnOptions& set_column_options,
const database_api::DatabaseDialect& dialect);
absl::StatusOr<std::shared_ptr<const ProtoBundle>> DropProtoBundle();
absl::Status DropFunction(const ddl::DropFunction& drop_function);
absl::StatusOr<Model::ModelColumn> CreateModelColumn(
const ddl::ColumnDefinition& ddl_column, const Model* model,
const ddl::CreateModel* ddl_model,
const database_api::DatabaseDialect& dialect);
absl::Status CreateModel(const ddl::CreateModel& ddl_model,
const database_api::DatabaseDialect& dialect);
absl::Status AlterModel(const ddl::AlterModel& alter_model);
absl::Status DropModel(const ddl::DropModel& drop_model);
template <typename ModelModifier>
absl::Status SetModelOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
ModelModifier* modifier);
// Adds a new schema object `node` to the schema copy being edited by
// `editor_`.
absl::Status AddNode(std::unique_ptr<const SchemaNode> node);
// Drops the schema object `node` in `latest_schema_` from the schema copy
// being edited by `editor_`.
absl::Status DropNode(const SchemaNode* node);
// Modifies the schema object `node` in `LatestSchema` in the schema
// copy being edited by `editor_`.
template <typename T>
absl::Status AlterNode(const T* node,
const SchemaGraphEditor::EditCallback<T>& alter_cb) {
ZETASQL_RET_CHECK_NE(node, nullptr);
ZETASQL_RETURN_IF_ERROR(editor_->EditNode<T>(node, alter_cb));
return absl::OkStatus();
}
absl::Status AlterInNamedSchema(
const std::string& object_name,
const SchemaGraphEditor::EditCallback<NamedSchema>& alter_cb);
// Type factory for the database. Not owned.
zetasql::TypeFactory* const type_factory_;
// Unique table ID generator for the database. Not owned.
TableIDGenerator* const table_id_generator_;
// Unique column ID generator for the database. Not owned.
ColumnIDGenerator* const column_id_generator_;
// Database's storage. For doing data-dependent validations and index
// backfills.
Storage* storage_;
// The timestamp at which the schema changes should be applied/validated
// against the database's contents.
const absl::Time schema_change_timestamp_;
// The latest schema snapshot corresponding to the statements preceding the
// statement currently being applied. Note that that does not guarantee that
// any verfication/backfill effects of those statements have been applied.
// Not owned.
const Schema* latest_schema_;
// The intermediate schema snapshots representing the schema state after
// applying each statement.
std::vector<std::unique_ptr<const Schema>> intermediate_schemas_;
// Validation context for the statement being currently processed.
// This is also being used in SchemaGraphEditor. Please make sure this is only
// passed by reference.
SchemaValidationContext* statement_context_;
// Editor used to modify the schema graph.
std::unique_ptr<SchemaGraphEditor> editor_;
// Manages global schema names to prevent and generate unique names.
GlobalSchemaNames global_names_;
// Assigns OIDs to database objects when dialect is POSTGRESQL. The assigner
// is owned by the database and is shared across all schema changes.
PgOidAssigner* pg_oid_assigner_;
};
absl::Status SchemaUpdaterImpl::Init() {
for (const SchemaNode* node :
latest_schema_->GetSchemaGraph()->GetSchemaNodes()) {
if (auto name = node->GetSchemaNameInfo(); name && name.value().global) {
ZETASQL_RETURN_IF_ERROR(
global_names_.AddName(name.value().kind, name.value().name));
}
}
return absl::OkStatus();
}
absl::Status SchemaUpdaterImpl::AddNode(
std::unique_ptr<const SchemaNode> node) {
ZETASQL_RETURN_IF_ERROR(editor_->AddNode(std::move(node)));
return absl::OkStatus();
}
absl::Status SchemaUpdaterImpl::DropNode(const SchemaNode* node) {
ZETASQL_RET_CHECK_NE(node, nullptr);
ZETASQL_RETURN_IF_ERROR(editor_->DeleteNode(node));
return absl::OkStatus();
}
absl::Status SchemaUpdaterImpl::AlterInNamedSchema(
const std::string& object_name,
const SchemaGraphEditor::EditCallback<NamedSchema>& alter_cb) {
const absl::string_view schema_name =
SDLObjectName::GetSchemaName(object_name);
const NamedSchema* named_schema =
latest_schema_->FindNamedSchema(std::string(schema_name));
if (named_schema == nullptr) {
return error::NamedSchemaNotFound(schema_name);
}
ZETASQL_RETURN_IF_ERROR(AlterNode<NamedSchema>(named_schema, alter_cb));
return absl::OkStatus();
}
absl::Status ValidateDdlStatement(const ddl::DDLStatement& ddl,
database_api::DatabaseDialect dialect) {
if ((ddl.has_create_function() || ddl.has_drop_function()) &&
!EmulatorFeatureFlags::instance().flags().enable_views) {
return error::ViewsNotSupported(ddl.has_create_function() ? "CREATE"
: "DROP");
}
if ((ddl.has_create_sequence() || ddl.has_alter_sequence() ||
ddl.has_drop_sequence()) &&
dialect == database_api::DatabaseDialect::POSTGRESQL &&
!EmulatorFeatureFlags::instance()
.flags()
.enable_bit_reversed_positive_sequences_postgresql) {
return error::SequenceNotSupportedInPostgreSQL();
}
return absl::OkStatus();
}
absl::StatusOr<std::unique_ptr<const Schema>>
SchemaUpdaterImpl::ApplyDDLStatement(
absl::string_view statement, absl::string_view proto_descriptor_bytes,
const database_api::DatabaseDialect& dialect) {
if (statement.empty()) {
return error::EmptyDDLStatement();
}
ZETASQL_RET_CHECK(!editor_->HasModifications());
ZETASQL_ASSIGN_OR_RETURN(std::unique_ptr<ddl::DDLStatement> ddl_statement,
ParseDDLByDialect(statement, dialect));
ZETASQL_RETURN_IF_ERROR(ValidateDdlStatement(*ddl_statement, dialect));
// Apply the statement to the schema graph.
auto proto_bundle = latest_schema_->proto_bundle();
switch (ddl_statement->statement_case()) {
case ddl::DDLStatement::kCreateProtoBundle: {
ZETASQL_ASSIGN_OR_RETURN(proto_bundle,
CreateProtoBundle(ddl_statement->create_proto_bundle(),
proto_descriptor_bytes));
break;
}
case ddl::DDLStatement::kCreateTable: {
ZETASQL_RETURN_IF_ERROR(CreateTable(ddl_statement->create_table(), dialect));
break;
}
case ddl::DDLStatement::kCreateChangeStream: {
ZETASQL_RETURN_IF_ERROR(
CreateChangeStream(ddl_statement->create_change_stream(), dialect)
.status());
break;
}
case ddl::DDLStatement::kCreateIndex: {
if (global_names_.HasName(ddl_statement->create_index().index_name()) &&
ddl_statement->create_index().existence_modifier() ==
ddl::IF_NOT_EXISTS) {
break;
}
ZETASQL_RETURN_IF_ERROR(CreateIndex(ddl_statement->create_index()).status());
break;
}
case ddl::DDLStatement::kCreateFunction: {
if (dialect == database_api::DatabaseDialect::POSTGRESQL) {
ddl::CreateFunction* create_function =
ddl_statement->mutable_create_function();
ZETASQL_RET_CHECK(create_function->has_sql_body_origin() &&
create_function->sql_body_origin().has_original_expression());
ZETASQL_ASSIGN_OR_RETURN(
ExpressionTranslateResult result,
TranslatePostgreSqlQueryInView(absl::StripAsciiWhitespace(
create_function->sql_body_origin().original_expression())));
// Overwrite the original_expression to the deparsed (formalized) PG
// expression which can be different from the user-input PG expression.
create_function->mutable_sql_body_origin()->set_original_expression(
result.original_postgresql_expression);
create_function->set_sql_body(result.translated_googlesql_expression);
}
ZETASQL_RETURN_IF_ERROR(CreateFunction(ddl_statement->create_function()));
break;
}
case ddl::DDLStatement::kCreateSequence: {
const ddl::CreateSequence& create_sequence =
ddl_statement->create_sequence();
if (latest_schema_->FindSequence(create_sequence.sequence_name()) !=
nullptr &&
create_sequence.existence_modifier() == ddl::IF_NOT_EXISTS) {
// A sequence with the same name already exists, and we have the
// IF NOT EXISTS clause in the statement, so return it as a no-op which
// would not cause any schema change.
return nullptr;
}
ZETASQL_RETURN_IF_ERROR(CreateSequence(ddl_statement->create_sequence()
)
.status());
break;
}
case ddl::DDLStatement::kCreateSchema: {
ZETASQL_RETURN_IF_ERROR(CreateNamedSchema(ddl_statement->create_schema()));
break;
}
case ddl::DDLStatement::kCreateSearchIndex: {
ZETASQL_RETURN_IF_ERROR(
CreateSearchIndex(ddl_statement->create_search_index()).status());
break;
}
case ddl::DDLStatement::kAlterDatabase: {
ZETASQL_RETURN_IF_ERROR(AlterDatabase(ddl_statement->alter_database()));
break;
}
case ddl::DDLStatement::kAlterTable: {
ZETASQL_RETURN_IF_ERROR(AlterTable(ddl_statement->alter_table(), dialect));
break;
}
case ddl::DDLStatement::kAlterChangeStream: {
ZETASQL_RETURN_IF_ERROR(AlterChangeStream(ddl_statement->alter_change_stream()));
break;
}
case ddl::DDLStatement::kAlterSequence: {
const ddl::AlterSequence& alter_sequence =
ddl_statement->alter_sequence();
const Sequence* current_sequence =
latest_schema_->FindSequence(alter_sequence.sequence_name()
);
if (current_sequence == nullptr) {
if (alter_sequence.existence_modifier() == ddl::IF_EXISTS) {
// The sequence doesn't exist, but we have the IF EXISTS clause
// in the statement, so return without error.
break;
}
return error::SequenceNotFound(alter_sequence.sequence_name());
}
ZETASQL_RETURN_IF_ERROR(AlterSequence(alter_sequence, current_sequence));
break;
}
case ddl::DDLStatement::kAlterIndex: {
ZETASQL_RETURN_IF_ERROR(AlterIndex(ddl_statement->alter_index()));
break;
}
case ddl::DDLStatement::kAlterSchema: {
ZETASQL_RETURN_IF_ERROR(AlterNamedSchema(ddl_statement->alter_schema()));
break;
}
case ddl::DDLStatement::kAlterProtoBundle: {
ZETASQL_ASSIGN_OR_RETURN(proto_bundle,
AlterProtoBundle(ddl_statement->alter_proto_bundle(),
proto_descriptor_bytes));
break;
}
case ddl::DDLStatement::kDropTable: {
ZETASQL_RETURN_IF_ERROR(DropTable(ddl_statement->drop_table()));
break;
}
case ddl::DDLStatement::kDropIndex: {
ZETASQL_RETURN_IF_ERROR(DropIndex(ddl_statement->drop_index()));
break;
}
case ddl::DDLStatement::kDropChangeStream: {
ZETASQL_RETURN_IF_ERROR(DropChangeStream(ddl_statement->drop_change_stream()));
break;
}
case ddl::DDLStatement::kDropFunction: {
ZETASQL_RETURN_IF_ERROR(DropFunction(ddl_statement->drop_function()));
break;
}
case ddl::DDLStatement::kDropSequence: {
const ddl::DropSequence& drop_sequence = ddl_statement->drop_sequence();
const Sequence* current_sequence =
latest_schema_->FindSequence(drop_sequence.sequence_name()
);
if (current_sequence == nullptr) {
if (drop_sequence.existence_modifier() == ddl::IF_EXISTS) {
// The sequence doesn't exist, but we have the IF EXISTS clause
// in the statement, so return without error.
break;
}
return error::SequenceNotFound(drop_sequence.sequence_name());
}
ZETASQL_RETURN_IF_ERROR(DropSequence(drop_sequence, current_sequence));
break;
}
case ddl::DDLStatement::kDropSchema: {
ZETASQL_RETURN_IF_ERROR(DropNamedSchema(ddl_statement->drop_schema()));
break;
}
case ddl::DDLStatement::kDropProtoBundle: {
ZETASQL_ASSIGN_OR_RETURN(proto_bundle, DropProtoBundle());
break;
}
case ddl::DDLStatement::kAnalyze:
// Intentionally no=op.
break;
case ddl::DDLStatement::kSetColumnOptions:
ZETASQL_RETURN_IF_ERROR(ApplyImplSetColumnOptions(
ddl_statement->set_column_options(), dialect));
break;
case ddl::DDLStatement::kCreateModel:
ZETASQL_RETURN_IF_ERROR(CreateModel(ddl_statement->create_model(), dialect));
break;
case ddl::DDLStatement::kAlterModel:
ZETASQL_RETURN_IF_ERROR(AlterModel(ddl_statement->alter_model()));
break;
case ddl::DDLStatement::kDropModel:
ZETASQL_RETURN_IF_ERROR(DropModel(ddl_statement->drop_model()));
break;
default:
ZETASQL_RET_CHECK(false) << "Unsupported ddl statement: "
<< ddl_statement->statement_case();
}
// Since Proto bundle needs to be used for column validation (via
// SchemaGraphEditor),this needs to be passed in statement context.
// SchemaValidationContext is being used and updated in both editor and
// updater and hence needs to be passed by reference.
// Use this proto_bundle only during validation (before schema
// generation). If there is a need to access proto_bundle after
// validation, please use schema->proto_bundle().
statement_context_->set_proto_bundle(proto_bundle);
ZETASQL_ASSIGN_OR_RETURN(auto new_schema_graph, editor_->CanonicalizeGraph());
return std::make_unique<const OwningSchema>(std::move(new_schema_graph),
proto_bundle, dialect);
}
absl::StatusOr<std::vector<SchemaValidationContext>>
SchemaUpdaterImpl::ApplyDDLStatements(
const SchemaChangeOperation& schema_change_operation) {
std::vector<SchemaValidationContext> pending_work;
for (const auto& statement : schema_change_operation.statements) {
ZETASQL_VLOG(2) << "Applying statement " << statement;
// Set up the SchemaValidationContext before passing it to `editor_`. This
// includes setting the old schema snapshot and a callback to construct
// a temporary schema snapshot of the pending new schema. The temporary
// schema snapshot does not own the new schema nodes but will remain alive
// for the lifetime of `editor_` and `statement_context_`. The callback
// mechanism is needed because 1) SchemaUpdater doesn't know at which point
// SchemaGraphEditor will validate the new schema and 2) SchemaGraphEditor
// or SchemaValidationContext cannot take a dependency on Schema.
std::unique_ptr<const Schema> new_tmp_schema = nullptr;
SchemaValidationContext statement_context{
storage_, &global_names_, type_factory_, schema_change_timestamp_,
schema_change_operation.database_dialect};
statement_context_ = &statement_context;
statement_context_->SetOldSchemaSnapshot(latest_schema_);
statement_context_->SetTempNewSchemaSnapshotConstructor(
[this,
&new_tmp_schema](const SchemaGraph* unowned_graph) -> const Schema* {
new_tmp_schema = std::make_unique<const Schema>(
unowned_graph, latest_schema_->proto_bundle(),
latest_schema_->dialect());
return new_tmp_schema.get();
});
// Initialize the editor that will be used to stage the schema changes.
editor_ = std::make_unique<SchemaGraphEditor>(
latest_schema_->GetSchemaGraph(), statement_context_);
// If there is a semantic validation error, then we return right away.
ZETASQL_ASSIGN_OR_RETURN(
auto new_schema,
ApplyDDLStatement(statement,
schema_change_operation.proto_descriptor_bytes,
schema_change_operation.database_dialect));
// This indicates that the statement was a no-op, e.g., a CREATE SEQUENCE IF
// NOT EXISTS statement for an existent sequence.
if (new_schema == nullptr) {
continue;
}
// We save every schema snapshot as verifiers/backfillers from the
// current/next statement may need to refer to the previous/current
// schema snapshots.
statement_context_->SetValidatedNewSchemaSnapshot(new_schema.get());
latest_schema_ = new_schema.get();
intermediate_schemas_.emplace_back(std::move(new_schema));
pg_oid_assigner_->MarkNextPostgresqlOidForIntermediateSchema();
// If everything was OK, make this the new schema snapshot for processing
// the next statement and save the pending schema snapshot and backfill
// work.
pending_work.emplace_back(std::move(statement_context));
}
return pending_work;
}
template <typename ColumnModifier>
absl::Status SchemaUpdaterImpl::SetColumnOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
const database_api::DatabaseDialect& dialect, ColumnModifier* modifier) {
std::optional<bool> allows_commit_timestamp = std::nullopt;
std::string commit_timestamp_option_name = ddl::kCommitTimestampOptionName;
if (dialect == database_api::DatabaseDialect::POSTGRESQL) {
// PG uses spanner.commit_timestamp while in ZetaSQL, the default option
// name is allow_commit_timestamp.
commit_timestamp_option_name = ddl::kPGCommitTimestampOptionName;
}
for (const ddl::SetOption& option : set_options) {
if (option.option_name() == commit_timestamp_option_name) {
if (option.has_bool_value()) {
allows_commit_timestamp = option.bool_value();
} else if (option.has_null_value()) {
allows_commit_timestamp = std::nullopt;
} else {
ZETASQL_RET_CHECK(false) << "Option " << commit_timestamp_option_name
<< " can only take bool_value or null_value.";
}
modifier->set_allow_commit_timestamp(allows_commit_timestamp);
} else {
ZETASQL_RET_CHECK(false) << "Invalid column option: " << option.option_name();
}
}
return absl::OkStatus();
}
template <typename Modifier>
absl::Status SchemaUpdaterImpl::SetDatabaseOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
Modifier* modifier) {
modifier->set_options(set_options);
return absl::OkStatus();
}
template <typename ChangeStreamModifier>
absl::Status SchemaUpdaterImpl::SetChangeStreamOptions(
const ::google::protobuf::RepeatedPtrField<ddl::SetOption>& set_options,
ChangeStreamModifier* modifier) {
modifier->set_options(set_options);
for (const ddl::SetOption& option : set_options) {
if (option.has_null_value()) {
continue;