Open History to see the last commit
1/**
2 * Tags Test Suite
3 *
4 * Tests Electric collection tag behavior with subqueries
5 * Only Electric collection supports tags (via shapes with subqueries)
6 */
7
8import { randomUUID } from 'node:crypto'
9import { beforeAll, describe, expect, it, vi } from 'vitest'
10import { createCollection } from '@tanstack/db'
11import { electricCollectionOptions } from '@tanstack/electric-db-collection'
12import { waitFor } from '../utils/helpers'
13import { expectNotificationHistory } from '../utils/notification-laws'
14import type { E2ETestConfig, Post, User } from '../types'
15import type { Client } from 'pg'
16import type { Collection } from '@tanstack/db'
17import type { ElectricCollectionUtils } from '@tanstack/electric-db-collection'
18
19interface TagsTestConfig extends E2ETestConfig {
20 tagsTestSetup: {
21 dbClient: Client
22 baseUrl: string
23 testSchema: string
24 usersTable: string
25 postsTable: string
26 }
27}
28
29type SyncMode = 'eager' | 'on-demand' | 'progressive'
30
31type MoveCollection = Pick<
32 Collection<Post, string>,
33 | 'entries'
34 | 'cleanup'
35 | 'subscribeChanges'
36 | 'preload'
37 | 'status'
38 | 'startSyncImmediate'
39>
40type CapturedPost = { key: string; value: Post }
41
42function capturePost(row: Post): Post {
43 return structuredClone({
44 id: row.id,
45 userId: row.userId,
46 title: row.title,
47 content: row.content,
48 viewCount: row.viewCount,
49 largeViewCount: row.largeViewCount,
50 publishedAt: row.publishedAt,
51 deletedAt: row.deletedAt,
52 })
53}
54
55function assertOwnedPosts(actual: Array<CapturedPost>, expected: Array<Post>) {
56 for (const entry of actual) expect(entry.key).toBe(entry.value.id)
57 const byId = (left: Post, right: Post) =>
58 left.id < right.id ? -1 : left.id > right.id ? 1 : 0
59 expect(actual.map((entry) => entry.value).sort(byId)).toStrictEqual(
60 [...expected].sort(byId),
61 )
62}
63
64interface MoveHistory {
65 own: <T extends MoveCollection>(collection: T) => T
66 ready: (collection: MoveCollection, syncMode: SyncMode) => Promise<void>
67 insertUser: (row: User) => Promise<void>
68 insertPost: (row: Post) => Promise<void>
69 setActive: (id: string, active: boolean) => void
70 setTitle: (id: string, title: string) => void
71 removePost: (id: string) => void
72 check: (collection: MoveCollection) => Promise<void>
73 observe: (collection: MoveCollection) => () => void
74}
75
76export function createMovesTestSuite(getConfig: () => Promise<TagsTestConfig>) {
77 describe(`Moves Suite`, () => {
78 let usersTable: string
79 let postsTable: string
80 let dbClient: Client
81 let baseUrl: string
82 let testSchema: string
83 let config: TagsTestConfig
84
85 beforeAll(async () => {
86 config = await getConfig()
87 const setup = config.tagsTestSetup
88 dbClient = setup.dbClient
89 baseUrl = setup.baseUrl
90 testSchema = setup.testSchema
91 usersTable = setup.usersTable
92 postsTable = setup.postsTable
93 })
94
95 // Helper to create a collection on posts table with WHERE clause that has nested subquery
96 // This creates a shape: posts WHERE userId IN (SELECT id FROM users WHERE isActive = true)
97 // When a user's isActive changes, posts will move in/out of this shape
98 function createPostsByActiveUsersCollection(
99 syncMode: SyncMode,
100 id?: string,
101 ): Collection<any, string, ElectricCollectionUtils, any, any> {
102 // Remove quotes from table names for the WHERE clause SQL
103 const usersTableUnquoted = usersTable.replace(/"/g, ``)
104 const collectionId =
105 id || `tags-posts-active-users-${syncMode}-${Date.now()}`
106
107 return createCollection(
108 electricCollectionOptions({
109 id: collectionId,
110 shapeOptions: {
111 url: `${baseUrl}/v1/shape`,
112 params: {
113 table: `${testSchema}.${postsTable}`,
114 // WHERE clause with nested subquery
115 // Posts will move in/out when users' isActive changes
116 // Column reference should be just the column name, not the full table path
117 where: `"userId" IN (SELECT id FROM ${testSchema}.${usersTableUnquoted} WHERE "isActive" = true)`,
118 },
119 },
120 syncMode,
121 getKey: (item: any) => item.id,
122 startSync: syncMode !== 'progressive',
123 }),
124 ) as any
125 }
126
127 // Helper to wait for collection to be ready
128 async function waitForReady(
129 collection: MoveCollection,
130 syncMode: SyncMode,
131 ) {
132 if (syncMode === 'progressive') {
133 // For progressive mode, start sync explicitly
134 collection.startSyncImmediate()
135 }
136 await collection.preload()
137 await waitFor(() => collection.status === `ready`, {
138 timeout: 30000,
139 message: `Collection did not become ready`,
140 })
141 }
142
143 // Helper to wait for a specific item to appear
144 async function waitForItem(
145 collection: Collection<any, any, any, any, any>,
146 itemId: string,
147 timeout: number = 10000,
148 ) {
149 await waitFor(() => collection.has(itemId), {
150 timeout,
151 message: `Item ${itemId} did not appear in collection`,
152 })
153 }
154
155 // Helper to wait for a specific item to disappear
156 async function waitForItemRemoved(
157 collection: Collection<any, any, any, any, any>,
158 itemId: string,
159 timeout: number = 2000,
160 ) {
161 await waitFor(() => !collection.has(itemId), {
162 timeout,
163 message: `Item ${itemId} was not removed from collection`,
164 })
165 }
166
167 // Helper to wait for users to be synced to Electric/TanStack DB
168 async function waitForUsersSynced(
169 userIds: Array<string>,
170 timeout: number = 10000,
171 ) {
172 // Use eager collection since it continuously syncs all data
173 const usersCollection = config.collections.eager.users
174 await waitFor(
175 () => {
176 return userIds.every((userId) => usersCollection.has(userId))
177 },
178 {
179 timeout,
180 message: `Users ${userIds.join(', ')} did not sync to collection`,
181 },
182 )
183 }
184
185 async function withMoveHistory(
186 run: (history: MoveHistory) => Promise<void>,
187 ) {
188 const mutations = config.mutations
189 if (!mutations) throw new Error('Mutations not configured')
190 const userIds = new Set<string>()
191 const postIds = new Set<string>()
192 const activeUsers = new Map<string, boolean>()
193 const posts = new Map<string, Post>()
194 const resources: Array<() => Promise<void>> = []
195 const archives: Array<() => void> = []
196 const errors: Array<unknown> = []
197 let priorNonempty: Array<CapturedPost> | undefined
198 try {
199 await run({
200 own(collection) {
201 resources.push(() => collection.cleanup())
202 return collection
203 },
204 async ready(collection, syncMode) {
205 if (syncMode === 'on-demand') {
206 // preload starts sync, but only a subscriber acquires existing rows.
207 // Keep that demand alive through the history, then release it.
208 const subscription = collection.subscribeChanges(() => {}, {
209 includeInitialState: true,
210 })
211 resources.push(() => {
212 subscription.unsubscribe()
213 return Promise.resolve()
214 })
215 }
216 await waitForReady(collection, syncMode)
217 },
218 async insertUser(row) {
219 // Own the exact key before a provider can partially write and fail.
220 userIds.add(row.id)
221 activeUsers.set(row.id, row.isActive)
222 await mutations.insertUser(structuredClone(row))
223 },
224 async insertPost(row) {
225 postIds.add(row.id)
226 posts.set(row.id, capturePost(row))
227 await mutations.insertPost(structuredClone(row))
228 },
229 setActive(id, active) {
230 if (!activeUsers.has(id)) throw new Error('Unknown owned user')
231 activeUsers.set(id, active)
232 },
233 setTitle(id, title) {
234 const row = posts.get(id)
235 if (!row) throw new Error('Unknown owned post')
236 posts.set(id, { ...row, title })
237 },
238 removePost(id) {
239 if (!posts.delete(id)) throw new Error('Unknown owned post')
240 },
241 async check(collection) {
242 // This finite world comes only from authored row/active commands.
243 // It does not use the provider's subquery parser or current output.
244 const expected = Array.from(posts.values())
245 .filter((post) => activeUsers.get(post.userId) === true)
246 .map(capturePost)
247 const captured = await vi.waitFor(
248 () => {
249 const actual = Array.from(collection.entries())
250 .filter(
251 ([key, value]) => postIds.has(key) || postIds.has(value.id),
252 )
253 .map(([key, value]) => ({ key, value: capturePost(value) }))
254 assertOwnedPosts(actual, expected)
255 return actual
256 },
257 { timeout: 10000 },
258 )
259 archives.push(() => assertOwnedPosts(captured, expected))
260 if (captured.length > 0) {
261 const wrongValue = structuredClone(captured)
262 wrongValue[0]!.value.title += '-wrong'
263 expect(() => assertOwnedPosts(wrongValue, expected)).toThrow()
264 const wrongKey = structuredClone(captured)
265 wrongKey[0]!.key += '-wrong'
266 expect(() => assertOwnedPosts(wrongKey, expected)).toThrow()
267 const missing = captured.slice(1)
268 expect(() => assertOwnedPosts(missing, expected)).toThrow()
269 priorNonempty = structuredClone(captured)
270 } else if (priorNonempty) {
271 expect(() => assertOwnedPosts(priorNonempty!, expected)).toThrow()
272 }
273 },
274 observe(collection) {
275 const callbacks: Array<{
276 changes: Array<{
277 type: string
278 key: string | number
279 value: Post
280 previousValue?: Post
281 }>
282 rows: Array<CapturedPost>
283 }> = []
284 const subscription = collection.subscribeChanges(
285 (changes) => {
286 // Empty callbacks and unowned peers stay visible as evidence.
287 // No SQL-transaction-to-single-delivery framing law is assumed.
288 callbacks.push({
289 changes: changes.map(
290 ({ type, key, value, previousValue }) => ({
291 type,
292 key,
293 value: capturePost(value),
294 previousValue:
295 previousValue === undefined
296 ? undefined
297 : capturePost(previousValue),
298 }),
299 ),
300 rows: Array.from(collection.entries(), ([key, value]) => ({
301 key,
302 value: capturePost(value),
303 })),
304 })
305 },
306 { includeInitialState: true },
307 )
308 resources.push(() => {
309 subscription.unsubscribe()
310 return Promise.resolve()
311 })
312 return () => {
313 const captured = structuredClone(callbacks)
314 const final = Array.from(collection.entries(), ([key, value]) => {
315 expect(key).toBe(value.id)
316 return capturePost(value)
317 })
318 const check = () =>
319 expectNotificationHistory(
320 [],
321 captured.map((callback) => ({
322 events: callback.changes,
323 rows: callback.rows.map(({ key, value }) => {
324 expect(key).toBe(value.id)
325 return value
326 }),
327 })),
328 final,
329 )
330 check()
331 archives.push(check)
332 }
333 },
334 })
335 } catch (error) {
336 errors.push(error)
337 } finally {
338 // Children precede parents; every failure still allows later cleanup.
339 for (const id of postIds) {
340 try {
341 await mutations.deletePost(id)
342 } catch (error) {
343 errors.push(error)
344 }
345 }
346 for (const id of userIds) {
347 try {
348 await mutations.deleteUser(id)
349 } catch (error) {
350 errors.push(error)
351 }
352 }
353 for (const cleanup of resources.reverse()) {
354 try {
355 await cleanup()
356 } catch (error) {
357 errors.push(error)
358 }
359 }
360 for (const check of archives) {
361 try {
362 check()
363 } catch (error) {
364 errors.push(error)
365 }
366 }
367 }
368 if (errors.length === 1) throw errors[0]
369 if (errors.length > 1)
370 throw new AggregateError(errors, 'Move history and cleanup failed')
371 }
372
373 // Helper function to run all tests for a given sync mode
374 function runTestsForSyncMode(syncMode: SyncMode) {
375 describe(`${syncMode} mode`, () => {
376 it(`Initial snapshot contains only posts from active users`, async () => {
377 await withMoveHistory(async (history) => {
378 if (!config.mutations) {
379 throw new Error(`Mutations not configured`)
380 }
381
382 // Insert 2 active users and 1 inactive user
383 const userId1 = randomUUID()
384 const userId2 = randomUUID()
385 const userId3 = randomUUID()
386
387 await history.insertUser({
388 id: userId1,
389 name: `Active User 1`,
390 email: `user1@test.com`,
391 age: 25,
392 isActive: true,
393 createdAt: new Date(),
394 metadata: null,
395 deletedAt: null,
396 })
397
398 await history.insertUser({
399 id: userId2,
400 name: `Active User 2`,
401 email: `user2@test.com`,
402 age: 30,
403 isActive: true,
404 createdAt: new Date(),
405 metadata: null,
406 deletedAt: null,
407 })
408
409 await history.insertUser({
410 id: userId3,
411 name: `Inactive User`,
412 email: `user3@test.com`,
413 age: 42,
414 isActive: false,
415 createdAt: new Date(),
416 metadata: null,
417 deletedAt: null,
418 })
419
420 // Wait for all 3 users to be synced to Electric before inserting posts
421 // This ensures the subquery in the WHERE clause can properly evaluate
422 await waitForUsersSynced([userId1, userId2, userId3])
423
424 // Insert posts for these users
425 const postId1 = randomUUID()
426 const postId2 = randomUUID()
427 const postId3 = randomUUID()
428
429 await history.insertPost({
430 id: postId1,
431 userId: userId1,
432 title: `Post 1`,
433 content: `Content 1`,
434 viewCount: 0,
435 largeViewCount: BigInt(0),
436 publishedAt: null,
437 deletedAt: null,
438 })
439
440 await history.insertPost({
441 id: postId2,
442 userId: userId2,
443 title: `Post 2`,
444 content: `Content 2`,
445 viewCount: 0,
446 largeViewCount: BigInt(0),
447 publishedAt: null,
448 deletedAt: null,
449 })
450
451 await history.insertPost({
452 id: postId3,
453 userId: userId3,
454 title: `Post 3`,
455 content: `Content 3`,
456 viewCount: 0,
457 largeViewCount: BigInt(0),
458 publishedAt: null,
459 deletedAt: null,
460 })
461
462 // Create collection on posts with WHERE clause: userId IN (SELECT id FROM users WHERE isActive = true)
463 const collection = history.own(
464 createPostsByActiveUsersCollection(syncMode),
465 )
466
467 // Wait for collection to sync
468 await history.ready(collection, syncMode)
469
470 // Wait for both posts to appear (users are active, so posts match the subquery)
471 await waitForItem(collection, postId1)
472 await waitForItem(collection, postId2)
473
474 // Verify only posts 1 and 2 are in the collection
475 expect(collection.has(postId1)).toBe(true)
476 await history.check(collection)
477 expect(collection.has(postId2)).toBe(true)
478 await history.check(collection)
479 expect(collection.has(postId3)).toBe(false)
480 await history.check(collection)
481
482 // Wait a bit to make sure post 3 is not coming in later
483 await new Promise((resolve) => setTimeout(resolve, 50))
484 expect(collection.has(postId3)).toBe(false)
485 await history.check(collection)
486
487 // Note: Tags are internal to Electric and may not be directly accessible
488 // The test verifies that posts with matching conditions appear in snapshot
489 })
490 })
491
492 it(`Move-in: row becomes eligible for subquery`, async () => {
493 await withMoveHistory(async (history) => {
494 const collection = history.own(
495 createPostsByActiveUsersCollection(syncMode),
496 )
497 await history.ready(collection, syncMode)
498
499 if (!config.mutations) {
500 throw new Error(`Mutations not configured`)
501 }
502
503 // Insert user with isActive = false
504 const userId = randomUUID()
505 await history.insertUser({
506 id: userId,
507 name: `Inactive User`,
508 email: `inactive@test.com`,
509 age: 25,
510 isActive: false,
511 createdAt: new Date(),
512 metadata: null,
513 deletedAt: null,
514 })
515
516 // Wait for user to be synced to Electric before inserting post
517 await waitForUsersSynced([userId])
518
519 // Insert post for this user
520 const postId = randomUUID()
521 await history.insertPost({
522 id: postId,
523 userId,
524 title: `Inactive User Post`,
525 content: `Content`,
526 viewCount: 0,
527 largeViewCount: BigInt(0),
528 publishedAt: null,
529 deletedAt: null,
530 })
531
532 // Wait a bit to ensure post doesn't appear (user is inactive, so post doesn't match subquery)
533 await new Promise((resolve) => setTimeout(resolve, 500))
534 expect(collection.has(postId)).toBe(false)
535 await history.check(collection)
536
537 // Update user to isActive = true (move-in for the post)
538 await config.mutations.updateUser(userId, { isActive: true })
539 history.setActive(userId, true)
540
541 // Wait for post to appear (move-in)
542 await waitForItem(collection, postId, 1000)
543 expect(collection.has(postId)).toBe(true)
544 await history.check(collection)
545 expect(collection.get(postId)?.title).toBe(`Inactive User Post`)
546 })
547 })
548
549 it(`Move-out: row becomes ineligible for subquery`, async () => {
550 await withMoveHistory(async (history) => {
551 const collection = history.own(
552 createPostsByActiveUsersCollection(syncMode),
553 )
554 await history.ready(collection, syncMode)
555
556 if (!config.mutations) {
557 throw new Error(`Mutations not configured`)
558 }
559
560 // Insert user with isActive = true
561 const userId = randomUUID()
562 await history.insertUser({
563 id: userId,
564 name: `Active User`,
565 email: `active@test.com`,
566 age: 25,
567 isActive: true,
568 createdAt: new Date(),
569 metadata: null,
570 deletedAt: null,
571 })
572
573 // Wait for user to be synced to Electric before inserting post
574 await waitForUsersSynced([userId])
575
576 // Insert post for this user
577 const postId = randomUUID()
578 await history.insertPost({
579 id: postId,
580 userId,
581 title: `Active User Post`,
582 content: `Content`,
583 viewCount: 0,
584 largeViewCount: BigInt(0),
585 publishedAt: null,
586 deletedAt: null,
587 })
588
589 // Wait for post to appear (user is active, so post matches subquery)
590 await waitForItem(collection, postId)
591 expect(collection.has(postId)).toBe(true)
592 await history.check(collection)
593
594 // Update user to isActive = false (move-out for the post)
595 await config.mutations.updateUser(userId, { isActive: false })
596 history.setActive(userId, false)
597
598 // Wait for post to be removed (move-out)
599 await waitForItemRemoved(collection, postId)
600 expect(collection.has(postId)).toBe(false)
601 await history.check(collection)
602 })
603 })
604
605 it(`Move-out → move-in cycle`, async () => {
606 await withMoveHistory(async (history) => {
607 const collection = history.own(
608 createPostsByActiveUsersCollection(syncMode),
609 )
610 await history.ready(collection, syncMode)
611
612 if (!config.mutations) {
613 throw new Error(`Mutations not configured`)
614 }
615
616 // Insert user with isActive = true
617 const userId = randomUUID()
618 await history.insertUser({
619 id: userId,
620 name: `Flapping User`,
621 email: `flapping@test.com`,
622 age: 25,
623 isActive: true,
624 createdAt: new Date(),
625 metadata: null,
626 deletedAt: null,
627 })
628
629 // Wait for user to be synced to Electric before inserting post
630 await waitForUsersSynced([userId])
631
632 // Insert post for this user
633 const postId = randomUUID()
634 await history.insertPost({
635 id: postId,
636 userId,
637 title: `Flapping Post`,
638 content: `Content`,
639 viewCount: 0,
640 largeViewCount: BigInt(0),
641 publishedAt: null,
642 deletedAt: null,
643 })
644
645 await waitForItem(collection, postId)
646 expect(collection.has(postId)).toBe(true)
647 await history.check(collection)
648
649 // Move-out: isActive = false
650 await config.mutations.updateUser(userId, { isActive: false })
651 history.setActive(userId, false)
652 await waitForItemRemoved(collection, postId, 15000)
653 expect(collection.has(postId)).toBe(false)
654 await history.check(collection)
655
656 // Move-in: isActive = true
657 await config.mutations.updateUser(userId, { isActive: true })
658 history.setActive(userId, true)
659 await waitForItem(collection, postId, 15000)
660 expect(collection.has(postId)).toBe(true)
661 await history.check(collection)
662 })
663 })
664
665 it(`Title update while row stays within subquery`, async () => {
666 await withMoveHistory(async (history) => {
667 const collection = history.own(
668 createPostsByActiveUsersCollection(syncMode),
669 )
670 await history.ready(collection, syncMode)
671
672 if (!config.mutations) {
673 throw new Error(`Mutations not configured`)
674 }
675
676 // Insert user with isActive = true
677 const userId = randomUUID()
678 await history.insertUser({
679 id: userId,
680 name: `Active User`,
681 email: `active@test.com`,
682 age: 25,
683 isActive: true,
684 createdAt: new Date(),
685 metadata: null,
686 deletedAt: null,
687 })
688
689 // Wait for user to be synced to Electric before inserting post
690 await waitForUsersSynced([userId])
691
692 // Insert post for this user
693 const postId = randomUUID()
694 await history.insertPost({
695 id: postId,
696 userId,
697 title: `Tagged Post`,
698 content: `Content`,
699 viewCount: 0,
700 largeViewCount: BigInt(0),
701 publishedAt: null,
702 deletedAt: null,
703 })
704
705 await waitForItem(collection, postId)
706 expect(collection.has(postId)).toBe(true)
707 await history.check(collection)
708
709 // This changes a visible row value; it is not a pure tag-only event.
710 // The post stays eligible because its user remains active.
711 await dbClient.query(
712 `UPDATE ${postsTable} SET title = $1 WHERE id = $2`,
713 [`Updated Tagged Post`, postId],
714 )
715 history.setTitle(postId, `Updated Tagged Post`)
716
717 // Wait a bit and verify post still exists
718 await new Promise((resolve) => setTimeout(resolve, 500))
719 expect(collection.has(postId)).toBe(true)
720 await history.check(collection)
721 expect(collection.get(postId)?.title).toBe(`Updated Tagged Post`)
722 })
723 })
724
725 it(`Database DELETE leads to row being removed from collection`, async () => {
726 await withMoveHistory(async (history) => {
727 const collection = history.own(
728 createPostsByActiveUsersCollection(syncMode),
729 )
730 await history.ready(collection, syncMode)
731
732 if (!config.mutations) {
733 throw new Error(`Mutations not configured`)
734 }
735
736 // Insert user with isActive = true
737 const userId = randomUUID()
738 await history.insertUser({
739 id: userId,
740 name: `Active User`,
741 email: `active@test.com`,
742 age: 25,
743 isActive: true,
744 createdAt: new Date(),
745 metadata: null,
746 deletedAt: null,
747 })
748
749 // Wait for user to be synced to Electric before inserting post
750 await waitForUsersSynced([userId])
751
752 // Insert post for this user
753 const postId = randomUUID()
754 await history.insertPost({
755 id: postId,
756 userId,
757 title: `To Be Deleted`,
758 content: `Content`,
759 viewCount: 0,
760 largeViewCount: BigInt(0),
761 publishedAt: null,
762 deletedAt: null,
763 })
764
765 await waitForItem(collection, postId)
766 expect(collection.has(postId)).toBe(true)
767 await history.check(collection)
768
769 // Delete post in Postgres
770 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
771 postId,
772 ])
773 history.removePost(postId)
774
775 // Wait for post to be removed
776 await waitForItemRemoved(collection, postId)
777 expect(collection.has(postId)).toBe(false)
778 await history.check(collection)
779 })
780 })
781
782 it(`Snapshot after move-out should not re-include removed rows`, async () => {
783 await withMoveHistory(async (history) => {
784 if (!config.mutations) {
785 throw new Error(`Mutations not configured`)
786 }
787
788 // Create first collection
789 const collection1 = history.own(
790 createPostsByActiveUsersCollection(syncMode),
791 )
792 await history.ready(collection1, syncMode)
793
794 // Insert user with isActive = true
795 const userId = randomUUID()
796 await history.insertUser({
797 id: userId,
798 name: `Snapshot Test User`,
799 email: `snapshot@test.com`,
800 age: 25,
801 isActive: true,
802 createdAt: new Date(),
803 metadata: null,
804 deletedAt: null,
805 })
806
807 // Wait for user to be synced to Electric before inserting post
808 await waitForUsersSynced([userId])
809
810 // Insert post for this user
811 const postId = randomUUID()
812 await history.insertPost({
813 id: postId,
814 userId,
815 title: `Snapshot Test Post`,
816 content: `Content`,
817 viewCount: 0,
818 largeViewCount: BigInt(0),
819 publishedAt: null,
820 deletedAt: null,
821 })
822
823 await waitForItem(collection1, postId)
824 expect(collection1.has(postId)).toBe(true)
825 await history.check(collection1)
826
827 // Update user → post moves out
828 await config.mutations.updateUser(userId, { isActive: false })
829 history.setActive(userId, false)
830
831 await waitForItemRemoved(collection1, postId)
832 expect(collection1.has(postId)).toBe(false)
833 await history.check(collection1)
834
835 // Clean up first collection
836 await collection1.cleanup()
837
838 // Create fresh collection (new subscription)
839 const collection2 = history.own(
840 createPostsByActiveUsersCollection(syncMode),
841 )
842 await history.ready(collection2, syncMode)
843
844 // Wait a bit to ensure snapshot is complete
845 await new Promise((resolve) => setTimeout(resolve, 1000))
846
847 // Snapshot should NOT include the removed post (user is inactive)
848 expect(collection2.has(postId)).toBe(false)
849 await history.check(collection2)
850 })
851 })
852
853 it(`Multi-row transaction: some rows move in, some move out`, async () => {
854 await withMoveHistory(async (history) => {
855 const collection = history.own(
856 createPostsByActiveUsersCollection(syncMode),
857 )
858 await history.ready(collection, syncMode)
859 const archiveCallbacks = history.observe(collection)
860
861 if (!config.mutations) {
862 throw new Error(`Mutations not configured`)
863 }
864
865 // Insert 3 users all with isActive = true
866 const userId1 = randomUUID()
867 const userId2 = randomUUID()
868 const userId3 = randomUUID()
869
870 await history.insertUser({
871 id: userId1,
872 name: `User 1`,
873 email: `user1@test.com`,
874 age: 25,
875 isActive: false,
876 createdAt: new Date(),
877 metadata: null,
878 deletedAt: null,
879 })
880
881 await history.insertUser({
882 id: userId2,
883 name: `User 2`,
884 email: `user2@test.com`,
885 age: 30,
886 isActive: true,
887 createdAt: new Date(),
888 metadata: null,
889 deletedAt: null,
890 })
891
892 await history.insertUser({
893 id: userId3,
894 name: `User 3`,
895 email: `user3@test.com`,
896 age: 35,
897 isActive: true,
898 createdAt: new Date(),
899 metadata: null,
900 deletedAt: null,
901 })
902
903 // Wait for all 3 users to be synced to Electric before inserting posts
904 // This ensures the subquery in the WHERE clause can properly evaluate
905 await waitForUsersSynced([userId1, userId2, userId3])
906
907 // Insert posts for these users
908 const postId1 = randomUUID()
909 const postId2 = randomUUID()
910 const postId3 = randomUUID()
911
912 await history.insertPost({
913 id: postId1,
914 userId: userId1,
915 title: `Post 1`,
916 content: `Content 1`,
917 viewCount: 0,
918 largeViewCount: BigInt(0),
919 publishedAt: null,
920 deletedAt: null,
921 })
922
923 await history.insertPost({
924 id: postId2,
925 userId: userId2,
926 title: `Post 2`,
927 content: `Content 2`,
928 viewCount: 0,
929 largeViewCount: BigInt(0),
930 publishedAt: null,
931 deletedAt: null,
932 })
933
934 await history.insertPost({
935 id: postId3,
936 userId: userId3,
937 title: `Post 3`,
938 content: `Content 3`,
939 viewCount: 0,
940 largeViewCount: BigInt(0),
941 publishedAt: null,
942 deletedAt: null,
943 })
944
945 // Wait for posts 2 and 3 to appear
946 await waitForItem(collection, postId2)
947 await waitForItem(collection, postId3)
948
949 expect(collection.has(postId1)).toBe(false)
950 await history.check(collection)
951
952 // In one SQL transaction:
953 // user1: isActive → true (post1 moves in)
954 // post2: title change (stays in since user2 is still active)
955 // user3: isActive → false (post3 moves out)
956 await dbClient.query(`BEGIN`)
957 try {
958 await dbClient.query(
959 `UPDATE ${usersTable} SET "isActive" = $1 WHERE id = $2`,
960 [true, userId1],
961 )
962 await dbClient.query(
963 `UPDATE ${postsTable} SET title = $1 WHERE id = $2`,
964 [`Updated Post 2`, postId2],
965 )
966 await dbClient.query(
967 `UPDATE ${usersTable} SET "isActive" = $1 WHERE id = $2`,
968 [false, userId3],
969 )
970 await dbClient.query(`COMMIT`)
971 } catch (error) {
972 try {
973 await dbClient.query(`ROLLBACK`)
974 } catch (rollbackError) {
975 throw new AggregateError(
976 [error, rollbackError],
977 'SQL transaction and rollback failed',
978 )
979 }
980 throw error
981 }
982 history.setActive(userId1, true)
983 history.setTitle(postId2, `Updated Post 2`)
984 history.setActive(userId3, false)
985
986 // Wait for changes to propagate
987 await waitForItemRemoved(collection, postId3)
988 await history.check(collection)
989 expect(collection.has(postId1)).toBe(true) // post1: moved in (user1 active)
990 await history.check(collection)
991 expect(collection.has(postId2)).toBe(true) // post2: still in (user2 active)
992 await history.check(collection)
993 expect(collection.get(postId2)?.title).toBe(`Updated Post 2`)
994 expect(collection.has(postId3)).toBe(false) // post3: moved out (user3 inactive)
995 await history.check(collection)
996
997 archiveCallbacks()
998 })
999 })
1000 })
1001 }
1002
1003 // Run tests for each sync mode
1004 runTestsForSyncMode('eager')
1005 runTestsForSyncMode('on-demand')
1006 runTestsForSyncMode('progressive')
1007 })
1008}