-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
import_stmt.go
2619 lines (2361 loc) · 85.7 KB
/
import_stmt.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.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package importccl
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"math"
"net/url"
"path"
"sort"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/featureflag"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/jobs/jobsprotectedts"
"github.com/cockroachdb/cockroach/pkg/keys"
"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"
"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/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/resolver"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"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/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"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/storage/cloud"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"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/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
)
const (
csvDelimiter = "delimiter"
csvComment = "comment"
csvNullIf = "nullif"
csvSkip = "skip"
csvRowLimit = "row_limit"
csvStrictQuotes = "strict_quotes"
mysqlOutfileRowSep = "rows_terminated_by"
mysqlOutfileFieldSep = "fields_terminated_by"
mysqlOutfileEnclose = "fields_enclosed_by"
mysqlOutfileEscape = "fields_escaped_by"
importOptionSSTSize = "sstsize"
importOptionDecompress = "decompress"
importOptionOversample = "oversample"
importOptionSkipFKs = "skip_foreign_keys"
importOptionDisableGlobMatch = "disable_glob_matching"
importOptionSaveRejected = "experimental_save_rejected"
importOptionDetached = "detached"
pgCopyDelimiter = "delimiter"
pgCopyNull = "nullif"
optMaxRowSize = "max_row_size"
// Turn on strict validation when importing avro records.
avroStrict = "strict_validation"
// Default input format is assumed to be OCF (object container file).
// This default can be changed by specified either of these options.
avroBinRecords = "data_as_binary_records"
avroJSONRecords = "data_as_json_records"
// Record separator; default "\n"
avroRecordsSeparatedBy = "records_terminated_by"
// If we are importing avro records (binary or JSON), we must specify schema
// as either an inline JSON schema, or an external schema URI.
avroSchema = "schema"
avroSchemaURI = "schema_uri"
pgDumpIgnoreAllUnsupported = "ignore_unsupported_statements"
pgDumpIgnoreShuntFileDest = "log_ignored_statements"
pgDumpUnsupportedSchemaStmtLog = "unsupported_schema_stmts"
pgDumpUnsupportedDataStmtLog = "unsupported_data_stmts"
// RunningStatusImportBundleParseSchema indicates to the user that a bundle format
// schema is being parsed
runningStatusImportBundleParseSchema jobs.RunningStatus = "parsing schema on Import Bundle"
)
var importOptionExpectValues = map[string]sql.KVStringOptValidate{
csvDelimiter: sql.KVStringOptRequireValue,
csvComment: sql.KVStringOptRequireValue,
csvNullIf: sql.KVStringOptRequireValue,
csvSkip: sql.KVStringOptRequireValue,
csvRowLimit: sql.KVStringOptRequireValue,
csvStrictQuotes: sql.KVStringOptRequireNoValue,
mysqlOutfileRowSep: sql.KVStringOptRequireValue,
mysqlOutfileFieldSep: sql.KVStringOptRequireValue,
mysqlOutfileEnclose: sql.KVStringOptRequireValue,
mysqlOutfileEscape: sql.KVStringOptRequireValue,
importOptionSSTSize: sql.KVStringOptRequireValue,
importOptionDecompress: sql.KVStringOptRequireValue,
importOptionOversample: sql.KVStringOptRequireValue,
importOptionSaveRejected: sql.KVStringOptRequireNoValue,
importOptionSkipFKs: sql.KVStringOptRequireNoValue,
importOptionDisableGlobMatch: sql.KVStringOptRequireNoValue,
importOptionDetached: sql.KVStringOptRequireNoValue,
optMaxRowSize: sql.KVStringOptRequireValue,
avroStrict: sql.KVStringOptRequireNoValue,
avroSchema: sql.KVStringOptRequireValue,
avroSchemaURI: sql.KVStringOptRequireValue,
avroRecordsSeparatedBy: sql.KVStringOptRequireValue,
avroBinRecords: sql.KVStringOptRequireNoValue,
avroJSONRecords: sql.KVStringOptRequireNoValue,
pgDumpIgnoreAllUnsupported: sql.KVStringOptRequireNoValue,
pgDumpIgnoreShuntFileDest: sql.KVStringOptRequireValue,
}
var pgDumpMaxLoggedStmts = 1024
func testingSetMaxLogIgnoredImportStatements(maxLogSize int) (cleanup func()) {
prevLogSize := pgDumpMaxLoggedStmts
pgDumpMaxLoggedStmts = maxLogSize
return func() {
pgDumpMaxLoggedStmts = prevLogSize
}
}
func makeStringSet(opts ...string) map[string]struct{} {
res := make(map[string]struct{}, len(opts))
for _, opt := range opts {
res[opt] = struct{}{}
}
return res
}
// Options common to all formats.
var allowedCommonOptions = makeStringSet(
importOptionSSTSize, importOptionDecompress, importOptionOversample,
importOptionSaveRejected, importOptionDisableGlobMatch, importOptionDetached)
// Format specific allowed options.
var avroAllowedOptions = makeStringSet(
avroStrict, avroBinRecords, avroJSONRecords,
avroRecordsSeparatedBy, avroSchema, avroSchemaURI, optMaxRowSize, csvRowLimit,
)
var csvAllowedOptions = makeStringSet(
csvDelimiter, csvComment, csvNullIf, csvSkip, csvStrictQuotes, csvRowLimit,
)
var mysqlOutAllowedOptions = makeStringSet(
mysqlOutfileRowSep, mysqlOutfileFieldSep, mysqlOutfileEnclose,
mysqlOutfileEscape, csvNullIf, csvSkip, csvRowLimit,
)
var mysqlDumpAllowedOptions = makeStringSet(importOptionSkipFKs, csvRowLimit)
var pgCopyAllowedOptions = makeStringSet(pgCopyDelimiter, pgCopyNull, optMaxRowSize)
var pgDumpAllowedOptions = makeStringSet(optMaxRowSize, importOptionSkipFKs, csvRowLimit,
pgDumpIgnoreAllUnsupported, pgDumpIgnoreShuntFileDest)
// DROP is required because the target table needs to be take offline during
// IMPORT INTO.
var importIntoRequiredPrivileges = []privilege.Kind{privilege.INSERT, privilege.DROP}
// File formats supported for IMPORT INTO
var allowedIntoFormats = map[string]struct{}{
"CSV": {},
"AVRO": {},
"DELIMITED": {},
"PGCOPY": {},
}
// featureImportEnabled is used to enable and disable the IMPORT feature.
var featureImportEnabled = settings.RegisterBoolSetting(
"feature.import.enabled",
"set to true to enable imports, false to disable; default is true",
featureflag.FeatureFlagEnabledDefault,
).WithPublic()
func validateFormatOptions(
format string, specified map[string]string, formatAllowed map[string]struct{},
) error {
for opt := range specified {
if _, ok := formatAllowed[opt]; !ok {
if _, ok = allowedCommonOptions[opt]; !ok {
return errors.Errorf(
"invalid option %q specified for %s import format", opt, format)
}
}
}
return nil
}
func importJobDescription(
p sql.PlanHookState,
orig *tree.Import,
defs tree.TableDefs,
files []string,
opts map[string]string,
) (string, error) {
stmt := *orig
stmt.CreateFile = nil
stmt.CreateDefs = defs
stmt.Files = nil
for _, file := range files {
clean, err := cloud.SanitizeExternalStorageURI(file, nil /* extraParams */)
if err != nil {
return "", err
}
stmt.Files = append(stmt.Files, tree.NewDString(clean))
}
stmt.Options = nil
for k, v := range opts {
opt := tree.KVOption{Key: tree.Name(k)}
val := importOptionExpectValues[k] == sql.KVStringOptRequireValue
val = val || (importOptionExpectValues[k] == sql.KVStringOptAny && len(v) > 0)
if val {
opt.Value = tree.NewDString(v)
}
stmt.Options = append(stmt.Options, opt)
}
sort.Slice(stmt.Options, func(i, j int) bool { return stmt.Options[i].Key < stmt.Options[j].Key })
ann := p.ExtendedEvalContext().Annotations
return tree.AsStringWithFQNames(&stmt, ann), nil
}
func ensureRequiredPrivileges(
ctx context.Context,
requiredPrivileges []privilege.Kind,
p sql.PlanHookState,
desc *tabledesc.Mutable,
) error {
for _, priv := range requiredPrivileges {
err := p.CheckPrivilege(ctx, desc, priv)
if err != nil {
return err
}
}
return nil
}
// addToFileFormatTelemetry records the different stages of IMPORT on a per file
// format basis.
//
// The current states being counted are:
// attempted: Counted at the very beginning of the IMPORT.
// started: Counted just before the IMPORT job is started.
// failed: Counted when the IMPORT job is failed or canceled.
// succeeded: Counted when the IMPORT job completes successfully.
func addToFileFormatTelemetry(fileFormat, state string) {
telemetry.Count(fmt.Sprintf("%s.%s.%s", "import", strings.ToLower(fileFormat), state))
}
// importPlanHook implements sql.PlanHookFn.
func importPlanHook(
ctx context.Context, stmt tree.Statement, p sql.PlanHookState,
) (sql.PlanHookRowFn, colinfo.ResultColumns, []sql.PlanNode, bool, error) {
importStmt, ok := stmt.(*tree.Import)
if !ok {
return nil, nil, nil, false, nil
}
addToFileFormatTelemetry(importStmt.FileFormat, "attempted")
if err := featureflag.CheckEnabled(
ctx,
p.ExecCfg(),
featureImportEnabled,
"IMPORT",
); err != nil {
return nil, nil, nil, false, err
}
filesFn, err := p.TypeAsStringArray(ctx, importStmt.Files, "IMPORT")
if err != nil {
return nil, nil, nil, false, err
}
var createFileFn func() (string, error)
if !importStmt.Bundle && !importStmt.Into && importStmt.CreateDefs == nil {
createFileFn, err = p.TypeAsString(ctx, importStmt.CreateFile, "IMPORT")
if err != nil {
return nil, nil, nil, false, err
}
}
optsFn, err := p.TypeAsStringOpts(ctx, importStmt.Options, importOptionExpectValues)
if err != nil {
return nil, nil, nil, false, err
}
opts, optsErr := optsFn()
var isDetached bool
if _, ok := opts[importOptionDetached]; ok {
isDetached = true
}
fn := func(ctx context.Context, _ []sql.PlanNode, resultsCh chan<- tree.Datums) error {
// TODO(dan): Move this span into sql.
ctx, span := tracing.ChildSpan(ctx, importStmt.StatementTag())
defer span.Finish()
walltime := p.ExecCfg().Clock.Now().WallTime
if !(p.ExtendedEvalContext().TxnImplicit || isDetached) {
return errors.Errorf("IMPORT cannot be used inside a transaction without DETACHED option")
}
if optsErr != nil {
return optsErr
}
filenamePatterns, err := filesFn()
if err != nil {
return err
}
// Certain ExternalStorage URIs require super-user access. Check all the
// URIs passed to the IMPORT command.
for _, file := range filenamePatterns {
conf, err := cloud.ExternalStorageConfFromURI(file, p.User())
if err != nil {
// If it is a workload URI, it won't parse as a storage config, but it
// also doesn't have any auth concerns so just continue.
if _, workloadErr := parseWorkloadConfig(file); workloadErr == nil {
continue
}
return err
}
if !conf.AccessIsWithExplicitAuth() {
err := p.RequireAdminRole(ctx,
fmt.Sprintf("IMPORT from the specified %s URI", conf.Provider.String()))
if err != nil {
return err
}
}
}
var files []string
if _, ok := opts[importOptionDisableGlobMatch]; ok {
files = filenamePatterns
} else {
for _, file := range filenamePatterns {
if cloud.URINeedsGlobExpansion(file) {
s, err := p.ExecCfg().DistSQLSrv.ExternalStorageFromURI(ctx, file, p.User())
if err != nil {
return err
}
expandedFiles, err := s.ListFiles(ctx, "")
if err != nil {
return err
}
if len(expandedFiles) < 1 {
return errors.Errorf(`no files matched uri provided: '%s'`, file)
}
files = append(files, expandedFiles...)
} else {
files = append(files, file)
}
}
}
// Typically the SQL grammar means it is only possible to specifying exactly
// one pgdump/mysqldump URI, but glob-expansion could have changed that.
if importStmt.Bundle && len(files) != 1 {
return pgerror.New(pgcode.FeatureNotSupported, "SQL dump files must be imported individually")
}
table := importStmt.Table
var db catalog.DatabaseDescriptor
var sc catalog.SchemaDescriptor
if table != nil {
// TODO: As part of work for #34240, we should be operating on
// UnresolvedObjectNames here, rather than TableNames.
// We have a target table, so it might specify a DB in its name.
un := table.ToUnresolvedObjectName()
found, prefix, resPrefix, err := resolver.ResolveTarget(ctx,
un, p, p.SessionData().Database, p.SessionData().SearchPath)
if err != nil {
return pgerror.Wrap(err, pgcode.UndefinedTable,
"resolving target import name")
}
if !found {
// Check if database exists right now. It might not after the import is done,
// but it's better to fail fast than wait until restore.
return pgerror.Newf(pgcode.UndefinedObject,
"database does not exist: %q", table)
}
table.ObjectNamePrefix = prefix
db = resPrefix.Database
sc = resPrefix.Schema
// If this is a non-INTO import that will thus be making a new table, we
// need the CREATE priv in the target DB.
if !importStmt.Into {
if err := p.CheckPrivilege(ctx, db, privilege.CREATE); err != nil {
return err
}
}
switch sc.SchemaKind() {
case catalog.SchemaVirtual:
return pgerror.Newf(pgcode.InvalidSchemaName,
"cannot import into schema %q", table.SchemaName)
}
} else {
// No target table means we're importing whatever we find into the session
// database, so it must exist.
txn := p.ExtendedEvalContext().Txn
db, err = p.Accessor().GetDatabaseDesc(ctx, txn, p.SessionData().Database, tree.DatabaseLookupFlags{
AvoidCached: true,
Required: true,
})
if err != nil {
return pgerror.Wrap(err, pgcode.UndefinedObject,
"could not resolve current database")
}
// If this is a non-INTO import that will thus be making a new table, we
// need the CREATE priv in the target DB.
if !importStmt.Into {
if err := p.CheckPrivilege(ctx, db, privilege.CREATE); err != nil {
return err
}
}
sc = schemadesc.GetPublicSchema()
}
format := roachpb.IOFileFormat{}
switch importStmt.FileFormat {
case "CSV":
if err = validateFormatOptions(importStmt.FileFormat, opts, csvAllowedOptions); err != nil {
return err
}
format.Format = roachpb.IOFileFormat_CSV
// Set the default CSV separator for the cases when it is not overwritten.
format.Csv.Comma = ','
if override, ok := opts[csvDelimiter]; ok {
comma, err := util.GetSingleRune(override)
if err != nil {
return pgerror.Wrap(err, pgcode.Syntax, "invalid comma value")
}
format.Csv.Comma = comma
}
if override, ok := opts[csvComment]; ok {
comment, err := util.GetSingleRune(override)
if err != nil {
return pgerror.Wrap(err, pgcode.Syntax, "invalid comment value")
}
format.Csv.Comment = comment
}
if override, ok := opts[csvNullIf]; ok {
format.Csv.NullEncoding = &override
}
if override, ok := opts[csvSkip]; ok {
skip, err := strconv.Atoi(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid %s value", csvSkip)
}
if skip < 0 {
return pgerror.Newf(pgcode.Syntax, "%s must be >= 0", csvSkip)
}
format.Csv.Skip = uint32(skip)
}
if _, ok := opts[csvStrictQuotes]; ok {
format.Csv.StrictQuotes = true
}
if _, ok := opts[importOptionSaveRejected]; ok {
format.SaveRejected = true
}
if override, ok := opts[csvRowLimit]; ok {
rowLimit, err := strconv.Atoi(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid numeric %s value", csvRowLimit)
}
if rowLimit <= 0 {
return pgerror.Newf(pgcode.Syntax, "%s must be > 0", csvRowLimit)
}
format.Csv.RowLimit = int64(rowLimit)
}
case "DELIMITED":
if err = validateFormatOptions(importStmt.FileFormat, opts, mysqlOutAllowedOptions); err != nil {
return err
}
format.Format = roachpb.IOFileFormat_MysqlOutfile
format.MysqlOut = roachpb.MySQLOutfileOptions{
RowSeparator: '\n',
FieldSeparator: '\t',
}
if override, ok := opts[mysqlOutfileRowSep]; ok {
c, err := util.GetSingleRune(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax,
"invalid %q value", mysqlOutfileRowSep)
}
format.MysqlOut.RowSeparator = c
}
if override, ok := opts[mysqlOutfileFieldSep]; ok {
c, err := util.GetSingleRune(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid %q value", mysqlOutfileFieldSep)
}
format.MysqlOut.FieldSeparator = c
}
if override, ok := opts[mysqlOutfileEnclose]; ok {
c, err := util.GetSingleRune(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid %q value", mysqlOutfileRowSep)
}
format.MysqlOut.Enclose = roachpb.MySQLOutfileOptions_Always
format.MysqlOut.Encloser = c
}
if override, ok := opts[mysqlOutfileEscape]; ok {
c, err := util.GetSingleRune(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid %q value", mysqlOutfileRowSep)
}
format.MysqlOut.HasEscape = true
format.MysqlOut.Escape = c
}
if override, ok := opts[csvSkip]; ok {
skip, err := strconv.Atoi(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid %s value", csvSkip)
}
if skip < 0 {
return pgerror.Newf(pgcode.Syntax, "%s must be >= 0", csvSkip)
}
format.MysqlOut.Skip = uint32(skip)
}
if override, ok := opts[csvNullIf]; ok {
format.MysqlOut.NullEncoding = &override
}
if _, ok := opts[importOptionSaveRejected]; ok {
format.SaveRejected = true
}
if override, ok := opts[csvRowLimit]; ok {
rowLimit, err := strconv.Atoi(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid numeric %s value", csvRowLimit)
}
if rowLimit <= 0 {
return pgerror.Newf(pgcode.Syntax, "%s must be > 0", csvRowLimit)
}
format.MysqlOut.RowLimit = int64(rowLimit)
}
case "MYSQLDUMP":
if err = validateFormatOptions(importStmt.FileFormat, opts, mysqlDumpAllowedOptions); err != nil {
return err
}
format.Format = roachpb.IOFileFormat_Mysqldump
if override, ok := opts[csvRowLimit]; ok {
rowLimit, err := strconv.Atoi(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid numeric %s value", csvRowLimit)
}
if rowLimit <= 0 {
return pgerror.Newf(pgcode.Syntax, "%s must be > 0", csvRowLimit)
}
format.MysqlDump.RowLimit = int64(rowLimit)
}
case "PGCOPY":
if err = validateFormatOptions(importStmt.FileFormat, opts, pgCopyAllowedOptions); err != nil {
return err
}
format.Format = roachpb.IOFileFormat_PgCopy
format.PgCopy = roachpb.PgCopyOptions{
Delimiter: '\t',
Null: `\N`,
}
if override, ok := opts[pgCopyDelimiter]; ok {
c, err := util.GetSingleRune(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid %q value", pgCopyDelimiter)
}
format.PgCopy.Delimiter = c
}
if override, ok := opts[pgCopyNull]; ok {
format.PgCopy.Null = override
}
maxRowSize := int32(defaultScanBuffer)
if override, ok := opts[optMaxRowSize]; ok {
sz, err := humanizeutil.ParseBytes(override)
if err != nil {
return err
}
if sz < 1 || sz > math.MaxInt32 {
return errors.Errorf("%d out of range: %d", maxRowSize, sz)
}
maxRowSize = int32(sz)
}
format.PgCopy.MaxRowSize = maxRowSize
case "PGDUMP":
if err = validateFormatOptions(importStmt.FileFormat, opts, pgDumpAllowedOptions); err != nil {
return err
}
format.Format = roachpb.IOFileFormat_PgDump
maxRowSize := int32(defaultScanBuffer)
if override, ok := opts[optMaxRowSize]; ok {
sz, err := humanizeutil.ParseBytes(override)
if err != nil {
return err
}
if sz < 1 || sz > math.MaxInt32 {
return errors.Errorf("%d out of range: %d", maxRowSize, sz)
}
maxRowSize = int32(sz)
}
format.PgDump.MaxRowSize = maxRowSize
if _, ok := opts[pgDumpIgnoreAllUnsupported]; ok {
format.PgDump.IgnoreUnsupported = true
}
if dest, ok := opts[pgDumpIgnoreShuntFileDest]; ok {
if !format.PgDump.IgnoreUnsupported {
return errors.New("cannot log unsupported PGDUMP stmts without `ignore_unsupported_statements` option")
}
format.PgDump.IgnoreUnsupportedLog = dest
}
if override, ok := opts[csvRowLimit]; ok {
rowLimit, err := strconv.Atoi(override)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax, "invalid numeric %s value", csvRowLimit)
}
if rowLimit <= 0 {
return pgerror.Newf(pgcode.Syntax, "%s must be > 0", csvRowLimit)
}
format.PgDump.RowLimit = int64(rowLimit)
}
case "AVRO":
if err = validateFormatOptions(importStmt.FileFormat, opts, avroAllowedOptions); err != nil {
return err
}
err := parseAvroOptions(ctx, opts, p, &format)
if err != nil {
return err
}
default:
return unimplemented.Newf("import.format", "unsupported import format: %q", importStmt.FileFormat)
}
// sstSize, if 0, will be set to an appropriate default by the specific
// implementation (local or distributed) since each has different optimal
// settings.
var sstSize int64
if override, ok := opts[importOptionSSTSize]; ok {
sz, err := humanizeutil.ParseBytes(override)
if err != nil {
return err
}
sstSize = sz
}
var oversample int64
if override, ok := opts[importOptionOversample]; ok {
os, err := strconv.ParseInt(override, 10, 64)
if err != nil {
return err
}
oversample = os
}
var skipFKs bool
if _, ok := opts[importOptionSkipFKs]; ok {
skipFKs = true
}
if override, ok := opts[importOptionDecompress]; ok {
found := false
for name, value := range roachpb.IOFileFormat_Compression_value {
if strings.EqualFold(name, override) {
format.Compression = roachpb.IOFileFormat_Compression(value)
found = true
break
}
}
if !found {
return unimplemented.Newf("import.compression", "unsupported compression value: %q", override)
}
}
var tableDetails []jobspb.ImportDetails_Table
var tableDescs []*tabledesc.Mutable // parallel with tableDetails
jobDesc, err := importJobDescription(p, importStmt, nil, filenamePatterns, opts)
if err != nil {
return err
}
if importStmt.Into {
// TODO(dt): this is a prototype for incremental import but there are many
// TODOs remaining before it is ready to graduate to prime-time. Some of
// them are captured in specific TODOs below, but some of the big, scary
// things to do are:
// - review planner vs txn use very carefully. We should try to get to a
// single txn used to plan the job and create it. Using the planner's
// txn today is very wrong since it will not commit until after the job
// has run, so starting a job based on reads it returned is very wrong.
// - audit every place that we resolve/lease/read table descs to be sure
// that the IMPORTING state is handled correctly. SQL lease acquisition
// is probably the easy one here since it has single read path -- the
// things that read directly like the queues or background jobs are the
// ones we'll need to really carefully look though.
// - Look at if/how cleanup/rollback works. Reconsider the cpu from the
// desc version (perhaps we should be re-reading instead?).
// - Write _a lot_ of tests.
if _, ok := allowedIntoFormats[importStmt.FileFormat]; !ok {
return errors.Newf(
"%s file format is currently unsupported by IMPORT INTO",
importStmt.FileFormat)
}
_, found, err := p.ResolveMutableTableDescriptor(ctx, table, true, tree.ResolveRequireTableDesc)
if err != nil {
return err
}
err = ensureRequiredPrivileges(ctx, importIntoRequiredPrivileges, p, found)
if err != nil {
return err
}
// IMPORT INTO does not currently support interleaved tables.
if found.IsInterleaved() {
// TODO(miretskiy): Handle import into when tables are interleaved.
return pgerror.New(pgcode.FeatureNotSupported, "Cannot use IMPORT INTO with interleaved tables")
}
// Validate target columns.
var intoCols []string
var isTargetCol = make(map[string]bool)
for _, name := range importStmt.IntoCols {
active, err := tabledesc.FindPublicColumnsWithNames(found, tree.NameList{name})
if err != nil {
return errors.Wrap(err, "verifying target columns")
}
isTargetCol[active[0].GetName()] = true
intoCols = append(intoCols, active[0].GetName())
}
// Ensure that non-target columns that don't have default
// expressions are nullable.
if len(isTargetCol) != 0 {
for _, col := range found.VisibleColumns() {
if !(isTargetCol[col.GetName()] || col.IsNullable() || col.HasDefault() || col.IsComputed()) {
return errors.Newf(
"all non-target columns in IMPORT INTO must be nullable "+
"or have default expressions, or have computed expressions"+
" but violated by column %q",
col.GetName(),
)
}
if isTargetCol[col.GetName()] && col.IsComputed() {
return schemaexpr.CannotWriteToComputedColError(col.GetName())
}
}
}
tableDescs = []*tabledesc.Mutable{found}
tableDetails = []jobspb.ImportDetails_Table{{Desc: &found.TableDescriptor, IsNew: false, TargetCols: intoCols}}
} else {
seqVals := make(map[descpb.ID]int64)
if importStmt.Bundle {
// If we target a single table, populate details with one entry of tableName.
if table != nil {
tableDetails = make([]jobspb.ImportDetails_Table, 1)
tableName := table.ObjectName.String()
// PGDUMP supports importing tables from non-public schemas, thus we
// must prepend the target table name with the target schema name.
if format.Format == roachpb.IOFileFormat_PgDump {
if table.Schema() == "" {
return errors.Newf("expected schema for target table %s to be resolved",
tableName)
}
tableName = fmt.Sprintf("%s.%s", table.SchemaName.String(),
table.ObjectName.String())
}
tableDetails[0] = jobspb.ImportDetails_Table{
Name: tableName,
IsNew: true,
}
}
} else {
if table == nil {
return errors.Errorf("non-bundle format %q should always have a table name", importStmt.FileFormat)
}
var create *tree.CreateTable
if importStmt.CreateDefs != nil {
create = &tree.CreateTable{
Table: *importStmt.Table,
Defs: importStmt.CreateDefs,
}
} else {
filename, err := createFileFn()
if err != nil {
return err
}
create, err = readCreateTableFromStore(ctx, filename,
p.ExecCfg().DistSQLSrv.ExternalStorageFromURI, p.User())
if err != nil {
return err
}
if table.ObjectName != create.Table.ObjectName {
return errors.Errorf(
"importing table %s, but file specifies a schema for table %s",
table.ObjectName, create.Table.ObjectName,
)
}
}
if create.Locality != nil &&
create.Locality.LocalityLevel == tree.LocalityLevelRow {
return unimplemented.NewWithIssueDetailf(
61133,
"import.regional-by-row",
"IMPORT to REGIONAL BY ROW table not supported",
)
}
tbl, err := MakeSimpleTableDescriptor(
ctx, p.SemaCtx(), p.ExecCfg().Settings, create, db, sc, defaultCSVTableID, NoFKs, walltime)
if err != nil {
return err
}
descStr, err := importJobDescription(p, importStmt, create.Defs, filenamePatterns, opts)
if err != nil {
return err
}
jobDesc = descStr
tableDescs = []*tabledesc.Mutable{tbl}
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")
}
}
}
tableDetails = make([]jobspb.ImportDetails_Table, len(tableDescs))
for i := range tableDescs {
tableDetails[i] = jobspb.ImportDetails_Table{
Desc: tableDescs[i].TableDesc(),
SeqVal: seqVals[tableDescs[i].ID],
IsNew: true,
}
}
}
// Due to how we generate and rewrite descriptor ID's for import, we run
// into problems when using user defined schemas.
if sc.GetID() != keys.PublicSchemaID {
err := errors.New("cannot use IMPORT with a user defined schema")
hint := errors.WithHint(err, "create the table with CREATE TABLE and use IMPORT INTO instead")
return hint
}
}
telemetry.CountBucketed("import.files", int64(len(files)))
// Record telemetry for userfile being used as the import target.
for _, file := range files {
uri, err := url.Parse(file)
// This should never be true as we have parsed these file names in an
// earlier step of import.
if err != nil {
log.Warningf(ctx, "failed to collect file specific import telemetry for %s", uri)
continue
}
if uri.Scheme == "userfile" {
telemetry.Count("import.storage.userfile")
break
}
}
if importStmt.Into {
telemetry.Count("import.into")
}
// Here we create the job and protected timestamp records in a side
// transaction and then kick off the job. This is awful. Rather we should be
// disallowing this statement in an explicit transaction and then we should
// create the job in the user's transaction here and then in a post-commit
// hook we should kick of the StartableJob which we attached to the
// connExecutor somehow.
importDetails := jobspb.ImportDetails{
URIs: files,
Format: format,
ParentID: db.GetID(),
Tables: tableDetails,
SSTSize: sstSize,
Oversample: oversample,
SkipFKs: skipFKs,
ParseBundleSchema: importStmt.Bundle,
}
// Prepare the protected timestamp record.
var spansToProtect []roachpb.Span
codec := p.(sql.PlanHookState).ExecCfg().Codec
for i := range tableDetails {
if td := &tableDetails[i]; !td.IsNew {
spansToProtect = append(spansToProtect, tableDescs[i].TableSpan(codec))
}
}
if len(spansToProtect) > 0 {
protectedtsID := uuid.MakeV4()
importDetails.ProtectedTimestampRecord = &protectedtsID
}
jr := jobs.Record{
Description: jobDesc,
Username: p.User(),
Details: importDetails,
Progress: jobspb.ImportProgress{},
}
if isDetached {
// When running inside an explicit transaction, we simply create the job
// record. We do not wait for the job to finish.
jobID := p.ExecCfg().JobRegistry.MakeJobID()
_, err := p.ExecCfg().JobRegistry.CreateAdoptableJobWithTxn(
ctx, jr, jobID, p.ExtendedEvalContext().Txn)
if err != nil {
return err
}
if err = protectTimestampForImport(ctx, p, p.ExtendedEvalContext().Txn, jobID, spansToProtect,
walltime, importDetails); err != nil {
return err
}
addToFileFormatTelemetry(format.Format.String(), "started")
resultsCh <- tree.Datums{tree.NewDInt(tree.DInt(jobID))}
return nil
}
// We create the job record in the planner's transaction to ensure that
// the job record creation happens transactionally.
plannerTxn := p.ExtendedEvalContext().Txn
// Construct the job and commit the transaction. Perform this work in a
// closure to ensure that the job is cleaned up if an error occurs.
var sj *jobs.StartableJob
if err := func() (err error) {
defer func() {
if err == nil || sj == nil {
return
}
if cleanupErr := sj.CleanupOnRollback(ctx); cleanupErr != nil {
log.Errorf(ctx, "failed to cleanup job: %v", cleanupErr)
}
}()
jobID := p.ExecCfg().JobRegistry.MakeJobID()
if err := p.ExecCfg().JobRegistry.CreateStartableJobWithTxn(ctx, &sj, jobID, plannerTxn, jr); err != nil {
return err
}
if err := protectTimestampForImport(ctx, p, plannerTxn, jobID, spansToProtect, walltime, importDetails); err != nil {