Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

moves.suite.ts

756 lines24.8 KB

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 } from 'vitest'
10import { createCollection } from '@tanstack/db'
11import { electricCollectionOptions } from '@tanstack/electric-db-collection'
12import { waitFor } from '../utils/helpers'
13import type { E2ETestConfig } from '../types'
14import type { Client } from 'pg'
15import type { Collection } from '@tanstack/db'
16import type { ElectricCollectionUtils } from '@tanstack/electric-db-collection'
17​
18interface TagsTestConfig extends E2ETestConfig {
19 tagsTestSetup: {
20 dbClient: Client
21 baseUrl: string
22 testSchema: string
23 usersTable: string
24 postsTable: string
25 }
27​
28type SyncMode = 'eager' | 'on-demand' | 'progressive'
29​
30export function createMovesTestSuite(getConfig: () => Promise<TagsTestConfig>) {
31 describe(`Moves Suite`, () => {
32 let usersTable: string
33 let postsTable: string
34 let dbClient: Client
35 let baseUrl: string
36 let testSchema: string
37 let config: TagsTestConfig
38​
39 beforeAll(async () => {
40 config = await getConfig()
41 const setup = config.tagsTestSetup
42 dbClient = setup.dbClient
43 baseUrl = setup.baseUrl
44 testSchema = setup.testSchema
45 usersTable = setup.usersTable
46 postsTable = setup.postsTable
47 })
48​
49 // Helper to create a collection on posts table with WHERE clause that has nested subquery
50 // This creates a shape: posts WHERE userId IN (SELECT id FROM users WHERE isActive = true)
51 // When a user's isActive changes, posts will move in/out of this shape
52 function createPostsByActiveUsersCollection(
53 syncMode: SyncMode,
54 id?: string,
55 ): Collection<any, string, ElectricCollectionUtils, any, any> {
56 // Remove quotes from table names for the WHERE clause SQL
57 const usersTableUnquoted = usersTable.replace(/"/g, ``)
58 const collectionId =
59 id || `tags-posts-active-users-${syncMode}-${Date.now()}`
60​
61 return createCollection(
62 electricCollectionOptions({
63 id: collectionId,
64 shapeOptions: {
65 url: `${baseUrl}/v1/shape`,
66 params: {
67 table: `${testSchema}.${postsTable}`,
68 // WHERE clause with nested subquery
69 // Posts will move in/out when users' isActive changes
70 // Column reference should be just the column name, not the full table path
71 where: `"userId" IN (SELECT id FROM ${testSchema}.${usersTableUnquoted} WHERE "isActive" = true)`,
72 },
73 },
74 syncMode,
75 getKey: (item: any) => item.id,
76 startSync: syncMode !== 'progressive',
77 }),
78 ) as any
79 }
80​
81 // Helper to wait for collection to be ready
82 async function waitForReady(
83 collection: Collection<any, any, any, any, any>,
84 syncMode: SyncMode,
85 ) {
86 if (syncMode === 'progressive') {
87 // For progressive mode, start sync explicitly
88 collection.startSyncImmediate()
89 }
90 await collection.preload()
91 await waitFor(() => collection.status === `ready`, {
92 timeout: 30000,
93 message: `Collection did not become ready`,
94 })
95 }
96​
97 // Helper to wait for a specific item to appear
98 async function waitForItem(
99 collection: Collection<any, any, any, any, any>,
100 itemId: string,
101 timeout: number = 10000,
102 ) {
103 await waitFor(() => collection.has(itemId), {
104 timeout,
105 message: `Item ${itemId} did not appear in collection`,
106 })
107 }
108​
109 // Helper to wait for a specific item to disappear
110 async function waitForItemRemoved(
111 collection: Collection<any, any, any, any, any>,
112 itemId: string,
113 timeout: number = 2000,
114 ) {
115 await waitFor(() => !collection.has(itemId), {
116 timeout,
117 message: `Item ${itemId} was not removed from collection`,
118 })
119 }
120​
121 // Helper to wait for users to be synced to Electric/TanStack DB
122 async function waitForUsersSynced(
123 userIds: Array<string>,
124 timeout: number = 10000,
125 ) {
126 // Use eager collection since it continuously syncs all data
127 const usersCollection = config.collections.eager.users
128 await waitFor(
129 () => {
130 return userIds.every((userId) => usersCollection.has(userId))
131 },
132 {
133 timeout,
134 message: `Users ${userIds.join(', ')} did not sync to collection`,
135 },
136 )
137 }
138​
139 // Helper function to run all tests for a given sync mode
140 function runTestsForSyncMode(syncMode: SyncMode) {
141 describe(`${syncMode} mode`, () => {
142 it(`Initial snapshot contains only posts from active users`, async () => {
143 // Create collection on posts with WHERE clause: userId IN (SELECT id FROM users WHERE isActive = true)
144 const collection = createPostsByActiveUsersCollection(syncMode)
145​
146 if (!config.mutations) {
147 throw new Error(`Mutations not configured`)
148 }
149​
150 // Insert 2 active users and 1 inactive user
151 const userId1 = randomUUID()
152 const userId2 = randomUUID()
153 const userId3 = randomUUID()
154​
155 await config.mutations.insertUser({
156 id: userId1,
157 name: `Active User 1`,
158 email: `user1@test.com`,
159 age: 25,
160 isActive: true,
161 createdAt: new Date(),
162 metadata: null,
163 deletedAt: null,
164 })
165​
166 await config.mutations.insertUser({
167 id: userId2,
168 name: `Active User 2`,
169 email: `user2@test.com`,
170 age: 30,
171 isActive: true,
172 createdAt: new Date(),
173 metadata: null,
174 deletedAt: null,
175 })
176​
177 await config.mutations.insertUser({
178 id: userId3,
179 name: `Inactive User`,
180 email: `user3@test.com`,
181 age: 42,
182 isActive: false,
183 createdAt: new Date(),
184 metadata: null,
185 deletedAt: null,
186 })
187​
188 // Wait for all 3 users to be synced to Electric before inserting posts
189 // This ensures the subquery in the WHERE clause can properly evaluate
190 await waitForUsersSynced([userId1, userId2, userId3])
191​
192 // Insert posts for these users
193 const postId1 = randomUUID()
194 const postId2 = randomUUID()
195 const postId3 = randomUUID()
196​
197 await config.mutations.insertPost({
198 id: postId1,
199 userId: userId1,
200 title: `Post 1`,
201 content: `Content 1`,
202 viewCount: 0,
203 largeViewCount: BigInt(0),
204 publishedAt: null,
205 deletedAt: null,
206 })
207​
208 await config.mutations.insertPost({
209 id: postId2,
210 userId: userId2,
211 title: `Post 2`,
212 content: `Content 2`,
213 viewCount: 0,
214 largeViewCount: BigInt(0),
215 publishedAt: null,
216 deletedAt: null,
217 })
218​
219 await config.mutations.insertPost({
220 id: postId3,
221 userId: userId3,
222 title: `Post 3`,
223 content: `Content 3`,
224 viewCount: 0,
225 largeViewCount: BigInt(0),
226 publishedAt: null,
227 deletedAt: null,
228 })
229​
230 // Wait for collection to sync
231 await waitForReady(collection, syncMode)
232​
233 // Wait for both posts to appear (users are active, so posts match the subquery)
234 await waitForItem(collection, postId1)
235 await waitForItem(collection, postId2)
236​
237 // Verify only posts 1 and 2 are in the collection
238 expect(collection.has(postId1)).toBe(true)
239 expect(collection.has(postId2)).toBe(true)
240 expect(collection.has(postId3)).toBe(false)
241​
242 // Wait a bit to make sure post 3 is not coming in later
243 await new Promise((resolve) => setTimeout(resolve, 50))
244 expect(collection.has(postId3)).toBe(false)
245​
246 // Note: Tags are internal to Electric and may not be directly accessible
247 // The test verifies that posts with matching conditions appear in snapshot
248​
249 // Clean up
250 await dbClient.query(`DELETE FROM ${postsTable}`)
251 await dbClient.query(`DELETE FROM ${usersTable}`)
252 await collection.cleanup()
253 })
254​
255 it(`Move-in: row becomes eligible for subquery`, async () => {
256 const collection = createPostsByActiveUsersCollection(syncMode)
257 await waitForReady(collection, syncMode)
258​
259 if (!config.mutations) {
260 throw new Error(`Mutations not configured`)
261 }
262​
263 // Insert user with isActive = false
264 const userId = randomUUID()
265 await config.mutations.insertUser({
266 id: userId,
267 name: `Inactive User`,
268 email: `inactive@test.com`,
269 age: 25,
270 isActive: false,
271 createdAt: new Date(),
272 metadata: null,
273 deletedAt: null,
274 })
275​
276 // Wait for user to be synced to Electric before inserting post
277 await waitForUsersSynced([userId])
278​
279 // Insert post for this user
280 const postId = randomUUID()
281 await config.mutations.insertPost({
282 id: postId,
283 userId,
284 title: `Inactive User Post`,
285 content: `Content`,
286 viewCount: 0,
287 largeViewCount: BigInt(0),
288 publishedAt: null,
289 deletedAt: null,
290 })
291​
292 // Wait a bit to ensure post doesn't appear (user is inactive, so post doesn't match subquery)
293 await new Promise((resolve) => setTimeout(resolve, 500))
294 expect(collection.has(postId)).toBe(false)
295​
296 // Update user to isActive = true (move-in for the post)
297 await config.mutations.updateUser(userId, { isActive: true })
298​
299 // Wait for post to appear (move-in)
300 await waitForItem(collection, postId, 1000)
301 expect(collection.has(postId)).toBe(true)
302 expect(collection.get(postId)?.title).toBe(`Inactive User Post`)
303​
304 // Clean up
305 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
306 postId,
307 ])
308 await config.mutations.deleteUser(userId)
309 await collection.cleanup()
310 })
311​
312 it(`Move-out: row becomes ineligible for subquery`, async () => {
313 const collection = createPostsByActiveUsersCollection(syncMode)
314 await waitForReady(collection, syncMode)
315​
316 if (!config.mutations) {
317 throw new Error(`Mutations not configured`)
318 }
319​
320 // Insert user with isActive = true
321 const userId = randomUUID()
322 await config.mutations.insertUser({
323 id: userId,
324 name: `Active User`,
325 email: `active@test.com`,
326 age: 25,
327 isActive: true,
328 createdAt: new Date(),
329 metadata: null,
330 deletedAt: null,
331 })
332​
333 // Wait for user to be synced to Electric before inserting post
334 await waitForUsersSynced([userId])
335​
336 // Insert post for this user
337 const postId = randomUUID()
338 await config.mutations.insertPost({
339 id: postId,
340 userId,
341 title: `Active User Post`,
342 content: `Content`,
343 viewCount: 0,
344 largeViewCount: BigInt(0),
345 publishedAt: null,
346 deletedAt: null,
347 })
348​
349 // Wait for post to appear (user is active, so post matches subquery)
350 await waitForItem(collection, postId)
351 expect(collection.has(postId)).toBe(true)
352​
353 // Update user to isActive = false (move-out for the post)
354 await config.mutations.updateUser(userId, { isActive: false })
355​
356 // Wait for post to be removed (move-out)
357 await waitForItemRemoved(collection, postId)
358 expect(collection.has(postId)).toBe(false)
359​
360 // Clean up
361 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
362 postId,
363 ])
364 await config.mutations.deleteUser(userId)
365 await collection.cleanup()
366 })
367​
368 it(`Move-out → move-in cycle`, async () => {
369 const collection = createPostsByActiveUsersCollection(syncMode)
370 await waitForReady(collection, syncMode)
371​
372 if (!config.mutations) {
373 throw new Error(`Mutations not configured`)
374 }
375​
376 // Insert user with isActive = true
377 const userId = randomUUID()
378 await config.mutations.insertUser({
379 id: userId,
380 name: `Flapping User`,
381 email: `flapping@test.com`,
382 age: 25,
383 isActive: true,
384 createdAt: new Date(),
385 metadata: null,
386 deletedAt: null,
387 })
388​
389 // Wait for user to be synced to Electric before inserting post
390 await waitForUsersSynced([userId])
391​
392 // Insert post for this user
393 const postId = randomUUID()
394 await config.mutations.insertPost({
395 id: postId,
396 userId,
397 title: `Flapping Post`,
398 content: `Content`,
399 viewCount: 0,
400 largeViewCount: BigInt(0),
401 publishedAt: null,
402 deletedAt: null,
403 })
404​
405 await waitForItem(collection, postId)
406 expect(collection.has(postId)).toBe(true)
407​
408 // Move-out: isActive = false
409 await config.mutations.updateUser(userId, { isActive: false })
410 await waitForItemRemoved(collection, postId, 15000)
411 expect(collection.has(postId)).toBe(false)
412​
413 // Move-in: isActive = true
414 await config.mutations.updateUser(userId, { isActive: true })
415 await waitForItem(collection, postId, 15000)
416 expect(collection.has(postId)).toBe(true)
417​
418 // Clean up
419 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
420 postId,
421 ])
422 await config.mutations.deleteUser(userId)
423 await collection.cleanup()
424 })
425​
426 it(`Tags-only update (row stays within subquery)`, async () => {
427 const collection = createPostsByActiveUsersCollection(syncMode)
428 await waitForReady(collection, syncMode)
429​
430 if (!config.mutations) {
431 throw new Error(`Mutations not configured`)
432 }
433​
434 // Insert user with isActive = true
435 const userId = randomUUID()
436 await config.mutations.insertUser({
437 id: userId,
438 name: `Active User`,
439 email: `active@test.com`,
440 age: 25,
441 isActive: true,
442 createdAt: new Date(),
443 metadata: null,
444 deletedAt: null,
445 })
446​
447 // Wait for user to be synced to Electric before inserting post
448 await waitForUsersSynced([userId])
449​
450 // Insert post for this user
451 const postId = randomUUID()
452 await config.mutations.insertPost({
453 id: postId,
454 userId,
455 title: `Tagged Post`,
456 content: `Content`,
457 viewCount: 0,
458 largeViewCount: BigInt(0),
459 publishedAt: null,
460 deletedAt: null,
461 })
462​
463 await waitForItem(collection, postId)
464 expect(collection.has(postId)).toBe(true)
465​
466 // Update post title (tags might change but post stays in subquery since user is still active)
467 await dbClient.query(
468 `UPDATE ${postsTable} SET title = $1 WHERE id = $2`,
469 [`Updated Tagged Post`, postId],
470 )
471​
472 // Wait a bit and verify post still exists
473 await new Promise((resolve) => setTimeout(resolve, 500))
474 expect(collection.has(postId)).toBe(true)
475 expect(collection.get(postId)?.title).toBe(`Updated Tagged Post`)
476​
477 // Clean up
478 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
479 postId,
480 ])
481 await config.mutations.deleteUser(userId)
482 await collection.cleanup()
483 })
484​
485 it(`Database DELETE leads to row being removed from collection`, async () => {
486 const collection = createPostsByActiveUsersCollection(syncMode)
487 await waitForReady(collection, syncMode)
488​
489 if (!config.mutations) {
490 throw new Error(`Mutations not configured`)
491 }
492​
493 // Insert user with isActive = true
494 const userId = randomUUID()
495 await config.mutations.insertUser({
496 id: userId,
497 name: `Active User`,
498 email: `active@test.com`,
499 age: 25,
500 isActive: true,
501 createdAt: new Date(),
502 metadata: null,
503 deletedAt: null,
504 })
505​
506 // Wait for user to be synced to Electric before inserting post
507 await waitForUsersSynced([userId])
508​
509 // Insert post for this user
510 const postId = randomUUID()
511 await config.mutations.insertPost({
512 id: postId,
513 userId,
514 title: `To Be Deleted`,
515 content: `Content`,
516 viewCount: 0,
517 largeViewCount: BigInt(0),
518 publishedAt: null,
519 deletedAt: null,
520 })
521​
522 await waitForItem(collection, postId)
523 expect(collection.has(postId)).toBe(true)
524​
525 // Delete post in Postgres
526 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
527 postId,
528 ])
529​
530 // Wait for post to be removed
531 await waitForItemRemoved(collection, postId)
532 expect(collection.has(postId)).toBe(false)
533​
534 // Clean up
535 await config.mutations.deleteUser(userId)
536 await collection.cleanup()
537 })
538​
539 it(`Snapshot after move-out should not re-include removed rows`, async () => {
540 if (!config.mutations) {
541 throw new Error(`Mutations not configured`)
542 }
543​
544 // Create first collection
545 const collection1 = createPostsByActiveUsersCollection(syncMode)
546 await waitForReady(collection1, syncMode)
547​
548 // Insert user with isActive = true
549 const userId = randomUUID()
550 await config.mutations.insertUser({
551 id: userId,
552 name: `Snapshot Test User`,
553 email: `snapshot@test.com`,
554 age: 25,
555 isActive: true,
556 createdAt: new Date(),
557 metadata: null,
558 deletedAt: null,
559 })
560​
561 // Wait for user to be synced to Electric before inserting post
562 await waitForUsersSynced([userId])
563​
564 // Insert post for this user
565 const postId = randomUUID()
566 await config.mutations.insertPost({
567 id: postId,
568 userId,
569 title: `Snapshot Test Post`,
570 content: `Content`,
571 viewCount: 0,
572 largeViewCount: BigInt(0),
573 publishedAt: null,
574 deletedAt: null,
575 })
576​
577 await waitForItem(collection1, postId)
578 expect(collection1.has(postId)).toBe(true)
579​
580 // Update user → post moves out
581 await config.mutations.updateUser(userId, { isActive: false })
582​
583 await waitForItemRemoved(collection1, postId)
584 expect(collection1.has(postId)).toBe(false)
585​
586 // Clean up first collection
587 await collection1.cleanup()
588​
589 // Create fresh collection (new subscription)
590 const collection2 = createPostsByActiveUsersCollection(syncMode)
591 await waitForReady(collection2, syncMode)
592​
593 // Wait a bit to ensure snapshot is complete
594 await new Promise((resolve) => setTimeout(resolve, 1000))
595​
596 // Snapshot should NOT include the removed post (user is inactive)
597 expect(collection2.has(postId)).toBe(false)
598​
599 // Clean up
600 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
601 postId,
602 ])
603 await config.mutations.deleteUser(userId)
604 await collection2.cleanup()
605 })
606​
607 it(`Multi-row transaction: some rows move in, some move out`, async () => {
608 const collection = createPostsByActiveUsersCollection(syncMode)
609 await waitForReady(collection, syncMode)
610​
611 if (!config.mutations) {
612 throw new Error(`Mutations not configured`)
613 }
614​
615 // Insert 3 users all with isActive = true
616 const userId1 = randomUUID()
617 const userId2 = randomUUID()
618 const userId3 = randomUUID()
619​
620 await config.mutations.insertUser({
621 id: userId1,
622 name: `User 1`,
623 email: `user1@test.com`,
624 age: 25,
625 isActive: false,
626 createdAt: new Date(),
627 metadata: null,
628 deletedAt: null,
629 })
630​
631 await config.mutations.insertUser({
632 id: userId2,
633 name: `User 2`,
634 email: `user2@test.com`,
635 age: 30,
636 isActive: true,
637 createdAt: new Date(),
638 metadata: null,
639 deletedAt: null,
640 })
641​
642 await config.mutations.insertUser({
643 id: userId3,
644 name: `User 3`,
645 email: `user3@test.com`,
646 age: 35,
647 isActive: true,
648 createdAt: new Date(),
649 metadata: null,
650 deletedAt: null,
651 })
652​
653 // Wait for all 3 users to be synced to Electric before inserting posts
654 // This ensures the subquery in the WHERE clause can properly evaluate
655 await waitForUsersSynced([userId1, userId2, userId3])
656​
657 // Insert posts for these users
658 const postId1 = randomUUID()
659 const postId2 = randomUUID()
660 const postId3 = randomUUID()
661​
662 await config.mutations.insertPost({
663 id: postId1,
664 userId: userId1,
665 title: `Post 1`,
666 content: `Content 1`,
667 viewCount: 0,
668 largeViewCount: BigInt(0),
669 publishedAt: null,
670 deletedAt: null,
671 })
672​
673 await config.mutations.insertPost({
674 id: postId2,
675 userId: userId2,
676 title: `Post 2`,
677 content: `Content 2`,
678 viewCount: 0,
679 largeViewCount: BigInt(0),
680 publishedAt: null,
681 deletedAt: null,
682 })
683​
684 await config.mutations.insertPost({
685 id: postId3,
686 userId: userId3,
687 title: `Post 3`,
688 content: `Content 3`,
689 viewCount: 0,
690 largeViewCount: BigInt(0),
691 publishedAt: null,
692 deletedAt: null,
693 })
694​
695 // Wait for posts 2 and 3 to appear
696 await waitForItem(collection, postId2)
697 await waitForItem(collection, postId3)
698​
699 expect(collection.has(postId1)).toBe(false)
700​
701 // In one SQL transaction:
702 // user1: isActive → true (post1 moves in)
703 // post2: title change (stays in since user2 is still active)
704 // user3: isActive → false (post3 moves out)
705 await dbClient.query(`BEGIN`)
706 try {
707 await dbClient.query(
708 `UPDATE ${usersTable} SET "isActive" = $1 WHERE id = $2`,
709 [true, userId1],
710 )
711 await dbClient.query(
712 `UPDATE ${postsTable} SET title = $1 WHERE id = $2`,
713 [`Updated Post 2`, postId2],
714 )
715 await dbClient.query(
716 `UPDATE ${usersTable} SET "isActive" = $1 WHERE id = $2`,
717 [false, userId3],
718 )
719 await dbClient.query(`COMMIT`)
720 } catch (error) {
721 await dbClient.query(`ROLLBACK`)
722 throw error
723 }
724​
725 // Wait for changes to propagate
726 await waitForItemRemoved(collection, postId3)
727 await new Promise((resolve) => setTimeout(resolve, 1000))
728 expect(collection.has(postId1)).toBe(true) // post1: moved in (user1 active)
729 expect(collection.has(postId2)).toBe(true) // post2: still in (user2 active)
730 expect(collection.get(postId2)?.title).toBe(`Updated Post 2`)
731 expect(collection.has(postId3)).toBe(false) // post3: moved out (user3 inactive)
732​
733 // Clean up
734 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
735 postId1,
736 ])
737 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
738 postId2,
739 ])
740 await dbClient.query(`DELETE FROM ${postsTable} WHERE id = $1`, [
741 postId3,
742 ])
743 await config.mutations.deleteUser(userId1)
744 await config.mutations.deleteUser(userId2)
745 await config.mutations.deleteUser(userId3)
746 await collection.cleanup()
747 })
748 })
749 }
750​
751 // Run tests for each sync mode
752 runTestsForSyncMode('eager')
753 runTestsForSyncMode('on-demand')
754 runTestsForSyncMode('progressive')
755 })