-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathsync.test.ts
More file actions
1281 lines (1142 loc) · 34.6 KB
/
sync.test.ts
File metadata and controls
1281 lines (1142 loc) · 34.6 KB
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
import {
ControlMessage,
Message,
ShapeStream,
ShapeStreamOptions,
} from '@electric-sql/client'
import { PGlite, PGliteInterfaceExtensions } from '@electric-sql/pglite'
import { Mock, beforeEach, describe, expect, it, vi } from 'vitest'
import { electricSync } from '../src/index.js'
vi.mock('@electric-sql/client', async (importOriginal) => {
const mod = await importOriginal<typeof import('@electric-sql/client')>()
const ShapeStream = vi.fn(() => ({
subscribe: vi.fn(),
}))
return { ...mod, ShapeStream }
})
const upToDateMsg: ControlMessage = {
headers: { control: 'up-to-date' },
}
describe('pglite-sync', () => {
let pg: PGlite &
PGliteInterfaceExtensions<{ electric: ReturnType<typeof electricSync> }>
const MockShapeStream = ShapeStream as unknown as Mock
beforeEach(async () => {
pg = await PGlite.create({
extensions: {
electric: electricSync(),
},
})
await pg.exec(`
CREATE TABLE IF NOT EXISTS todo (
id SERIAL PRIMARY KEY,
task TEXT,
done BOOLEAN
);
`)
await pg.exec(`TRUNCATE todo;`)
})
it('handles inserts/updates/deletes', async () => {
let feedMessage: (message: Message) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessage = (message) => cb([message, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
shapeKey: null
})
// insert
await feedMessage({
headers: { operation: 'insert' },
offset: '-1',
key: 'id1',
value: {
id: 1,
task: 'task1',
done: false,
},
})
expect((await pg.sql`SELECT* FROM todo;`).rows).toEqual([
{
id: 1,
task: 'task1',
done: false,
},
])
// update
await feedMessage({
headers: { operation: 'update' },
offset: '-1',
key: 'id1',
value: {
id: 1,
task: 'task2',
done: true,
},
})
expect((await pg.sql`SELECT* FROM todo;`).rows).toEqual([
{
id: 1,
task: 'task2',
done: true,
},
])
// delete
await feedMessage({
headers: { operation: 'delete' },
offset: '-1',
key: 'id1',
value: {
id: 1,
task: 'task2',
done: true,
},
})
expect((await pg.sql`SELECT* FROM todo;`).rows).toEqual([])
shape.unsubscribe()
})
it('performs operations within a transaction', async () => {
let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessages = (messages) => cb([...messages, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
shapeKey: null
})
const numInserts = 10000
const numBatches = 5
for (let i = 0; i < numBatches; i++) {
const numBatchInserts = numInserts / numBatches
feedMessages(
Array.from({ length: numBatchInserts }, (_, idx) => {
const itemIdx = i * numBatchInserts + idx
return {
headers: { operation: 'insert' },
offset: `1_${itemIdx}`,
key: `id${itemIdx}`,
value: {
id: itemIdx,
task: `task${itemIdx}`,
done: false,
},
}
}),
)
}
// let timeToProcessMicrotask = Infinity
// const startTime = performance.now()
// Promise.resolve().then(() => {
// timeToProcessMicrotask = performance.now() - startTime
// })
let numItemsInserted = 0
await vi.waitUntil(async () => {
numItemsInserted =
(
await pg.sql<{
count: number
}>`SELECT COUNT(*) as count FROM todo;`
).rows[0]?.['count'] ?? 0
return numItemsInserted > 0
})
// should have exact number of inserts added transactionally
expect(numItemsInserted).toBe(numInserts)
// should have processed microtask within few ms, not blocking main loop
// expect(timeToProcessMicrotask).toBeLessThan(15) // TODO: flaky on CI
await shape.unsubscribe()
})
it('persists shape stream state and automatically resumes', async () => {
let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
const shapeStreamInits = vi.fn()
let mockShapeId: string | void = undefined
MockShapeStream.mockImplementation((initOpts: ShapeStreamOptions) => {
shapeStreamInits(initOpts)
return {
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessages = (messages) => {
mockShapeId ??= Math.random() + ''
return cb([...messages, upToDateMsg])
}
}),
unsubscribeAll: vi.fn(),
get shapeId() {
return mockShapeId
},
}
})
let totalRowCount = 0
const numInserts = 100
const shapeIds: string[] = []
const numResumes = 3
for (let i = 0; i < numResumes; i++) {
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
shapeKey: 'foo',
})
await feedMessages(
Array.from({ length: numInserts }, (_, idx) => ({
headers: { operation: 'insert' },
offset: `1_${i * numInserts + idx}`,
key: `id${i * numInserts + idx}`,
value: {
id: i * numInserts + idx,
task: `task${idx}`,
done: false,
},
})),
)
await vi.waitUntil(async () => {
const result = await pg.sql<{
count: number
}>`SELECT COUNT(*) as count FROM todo;`
if (result.rows[0]?.count > totalRowCount) {
totalRowCount = result.rows[0].count
return true
}
return false
})
shapeIds.push(mockShapeId!)
expect(shapeStreamInits).toHaveBeenCalledTimes(i + 1)
if (i === 0) {
expect(shapeStreamInits.mock.calls[i][0]).not.toHaveProperty('shapeId')
expect(shapeStreamInits.mock.calls[i][0]).not.toHaveProperty('offset')
}
shape.unsubscribe()
}
})
it('clears and restarts persisted shape stream state on refetch', async () => {
let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
const shapeStreamInits = vi.fn()
let mockShapeId: string | void = undefined
MockShapeStream.mockImplementation((initOpts: ShapeStreamOptions) => {
shapeStreamInits(initOpts)
return {
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessages = (messages) => {
mockShapeId ??= Math.random() + ''
if (messages.find((m) => m.headers.control === 'must-refetch')) {
mockShapeId = undefined
}
return cb([...messages, upToDateMsg])
}
}),
unsubscribeAll: vi.fn(),
get shapeId() {
return mockShapeId
},
}
})
const numInserts = 100
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
shapeKey: 'foo',
})
await feedMessages(
Array.from({ length: numInserts }, (_, idx) => ({
headers: { operation: 'insert' },
offset: `1_${idx}`,
key: `id${idx}`,
value: {
id: idx,
task: `task${idx}`,
done: false,
},
})),
)
await vi.waitUntil(async () => {
const result = await pg.sql<{
count: number
}>`SELECT COUNT(*) as count FROM todo;`
return result.rows[0]?.count === numInserts
})
// feed a must-refetch message that should clear the table
// and any aggregated messages
await feedMessages([
{
headers: { operation: 'insert' },
offset: `1_${numInserts}`,
key: `id${numInserts}`,
value: {
id: numInserts,
task: `task`,
done: false,
},
},
{ headers: { control: 'must-refetch' } },
{
headers: { operation: 'insert' },
offset: `2_1`,
key: `id21`,
value: {
id: 21,
task: `task`,
done: false,
},
},
])
const result = await pg.query(`SELECT * FROM todo;`)
expect(result.rows).toHaveLength(1)
expect(result.rows[0]).toEqual({
id: 21,
done: false,
task: 'task',
})
shape.unsubscribe()
// resuming should
const resumedShape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
shapeKey: 'foo',
})
resumedShape.unsubscribe()
expect(shapeStreamInits).toHaveBeenCalledTimes(2)
expect(shapeStreamInits.mock.calls[1][0]).not.toHaveProperty('shapeId')
expect(shapeStreamInits.mock.calls[1][0]).not.toHaveProperty('offset')
})
it('uses the specified metadata schema for subscription metadata', async () => {
const metadataSchema = 'foobar'
const db = await PGlite.create({
extensions: {
electric: electricSync({
metadataSchema,
}),
},
})
await db.electric.initMetadataTables()
const result = await db.query(
`SELECT schema_name FROM information_schema.schemata WHERE schema_name = $1`,
[metadataSchema],
)
expect(result.rows).toHaveLength(1)
expect(result.rows[0]).toEqual({ schema_name: metadataSchema })
})
it('forbids multiple subscriptions to the same table', async () => {
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn(),
unsubscribeAll: vi.fn(),
}))
const table = 'foo'
const altTable = 'bar'
const shape1 = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: table,
primaryKey: ['id'],
shapeKey: null
})
// should throw if syncing more shapes into same table
await expect(
async () =>
await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo_alt' },
},
table: table,
primaryKey: ['id'],
shapeKey: null
}),
).rejects.toThrowError(`Already syncing shape for table ${table}`)
// should be able to sync shape into other table
const altShape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'bar' },
},
table: altTable,
primaryKey: ['id'],
shapeKey: null
})
altShape.unsubscribe()
// should be able to sync different shape if previous is unsubscribed
// (and we assume data has been cleaned up?)
shape1.unsubscribe()
const shape2 = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo_alt' },
},
table: table,
primaryKey: ['id'],
shapeKey: null
})
shape2.unsubscribe()
})
it('handles an update message with no columns to update', async () => {
let feedMessage: (message: Message) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessage = (message) => cb([message, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
shapeKey: null
})
// insert
await feedMessage({
headers: { operation: 'insert' },
offset: '-1',
key: 'id1',
value: {
id: 1,
task: 'task1',
done: false,
},
})
expect((await pg.sql`SELECT* FROM todo;`).rows).toEqual([
{
id: 1,
task: 'task1',
done: false,
},
])
// update with no columns to update
await feedMessage({
headers: { operation: 'update' },
offset: '-1',
key: 'id1',
value: {
id: 1,
},
})
expect((await pg.sql`SELECT* FROM todo;`).rows).toEqual([
{
id: 1,
task: 'task1',
done: false,
},
])
shape.unsubscribe()
})
it('sets the syncing flag to true when syncing begins', async () => {
let feedMessage: (message: Message) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessage = (message) => cb([message, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
await pg.exec(`
CREATE TABLE test_syncing (
id TEXT PRIMARY KEY,
value TEXT,
is_syncing BOOLEAN
);
CREATE OR REPLACE FUNCTION check_syncing()
RETURNS TRIGGER AS $$
DECLARE
is_syncing BOOLEAN;
BEGIN
is_syncing := COALESCE(current_setting('electric.syncing', true)::boolean, false);
IF is_syncing THEN
NEW.is_syncing := TRUE;
ELSE
NEW.is_syncing := FALSE;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER test_syncing_trigger
BEFORE INSERT ON test_syncing
FOR EACH ROW EXECUTE FUNCTION check_syncing();
`)
// Check the flag is not set outside of a sync
const result0 =
await pg.sql`SELECT current_setting('electric.syncing', true)`
expect(result0.rows[0]).toEqual({ current_setting: null }) // not set yet as syncShapeToTable hasn't been called
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'test_syncing' },
},
table: 'test_syncing',
primaryKey: ['id'],
shapeKey: null
})
await feedMessage({
headers: { operation: 'insert' },
offset: '-1',
key: 'id1',
value: {
id: 'id1',
value: 'test value',
},
})
// Check the flag is set during a sync
const result = await pg.sql`SELECT * FROM test_syncing WHERE id = 'id1'`
expect(result.rows).toHaveLength(1)
expect(result.rows[0]).toEqual({
id: 'id1',
value: 'test value',
is_syncing: true,
})
// Check the flag is not set outside of a sync
const result2 =
await pg.sql`SELECT current_setting('electric.syncing', true)`
expect(result2.rows[0]).toEqual({ current_setting: 'false' })
shape.unsubscribe()
})
it('uses COPY FROM for initial batch of inserts', async () => {
let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessages = (messages) => cb([...messages, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
useCopy: true,
shapeKey: null
})
// Create a batch of insert messages followed by an update
const numInserts = 1000
const messages: Message[] = [
...Array.from(
{ length: numInserts },
(_, idx) =>
({
headers: { operation: 'insert' as const },
offset: `1_${idx}`,
key: `id${idx}`,
value: {
id: idx,
task: `task${idx}`,
done: idx % 2 === 0,
},
}) as Message,
),
{
headers: { operation: 'update' as const },
offset: `1_${numInserts}`,
key: `id0`,
value: {
id: 0,
task: 'updated task',
done: true,
},
},
]
await feedMessages(messages)
// Wait for all inserts to complete
await vi.waitUntil(async () => {
const result = await pg.sql<{ count: number }>`
SELECT COUNT(*) as count FROM todo;
`
return result.rows[0].count === numInserts
})
// Verify the data was inserted correctly
const result = await pg.sql`
SELECT * FROM todo ORDER BY id LIMIT 5;
`
expect(result.rows).toEqual([
{ id: 0, task: 'updated task', done: true },
{ id: 1, task: 'task1', done: false },
{ id: 2, task: 'task2', done: true },
{ id: 3, task: 'task3', done: false },
{ id: 4, task: 'task4', done: true },
])
// Verify total count
const countResult = await pg.sql<{ count: number }>`
SELECT COUNT(*) as count FROM todo;
`
expect(countResult.rows[0].count).toBe(numInserts)
shape.unsubscribe()
})
it('handles special characters in COPY FROM data', async () => {
let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessages = (messages) => cb([...messages, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
useCopy: true,
shapeKey: null
})
const specialCharMessages: Message[] = [
{
headers: { operation: 'insert' },
offset: '1_0',
key: 'id1',
value: {
id: 1,
task: 'task with, comma',
done: false,
},
},
{
headers: { operation: 'insert' },
offset: '2_0',
key: 'id2',
value: {
id: 2,
task: 'task with "quotes"',
done: true,
},
},
{
headers: { operation: 'insert' },
offset: '3_0',
key: 'id3',
value: {
id: 3,
task: 'task with\nnewline',
done: false,
},
},
]
await feedMessages(specialCharMessages)
// Wait for inserts to complete
await vi.waitUntil(async () => {
const result = await pg.sql<{ count: number }>`
SELECT COUNT(*) as count FROM todo;
`
return result.rows[0].count === specialCharMessages.length
})
// Verify the data was inserted correctly with special characters preserved
const result = await pg.sql`
SELECT * FROM todo ORDER BY id;
`
expect(result.rows).toEqual([
{ id: 1, task: 'task with, comma', done: false },
{ id: 2, task: 'task with "quotes"', done: true },
{ id: 3, task: 'task with\nnewline', done: false },
])
shape.unsubscribe()
})
it('respects numeric batch commit granularity settings', async () => {
let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessages = (messages) => cb([...messages, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
// Create a trigger to notify on transaction commit
await pg.exec(`
CREATE OR REPLACE FUNCTION notify_transaction()
RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify('transaction_commit', TG_TABLE_NAME);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER todo_transaction_trigger
AFTER INSERT ON todo
FOR EACH STATEMENT
EXECUTE FUNCTION notify_transaction();
`)
const commits: string[] = []
const unsubscribe = await pg.listen('transaction_commit', (payload) => {
commits.push(payload)
})
const batchSize = 5
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
commitGranularity: batchSize,
shapeKey: null
})
// Create test messages - 7 total (should see batch of 5, then 2)
const messages = Array.from(
{ length: 7 },
(_, idx) =>
({
headers: { operation: 'insert' },
offset: `1_${idx}`,
key: `id${idx}`,
value: {
id: idx,
task: `task${idx}`,
done: false,
},
}) satisfies Message,
)
await feedMessages(messages)
// Wait for all inserts to complete
await vi.waitUntil(async () => {
const result = await pg.sql<{ count: number }>`
SELECT COUNT(*) as count FROM todo;
`
return result.rows[0].count === 7
})
// Verify all rows were inserted
const result = await pg.sql`
SELECT * FROM todo ORDER BY id;
`
expect(result.rows).toEqual(
messages.map((m) => ({
id: m.value.id,
task: m.value.task,
done: m.value.done,
})),
)
// Should have received 2 commit notifications:
// - One for the first batch of 5
// - One for the remaining 2 (triggered by up-to-date message)
expect(commits).toHaveLength(2)
expect(commits).toEqual(['todo', 'todo'])
await unsubscribe()
shape.unsubscribe()
})
// Removed until Electric has stabilised on LSN metadata
// it('respects transaction commit granularity', async () => {
// let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
// MockShapeStream.mockImplementation(() => ({
// subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
// feedMessages = (messages) => cb([...messages, upToDateMsg])
// }),
// unsubscribeAll: vi.fn(),
// }))
// // Create a trigger to notify on transaction commit
// await pg.exec(`
// CREATE OR REPLACE FUNCTION notify_transaction()
// RETURNS TRIGGER AS $$
// BEGIN
// PERFORM pg_notify('transaction_commit', TG_TABLE_NAME);
// RETURN NEW;
// END;
// $$ LANGUAGE plpgsql;
// CREATE TRIGGER todo_transaction_trigger
// AFTER INSERT ON todo
// FOR EACH STATEMENT
// EXECUTE FUNCTION notify_transaction();
// `)
// // Track transaction commits
// const transactionCommits: string[] = []
// const unsubscribe = await pg.listen('transaction_commit', (payload) => {
// transactionCommits.push(payload)
// })
// const shape = await pg.electric.syncShapeToTable({
// shape: {
// url: 'http://localhost:3000/v1/shape',
// params: { table: 'todo' },
// },
// table: 'todo',
// primaryKey: ['id'],
// commitGranularity: 'transaction',
// })
// // Send messages with different LSNs (first part of offset before _)
// await feedMessages([
// {
// headers: { operation: 'insert' },
// offset: '1_1', // Transaction 1
// key: 'id1',
// value: {
// id: 1,
// task: 'task1',
// done: false,
// },
// },
// {
// headers: { operation: 'insert' },
// offset: '1_2', // Same transaction
// key: 'id2',
// value: {
// id: 2,
// task: 'task2',
// done: false,
// },
// },
// {
// headers: { operation: 'insert' },
// offset: '2_1', // New transaction
// key: 'id3',
// value: {
// id: 3,
// task: 'task3',
// done: false,
// },
// },
// ])
// // Wait for all inserts to complete
// await vi.waitUntil(async () => {
// const result = await pg.sql<{ count: number }>`
// SELECT COUNT(*) as count FROM todo;
// `
// return result.rows[0].count === 3
// })
// // Verify all rows were inserted
// const result = await pg.sql`
// SELECT * FROM todo ORDER BY id;
// `
// expect(result.rows).toEqual([
// { id: 1, task: 'task1', done: false },
// { id: 2, task: 'task2', done: false },
// { id: 3, task: 'task3', done: false },
// ])
// // Should have received 2 transaction notifications
// // One for LSN 1 (containing 2 inserts) and one for LSN 2 (containing 1 insert)
// expect(transactionCommits).toHaveLength(2)
// expect(transactionCommits).toEqual(['todo', 'todo'])
// await unsubscribe()
// shape.unsubscribe()
// })
it('respects up-to-date commit granularity settings', async () => {
let feedMessages: (messages: Message[]) => Promise<void> = async (_) => {}
MockShapeStream.mockImplementation(() => ({
subscribe: vi.fn((cb: (messages: Message[]) => Promise<void>) => {
feedMessages = (messages) => cb([...messages, upToDateMsg])
}),
unsubscribeAll: vi.fn(),
}))
// Create a trigger to notify on transaction commit
await pg.exec(`
CREATE OR REPLACE FUNCTION notify_transaction()
RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify('transaction_commit', TG_TABLE_NAME);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER todo_transaction_trigger
AFTER INSERT ON todo
FOR EACH STATEMENT
EXECUTE FUNCTION notify_transaction();
`)
const commits: string[] = []
const unsubscribe = await pg.listen('transaction_commit', (payload) => {
commits.push(payload)
})
const shape = await pg.electric.syncShapeToTable({
shape: {
url: 'http://localhost:3000/v1/shape',
params: { table: 'todo' },
},
table: 'todo',
primaryKey: ['id'],
commitGranularity: 'up-to-date',
shapeKey: null
})
// Send multiple messages
await feedMessages([
{
headers: { operation: 'insert' },
offset: '1_1',
key: 'id1',
value: { id: 1, task: 'task1', done: false },
},
{
headers: { operation: 'insert' },
offset: '2_1',
key: 'id2',
value: { id: 2, task: 'task2', done: false },
},
{
headers: { operation: 'insert' },
offset: '3_1',
key: 'id3',
value: { id: 3, task: 'task3', done: false },
},
])
// Wait for all inserts to complete
await vi.waitUntil(async () => {
const result = await pg.sql<{ count: number }>`
SELECT COUNT(*) as count FROM todo;
`
return result.rows[0].count === 3