-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathimport_job.go
1725 lines (1560 loc) · 58.9 KB
/
import_job.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 2017 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 importer
import (
"bytes"
"context"
"fmt"
"math"
"time"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/joberror"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descidgen"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/ingesting"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/rewrite"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/gcjob"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/ioctx"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
)
type importResumer struct {
job *jobs.Job
settings *cluster.Settings
res roachpb.RowCount
testingKnobs struct {
afterImport func(summary roachpb.RowCount) error
alwaysFlushJobProgress bool
}
}
func (r *importResumer) TestingSetAfterImportKnob(fn func(summary roachpb.RowCount) error) {
r.testingKnobs.afterImport = fn
}
var _ jobs.TraceableJob = &importResumer{}
func (r *importResumer) ForceRealSpan() bool {
return true
}
var _ jobs.Resumer = &importResumer{}
var processorsPerNode = settings.RegisterIntSetting(
settings.TenantWritable,
"bulkio.import.processors_per_node",
"number of input processors to run on each sql instance", 1,
settings.PositiveInt,
)
type preparedSchemaMetadata struct {
schemaPreparedDetails jobspb.ImportDetails
schemaRewrites jobspb.DescRewriteMap
newSchemaIDToName map[descpb.ID]string
oldSchemaIDToName map[descpb.ID]string
queuedSchemaJobs []jobspb.JobID
}
// Resume is part of the jobs.Resumer interface.
func (r *importResumer) Resume(ctx context.Context, execCtx interface{}) error {
p := execCtx.(sql.JobExecContext)
if err := r.parseBundleSchemaIfNeeded(ctx, p); err != nil {
return err
}
details := r.job.Details().(jobspb.ImportDetails)
files := details.URIs
format := details.Format
tables := make(map[string]*execinfrapb.ReadImportDataSpec_ImportTable, len(details.Tables))
if details.Tables != nil {
// Skip prepare stage on job resumption, if it has already been completed.
if !details.PrepareComplete {
var schemaMetadata *preparedSchemaMetadata
if err := sql.DescsTxn(ctx, p.ExecCfg(), func(
ctx context.Context, txn *kv.Txn, descsCol *descs.Collection,
) error {
var preparedDetails jobspb.ImportDetails
schemaMetadata = &preparedSchemaMetadata{
newSchemaIDToName: make(map[descpb.ID]string),
oldSchemaIDToName: make(map[descpb.ID]string),
}
var err error
curDetails := details
if len(details.Schemas) != 0 {
schemaMetadata, err = r.prepareSchemasForIngestion(ctx, p, curDetails, txn, descsCol)
if err != nil {
return err
}
curDetails = schemaMetadata.schemaPreparedDetails
}
// In 22.1, the Public schema should always be present in the database.
// Make sure it is part of schemaMetadata, it is not guaranteed to
// be added in prepareSchemasForIngestion if we're not importing any
// schemas.
// The Public schema will not change in the database so both the
// oldSchemaIDToName and newSchemaIDToName entries will be the
// same for the Public schema.
_, dbDesc, err := descsCol.GetImmutableDatabaseByID(ctx, txn, details.ParentID, tree.DatabaseLookupFlags{Required: true})
if err != nil {
return err
}
schemaMetadata.oldSchemaIDToName[dbDesc.GetSchemaID(tree.PublicSchema)] = tree.PublicSchema
schemaMetadata.newSchemaIDToName[dbDesc.GetSchemaID(tree.PublicSchema)] = tree.PublicSchema
preparedDetails, err = r.prepareTablesForIngestion(ctx, p, curDetails, txn, descsCol,
schemaMetadata)
if err != nil {
return err
}
// Telemetry for multi-region.
for _, table := range preparedDetails.Tables {
_, dbDesc, err := descsCol.GetImmutableDatabaseByID(
ctx, txn, table.Desc.GetParentID(), tree.DatabaseLookupFlags{Required: true})
if err != nil {
return err
}
if dbDesc.IsMultiRegion() {
telemetry.Inc(sqltelemetry.ImportIntoMultiRegionDatabaseCounter)
}
}
// Update the job details now that the schemas and table descs have
// been "prepared".
return r.job.Update(ctx, txn, func(
txn *kv.Txn, md jobs.JobMetadata, ju *jobs.JobUpdater,
) error {
pl := md.Payload
*pl.GetImport() = preparedDetails
// Update the set of descriptors for later observability.
// TODO(ajwerner): Do we need this idempotence test?
prev := md.Payload.DescriptorIDs
if prev == nil {
var descriptorIDs []descpb.ID
for _, schema := range preparedDetails.Schemas {
descriptorIDs = append(descriptorIDs, schema.Desc.GetID())
}
for _, table := range preparedDetails.Tables {
descriptorIDs = append(descriptorIDs, table.Desc.GetID())
}
pl.DescriptorIDs = descriptorIDs
}
ju.UpdatePayload(pl)
return nil
})
}); err != nil {
return err
}
// Run the queued job which updates the database descriptor to contain the
// newly created schemas.
// NB: Seems like the registry eventually adopts the job anyways but this
// is in keeping with the semantics we use when creating a schema during
// sql execution. Namely, queue job in the txn which creates the schema
// desc and run once the txn has committed.
if err := p.ExecCfg().JobRegistry.Run(ctx, p.ExecCfg().InternalExecutor,
schemaMetadata.queuedSchemaJobs); err != nil {
return err
}
// Re-initialize details after prepare step.
details = r.job.Details().(jobspb.ImportDetails)
emitImportJobEvent(ctx, p, jobs.StatusRunning, r.job)
}
// Create a mapping from schemaID to schemaName.
schemaIDToName := make(map[descpb.ID]string)
for _, i := range details.Schemas {
schemaIDToName[i.Desc.GetID()] = i.Desc.GetName()
}
for _, i := range details.Tables {
var tableName string
if i.Name != "" {
tableName = i.Name
} else if i.Desc != nil {
tableName = i.Desc.Name
} else {
return errors.New("invalid table specification")
}
// If we are importing from PGDUMP, qualify the table name with the schema
// name since we support non-public schemas.
if details.Format.Format == roachpb.IOFileFormat_PgDump {
schemaName := tree.PublicSchema
if schema, ok := schemaIDToName[i.Desc.GetUnexposedParentSchemaID()]; ok {
schemaName = schema
}
tableName = fmt.Sprintf("%s.%s", schemaName, tableName)
}
tables[tableName] = &execinfrapb.ReadImportDataSpec_ImportTable{
Desc: i.Desc,
TargetCols: i.TargetCols,
}
}
}
typeDescs := make([]*descpb.TypeDescriptor, len(details.Types))
for i, t := range details.Types {
typeDescs[i] = t.Desc
}
// If details.Walltime is still 0, then it was not set during
// `prepareTablesForIngestion`. This indicates that we are in an IMPORT INTO,
// and that the walltime was not set in a previous run of IMPORT.
//
// In the case of importing into existing tables we must wait for all nodes
// to see the same version of the updated table descriptor, after which we
// shall chose a ts to import from.
if details.Walltime == 0 {
// Now that we know all the tables are offline, pick a walltime at which we
// will write.
details.Walltime = p.ExecCfg().Clock.Now().WallTime
// Check if the tables being imported into are starting empty, in which
// case we can cheaply clear-range instead of revert-range to cleanup.
for i := range details.Tables {
if !details.Tables[i].IsNew {
tblDesc := tabledesc.NewBuilder(details.Tables[i].Desc).BuildImmutableTable()
tblSpan := tblDesc.TableSpan(p.ExecCfg().Codec)
res, err := p.ExecCfg().DB.Scan(ctx, tblSpan.Key, tblSpan.EndKey, 1 /* maxRows */)
if err != nil {
return errors.Wrap(err, "checking if existing table is empty")
}
details.Tables[i].WasEmpty = len(res) == 0
}
}
if err := r.job.SetDetails(ctx, nil /* txn */, details); err != nil {
return err
}
}
procsPerNode := int(processorsPerNode.Get(&p.ExecCfg().Settings.SV))
res, err := ingestWithRetry(ctx, p, r.job, tables, typeDescs, files, format, details.Walltime,
r.testingKnobs.alwaysFlushJobProgress, procsPerNode)
if err != nil {
return err
}
pkIDs := make(map[uint64]struct{}, len(details.Tables))
for _, t := range details.Tables {
pkIDs[roachpb.BulkOpSummaryID(uint64(t.Desc.ID), uint64(t.Desc.PrimaryIndex.ID))] = struct{}{}
}
r.res.DataSize = res.DataSize
for id, count := range res.EntryCounts {
if _, ok := pkIDs[id]; ok {
r.res.Rows += count
} else {
r.res.IndexEntries += count
}
}
if r.testingKnobs.afterImport != nil {
if err := r.testingKnobs.afterImport(r.res); err != nil {
return err
}
}
if err := p.ExecCfg().JobRegistry.CheckPausepoint("import.after_ingest"); err != nil {
return err
}
if err := r.checkVirtualConstraints(ctx, p.ExecCfg(), r.job, p.User()); err != nil {
return err
}
// If the table being imported into referenced UDTs, ensure that a concurrent
// schema change on any of the typeDescs has not modified the type descriptor. If
// it has, it is unsafe to import the data and we fail the import job.
if err := r.checkForUDTModification(ctx, p.ExecCfg()); err != nil {
return err
}
if err := r.publishSchemas(ctx, p.ExecCfg()); err != nil {
return err
}
if err := r.publishTables(ctx, p.ExecCfg(), res); err != nil {
return err
}
// As of 21.2 we do not write a protected timestamp record during IMPORT INTO.
// In case of a mixed version cluster with 21.1 and 21.2 nodes, it is possible
// that the job was planned on an older node and then resumed on a 21.2 node.
// Thus, we still need to clear the timestamp record that was written when the
// IMPORT INTO was planned on the older node.
//
// TODO(adityamaru): Remove in 22.1.
if err := p.ExecCfg().DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
return r.releaseProtectedTimestamp(ctx, txn, p.ExecCfg().ProtectedTimestampProvider)
}); err != nil {
log.Errorf(ctx, "failed to release protected timestamp: %v", err)
}
emitImportJobEvent(ctx, p, jobs.StatusSucceeded, r.job)
addToFileFormatTelemetry(details.Format.Format.String(), "succeeded")
telemetry.CountBucketed("import.rows", r.res.Rows)
const mb = 1 << 20
sizeMb := r.res.DataSize / mb
telemetry.CountBucketed("import.size-mb", sizeMb)
sec := int64(timeutil.Since(timeutil.FromUnixMicros(r.job.Payload().StartedMicros)).Seconds())
var mbps int64
if sec > 0 {
mbps = mb / sec
}
telemetry.CountBucketed("import.duration-sec.succeeded", sec)
telemetry.CountBucketed("import.speed-mbps", mbps)
// Tiny imports may skew throughput numbers due to overhead.
if sizeMb > 10 {
telemetry.CountBucketed("import.speed-mbps.over10mb", mbps)
}
return nil
}
// prepareTablesForIngestion prepares table descriptors for the ingestion
// step of import. The descriptors are in an IMPORTING state (offline) on
// successful completion of this method.
func (r *importResumer) prepareTablesForIngestion(
ctx context.Context,
p sql.JobExecContext,
details jobspb.ImportDetails,
txn *kv.Txn,
descsCol *descs.Collection,
schemaMetadata *preparedSchemaMetadata,
) (jobspb.ImportDetails, error) {
importDetails := details
importDetails.Tables = make([]jobspb.ImportDetails_Table, len(details.Tables))
newSchemaAndTableNameToIdx := make(map[string]int, len(importDetails.Tables))
var hasExistingTables bool
var err error
var newTableDescs []jobspb.ImportDetails_Table
var desc *descpb.TableDescriptor
for i, table := range details.Tables {
if !table.IsNew {
desc, err = prepareExistingTablesForIngestion(ctx, txn, descsCol, table.Desc)
if err != nil {
return importDetails, err
}
importDetails.Tables[i] = jobspb.ImportDetails_Table{
Desc: desc, Name: table.Name,
SeqVal: table.SeqVal,
IsNew: table.IsNew,
TargetCols: table.TargetCols,
}
hasExistingTables = true
} else {
// PGDUMP imports support non-public schemas.
// For the purpose of disambiguation we must take the schema into
// account when constructing the newTablenameToIdx map.
// At this point the table descriptor's parent schema ID has not being
// remapped to the newly generated schema ID.
key, err := constructSchemaAndTableKey(ctx, table.Desc, schemaMetadata.oldSchemaIDToName, p.ExecCfg().Settings.Version)
if err != nil {
return importDetails, err
}
newSchemaAndTableNameToIdx[key.String()] = i
// Make a deep copy of the table descriptor so that rewrites do not
// partially clobber the descriptor stored in details.
newTableDescs = append(newTableDescs,
*protoutil.Clone(&table).(*jobspb.ImportDetails_Table))
}
}
// Prepare the table descriptors for newly created tables being imported
// into.
//
// TODO(adityamaru): This is still unnecessarily complicated. If we can get
// the new table desc preparation to work on a per desc basis, rather than
// requiring all the newly created descriptors, then this can look like the
// call to prepareExistingTablesForIngestion. Currently, FK references
// misbehave when I tried to write the desc one at a time.
if len(newTableDescs) != 0 {
res, err := prepareNewTablesForIngestion(
ctx, txn, descsCol, p, newTableDescs, importDetails.ParentID, schemaMetadata.schemaRewrites)
if err != nil {
return importDetails, err
}
for _, desc := range res {
key, err := constructSchemaAndTableKey(ctx, desc, schemaMetadata.newSchemaIDToName, p.ExecCfg().Settings.Version)
if err != nil {
return importDetails, err
}
i := newSchemaAndTableNameToIdx[key.String()]
table := details.Tables[i]
importDetails.Tables[i] = jobspb.ImportDetails_Table{
Desc: desc,
Name: table.Name,
SeqVal: table.SeqVal,
IsNew: table.IsNew,
TargetCols: table.TargetCols,
}
}
}
importDetails.PrepareComplete = true
// If we do not have pending schema changes on existing descriptors we can
// choose our Walltime (to IMPORT from) immediately. Otherwise, we have to
// wait for all nodes to see the same descriptor version before doing so.
if !hasExistingTables {
importDetails.Walltime = p.ExecCfg().Clock.Now().WallTime
} else {
importDetails.Walltime = 0
}
return importDetails, nil
}
// prepareExistingTablesForIngestion prepares descriptors for existing tables
// being imported into.
func prepareExistingTablesForIngestion(
ctx context.Context, txn *kv.Txn, descsCol *descs.Collection, desc *descpb.TableDescriptor,
) (*descpb.TableDescriptor, error) {
if len(desc.Mutations) > 0 {
return nil, errors.Errorf("cannot IMPORT INTO a table with schema changes in progress -- try again later (pending mutation %s)", desc.Mutations[0].String())
}
// Note that desc is just used to verify that the version matches.
importing, err := descsCol.GetMutableTableVersionByID(ctx, desc.ID, txn)
if err != nil {
return nil, err
}
// Ensure that the version of the table has not been modified since this
// job was created.
if got, exp := importing.Version, desc.Version; got != exp {
return nil, errors.Errorf("another operation is currently operating on the table")
}
// Take the table offline for import.
// TODO(dt): audit everywhere we get table descs (leases or otherwise) to
// ensure that filtering by state handles IMPORTING correctly.
importing.SetOffline("importing")
// TODO(dt): de-validate all the FKs.
if err := descsCol.WriteDesc(
ctx, false /* kvTrace */, importing, txn,
); err != nil {
return nil, err
}
return importing.TableDesc(), nil
}
// prepareNewTablesForIngestion prepares descriptors for newly created
// tables being imported into.
func prepareNewTablesForIngestion(
ctx context.Context,
txn *kv.Txn,
descsCol *descs.Collection,
p sql.JobExecContext,
importTables []jobspb.ImportDetails_Table,
parentID descpb.ID,
schemaRewrites jobspb.DescRewriteMap,
) ([]*descpb.TableDescriptor, error) {
newMutableTableDescriptors := make([]*tabledesc.Mutable, len(importTables))
for i := range importTables {
newMutableTableDescriptors[i] = tabledesc.NewBuilder(importTables[i].Desc).BuildCreatedMutableTable()
}
// Verification steps have passed, generate a new table ID if we're
// restoring. We do this last because we want to avoid calling
// GenerateUniqueDescID if there's any kind of error above.
// Reserving a table ID now means we can avoid the rekey work during restore.
//
// schemaRewrites may contain information which is used in rewrite.TableDescs
// to rewrite the parent schema ID in the table desc to point to the correct
// schema ID.
tableRewrites := schemaRewrites
if tableRewrites == nil {
tableRewrites = make(jobspb.DescRewriteMap)
}
seqVals := make(map[descpb.ID]int64, len(importTables))
for _, tableDesc := range importTables {
id, err := p.ExecCfg().DescIDGenerator.GenerateUniqueDescID(ctx)
if err != nil {
return nil, err
}
oldParentSchemaID := tableDesc.Desc.GetUnexposedParentSchemaID()
parentSchemaID := oldParentSchemaID
if rw, ok := schemaRewrites[oldParentSchemaID]; ok {
parentSchemaID = rw.ID
}
tableRewrites[tableDesc.Desc.ID] = &jobspb.DescriptorRewrite{
ID: id,
ParentSchemaID: parentSchemaID,
ParentID: parentID,
}
seqVals[id] = tableDesc.SeqVal
}
if err := rewrite.TableDescs(
newMutableTableDescriptors, tableRewrites, "",
); err != nil {
return nil, err
}
// After all of the ID's have been remapped, ensure that there aren't any name
// collisions with any importing tables.
for i := range newMutableTableDescriptors {
tbl := newMutableTableDescriptors[i]
err := descsCol.Direct().CheckObjectCollision(
ctx,
txn,
tbl.GetParentID(),
tbl.GetParentSchemaID(),
tree.NewUnqualifiedTableName(tree.Name(tbl.GetName())),
)
if err != nil {
return nil, err
}
}
// tableDescs contains the same slice as newMutableTableDescriptors but
// as tabledesc.TableDescriptor.
tableDescs := make([]catalog.TableDescriptor, len(newMutableTableDescriptors))
for i := range tableDescs {
newMutableTableDescriptors[i].SetOffline("importing")
tableDescs[i] = newMutableTableDescriptors[i]
}
var seqValKVs []roachpb.KeyValue
for _, desc := range newMutableTableDescriptors {
if v, ok := seqVals[desc.GetID()]; ok && v != 0 {
key, val, err := sql.MakeSequenceKeyVal(p.ExecCfg().Codec, desc, v, false)
if err != nil {
return nil, err
}
kv := roachpb.KeyValue{Key: key}
kv.Value.SetInt(val)
seqValKVs = append(seqValKVs, kv)
}
}
// Write the new TableDescriptors and flip the namespace entries over to
// them. After this call, any queries on a table will be served by the newly
// imported data.
if err := ingesting.WriteDescriptors(ctx, p.ExecCfg().Codec, txn, p.User(), descsCol,
nil /* databases */, nil, /* schemas */
tableDescs, nil, tree.RequestedDescriptors, seqValKVs, "" /* inheritParentName */); err != nil {
return nil, errors.Wrapf(err, "creating importTables")
}
newPreparedTableDescs := make([]*descpb.TableDescriptor, len(newMutableTableDescriptors))
for i := range newMutableTableDescriptors {
newPreparedTableDescs[i] = newMutableTableDescriptors[i].TableDesc()
}
return newPreparedTableDescs, nil
}
// prepareSchemasForIngestion is responsible for assigning the created schema
// descriptors actual IDs, updating the parent DB with references to the new
// schemas and writing the schema descriptors to disk.
func (r *importResumer) prepareSchemasForIngestion(
ctx context.Context,
p sql.JobExecContext,
details jobspb.ImportDetails,
txn *kv.Txn,
descsCol *descs.Collection,
) (*preparedSchemaMetadata, error) {
schemaMetadata := &preparedSchemaMetadata{
schemaPreparedDetails: details,
newSchemaIDToName: make(map[descpb.ID]string),
oldSchemaIDToName: make(map[descpb.ID]string),
}
schemaMetadata.schemaPreparedDetails.Schemas = make([]jobspb.ImportDetails_Schema,
len(details.Schemas))
desc, err := descsCol.GetMutableDescriptorByID(ctx, txn, details.ParentID)
if err != nil {
return nil, err
}
dbDesc, ok := desc.(*dbdesc.Mutable)
if !ok {
return nil, errors.Newf("expected ID %d to refer to the database being imported into",
details.ParentID)
}
schemaMetadata.schemaRewrites = make(jobspb.DescRewriteMap)
mutableSchemaDescs := make([]*schemadesc.Mutable, 0)
for _, desc := range details.Schemas {
schemaMetadata.oldSchemaIDToName[desc.Desc.GetID()] = desc.Desc.GetName()
newMutableSchemaDescriptor := schemadesc.NewBuilder(desc.Desc).BuildCreatedMutable().(*schemadesc.Mutable)
// Verification steps have passed, generate a new schema ID. We do this
// last because we want to avoid calling GenerateUniqueDescID if there's
// any kind of error in the prior stages of import.
id, err := p.ExecCfg().DescIDGenerator.GenerateUniqueDescID(ctx)
if err != nil {
return nil, err
}
newMutableSchemaDescriptor.Version = 1
newMutableSchemaDescriptor.ID = id
mutableSchemaDescs = append(mutableSchemaDescs, newMutableSchemaDescriptor)
schemaMetadata.newSchemaIDToName[id] = newMutableSchemaDescriptor.GetName()
// Update the parent database with this schema information.
dbDesc.AddSchemaToDatabase(newMutableSchemaDescriptor.Name,
descpb.DatabaseDescriptor_SchemaInfo{ID: newMutableSchemaDescriptor.ID})
schemaMetadata.schemaRewrites[desc.Desc.ID] = &jobspb.DescriptorRewrite{
ID: id,
}
}
// Queue a job to write the updated database descriptor.
schemaMetadata.queuedSchemaJobs, err = writeNonDropDatabaseChange(ctx, dbDesc, txn, descsCol, p,
fmt.Sprintf("updating parent database %s when importing new schemas", dbDesc.GetName()))
if err != nil {
return nil, err
}
// Finally create the schemas on disk.
for i, mutDesc := range mutableSchemaDescs {
nameKey := catalogkeys.MakeSchemaNameKey(p.ExecCfg().Codec, dbDesc.ID, mutDesc.GetName())
err = createSchemaDescriptorWithID(ctx, nameKey, mutDesc.ID, mutDesc, p, descsCol, txn)
if err != nil {
return nil, err
}
schemaMetadata.schemaPreparedDetails.Schemas[i] = jobspb.ImportDetails_Schema{
Desc: mutDesc.SchemaDesc(),
}
}
return schemaMetadata, err
}
// createSchemaDescriptorWithID writes a schema descriptor with `id` to disk.
func createSchemaDescriptorWithID(
ctx context.Context,
idKey roachpb.Key,
id descpb.ID,
descriptor catalog.Descriptor,
p sql.JobExecContext,
descsCol *descs.Collection,
txn *kv.Txn,
) error {
if descriptor.GetID() == descpb.InvalidID {
return errors.AssertionFailedf("cannot create descriptor with an empty ID: %v", descriptor)
}
if descriptor.GetID() != id {
return errors.AssertionFailedf("cannot create descriptor with an ID %v; expected ID %v; descriptor %v",
id, descriptor.GetID(), descriptor)
}
b := &kv.Batch{}
descID := descriptor.GetID()
if p.ExtendedEvalContext().Tracing.KVTracingEnabled() {
log.VEventf(ctx, 2, "CPut %s -> %d", idKey, descID)
}
b.CPut(idKey, descID, nil)
if err := descsCol.Direct().WriteNewDescToBatch(
ctx,
p.ExtendedEvalContext().Tracing.KVTracingEnabled(),
b,
descriptor,
); err != nil {
return err
}
mutDesc, ok := descriptor.(catalog.MutableDescriptor)
if !ok {
return errors.Newf("unexpected type %T when creating descriptor", descriptor)
}
switch mutDesc.(type) {
case *schemadesc.Mutable:
if err := descsCol.AddUncommittedDescriptor(ctx, mutDesc); err != nil {
return err
}
default:
return errors.Newf("unexpected type %T when creating descriptor", mutDesc)
}
return txn.Run(ctx, b)
}
// parseBundleSchemaIfNeeded parses dump files (PGDUMP, MYSQLDUMP) for DDL
// statements and creates the relevant database, schema, table and type
// descriptors. Data from the dump files is ingested into these descriptors in
// the next phase of the import.
func (r *importResumer) parseBundleSchemaIfNeeded(ctx context.Context, phs interface{}) error {
p := phs.(sql.JobExecContext)
seqVals := make(map[descpb.ID]int64)
details := r.job.Details().(jobspb.ImportDetails)
skipFKs := details.SkipFKs
parentID := details.ParentID
files := details.URIs
format := details.Format
owner := r.job.Payload().UsernameProto.Decode()
p.SessionDataMutatorIterator().SetSessionDefaultIntSize(details.DefaultIntSize)
if details.ParseBundleSchema {
var span *tracing.Span
ctx, span = tracing.ChildSpan(ctx, "import-parsing-bundle-schema")
defer span.Finish()
if err := r.job.RunningStatus(ctx, nil /* txn */, func(_ context.Context, _ jobspb.Details) (jobs.RunningStatus, error) {
return runningStatusImportBundleParseSchema, nil
}); err != nil {
return errors.Wrapf(err, "failed to update running status of job %d", errors.Safe(r.job.ID()))
}
var dbDesc catalog.DatabaseDescriptor
{
if err := sql.DescsTxn(ctx, p.ExecCfg(), func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) (err error) {
_, dbDesc, err = descriptors.GetImmutableDatabaseByID(ctx, txn, parentID, tree.DatabaseLookupFlags{
Required: true,
AvoidLeased: true,
})
if err != nil {
return err
}
return err
}); err != nil {
return err
}
}
var schemaDescs []*schemadesc.Mutable
var tableDescs []*tabledesc.Mutable
var err error
walltime := p.ExecCfg().Clock.Now().WallTime
if tableDescs, schemaDescs, err = parseAndCreateBundleTableDescs(
ctx, p, details, seqVals, skipFKs, dbDesc, files, format, walltime, owner,
r.job.ID()); err != nil {
return err
}
schemaDetails := make([]jobspb.ImportDetails_Schema, len(schemaDescs))
for i, schemaDesc := range schemaDescs {
schemaDetails[i] = jobspb.ImportDetails_Schema{Desc: schemaDesc.SchemaDesc()}
}
details.Schemas = schemaDetails
tableDetails := make([]jobspb.ImportDetails_Table, len(tableDescs))
for i, tableDesc := range tableDescs {
tableDetails[i] = jobspb.ImportDetails_Table{
Name: tableDesc.GetName(),
Desc: tableDesc.TableDesc(),
SeqVal: seqVals[tableDescs[i].ID],
IsNew: true,
}
}
details.Tables = tableDetails
for _, tbl := range tableDescs {
// For reasons relating to #37691, we disallow user defined types in
// the standard IMPORT case.
for _, col := range tbl.Columns {
if col.Type.UserDefined() {
return errors.Newf("IMPORT cannot be used with user defined types; use IMPORT INTO instead")
}
}
}
// Prevent job from redoing schema parsing and table desc creation
// on subsequent resumptions.
details.ParseBundleSchema = false
if err := r.job.SetDetails(ctx, nil /* txn */, details); err != nil {
return err
}
}
return nil
}
func getPublicSchemaDescForDatabase(
ctx context.Context, execCfg *sql.ExecutorConfig, db catalog.DatabaseDescriptor,
) (scDesc catalog.SchemaDescriptor, err error) {
if err := sql.DescsTxn(ctx, execCfg, func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) error {
publicSchemaID := db.GetSchemaID(tree.PublicSchema)
scDesc, err = descriptors.GetImmutableSchemaByID(ctx, txn, publicSchemaID, tree.SchemaLookupFlags{Required: true})
return err
}); err != nil {
return nil, err
}
return scDesc, nil
}
// parseAndCreateBundleTableDescs parses and creates the table
// descriptors for bundle formats.
func parseAndCreateBundleTableDescs(
ctx context.Context,
p sql.JobExecContext,
details jobspb.ImportDetails,
seqVals map[descpb.ID]int64,
skipFKs bool,
parentDB catalog.DatabaseDescriptor,
files []string,
format roachpb.IOFileFormat,
walltime int64,
owner username.SQLUsername,
jobID jobspb.JobID,
) ([]*tabledesc.Mutable, []*schemadesc.Mutable, error) {
var schemaDescs []*schemadesc.Mutable
var tableDescs []*tabledesc.Mutable
var tableName string
// A single table entry in the import job details when importing a bundle format
// indicates that we are performing a single table import.
// This info is populated during the planning phase.
if len(details.Tables) > 0 {
tableName = details.Tables[0].Name
}
store, err := p.ExecCfg().DistSQLSrv.ExternalStorageFromURI(ctx, files[0], p.User())
if err != nil {
return tableDescs, schemaDescs, err
}
defer store.Close()
raw, err := store.ReadFile(ctx, "")
if err != nil {
return tableDescs, schemaDescs, err
}
defer raw.Close(ctx)
reader, err := decompressingReader(ioctx.ReaderCtxAdapter(ctx, raw), files[0], format.Compression)
if err != nil {
return tableDescs, schemaDescs, err
}
defer reader.Close()
fks := fkHandler{skip: skipFKs, allowed: true, resolver: fkResolver{
tableNameToDesc: make(map[string]*tabledesc.Mutable),
}}
switch format.Format {
case roachpb.IOFileFormat_Mysqldump:
id, err := descidgen.PeekNextUniqueDescID(ctx, p.ExecCfg().DB, p.ExecCfg().Codec)
if err != nil {
return tableDescs, schemaDescs, err
}
fks.resolver.format.Format = roachpb.IOFileFormat_Mysqldump
evalCtx := &p.ExtendedEvalContext().Context
tableDescs, err = readMysqlCreateTable(
ctx, reader, evalCtx, p, id, parentDB, tableName, fks,
seqVals, owner, walltime,
)
if err != nil {
return tableDescs, schemaDescs, err
}
case roachpb.IOFileFormat_PgDump:
fks.resolver.format.Format = roachpb.IOFileFormat_PgDump
evalCtx := &p.ExtendedEvalContext().Context
// Setup a logger to handle unsupported DDL statements in the PGDUMP file.
unsupportedStmtLogger := makeUnsupportedStmtLogger(ctx, p.User(), int64(jobID),
format.PgDump.IgnoreUnsupported, format.PgDump.IgnoreUnsupportedLog, schemaParsing,
p.ExecCfg().DistSQLSrv.ExternalStorage)
tableDescs, schemaDescs, err = readPostgresCreateTable(ctx, reader, evalCtx, p, tableName,
parentDB, walltime, fks, int(format.PgDump.MaxRowSize), owner, unsupportedStmtLogger)
logErr := unsupportedStmtLogger.flush()
if logErr != nil {
return nil, nil, logErr
}
default:
return tableDescs, schemaDescs, errors.Errorf(
"non-bundle format %q does not support reading schemas", format.Format.String())
}
if err != nil {
return tableDescs, schemaDescs, err
}
if tableDescs == nil && len(details.Tables) > 0 {
return tableDescs, schemaDescs, errors.Errorf("table definition not found for %q", tableName)
}
return tableDescs, schemaDescs, err
}
// publishTables updates the status of imported tables from OFFLINE to PUBLIC.
func (r *importResumer) publishTables(
ctx context.Context, execCfg *sql.ExecutorConfig, res roachpb.BulkOpSummary,
) error {
details := r.job.Details().(jobspb.ImportDetails)
// Tables should only be published once.
if details.TablesPublished {
return nil
}
// Write stub statistics for new tables created during the import. This should
// be sufficient until the CREATE STATISTICS run finishes.
r.writeStubStatisticsForImportedTables(ctx, execCfg, res)
log.Event(ctx, "making tables live")
err := sql.DescsTxn(ctx, execCfg, func(
ctx context.Context, txn *kv.Txn, descsCol *descs.Collection,
) error {
b := txn.NewBatch()
for _, tbl := range details.Tables {
newTableDesc, err := descsCol.GetMutableTableVersionByID(ctx, tbl.Desc.ID, txn)
if err != nil {
return err
}
newTableDesc.SetPublic()
if !tbl.IsNew {
// NB: This is not using AllNonDropIndexes or directly mutating the
// constraints returned by the other usual helpers because we need to
// replace the `OutboundFKs` and `Checks` slices of newTableDesc with copies
// that we can mutate. We need to do that because newTableDesc is a shallow
// copy of tbl.Desc that we'll be asserting is the current version when we
// CPut below.
//
// Set FK constraints to unvalidated before publishing the table imported
// into.
newTableDesc.OutboundFKs = make([]descpb.ForeignKeyConstraint, len(newTableDesc.OutboundFKs))
copy(newTableDesc.OutboundFKs, tbl.Desc.OutboundFKs)
for i := range newTableDesc.OutboundFKs {
newTableDesc.OutboundFKs[i].Validity = descpb.ConstraintValidity_Unvalidated
}
// Set CHECK constraints to unvalidated before publishing the table imported into.
for _, c := range newTableDesc.AllActiveAndInactiveChecks() {
c.Validity = descpb.ConstraintValidity_Unvalidated
}
}
// TODO(dt): re-validate any FKs?
if err := descsCol.WriteDescToBatch(
ctx, false /* kvTrace */, newTableDesc, b,
); err != nil {
return errors.Wrapf(err, "publishing table %d", newTableDesc.ID)
}
}
if err := txn.Run(ctx, b); err != nil {
return errors.Wrap(err, "publishing tables")
}
// Update job record to mark tables published state as complete.
details.TablesPublished = true
err := r.job.SetDetails(ctx, txn, details)
if err != nil {
return errors.Wrap(err, "updating job details after publishing tables")
}
return nil
})
if err != nil {
return err
}