-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathsystem.go
2695 lines (2552 loc) · 96.6 KB
/
system.go
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 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package systemschema
import (
"context"
"math"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catprivilege"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
)
// sql CREATE commands and full schema for each system table.
// These strings are *not* used at runtime, but are checked by the
// `TestSystemTableLiterals` test that compares the table generated by
// evaluating the `CREATE TABLE` statement to the descriptor literal that is
// actually used at runtime.
// These system tables are part of the system config.
const (
NamespaceTableSchema = `
CREATE TABLE system.namespace (
"parentID" INT8,
"parentSchemaID" INT8,
name STRING,
id INT8,
CONSTRAINT "primary" PRIMARY KEY ("parentID", "parentSchemaID", name)
);`
DescriptorTableSchema = `
CREATE TABLE system.descriptor (
id INT8,
descriptor BYTES,
CONSTRAINT "primary" PRIMARY KEY (id)
);`
// UsersTableSchema represents the system.users table.
UsersTableSchema = `
CREATE TABLE system.users (
username STRING NOT NULL,
"hashedPassword" BYTES NULL,
"isRole" BOOL NOT NULL DEFAULT false,
user_id OID NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (username),
UNIQUE INDEX users_user_id_idx (user_id ASC),
FAMILY "primary" (username, user_id)
);`
RoleOptionsTableSchema = `
CREATE TABLE system.role_options (
username STRING NOT NULL,
option STRING NOT NULL,
value STRING,
user_id OID NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (username, option),
INDEX users_user_id_idx (user_id ASC),
FAMILY "primary" (username, option, value, user_id)
)`
// Zone settings per DB/Table.
ZonesTableSchema = `
CREATE TABLE system.zones (
id INT8,
config BYTES,
CONSTRAINT "primary" PRIMARY KEY (id)
);`
SettingsTableSchema = `
CREATE TABLE system.settings (
name STRING NOT NULL,
value STRING NOT NULL,
"lastUpdated" TIMESTAMP NOT NULL DEFAULT now(),
"valueType" STRING,
CONSTRAINT "primary" PRIMARY KEY (name),
FAMILY (name, value, "lastUpdated", "valueType")
);`
DescIDSequenceSchema = `
CREATE SEQUENCE system.descriptor_id_seq;`
tenantNameComputeExpr = `crdb_internal.pb_to_json('cockroach.sql.sqlbase.TenantInfo':::STRING, info)->>'name':::STRING`
TenantsTableSchema = `
CREATE TABLE system.tenants (
id INT8 NOT NULL,
active BOOL NOT NULL DEFAULT true,
info BYTES,
name STRING GENERATED ALWAYS AS (` + tenantNameComputeExpr + `) VIRTUAL,
CONSTRAINT "primary" PRIMARY KEY (id),
FAMILY "primary" (id, active, info),
UNIQUE INDEX tenants_name_idx (name ASC)
);`
// RoleIDSequenceSchema starts at 100 so we have reserved IDs for special
// roles such as root and admin.
RoleIDSequenceSchema = `
CREATE SEQUENCE system.role_id_seq START 100 MINVALUE 100 MAXVALUE 2147483647;`
)
var tenantNameComputeExprStr = tenantNameComputeExpr
// These system tables are not part of the system config.
const (
// Note: the column "nodeID" refers to the SQL instance ID.
// It is named "nodeID" for historical reasons.
LeaseTableSchema = `
CREATE TABLE system.lease (
"descID" INT8,
version INT8,
"nodeID" INT8,
expiration TIMESTAMP,
CONSTRAINT "primary" PRIMARY KEY ("descID", version, expiration, "nodeID")
);`
// system.eventlog contains notable events from the cluster.
//
// This data is also exported to the Observability Service. This table might
// go away in the future.
//
// The "reportingID" column is the SQL instance ID of the
// server that reported the event. For node events, this
// value is also equal to the node ID.
//
// Note: the column "targetID" was deprecated in v21.1 and
// is not populated any more as of v22.2 (its value remains zero).
// TODO(knz): Implement a migration to remove it.
EventLogTableSchema = `
CREATE TABLE system.eventlog (
timestamp TIMESTAMP NOT NULL,
"eventType" STRING NOT NULL,
"targetID" INT8 NOT NULL,
"reportingID" INT8 NOT NULL,
info STRING,
"uniqueID" BYTES DEFAULT uuid_v4(),
CONSTRAINT "primary" PRIMARY KEY (timestamp, "uniqueID")
);`
// rangelog is currently envisioned as a wide table; many different event
// types can be recorded to the table.
RangeEventTableSchema = `
CREATE TABLE system.rangelog (
timestamp TIMESTAMP NOT NULL,
"rangeID" INT8 NOT NULL,
"storeID" INT8 NOT NULL,
"eventType" STRING NOT NULL,
"otherRangeID" INT8,
info STRING,
"uniqueID" INT8 DEFAULT unique_rowid(),
CONSTRAINT "primary" PRIMARY KEY (timestamp, "uniqueID")
);`
UITableSchema = `
CREATE TABLE system.ui (
key STRING,
value BYTES,
"lastUpdated" TIMESTAMP NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (key)
);`
// JobsRunStatsIdxPredicate is the predicate in jobs_run_stats_idx in JobsTable.
JobsRunStatsIdxPredicate = `status IN ('running':::STRING, 'reverting':::STRING, 'pending':::STRING, 'pause-requested':::STRING, 'cancel-requested':::STRING)`
// Note: this schema is changed in a migration (a progress column is added in
// a separate family).
// NB: main column family uses old, pre created_by_type/created_by_id columns, named.
// This is done to minimize migration work required.
JobsTableSchema = `
CREATE TABLE system.jobs (
id INT8 DEFAULT unique_rowid(),
status STRING NOT NULL,
created TIMESTAMP NOT NULL DEFAULT now(),
payload BYTES NOT NULL,
progress BYTES,
created_by_type STRING,
created_by_id INT,
claim_session_id BYTES,
claim_instance_id INT8,
num_runs INT8,
last_run TIMESTAMP,
CONSTRAINT "primary" PRIMARY KEY (id),
INDEX (status, created),
INDEX (created_by_type, created_by_id) STORING (status),
INDEX jobs_run_stats_idx (
claim_session_id,
status,
created
) STORING(last_run, num_runs, claim_instance_id)
WHERE ` + JobsRunStatsIdxPredicate + `,
FAMILY fam_0_id_status_created_payload (id, status, created, payload, created_by_type, created_by_id),
FAMILY progress (progress),
FAMILY claim (claim_session_id, claim_instance_id, num_runs, last_run)
);`
// web_sessions are used to track authenticated user actions over stateless
// connections, such as the cookie-based authentication used by the Admin
// UI.
// Design outlined in /docs/RFCS/web_session_login.rfc
WebSessionsTableSchema = `
CREATE TABLE system.web_sessions (
id INT8 NOT NULL DEFAULT unique_rowid(),
"hashedSecret" BYTES NOT NULL,
username STRING NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"expiresAt" TIMESTAMP NOT NULL,
"revokedAt" TIMESTAMP,
"lastUsedAt" TIMESTAMP NOT NULL DEFAULT now(),
"auditInfo" STRING,
CONSTRAINT "primary" PRIMARY KEY (id),
INDEX ("expiresAt"),
INDEX ("createdAt"),
INDEX ("revokedAt"),
INDEX ("lastUsedAt"),
FAMILY (id, "hashedSecret", username, "createdAt", "expiresAt", "revokedAt", "lastUsedAt", "auditInfo")
);`
// table_statistics is used to track statistics collected about individual
// columns or groups of columns from every table in the database. Each row
// contains the number of distinct values of the column group, the number of
// null values, the average size of the column(s), and (optionally) a
// histogram if there is only one column in columnIDs.
//
// Design outlined in /docs/RFCS/20170908_sql_optimizer_statistics.md
// Note: avgSize is a newer statistic than the RFC above. It contains the
// average size of the column group in bytes.
TableStatisticsTableSchema = `
CREATE TABLE system.table_statistics (
"tableID" INT8 NOT NULL,
"statisticID" INT8 NOT NULL DEFAULT unique_rowid(),
name STRING,
"columnIDs" INT8[] NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"rowCount" INT8 NOT NULL,
"distinctCount" INT8 NOT NULL,
"nullCount" INT8 NOT NULL,
histogram BYTES,
"avgSize" INT8 NOT NULL DEFAULT 0,
CONSTRAINT "primary" PRIMARY KEY ("tableID", "statisticID"),
FAMILY "fam_0_tableID_statisticID_name_columnIDs_createdAt_rowCount_distinctCount_nullCount_histogram" ("tableID", "statisticID", name, "columnIDs", "createdAt", "rowCount", "distinctCount", "nullCount", histogram, "avgSize")
);`
// locations are used to map a locality specified by a node to geographic
// latitude, longitude coordinates, specified as degrees.
LocationsTableSchema = `
CREATE TABLE system.locations (
"localityKey" STRING,
"localityValue" STRING,
latitude DECIMAL(18,15) NOT NULL,
longitude DECIMAL(18,15) NOT NULL,
CONSTRAINT "primary" PRIMARY KEY ("localityKey", "localityValue"),
FAMILY ("localityKey", "localityValue", latitude, longitude)
);`
// role_members stores relationships between roles (role->role and role->user).
RoleMembersTableSchema = `
CREATE TABLE system.role_members (
"role" STRING NOT NULL,
"member" STRING NOT NULL,
"isAdmin" BOOL NOT NULL,
CONSTRAINT "primary" PRIMARY KEY ("role", "member"),
INDEX ("role"),
INDEX ("member")
);`
// comments stores comments(database, table, column...).
CommentsTableSchema = `
CREATE TABLE system.comments (
type INT NOT NULL, -- type of object, to distinguish between db, table, column and others
object_id INT NOT NULL, -- object ID, this will be usually db/table desc ID
sub_id INT NOT NULL, -- sub ID for column or indexes inside table, 0 for pure table
comment STRING NOT NULL, -- the comment
CONSTRAINT "primary" PRIMARY KEY (type, object_id, sub_id)
);`
// reports_meta stores reports metadata
ReportsMetaTableSchema = `
CREATE TABLE system.reports_meta (
id INT8 NOT NULL, "generated" TIMESTAMPTZ NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (id ASC),
FAMILY "primary" (id, "generated")
);`
// replication_constraint_stats stores replication constraint statistics
ReplicationConstraintStatsTableSchema = `
CREATE TABLE system.replication_constraint_stats (
zone_id
INT8 NOT NULL,
subzone_id
INT8 NOT NULL,
type
STRING NOT NULL,
config
STRING NOT NULL,
report_id
INT8 NOT NULL,
violation_start
TIMESTAMPTZ NULL,
violating_ranges
INT8 NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (zone_id ASC, subzone_id ASC, type ASC, config ASC),
FAMILY "primary" (zone_id, subzone_id, type, config, report_id, violation_start, violating_ranges)
);`
// replication_critical_localities stores replication critical localities
ReplicationCriticalLocalitiesTableSchema = `
CREATE TABLE system.replication_critical_localities (
zone_id
INT8 NOT NULL,
subzone_id
INT8 NOT NULL,
locality
STRING NOT NULL,
report_id
INT8 NOT NULL,
at_risk_ranges
INT8 NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (zone_id ASC, subzone_id ASC, locality ASC),
FAMILY "primary" (zone_id, subzone_id, locality, report_id, at_risk_ranges)
);`
// replication_stats stores replication statistics
ReplicationStatsTableSchema = `
CREATE TABLE system.replication_stats (
zone_id
INT8 NOT NULL,
subzone_id
INT8 NOT NULL,
report_id
INT8 NOT NULL,
total_ranges
INT8 NOT NULL,
unavailable_ranges
INT8 NOT NULL,
under_replicated_ranges
INT8 NOT NULL,
over_replicated_ranges
INT8 NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (zone_id, subzone_id),
FAMILY "primary" (
zone_id,
subzone_id,
report_id,
total_ranges,
unavailable_ranges,
under_replicated_ranges,
over_replicated_ranges
)
);`
// protected_ts_meta stores a single row of metadata for the protectedts
// subsystem.
ProtectedTimestampsMetaTableSchema = `
CREATE TABLE system.protected_ts_meta (
singleton BOOL NOT NULL DEFAULT (true),
version INT8 NOT NULL,
num_records INT8 NOT NULL,
num_spans INT8 NOT NULL,
total_bytes INT8 NOT NULL,
CONSTRAINT check_singleton CHECK (singleton),
CONSTRAINT "primary" PRIMARY KEY (singleton),
FAMILY "primary" (singleton, version, num_records, num_spans, total_bytes)
);`
ProtectedTimestampsRecordsTableSchema = `
CREATE TABLE system.protected_ts_records (
id UUID NOT NULL,
ts DECIMAL NOT NULL,
meta_type STRING NOT NULL,
meta BYTES,
num_spans INT8 NOT NULL, -- num spans is important to know how to decode spans
spans BYTES NOT NULL,
verified BOOL NOT NULL DEFAULT (false),
target BYTES, -- target is an encoded protobuf that specifies what the pts record will protect
CONSTRAINT "primary" PRIMARY KEY (id),
FAMILY "primary" (id, ts, meta_type, meta, num_spans, spans, verified, target)
);`
StatementBundleChunksTableSchema = `
CREATE TABLE system.statement_bundle_chunks (
id INT8 DEFAULT unique_rowid(),
description STRING,
data BYTES NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (id),
FAMILY "primary" (id, description, data)
);`
StatementDiagnosticsRequestsTableSchema = `
CREATE TABLE system.statement_diagnostics_requests(
id INT8 DEFAULT unique_rowid() NOT NULL,
completed BOOL NOT NULL DEFAULT FALSE,
statement_fingerprint STRING NOT NULL,
statement_diagnostics_id INT8,
requested_at TIMESTAMPTZ NOT NULL,
min_execution_latency INTERVAL NULL,
expires_at TIMESTAMPTZ NULL,
sampling_probability FLOAT NULL,
CONSTRAINT "primary" PRIMARY KEY (id),
CONSTRAINT check_sampling_probability CHECK (sampling_probability BETWEEN 0.0 AND 1.0),
INDEX completed_idx (completed, id) STORING (statement_fingerprint, min_execution_latency, expires_at, sampling_probability),
FAMILY "primary" (id, completed, statement_fingerprint, statement_diagnostics_id, requested_at, min_execution_latency, expires_at, sampling_probability)
);`
StatementDiagnosticsTableSchema = `
create table system.statement_diagnostics(
id INT8 DEFAULT unique_rowid() NOT NULL,
statement_fingerprint STRING NOT NULL,
statement STRING NOT NULL,
collected_at TIMESTAMPTZ NOT NULL,
trace JSONB,
bundle_chunks INT ARRAY,
error STRING,
CONSTRAINT "primary" PRIMARY KEY (id),
FAMILY "primary" (id, statement_fingerprint, statement, collected_at, trace, bundle_chunks, error)
);`
ScheduledJobsTableSchema = `
CREATE TABLE system.scheduled_jobs (
schedule_id INT DEFAULT unique_rowid() NOT NULL,
schedule_name STRING NOT NULL,
created TIMESTAMPTZ NOT NULL DEFAULT now(),
owner STRING NOT NULL,
next_run TIMESTAMPTZ,
schedule_state BYTES,
schedule_expr STRING,
schedule_details BYTES,
executor_type STRING NOT NULL,
execution_args BYTES NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (schedule_id),
INDEX "next_run_idx" (next_run),
FAMILY sched (schedule_id, next_run, schedule_state),
FAMILY other (
schedule_name, created, owner, schedule_expr,
schedule_details, executor_type, execution_args
)
)`
SqllivenessTableSchema = `
CREATE TABLE system.sqlliveness (
session_id BYTES NOT NULL,
expiration DECIMAL NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (session_id),
FAMILY fam0_session_id_expiration (session_id, expiration)
)`
MrSqllivenessTableSchema = `
CREATE TABLE system.sqlliveness (
session_uuid BYTES NOT NULL,
expiration DECIMAL NOT NULL,
crdb_region BYTES NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (crdb_region, session_uuid),
FAMILY "primary" (crdb_region, session_uuid, expiration)
)`
MigrationsTableSchema = `
CREATE TABLE system.migrations (
major INT8 NOT NULL,
minor INT8 NOT NULL,
patch INT8 NOT NULL,
internal INT8 NOT NULL,
completed_at TIMESTAMPTZ NOT NULL,
FAMILY "primary" (major, minor, patch, internal, completed_at),
CONSTRAINT "primary" PRIMARY KEY (major, minor, patch, internal)
)`
JoinTokensTableSchema = `
CREATE TABLE system.join_tokens (
id UUID NOT NULL,
secret BYTES NOT NULL,
expiration TIMESTAMPTZ NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (id),
FAMILY "primary" (id, secret, expiration)
)`
// TODO(azhng): Currently we choose number of bucket for hash-sharding to be
// 8 for both statement statistics table and transaction statistics table.
// This is an arbitrary choice for now. After persisted SQL Stats is fully
// implemented, we need to revisit this choice and retune the configuration.
StatementStatisticsTableSchema = `
CREATE TABLE system.statement_statistics (
aggregated_ts TIMESTAMPTZ NOT NULL,
fingerprint_id BYTES NOT NULL,
transaction_fingerprint_id BYTES NOT NULL,
plan_hash BYTES NOT NULL,
app_name STRING NOT NULL,
node_id INT8 NOT NULL,
agg_interval INTERVAL NOT NULL,
metadata JSONB NOT NULL,
statistics JSONB NOT NULL,
plan JSONB NOT NULL,
crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_plan_hash_transaction_fingerprint_id_shard_8 INT4 NOT VISIBLE NOT NULL AS (
mod(fnv32(crdb_internal.datums_to_bytes(aggregated_ts, app_name, fingerprint_id, node_id, plan_hash, transaction_fingerprint_id)), 8:::INT8)
) STORED,
index_recommendations STRING[] NOT NULL DEFAULT (array[]::STRING[]),
CONSTRAINT "primary" PRIMARY KEY (aggregated_ts, fingerprint_id, transaction_fingerprint_id, plan_hash, app_name, node_id)
USING HASH WITH (bucket_count=8),
INDEX "fingerprint_stats_idx" (fingerprint_id, transaction_fingerprint_id),
FAMILY "primary" (
crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_plan_hash_transaction_fingerprint_id_shard_8,
aggregated_ts,
fingerprint_id,
transaction_fingerprint_id,
plan_hash,
app_name,
node_id,
agg_interval,
metadata,
statistics,
plan,
index_recommendations
)
)
`
TransactionStatisticsTableSchema = `
CREATE TABLE system.transaction_statistics (
aggregated_ts TIMESTAMPTZ NOT NULL,
fingerprint_id BYTES NOT NULL,
app_name STRING NOT NULL,
node_id INT8 NOT NULL,
agg_interval INTERVAL NOT NULL,
metadata JSONB NOT NULL,
statistics JSONB NOT NULL,
crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_shard_8 INT4 NOT VISIBLE NOT NULL AS (
mod(fnv32("crdb_internal.datums_to_bytes"(aggregated_ts, app_name, fingerprint_id, node_id)), 8:::INT8
)) STORED,
CONSTRAINT "primary" PRIMARY KEY (aggregated_ts, fingerprint_id, app_name, node_id)
USING HASH WITH (bucket_count=8),
INDEX "fingerprint_stats_idx" (fingerprint_id),
FAMILY "primary" (
crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_shard_8,
aggregated_ts,
fingerprint_id,
app_name,
node_id,
agg_interval,
metadata,
statistics
)
);
`
DatabaseRoleSettingsTableSchema = `
CREATE TABLE system.database_role_settings (
database_id OID NOT NULL,
role_name STRING NOT NULL,
settings STRING[] NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (database_id, role_name),
FAMILY "primary" (
database_id,
role_name,
settings
)
);`
TenantUsageTableSchema = `
CREATE TABLE system.tenant_usage (
tenant_id INT NOT NULL,
-- For each tenant, there is a special row with instance_id = 0 which contains
-- per-tenant stat. Each SQL instance (pod) also has its own row with
-- per-instance state.
instance_id INT NOT NULL,
-- next_instance_id identifies the next live instance ID, with the smallest ID
-- larger than this instance_id (or 0 if there is no such ID).
-- We are overlaying a circular linked list of all live instances, with
-- instance 0 acting as a sentinel (always the head of the list).
next_instance_id INT NOT NULL,
-- Time when we last interacted with this row. For the per-tenant row, this
-- is the time of the last update from any instance. For instance rows, this
-- is the time of the last update from that particular instance.
last_update TIMESTAMP NOT NULL,
-- -------------------------------------------------------------------
-- The following fields are used only for the per-tenant state, when
-- instance_id = 0.
-- -------------------------------------------------------------------
-- Bucket configuration.
ru_burst_limit FLOAT,
ru_refill_rate FLOAT,
-- Current amount of RUs in the bucket.
ru_current FLOAT,
-- Current sum of the shares values for all instances.
current_share_sum FLOAT,
-- Cumulative usage statistics, encoded as roachpb.TenantConsumption.
total_consumption BYTES,
-- -------------------------------------------------------------
-- The following fields are used for per-instance state, when
-- instance_id != 0.
-- --------------------------------------------------------------
-- The lease is a unique identifier for this instance, necessary because
-- instance IDs can be reused.
instance_lease BYTES,
-- Last request sequence number. These numbers are provided by the
-- instance and are monotonically increasing; used to detect duplicate
-- requests and provide idempotency.
instance_seq INT,
-- Current shares value for this instance.
instance_shares FLOAT,
FAMILY "primary" (
tenant_id, instance_id, next_instance_id, last_update,
ru_burst_limit, ru_refill_rate, ru_current, current_share_sum,
total_consumption,
instance_lease, instance_seq, instance_shares
),
CONSTRAINT "primary" PRIMARY KEY (tenant_id, instance_id)
)`
SQLInstancesTableSchema = `
CREATE TABLE system.sql_instances (
id INT NOT NULL,
addr STRING,
session_id BYTES,
locality JSONB,
CONSTRAINT "primary" PRIMARY KEY (id),
FAMILY "primary" (id, addr, session_id, locality)
)`
SpanConfigurationsTableSchema = `
CREATE TABLE system.span_configurations (
start_key BYTES NOT NULL,
end_key BYTES NOT NULL,
config BYTES NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (start_key),
CONSTRAINT check_bounds CHECK (start_key < end_key),
FAMILY "primary" (start_key, end_key, config)
)`
TenantSettingsTableSchema = `
CREATE TABLE system.tenant_settings (
-- A non-zero tenant_id indicates that this is a setting specific to that
-- particular tenant. A zero tenant_id indicates an "all tenant" setting that
-- applies to all tenants which don't a tenant-specific value for this
-- setting.
tenant_id INT8 NOT NULL,
name STRING NOT NULL,
value STRING NOT NULL,
last_updated TIMESTAMP NOT NULL DEFAULT now(),
value_type STRING NOT NULL,
-- reason is unused for now.
reason STRING,
CONSTRAINT "primary" PRIMARY KEY (tenant_id, name),
FAMILY (tenant_id, name, value, last_updated, value_type, reason)
);`
SpanCountTableSchema = `
CREATE TABLE system.span_count (
singleton BOOL DEFAULT TRUE,
span_count INT NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (singleton),
CONSTRAINT single_row CHECK (singleton),
FAMILY "primary" (singleton, span_count)
);`
SystemPrivilegeTableSchema = `
CREATE TABLE system.privileges (
username STRING NOT NULL,
path STRING NOT NULL,
privileges STRING[] NOT NULL,
grant_options STRING[] NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (username, path),
FAMILY "primary" (username, path, privileges, grant_options)
);`
SystemExternalConnectionsTableSchema = `
CREATE TABLE system.external_connections (
connection_name STRING NOT NULL,
created TIMESTAMP NOT NULL DEFAULT now(),
updated TIMESTAMP NOT NULL DEFAULT now(),
connection_type STRING NOT NULL,
connection_details BYTES NOT NULL,
owner STRING NOT NULL,
CONSTRAINT "primary" PRIMARY KEY (connection_name),
FAMILY "primary" (connection_name, created, updated, connection_type, connection_details, owner)
);`
)
func pk(name string) descpb.IndexDescriptor {
return descpb.IndexDescriptor{
Name: tabledesc.LegacyPrimaryKeyIndexName,
ID: 1,
Unique: true,
KeyColumnNames: []string{name},
KeyColumnDirections: singleASC,
KeyColumnIDs: singleID1,
}
}
// Helpers used to make some of the descpb.TableDescriptor literals below more concise.
var (
singleASC = []catpb.IndexColumn_Direction{catpb.IndexColumn_ASC}
singleID1 = []descpb.ColumnID{1}
// The hash computation expression below is generated by running the CREATE
// TABLE statements for both statement and transaction tables in a SQL shell.
// If we are to change how we compute hash values in the future, we need to
// modify these two expressions as well.
sqlStmtHashComputeExpr = `mod(fnv32(crdb_internal.datums_to_bytes(aggregated_ts, app_name, fingerprint_id, node_id, plan_hash, transaction_fingerprint_id)), 8:::INT8)`
sqlTxnHashComputeExpr = `mod(fnv32(crdb_internal.datums_to_bytes(aggregated_ts, app_name, fingerprint_id, node_id)), 8:::INT8)`
)
const (
// SQLStatsHashShardBucketCount is the number of buckets used in the hash sharded
// primary key in the sql stats tables. If we are to change the number of buckets
// in the hash sharded primary key in the sql stats tables, this value needs to
// be updated.
SQLStatsHashShardBucketCount = 8
// StmtStatsHashColumnName is the name of the hash column of
// system.statement_statistics.
StmtStatsHashColumnName = "crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_plan_hash_transaction_fingerprint_id_shard_8"
// TxnStatsHashColumnName is the name of the hash column of
// system.transaction_statistics.
TxnStatsHashColumnName = "crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_shard_8"
)
// SystemDatabaseName is the name of the system database.
const SystemDatabaseName = catconstants.SystemDatabaseName
// MakeSystemDatabaseDesc constructs a copy of the system database
// descriptor.
func MakeSystemDatabaseDesc() catalog.DatabaseDescriptor {
priv := privilege.List{privilege.CONNECT}
return dbdesc.NewBuilder(&descpb.DatabaseDescriptor{
Name: SystemDatabaseName,
ID: keys.SystemDatabaseID,
Version: 1,
// Assign max privileges to root user.
Privileges: catpb.NewCustomSuperuserPrivilegeDescriptor(
priv, username.NodeUserName()),
}).BuildImmutableDatabase()
}
func systemTable(
name catconstants.SystemTableName,
id descpb.ID,
columns []descpb.ColumnDescriptor,
families []descpb.ColumnFamilyDescriptor,
indexes ...descpb.IndexDescriptor,
) descpb.TableDescriptor {
tbl := descpb.TableDescriptor{
Name: string(name),
ID: id,
ParentID: keys.SystemDatabaseID,
UnexposedParentSchemaID: keys.SystemPublicSchemaID,
Version: 1,
Columns: columns,
Families: families,
PrimaryIndex: indexes[0],
Indexes: indexes[1:],
FormatVersion: descpb.InterleavedFormatVersion,
NextMutationID: 1,
NextConstraintID: 1,
}
for _, col := range columns {
if tbl.NextColumnID <= col.ID {
tbl.NextColumnID = col.ID + 1
}
}
for _, fam := range families {
if tbl.NextFamilyID <= fam.ID {
tbl.NextFamilyID = fam.ID + 1
}
}
for i, idx := range indexes {
if tbl.NextIndexID <= idx.ID {
tbl.NextIndexID = idx.ID + 1
}
// Only assigned constraint IDs to unique non-primary indexes.
if idx.Unique && i >= 1 {
tbl.Indexes[i-1].ConstraintID = tbl.NextConstraintID
tbl.NextConstraintID++
}
}
// When creating tables normally, unique index constraint ids are
// assigned before the primary index.
tbl.PrimaryIndex.ConstraintID = tbl.NextConstraintID
tbl.NextConstraintID++
return tbl
}
func registerSystemTable(
createTableStmt string, tbl descpb.TableDescriptor, fns ...func(tbl *descpb.TableDescriptor),
) catalog.TableDescriptor {
ctx := context.Background()
if _, alreadyExists := SystemTableDescriptors[createTableStmt]; alreadyExists {
log.Fatalf(ctx, "system table %q cannot be registered, existing entry for %s", tbl.Name, createTableStmt)
}
{
nameInfo := descpb.NameInfo{
ParentID: tbl.ParentID,
ParentSchemaID: tbl.UnexposedParentSchemaID,
Name: tbl.Name,
}
privs := catprivilege.SystemSuperuserPrivileges(nameInfo)
if privs == nil {
log.Fatalf(ctx, "no superuser privileges found when building descriptor of system table %q", tbl.Name)
}
tbl.Privileges = catpb.NewCustomSuperuserPrivilegeDescriptor(privs, username.NodeUserName())
}
for _, fn := range fns {
fn(&tbl)
}
b := tabledesc.NewBuilder(&tbl)
if err := b.RunPostDeserializationChanges(); err != nil {
log.Fatalf(
ctx, "system table %q cannot be registered, error during RunPostDeserializationChanges: %+v",
tbl.Name, err,
)
}
desc := b.BuildImmutableTable()
SystemTableDescriptors[createTableStmt] = desc
return desc
}
var (
// SystemDB is the descriptor for the system database.
SystemDB = MakeSystemDatabaseDesc()
// SystemTableDescriptors contains the registered table descriptors for each
// system table. The map is populated by calling registerSystemTable and is
// keyed by the CREATE TABLE statements with which these descriptors are
// tested against in TestSystemTableLiterals.
SystemTableDescriptors = make(map[string]catalog.TableDescriptor)
)
// These system config descpb.TableDescriptor literals should match the descriptor
// that would be produced by evaluating one of the above `CREATE TABLE`
// statements. See the `TestSystemTableLiterals` which checks that they do
// indeed match, and has suggestions on writing and maintaining them.
var (
// NamespaceTable is the descriptor for the namespace table. Note that this
// table should only be written to via KV puts, not via the SQL layer. Some
// code assumes that it only has KV entries for column family 4, not the
// "sentinel" column family 0 which would be written by SQL.
NamespaceTable = registerSystemTable(
NamespaceTableSchema,
systemTable(
catconstants.NamespaceTableName,
keys.NamespaceTableID,
[]descpb.ColumnDescriptor{
{Name: "parentID", ID: 1, Type: types.Int},
{Name: "parentSchemaID", ID: 2, Type: types.Int},
{Name: "name", ID: 3, Type: types.String},
{Name: "id", ID: 4, Type: types.Int, Nullable: true},
},
[]descpb.ColumnFamilyDescriptor{
{Name: "primary", ID: 0, ColumnNames: []string{"parentID", "parentSchemaID", "name"}, ColumnIDs: []descpb.ColumnID{1, 2, 3}},
{Name: "fam_4_id", ID: catconstants.NamespaceTableFamilyID, ColumnNames: []string{"id"}, ColumnIDs: []descpb.ColumnID{4}, DefaultColumnID: 4},
},
descpb.IndexDescriptor{
Name: "primary",
ID: catconstants.NamespaceTablePrimaryIndexID,
Unique: true,
KeyColumnNames: []string{"parentID", "parentSchemaID", "name"},
KeyColumnDirections: []catpb.IndexColumn_Direction{catpb.IndexColumn_ASC, catpb.IndexColumn_ASC, catpb.IndexColumn_ASC},
KeyColumnIDs: []descpb.ColumnID{1, 2, 3},
},
))
// DescriptorTable is the descriptor for the descriptor table.
DescriptorTable = registerSystemTable(
DescriptorTableSchema,
systemTable(
catconstants.DescriptorTableName,
keys.DescriptorTableID,
[]descpb.ColumnDescriptor{
{Name: "id", ID: 1, Type: types.Int},
{Name: "descriptor", ID: keys.DescriptorTableDescriptorColID, Type: types.Bytes, Nullable: true},
},
[]descpb.ColumnFamilyDescriptor{
// The id of the first col fam is hardcoded in keys.MakeDescMetadataKey().
{Name: "primary", ID: 0, ColumnNames: []string{"id"}, ColumnIDs: singleID1},
{
Name: "fam_2_descriptor", ID: keys.DescriptorTableDescriptorColFamID,
ColumnNames: []string{"descriptor"},
ColumnIDs: []descpb.ColumnID{keys.DescriptorTableDescriptorColID},
DefaultColumnID: keys.DescriptorTableDescriptorColID,
},
},
pk("id"),
))
falseBoolString = "false"
trueBoolString = "true"
zeroIntString = "0:::INT8"
// UsersTable is the descriptor for the users table.
UsersTable = registerSystemTable(
UsersTableSchema,
systemTable(
catconstants.UsersTableName,
keys.UsersTableID,
[]descpb.ColumnDescriptor{
{Name: "username", ID: 1, Type: types.String},
{Name: "hashedPassword", ID: 2, Type: types.Bytes, Nullable: true},
{Name: "isRole", ID: 3, Type: types.Bool, DefaultExpr: &falseBoolString},
{Name: "user_id", ID: 4, Type: types.Oid},
},
[]descpb.ColumnFamilyDescriptor{
{Name: "primary", ID: 0, ColumnNames: []string{"username", "user_id"}, ColumnIDs: []descpb.ColumnID{1, 4}, DefaultColumnID: 4},
{Name: "fam_2_hashedPassword", ID: 2, ColumnNames: []string{"hashedPassword"}, ColumnIDs: []descpb.ColumnID{2}, DefaultColumnID: 2},
{Name: "fam_3_isRole", ID: 3, ColumnNames: []string{"isRole"}, ColumnIDs: []descpb.ColumnID{3}, DefaultColumnID: 3},
},
pk("username"),
descpb.IndexDescriptor{
Name: "users_user_id_idx",
ID: 2,
Unique: true,
KeyColumnNames: []string{"user_id"},
KeyColumnDirections: []catpb.IndexColumn_Direction{catpb.IndexColumn_ASC},
KeyColumnIDs: []descpb.ColumnID{4},
KeySuffixColumnIDs: []descpb.ColumnID{1},
Version: descpb.StrictIndexColumnIDGuaranteesVersion,
},
))
// ZonesTable is the descriptor for the zones table.
ZonesTable = registerSystemTable(
ZonesTableSchema,
systemTable(
catconstants.ZonesTableName,
keys.ZonesTableID,
[]descpb.ColumnDescriptor{
{Name: "id", ID: 1, Type: types.Int},
{Name: "config", ID: keys.ZonesTableConfigColumnID, Type: types.Bytes, Nullable: true},
},
[]descpb.ColumnFamilyDescriptor{
{Name: "primary", ID: 0, ColumnNames: []string{"id"}, ColumnIDs: singleID1},
{Name: "fam_2_config", ID: keys.ZonesTableConfigColFamID, ColumnNames: []string{"config"},
ColumnIDs: []descpb.ColumnID{keys.ZonesTableConfigColumnID}, DefaultColumnID: keys.ZonesTableConfigColumnID},
},
descpb.IndexDescriptor{
Name: "primary",
ID: keys.ZonesTablePrimaryIndexID,
Unique: true,
KeyColumnNames: []string{"id"},
KeyColumnDirections: singleASC,
KeyColumnIDs: []descpb.ColumnID{keys.ZonesTablePrimaryIndexID},
},
))
// SettingsTable is the descriptor for the settings table.
// It contains all cluster settings for which a value has been set.
SettingsTable = registerSystemTable(
SettingsTableSchema,
systemTable(
catconstants.SettingsTableName,
keys.SettingsTableID,
[]descpb.ColumnDescriptor{
{Name: "name", ID: 1, Type: types.String},
{Name: "value", ID: 2, Type: types.String},
{Name: "lastUpdated", ID: 3, Type: types.Timestamp, DefaultExpr: &nowString},
{Name: "valueType", ID: 4, Type: types.String, Nullable: true},
},
[]descpb.ColumnFamilyDescriptor{
{