Open History to see the last commit
1/**
2 * Collation Test Suite
3 *
4 * Tests string collation configuration and behavior
5 */
6
7import { randomUUID } from 'node:crypto'
8import { describe, expect, it } from 'vitest'
9import { createLiveQueryCollection, eq, inArray } from '@tanstack/db'
10import { waitFor, waitForQueryData } from '../utils/helpers'
11import { withQueryCleanup } from './mutations.suite'
12import type { E2ETestConfig, User } from '../types'
13
14export function createCollationTestSuite(
15 getConfig: () => Promise<E2ETestConfig>,
16) {
17 describe(`Collation Suite`, () => {
18 describe(`Default Collation`, () => {
19 it(`should use default collation for string comparisons`, async () => {
20 await withQueryCleanup(async (own) => {
21 const config = await getConfig()
22 const usersCollection = config.collections.onDemand.users
23
24 const query = own(
25 createLiveQueryCollection((q) =>
26 q
27 .from({ user: usersCollection })
28 .orderBy(({ user }) => user.name, `asc`),
29 ),
30 )
31
32 await query.preload()
33 await waitForQueryData(query, { minSize: 1 })
34
35 const results = Array.from(query.state.values())
36 expect(results.length).toBeGreaterThan(0)
37 })
38 })
39
40 it(`should handle case-sensitive comparisons by default`, async () => {
41 await withQueryCleanup(async (own) => {
42 const config = await getConfig()
43 const usersCollection = config.collections.onDemand.users
44
45 // Different case variations should be treated as different
46 const query = own(
47 createLiveQueryCollection(
48 (q) =>
49 q
50 .from({ user: usersCollection })
51 .where(({ user }) => eq(user.name, `alice 0`)), // lowercase
52 ),
53 )
54
55 await query.preload()
56
57 const results = Array.from(query.state.values())
58 // Should NOT match because seed data has "Alice 0" (capitalized) and default is case-sensitive
59 expect(results.length).toBe(0)
60 })
61 })
62 })
63
64 describe(`Custom Collection-Level Collation`, () => {
65 it(`should use custom defaultStringCollation at collection level`, async () => {
66 await withQueryCleanup(async (own) => {
67 const config = await getConfig()
68
69 // Test will use collection with custom collation if provided
70 const query = own(
71 createLiveQueryCollection({
72 query: (q) => q.from({ user: config.collections.onDemand.users }),
73 defaultStringCollation: {
74 stringSort: `lexical`,
75 },
76 }),
77 )
78
79 await query.preload()
80
81 expect(query.compareOptions.stringSort).toBe(`lexical`)
82 })
83 })
84
85 it(`should support locale-based collation`, async () => {
86 await withQueryCleanup(async (own) => {
87 const config = await getConfig()
88
89 const query = own(
90 createLiveQueryCollection({
91 query: (q) => q.from({ user: config.collections.onDemand.users }),
92 defaultStringCollation: {
93 stringSort: `locale`,
94 locale: `de-DE`,
95 },
96 }),
97 )
98
99 await query.preload()
100
101 expect(query.compareOptions.stringSort).toBe(`locale`)
102 // Type narrow: when stringSort is 'locale', locale property exists
103 if (query.compareOptions.stringSort === `locale`) {
104 expect(query.compareOptions.locale).toBe(`de-DE`)
105 }
106 })
107 })
108 })
109
110 describe(`Query-Level Collation Override`, () => {
111 it(`should override collection collation at query level`, async () => {
112 await withQueryCleanup(async (own) => {
113 const config = await getConfig()
114
115 const query = own(
116 createLiveQueryCollection({
117 query: (q) => q.from({ user: config.collections.onDemand.users }),
118 defaultStringCollation: {
119 stringSort: `lexical`,
120 },
121 }),
122 )
123
124 await query.preload()
125
126 expect(query.compareOptions.stringSort).toBe(`lexical`)
127 })
128 })
129 })
130
131 describe(`Collation in OrderBy`, () => {
132 it(`should respect collation when sorting strings`, async () => {
133 const config = await getConfig()
134 if (!config.mutations) {
135 throw new Error(`Mutations not configured - test cannot run`)
136 }
137 const mutations = config.mutations
138 const usersCollection = config.collections.onDemand.users
139
140 const query = createLiveQueryCollection((q) =>
141 q
142 .from({ user: usersCollection })
143 .orderBy(({ user }) => user.name, `asc`),
144 )
145
146 const cleanups: Array<() => Promise<void>> = [() => query.cleanup()]
147 const errors: Array<unknown> = []
148 try {
149 await query.preload()
150 await waitForQueryData(query, { minSize: 1 })
151
152 const results = Array.from(query.state.values())
153 expect(results.length).toBeGreaterThan(0)
154 // Retain the old default-collation smoke check. Nonempty names alone
155 // do not prove an order; the independent explicit law follows below.
156 for (let i = 1; i < results.length; i++) {
157 expect(results[i - 1]!.name).toBeTruthy()
158 }
159
160 // This literal sequence is UTF-16 lexical order, not host locale order.
161 const expected: Array<User> = [`A10`, `A2`, `Z`, `a`, `ä`].map(
162 (name, index) => ({
163 id: randomUUID(),
164 name,
165 email: null,
166 age: 40 + index,
167 isActive: true,
168 createdAt: new Date(1_710_381_566_535 + index),
169 metadata: { collation: index },
170 deletedAt: null,
171 }),
172 )
173 for (const index of [4, 2, 0, 3, 1]) {
174 const row = expected[index]!
175 cleanups.push(async () => {
176 await mutations.deleteUser(row.id)
177 await waitFor(
178 () =>
179 !query.has(row.id) &&
180 !config.collections.eager.users.has(row.id),
181 { message: `Owned collation row was not removed: ${row.id}` },
182 )
183 })
184 await mutations.insertUser(structuredClone(row))
185 }
186
187 const ownedIds = expected.map((row) => row.id)
188 const lexicalQuery = createLiveQueryCollection({
189 query: (q) =>
190 q
191 .from({ user: usersCollection })
192 .where(({ user }) => inArray(user.id, ownedIds))
193 .orderBy(({ user }) => user.name, {
194 direction: `asc`,
195 stringSort: `lexical`,
196 }),
197 defaultStringCollation: { stringSort: `lexical` },
198 })
199 cleanups.push(() => lexicalQuery.cleanup())
200 await lexicalQuery.preload()
201 await waitFor(() => lexicalQuery.size === expected.length, {
202 message: `Lexical query did not load all owned rows`,
203 })
204 const captureRows = (rows: Iterable<User>) =>
205 Array.from(rows, (row) =>
206 structuredClone({
207 id: row.id,
208 name: row.name,
209 email: row.email,
210 age: row.age,
211 isActive: row.isActive,
212 createdAt: row.createdAt,
213 metadata: row.metadata,
214 deletedAt: row.deletedAt,
215 }),
216 )
217 const observed = captureRows(lexicalQuery.values())
218 const expectOrderedRows = (rows: Array<User>) => {
219 expect(rows).toStrictEqual(expected)
220 }
221 expectOrderedRows(observed)
222 expect(() => expectOrderedRows([...observed].reverse())).toThrow()
223 const corrupted = structuredClone(observed)
224 corrupted[0]!.age += 1
225 expect(() => expectOrderedRows(corrupted)).toThrow()
226 const wrongMetadata = structuredClone(observed)
227 const metadata = wrongMetadata[0]!.metadata
228 if (metadata === null)
229 throw new Error('Expected captured non-null collation metadata')
230 Object.defineProperty(metadata, 'unexpected', {
231 value: undefined,
232 enumerable: true,
233 })
234 expect(
235 Object.prototype.hasOwnProperty.call(metadata, 'unexpected'),
236 ).toBe(true)
237 expect(() => expectOrderedRows(wrongMetadata)).toThrow()
238
239 // The configured output default governs a subsequent query consuming
240 // this collection. The producing query's explicit clause is separate.
241 expect(lexicalQuery.compareOptions.stringSort).toBe(`lexical`)
242 const downstream = createLiveQueryCollection((q) =>
243 q
244 .from({ user: lexicalQuery })
245 .orderBy(({ user }) => user.name, `asc`),
246 )
247 cleanups.push(() => downstream.cleanup())
248 await downstream.preload()
249 await waitFor(() => downstream.size === expected.length, {
250 message: `Downstream query did not load all owned rows`,
251 })
252 expectOrderedRows(captureRows(downstream.values()))
253 expectOrderedRows(observed)
254 } catch (error) {
255 errors.push(error)
256 } finally {
257 for (const cleanup of cleanups.reverse()) {
258 try {
259 await cleanup()
260 } catch (error) {
261 errors.push(error)
262 }
263 }
264 }
265 if (errors.length === 1) throw errors[0]
266 if (errors.length > 1) {
267 throw new AggregateError(errors, `Collation test and cleanup failed`)
268 }
269 })
270 })
271 })
272}