-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
changefeed_test.go
5097 lines (4517 loc) · 185 KB
/
changefeed_test.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 2018 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 changefeedccl
import (
"context"
gosql "database/sql"
"encoding/json"
"fmt"
"math"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/cdctest"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/changefeedbase"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/kvevent"
// Imported to allow multi-tenant tests
_ "github.com/cockroachdb/cockroach/pkg/ccl/kvccl/kvtenantccl"
// Imported to allow locality-related table mutations
_ "github.com/cockroachdb/cockroach/pkg/ccl/multiregionccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/partitionccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
_ "github.com/cockroachdb/cockroach/pkg/cloud/impl" // registers cloud storage providers
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/dustin/go-humanize"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var testServerRegion = "us-east-1"
func TestChangefeedBasics(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO foo VALUES (0, 'initial')`)
sqlDB.Exec(t, `UPSERT INTO foo VALUES (0, 'updated')`)
foo := feed(t, f, `CREATE CHANGEFEED FOR foo`)
defer closeFeed(t, foo)
// 'initial' is skipped because only the latest value ('updated') is
// emitted by the initial scan.
assertPayloads(t, foo, []string{
`foo: [0]->{"after": {"a": 0, "b": "updated"}}`,
})
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'a'), (2, 'b')`)
assertPayloads(t, foo, []string{
`foo: [1]->{"after": {"a": 1, "b": "a"}}`,
`foo: [2]->{"after": {"a": 2, "b": "b"}}`,
})
sqlDB.Exec(t, `UPSERT INTO foo VALUES (2, 'c'), (3, 'd')`)
assertPayloads(t, foo, []string{
`foo: [2]->{"after": {"a": 2, "b": "c"}}`,
`foo: [3]->{"after": {"a": 3, "b": "d"}}`,
})
sqlDB.Exec(t, `DELETE FROM foo WHERE a = 1`)
assertPayloads(t, foo, []string{
`foo: [1]->{"after": null}`,
})
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`cloudstorage`, cloudStorageTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
// NB running TestChangefeedBasics, which includes a DELETE, with
// cloudStorageTest is a regression test for #36994.
}
func TestChangefeedBasicConfluentKafka(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO foo VALUES (0, 'initial')`)
sqlDB.Exec(t, `UPSERT INTO foo VALUES (0, 'updated')`)
foo := feed(t, f,
fmt.Sprintf(`CREATE CHANGEFEED FOR foo WITH format=%s`, changefeedbase.OptFormatAvro))
defer closeFeed(t, foo)
// 'initial' is skipped because only the latest value ('updated') is
// emitted by the initial scan.
assertPayloads(t, foo, []string{
`foo: {"a":{"long":0}}->{"after":{"foo":{"a":{"long":0},"b":{"string":"updated"}}}}`,
})
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'a'), (2, 'b')`)
assertPayloads(t, foo, []string{
`foo: {"a":{"long":1}}->{"after":{"foo":{"a":{"long":1},"b":{"string":"a"}}}}`,
`foo: {"a":{"long":2}}->{"after":{"foo":{"a":{"long":2},"b":{"string":"b"}}}}`,
})
sqlDB.Exec(t, `UPSERT INTO foo VALUES (2, 'c'), (3, 'd')`)
assertPayloads(t, foo, []string{
`foo: {"a":{"long":2}}->{"after":{"foo":{"a":{"long":2},"b":{"string":"c"}}}}`,
`foo: {"a":{"long":3}}->{"after":{"foo":{"a":{"long":3},"b":{"string":"d"}}}}`,
})
sqlDB.Exec(t, `DELETE FROM foo WHERE a = 1`)
assertPayloads(t, foo, []string{
`foo: {"a":{"long":1}}->{"after":null}`,
})
}
t.Run(`kafka`, kafkaTest(testFn))
}
func TestChangefeedDiff(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO foo VALUES (0, 'initial')`)
sqlDB.Exec(t, `UPSERT INTO foo VALUES (0, 'updated')`)
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH diff`)
defer closeFeed(t, foo)
// 'initial' is skipped because only the latest value ('updated') is
// emitted by the initial scan.
assertPayloads(t, foo, []string{
`foo: [0]->{"after": {"a": 0, "b": "updated"}, "before": null}`,
})
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'a'), (2, 'b')`)
assertPayloads(t, foo, []string{
`foo: [1]->{"after": {"a": 1, "b": "a"}, "before": null}`,
`foo: [2]->{"after": {"a": 2, "b": "b"}, "before": null}`,
})
sqlDB.Exec(t, `UPSERT INTO foo VALUES (2, 'c'), (3, 'd')`)
assertPayloads(t, foo, []string{
`foo: [2]->{"after": {"a": 2, "b": "c"}, "before": {"a": 2, "b": "b"}}`,
`foo: [3]->{"after": {"a": 3, "b": "d"}, "before": null}`,
})
sqlDB.Exec(t, `DELETE FROM foo WHERE a = 1`)
assertPayloads(t, foo, []string{
`foo: [1]->{"after": null, "before": {"a": 1, "b": "a"}}`,
})
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'new a')`)
assertPayloads(t, foo, []string{
`foo: [1]->{"after": {"a": 1, "b": "new a"}, "before": null}`,
})
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`cloudstorage`, cloudStorageTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedTenants(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
kvServer, kvSQLdb, cleanup := startTestServer(t, feedTestOptions{argsFn: func(args *base.TestServerArgs) {
args.ExternalIODirConfig.DisableOutbound = true
}})
defer cleanup()
tenantArgs := base.TestTenantArgs{
// crdb_internal.create_tenant called by StartTenant
TenantID: serverutils.TestTenantID(),
// Non-enterprise changefeeds are currently only
// disabled by setting DisableOutbound true
// everywhere.
ExternalIODirConfig: base.ExternalIODirConfig{
DisableOutbound: true,
},
UseDatabase: `d`,
}
tenantServer, tenantDB := serverutils.StartTenant(t, kvServer, tenantArgs)
tenantSQL := sqlutils.MakeSQLRunner(tenantDB)
tenantSQL.Exec(t, serverSetupStatements)
tenantSQL.Exec(t, `CREATE TABLE foo_in_tenant (pk INT PRIMARY KEY)`)
t.Run("changefeed on non-tenant table fails", func(t *testing.T) {
kvSQL := sqlutils.MakeSQLRunner(kvSQLdb)
kvSQL.Exec(t, `CREATE TABLE d.foo (pk INT PRIMARY KEY)`)
tenantSQL.ExpectErr(t, `table "foo" does not exist`,
`CREATE CHANGEFEED FOR foo`,
)
})
t.Run("sinkful changefeed fails", func(t *testing.T) {
tenantSQL.ExpectErr(t, "Outbound IO is disabled by configuration, cannot create changefeed into kafka",
`CREATE CHANGEFEED FOR foo_in_tenant INTO 'kafka://does-not-matter'`,
)
})
t.Run("sinkless changefeed works", func(t *testing.T) {
sqlAddr := tenantServer.SQLAddr()
sink, cleanup := sqlutils.PGUrl(t, sqlAddr, t.Name(), url.User(security.RootUser))
defer cleanup()
// kvServer is used here because we require a
// TestServerInterface implementor. It is only used as
// the return value for f.Server()
f := makeSinklessFeedFactory(kvServer, sink)
tenantSQL.Exec(t, `INSERT INTO foo_in_tenant VALUES (1)`)
feed := feed(t, f, `CREATE CHANGEFEED FOR foo_in_tenant`)
assertPayloads(t, feed, []string{
`foo_in_tenant: [1]->{"after": {"pk": 1}}`,
})
})
}
func TestMissingTableErr(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
_, kvSQLdb, cleanup := startTestServer(t, feedTestOptions{argsFn: func(args *base.TestServerArgs) {
args.ExternalIODirConfig.DisableOutbound = true
}})
defer cleanup()
t.Run("changefeed on non existing table fails", func(t *testing.T) {
kvSQL := sqlutils.MakeSQLRunner(kvSQLdb)
kvSQL.ExpectErr(t, `^pq: failed to resolve targets in the CHANGEFEED stmt: table "foo" does not exist$`,
`CREATE CHANGEFEED FOR foo`,
)
})
}
func TestChangefeedTenantsExternalIOEnabled(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
kvServer, _, cleanup := startTestServer(t, feedTestOptions{argsFn: func(args *base.TestServerArgs) {
args.ExternalIODirConfig.DisableOutbound = true
}})
defer cleanup()
tenantArgs := base.TestTenantArgs{
// crdb_internal.create_tenant called by StartTenant
TenantID: serverutils.TestTenantID(),
UseDatabase: `d`,
TestingKnobs: base.TestingKnobs{
DistSQL: &execinfra.TestingKnobs{Changefeed: &TestingKnobs{}},
JobsTestingKnobs: jobs.NewTestingKnobsWithShortIntervals(),
},
}
tenantServer, tenantDB := serverutils.StartTenant(t, kvServer, tenantArgs)
tenantSQL := sqlutils.MakeSQLRunner(tenantDB)
tenantSQL.Exec(t, serverSetupStatements)
tenantSQL.Exec(t, `CREATE TABLE foo_in_tenant (pk INT PRIMARY KEY)`)
t.Run("sinkful changefeed fails if protect_data_from_gc_on_pause is set", func(t *testing.T) {
tenantSQL.ExpectErr(t, "operation is unsupported in multi-tenancy mode",
`CREATE CHANGEFEED FOR foo_in_tenant INTO 'kafka://does-not-matter' WITH protect_data_from_gc_on_pause`,
)
})
t.Run("sinkful changefeed works", func(t *testing.T) {
f := makeKafkaFeedFactory(&testServerShim{
TestTenantInterface: tenantServer,
kvServer: kvServer},
tenantDB)
tenantSQL.Exec(t, `INSERT INTO foo_in_tenant VALUES (1)`)
feed := feed(t, f, `CREATE CHANGEFEED FOR foo_in_tenant`)
defer closeFeed(t, feed)
assertPayloads(t, feed, []string{
`foo_in_tenant: [1]->{"after": {"pk": 1}}`,
})
})
}
func TestChangefeedEnvelope(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'a')`)
t.Run(`envelope=row`, func(t *testing.T) {
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH envelope='row'`)
defer closeFeed(t, foo)
assertPayloads(t, foo, []string{`foo: [1]->{"a": 1, "b": "a"}`})
})
t.Run(`envelope=deprecated_row`, func(t *testing.T) {
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH envelope='deprecated_row'`)
defer closeFeed(t, foo)
assertPayloads(t, foo, []string{`foo: [1]->{"a": 1, "b": "a"}`})
})
t.Run(`envelope=key_only`, func(t *testing.T) {
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH envelope='key_only'`)
defer closeFeed(t, foo)
assertPayloads(t, foo, []string{`foo: [1]->`})
})
t.Run(`envelope=wrapped`, func(t *testing.T) {
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH envelope='wrapped'`)
defer closeFeed(t, foo)
assertPayloads(t, foo, []string{`foo: [1]->{"after": {"a": 1, "b": "a"}}`})
})
t.Run(`envelope=wrapped,key_in_value`, func(t *testing.T) {
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH key_in_value, envelope='wrapped'`)
defer closeFeed(t, foo)
assertPayloads(t, foo, []string{`foo: [1]->{"after": {"a": 1, "b": "a"}, "key": [1]}`})
})
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
}
func TestChangefeedFullTableName(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'a')`)
t.Run(`envelope=row`, func(t *testing.T) {
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH full_table_name`)
defer closeFeed(t, foo)
assertPayloads(t, foo, []string{`d.public.foo: [1]->{"after": {"a": 1, "b": "a"}}`})
})
}
//TODO(zinger): Plumb this option through to all encoders so it works in sinkless mode
//t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
//t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedMultiTable(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'a')`)
sqlDB.Exec(t, `CREATE TABLE bar (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO bar VALUES (2, 'b')`)
fooAndBar := feed(t, f, `CREATE CHANGEFEED FOR foo, bar`)
defer closeFeed(t, fooAndBar)
assertPayloads(t, fooAndBar, []string{
`foo: [1]->{"after": {"a": 1, "b": "a"}}`,
`bar: [2]->{"after": {"a": 2, "b": "b"}}`,
})
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedCursor(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY, b STRING)`)
// To make sure that these timestamps are after 'before' and before
// 'after', throw a couple sleeps around them. We round timestamps to
// Microsecond granularity for Postgres compatibility, so make the
// sleeps 10x that.
sqlDB.Exec(t, `INSERT INTO foo VALUES (1, 'before')`)
time.Sleep(10 * time.Microsecond)
var tsLogical string
sqlDB.QueryRow(t, `SELECT cluster_logical_timestamp()`).Scan(&tsLogical)
var tsClock time.Time
sqlDB.QueryRow(t, `SELECT clock_timestamp()`).Scan(&tsClock)
time.Sleep(10 * time.Microsecond)
sqlDB.Exec(t, `INSERT INTO foo VALUES (2, 'after')`)
fooLogical := feed(t, f, `CREATE CHANGEFEED FOR foo WITH cursor=$1`, tsLogical)
defer closeFeed(t, fooLogical)
assertPayloads(t, fooLogical, []string{
`foo: [2]->{"after": {"a": 2, "b": "after"}}`,
})
nanosStr := strconv.FormatInt(tsClock.UnixNano(), 10)
fooNanosStr := feed(t, f, `CREATE CHANGEFEED FOR foo WITH cursor=$1`, nanosStr)
defer closeFeed(t, fooNanosStr)
assertPayloads(t, fooNanosStr, []string{
`foo: [2]->{"after": {"a": 2, "b": "after"}}`,
})
timeStr := tsClock.Format(`2006-01-02 15:04:05.999999`)
fooString := feed(t, f, `CREATE CHANGEFEED FOR foo WITH cursor=$1`, timeStr)
defer closeFeed(t, fooString)
assertPayloads(t, fooString, []string{
`foo: [2]->{"after": {"a": 2, "b": "after"}}`,
})
// Check that the cursor is properly hooked up to the job statement
// time. The sinkless tests currently don't have a way to get the
// statement timestamp, so only verify this for enterprise.
if e, ok := fooLogical.(cdctest.EnterpriseTestFeed); ok {
var bytes []byte
sqlDB.QueryRow(t, `SELECT payload FROM system.jobs WHERE id=$1`, e.JobID()).Scan(&bytes)
var payload jobspb.Payload
require.NoError(t, protoutil.Unmarshal(bytes, &payload))
require.Equal(t, parseTimeToHLC(t, tsLogical), payload.GetChangefeed().StatementTime)
}
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedTimestamps(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
ctx := context.Background()
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY)`)
sqlDB.Exec(t, `INSERT INTO foo VALUES (0)`)
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH updated, resolved`)
defer closeFeed(t, foo)
// Grab the first non resolved-timestamp row.
var row0 *cdctest.TestFeedMessage
for {
var err error
row0, err = foo.Next()
assert.NoError(t, err)
if len(row0.Value) > 0 {
break
}
}
// If this changefeed uses jobs (and thus stores a ChangefeedDetails), get
// the statement timestamp from row0 and verify that they match. Otherwise,
// just skip the row.
if jf, ok := foo.(cdctest.EnterpriseTestFeed); ok {
d, err := jf.Details()
assert.NoError(t, err)
expected := `{"after": {"a": 0}, "updated": "` + d.StatementTime.AsOfSystemTime() + `"}`
assert.Equal(t, expected, string(row0.Value))
}
// Assert the remaining key using assertPayloads, since we know the exact
// timestamp expected.
var ts1 string
if err := crdb.ExecuteTx(ctx, db, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow(
`INSERT INTO foo VALUES (1) RETURNING cluster_logical_timestamp()`,
).Scan(&ts1)
}); err != nil {
t.Fatal(err)
}
assertPayloads(t, foo, []string{
`foo: [1]->{"after": {"a": 1}, "updated": "` + ts1 + `"}`,
})
// Check that we eventually get a resolved timestamp greater than ts1.
parsed := parseTimeToHLC(t, ts1)
for {
if resolved, _ := expectResolvedTimestamp(t, foo); parsed.Less(resolved) {
break
}
}
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedMVCCTimestamps(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE mvcc_timestamp_test_table (id UUID PRIMARY KEY DEFAULT gen_random_uuid())`)
rowCount := 5
expectedPayloads := make([]string, rowCount)
for i := 0; i < rowCount; i++ {
row := sqlDB.QueryRow(t, `INSERT INTO mvcc_timestamp_test_table VALUES (DEFAULT) RETURNING id, cluster_logical_timestamp()`)
var id string
var mvccTimestamp string
row.Scan(&id, &mvccTimestamp)
expectedPayloads[i] = fmt.Sprintf(`mvcc_timestamp_test_table: ["%[1]s"]->{"after": {"id": "%[1]s"}, "mvcc_timestamp": "%[2]s"}`,
id, mvccTimestamp)
}
changeFeed := feed(t, f, `CREATE CHANGEFEED FOR mvcc_timestamp_test_table WITH mvcc_timestamp`)
defer closeFeed(t, changeFeed)
assertPayloads(t, changeFeed, expectedPayloads)
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedResolvedFrequency(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, `CREATE TABLE foo (a INT PRIMARY KEY)`)
const freq = 10 * time.Millisecond
foo := feed(t, f, `CREATE CHANGEFEED FOR foo WITH resolved=$1`, freq.String())
defer closeFeed(t, foo)
// We get each resolved timestamp notification once in each partition.
// Grab the first `2 * #partitions`, sort because we might get all from
// one partition first, and compare the first and last.
resolved := make([]hlc.Timestamp, 2*len(foo.Partitions()))
for i := range resolved {
resolved[i], _ = expectResolvedTimestamp(t, foo)
}
sort.Slice(resolved, func(i, j int) bool { return resolved[i].Less(resolved[j]) })
first, last := resolved[0], resolved[len(resolved)-1]
if d := last.GoTime().Sub(first.GoTime()); d < freq {
t.Errorf(`expected %s between resolved timestamps, but got %s`, freq, d)
}
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
// Test how Changefeeds react to schema changes that do not require a backfill
// operation.
func TestChangefeedInitialScan(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
t.Run(`no cursor - no initial scan`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE no_initial_scan (a INT PRIMARY KEY)`)
sqlDB.Exec(t, `INSERT INTO no_initial_scan VALUES (1)`)
noInitialScan := feed(t, f, `CREATE CHANGEFEED FOR no_initial_scan `+
`WITH no_initial_scan, resolved='1s'`)
defer closeFeed(t, noInitialScan)
expectResolvedTimestamp(t, noInitialScan)
sqlDB.Exec(t, `INSERT INTO no_initial_scan VALUES (2)`)
assertPayloads(t, noInitialScan, []string{
`no_initial_scan: [2]->{"after": {"a": 2}}`,
})
})
t.Run(`cursor - with initial scan`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE initial_scan (a INT PRIMARY KEY)`)
sqlDB.Exec(t, `INSERT INTO initial_scan VALUES (1), (2), (3)`)
var tsStr string
var i int
sqlDB.QueryRow(t, `SELECT count(*), cluster_logical_timestamp() from initial_scan`).Scan(&i, &tsStr)
initialScan := feed(t, f, `CREATE CHANGEFEED FOR initial_scan `+
`WITH initial_scan, resolved='1s', cursor='`+tsStr+`'`)
defer closeFeed(t, initialScan)
assertPayloads(t, initialScan, []string{
`initial_scan: [1]->{"after": {"a": 1}}`,
`initial_scan: [2]->{"after": {"a": 2}}`,
`initial_scan: [3]->{"after": {"a": 3}}`,
})
sqlDB.Exec(t, `INSERT INTO initial_scan VALUES (4)`)
assertPayloads(t, initialScan, []string{
`initial_scan: [4]->{"after": {"a": 4}}`,
})
})
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedUserDefinedTypes(t *testing.T) {
defer leaktest.AfterTest(t)()
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
// Set up a type and table.
sqlDB.Exec(t, `CREATE TYPE t AS ENUM ('hello', 'howdy', 'hi')`)
sqlDB.Exec(t, `CREATE TABLE tt (x INT PRIMARY KEY, y t)`)
sqlDB.Exec(t, `INSERT INTO tt VALUES (0, 'hello')`)
// Open up the changefeed.
cf := feed(t, f, `CREATE CHANGEFEED FOR tt`)
defer closeFeed(t, cf)
assertPayloads(t, cf, []string{
`tt: [0]->{"after": {"x": 0, "y": "hello"}}`,
})
sqlDB.Exec(t, `INSERT INTO tt VALUES (1, 'howdy'), (2, 'hi')`)
assertPayloads(t, cf, []string{
`tt: [1]->{"after": {"x": 1, "y": "howdy"}}`,
`tt: [2]->{"after": {"x": 2, "y": "hi"}}`,
})
// Alter the type and insert a new value.
sqlDB.Exec(t, `ALTER TYPE t ADD VALUE 'hiya'`)
sqlDB.Exec(t, `INSERT INTO tt VALUES (3, 'hiya')`)
assertPayloads(t, cf, []string{
`tt: [3]->{"after": {"x": 3, "y": "hiya"}}`,
})
// If we create a new type and add that type to tt, it should be picked
// up by the schema feed.
sqlDB.Exec(t, `CREATE TYPE t2 AS ENUM ('bye', 'cya')`)
sqlDB.Exec(t, `ALTER TABLE tt ADD COLUMN z t2 DEFAULT 'bye'`)
sqlDB.Exec(t, `INSERT INTO tt VALUES (4, 'hello', 'cya')`)
assertPayloads(t, cf, []string{
`tt: [0]->{"after": {"x": 0, "y": "hello", "z": "bye"}}`,
`tt: [1]->{"after": {"x": 1, "y": "howdy", "z": "bye"}}`,
`tt: [2]->{"after": {"x": 2, "y": "hi", "z": "bye"}}`,
`tt: [3]->{"after": {"x": 3, "y": "hiya", "z": "bye"}}`,
`tt: [4]->{"after": {"x": 4, "y": "hello", "z": "cya"}}`,
})
// If we rename a value in an existing type, it doesn't count as a change
// but the rename is reflected in future changes.
sqlDB.Exec(t, `ALTER TYPE t RENAME VALUE 'hi' TO 'yo'`)
sqlDB.Exec(t, `UPDATE tt SET z='cya' where x=2`)
assertPayloads(t, cf, []string{
`tt: [2]->{"after": {"x": 2, "y": "yo", "z": "cya"}}`,
})
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
}
func TestChangefeedExternalIODisabled(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
t.Run("sinkful changefeeds not allowed with disabled external io", func(t *testing.T) {
disallowedSinkProtos := []string{
changefeedbase.SinkSchemeExperimentalSQL,
changefeedbase.SinkSchemeKafka,
changefeedbase.SinkSchemeNull, // Doesn't work because all sinkful changefeeds are disallowed
// Cloud sink schemes
"experimental-s3",
"experimental-gs",
"experimental-nodelocal",
"experimental-http",
"experimental-https",
"experimental-azure",
}
ctx := context.Background()
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{
ExternalIODirConfig: base.ExternalIODirConfig{
DisableOutbound: true,
},
})
defer s.Stopper().Stop(ctx)
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, serverSetupStatements)
sqlDB.Exec(t, "CREATE TABLE target_table (pk INT PRIMARY KEY)")
for _, proto := range disallowedSinkProtos {
sqlDB.ExpectErr(t, "Outbound IO is disabled by configuration, cannot create changefeed",
"CREATE CHANGEFEED FOR target_table INTO $1",
fmt.Sprintf("%s://does-not-matter", proto),
)
}
})
withDisabledOutbound := func(args *base.TestServerArgs) { args.ExternalIODirConfig.DisableOutbound = true }
t.Run("sinkless changfeeds are allowed with disabled external io",
sinklessTest(func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.Exec(t, "CREATE TABLE target_table (pk INT PRIMARY KEY)")
sqlDB.Exec(t, "INSERT INTO target_table VALUES (1)")
feed := feed(t, f, "CREATE CHANGEFEED FOR target_table")
defer closeFeed(t, feed)
assertPayloads(t, feed, []string{
`target_table: [1]->{"after": {"pk": 1}}`,
})
}, withArgsFn(withDisabledOutbound)))
}
// Test how Changefeeds react to schema changes that do not require a backfill
// operation.
func TestChangefeedSchemaChangeNoBackfill(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "takes >1 min under race")
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
// Schema changes that predate the changefeed.
t.Run(`historical`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE historical (a INT PRIMARY KEY, b STRING DEFAULT 'before')`)
var start string
sqlDB.QueryRow(t, `SELECT cluster_logical_timestamp()`).Scan(&start)
sqlDB.Exec(t, `INSERT INTO historical (a, b) VALUES (0, '0')`)
sqlDB.Exec(t, `INSERT INTO historical (a) VALUES (1)`)
sqlDB.Exec(t, `ALTER TABLE historical ALTER COLUMN b SET DEFAULT 'after'`)
sqlDB.Exec(t, `INSERT INTO historical (a) VALUES (2)`)
sqlDB.Exec(t, `ALTER TABLE historical ADD COLUMN c INT`)
sqlDB.Exec(t, `INSERT INTO historical (a) VALUES (3)`)
sqlDB.Exec(t, `INSERT INTO historical (a, c) VALUES (4, 14)`)
historical := feed(t, f, `CREATE CHANGEFEED FOR historical WITH cursor=$1`, start)
defer closeFeed(t, historical)
assertPayloads(t, historical, []string{
`historical: [0]->{"after": {"a": 0, "b": "0"}}`,
`historical: [1]->{"after": {"a": 1, "b": "before"}}`,
`historical: [2]->{"after": {"a": 2, "b": "after"}}`,
`historical: [3]->{"after": {"a": 3, "b": "after", "c": null}}`,
`historical: [4]->{"after": {"a": 4, "b": "after", "c": 14}}`,
})
})
t.Run(`add column`, func(t *testing.T) {
// NB: the default is a nullable column
sqlDB.Exec(t, `CREATE TABLE add_column (a INT PRIMARY KEY)`)
sqlDB.Exec(t, `INSERT INTO add_column VALUES (1)`)
addColumn := feed(t, f, `CREATE CHANGEFEED FOR add_column`)
defer closeFeed(t, addColumn)
assertPayloads(t, addColumn, []string{
`add_column: [1]->{"after": {"a": 1}}`,
})
sqlDB.Exec(t, `ALTER TABLE add_column ADD COLUMN b STRING`)
sqlDB.Exec(t, `INSERT INTO add_column VALUES (2, '2')`)
assertPayloads(t, addColumn, []string{
`add_column: [2]->{"after": {"a": 2, "b": "2"}}`,
})
})
t.Run(`rename column`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE rename_column (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO rename_column VALUES (1, '1')`)
renameColumn := feed(t, f, `CREATE CHANGEFEED FOR rename_column`)
defer closeFeed(t, renameColumn)
assertPayloads(t, renameColumn, []string{
`rename_column: [1]->{"after": {"a": 1, "b": "1"}}`,
})
sqlDB.Exec(t, `ALTER TABLE rename_column RENAME COLUMN b TO c`)
sqlDB.Exec(t, `INSERT INTO rename_column VALUES (2, '2')`)
assertPayloads(t, renameColumn, []string{
`rename_column: [2]->{"after": {"a": 2, "c": "2"}}`,
})
})
t.Run(`add default`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE add_default (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO add_default (a, b) VALUES (1, '1')`)
addDefault := feed(t, f, `CREATE CHANGEFEED FOR add_default`)
defer closeFeed(t, addDefault)
sqlDB.Exec(t, `ALTER TABLE add_default ALTER COLUMN b SET DEFAULT 'd'`)
sqlDB.Exec(t, `INSERT INTO add_default (a) VALUES (2)`)
assertPayloads(t, addDefault, []string{
`add_default: [1]->{"after": {"a": 1, "b": "1"}}`,
`add_default: [2]->{"after": {"a": 2, "b": "d"}}`,
})
})
t.Run(`drop default`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE drop_default (a INT PRIMARY KEY, b STRING DEFAULT 'd')`)
sqlDB.Exec(t, `INSERT INTO drop_default (a) VALUES (1)`)
dropDefault := feed(t, f, `CREATE CHANGEFEED FOR drop_default`)
defer closeFeed(t, dropDefault)
sqlDB.Exec(t, `ALTER TABLE drop_default ALTER COLUMN b DROP DEFAULT`)
sqlDB.Exec(t, `INSERT INTO drop_default (a) VALUES (2)`)
assertPayloads(t, dropDefault, []string{
`drop_default: [1]->{"after": {"a": 1, "b": "d"}}`,
`drop_default: [2]->{"after": {"a": 2, "b": null}}`,
})
})
t.Run(`drop not null`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE drop_notnull (a INT PRIMARY KEY, b STRING NOT NULL)`)
sqlDB.Exec(t, `INSERT INTO drop_notnull VALUES (1, '1')`)
dropNotNull := feed(t, f, `CREATE CHANGEFEED FOR drop_notnull`)
defer closeFeed(t, dropNotNull)
sqlDB.Exec(t, `ALTER TABLE drop_notnull ALTER b DROP NOT NULL`)
sqlDB.Exec(t, `INSERT INTO drop_notnull VALUES (2, NULL)`)
assertPayloads(t, dropNotNull, []string{
`drop_notnull: [1]->{"after": {"a": 1, "b": "1"}}`,
`drop_notnull: [2]->{"after": {"a": 2, "b": null}}`,
})
})
t.Run(`checks`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE checks (a INT PRIMARY KEY)`)
sqlDB.Exec(t, `INSERT INTO checks VALUES (1)`)
checks := feed(t, f, `CREATE CHANGEFEED FOR checks`)
defer closeFeed(t, checks)
sqlDB.Exec(t, `ALTER TABLE checks ADD CONSTRAINT c CHECK (a < 5) NOT VALID`)
sqlDB.Exec(t, `INSERT INTO checks VALUES (2)`)
sqlDB.Exec(t, `ALTER TABLE checks VALIDATE CONSTRAINT c`)
sqlDB.Exec(t, `INSERT INTO checks VALUES (3)`)
sqlDB.Exec(t, `ALTER TABLE checks DROP CONSTRAINT c`)
sqlDB.Exec(t, `INSERT INTO checks VALUES (6)`)
assertPayloads(t, checks, []string{
`checks: [1]->{"after": {"a": 1}}`,
`checks: [2]->{"after": {"a": 2}}`,
`checks: [3]->{"after": {"a": 3}}`,
`checks: [6]->{"after": {"a": 6}}`,
})
})
t.Run(`add index`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE add_index (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO add_index VALUES (1, '1')`)
addIndex := feed(t, f, `CREATE CHANGEFEED FOR add_index`)
defer closeFeed(t, addIndex)
sqlDB.Exec(t, `CREATE INDEX b_idx ON add_index (b)`)
sqlDB.Exec(t, `SELECT * FROM add_index@b_idx`)
sqlDB.Exec(t, `INSERT INTO add_index VALUES (2, '2')`)
assertPayloads(t, addIndex, []string{
`add_index: [1]->{"after": {"a": 1, "b": "1"}}`,
`add_index: [2]->{"after": {"a": 2, "b": "2"}}`,
})
})
t.Run(`unique`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE "unique" (a INT PRIMARY KEY, b STRING)`)
sqlDB.Exec(t, `INSERT INTO "unique" VALUES (1, '1')`)
unique := feed(t, f, `CREATE CHANGEFEED FOR "unique"`)
defer closeFeed(t, unique)
sqlDB.Exec(t, `ALTER TABLE "unique" ADD CONSTRAINT u UNIQUE (b)`)
sqlDB.Exec(t, `INSERT INTO "unique" VALUES (2, '2')`)
assertPayloads(t, unique, []string{
`unique: [1]->{"after": {"a": 1, "b": "1"}}`,
`unique: [2]->{"after": {"a": 2, "b": "2"}}`,
})
})
t.Run(`alter default`, func(t *testing.T) {
sqlDB.Exec(
t, `CREATE TABLE alter_default (a INT PRIMARY KEY, b STRING DEFAULT 'before')`)
sqlDB.Exec(t, `INSERT INTO alter_default (a) VALUES (1)`)
alterDefault := feed(t, f, `CREATE CHANGEFEED FOR alter_default`)
defer closeFeed(t, alterDefault)
sqlDB.Exec(t, `ALTER TABLE alter_default ALTER COLUMN b SET DEFAULT 'after'`)
sqlDB.Exec(t, `INSERT INTO alter_default (a) VALUES (2)`)
assertPayloads(t, alterDefault, []string{
`alter_default: [1]->{"after": {"a": 1, "b": "before"}}`,
`alter_default: [2]->{"after": {"a": 2, "b": "after"}}`,
})
})
// Test adding a column with explicitly setting the default value to be NULL
t.Run(`add column with DEFAULT NULL`, func(t *testing.T) {
sqlDB.Exec(t, `CREATE TABLE t (id INT PRIMARY KEY)`)
sqlDB.Exec(t, `INSERT INTO t VALUES (1)`)
defaultNull := feed(t, f, `CREATE CHANGEFEED FOR t`)
defer closeFeed(t, defaultNull)
sqlDB.Exec(t, `ALTER TABLE t ADD COLUMN c INT DEFAULT NULL`)
sqlDB.Exec(t, `INSERT INTO t VALUES (2, 2)`)
assertPayloads(t, defaultNull, []string{
// Verify that no column backfill occurs
`t: [1]->{"after": {"id": 1}}`,
`t: [2]->{"after": {"c": 2, "id": 2}}`,
})
})
}
t.Run(`sinkless`, sinklessTest(testFn))
t.Run(`enterprise`, enterpriseTest(testFn))
t.Run(`kafka`, kafkaTest(testFn))
t.Run(`webhook`, webhookTest(testFn))
t.Run(`pubsub`, pubsubTest(testFn))
log.Flush()
entries, err := log.FetchEntriesFromFiles(0, math.MaxInt64, 1, regexp.MustCompile("cdc ux violation"),
log.WithFlattenedSensitiveData)
if err != nil {
t.Fatal(err)
}
if len(entries) > 0 {
t.Fatalf("Found violation of CDC's guarantees: %v", entries)
}
}
// Test checkpointing during schema change backfills that can be paused and
// resumed multiple times during execution
func TestChangefeedSchemaChangeBackfillCheckpoint(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
rnd, _ := randutil.NewPseudoRand()
// This test asserts that a second checkpoint made after resumption does its
// best to not lose information from the first checkpoint, therefore the
// maxCheckpointSize should be large enough to hold both without any
// truncation
var maxCheckpointSize int64 = 100 << 20
testFn := func(t *testing.T, db *gosql.DB, f cdctest.TestFeedFactory) {
sqlDB := sqlutils.MakeSQLRunner(db)
knobs := f.Server().(*server.TestServer).Cfg.TestingKnobs.
DistSQL.(*execinfra.TestingKnobs).
Changefeed.(*TestingKnobs)
// Initialize table