bunsane 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunsane",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "author": {
5
5
  "name": "yaaruu"
6
6
  },
@@ -54,11 +54,15 @@ export class ComponentInclusionNode extends QueryNode {
54
54
 
55
55
  let sql = "";
56
56
  const componentCount = componentIds.length;
57
- const useLateralJoins = Boolean(shouldUseLateralJoins());
58
57
 
59
58
  // Check if CTE is available and use it to avoid redundant entity_components scans
60
59
  const useCTE = Boolean(context.hasCTE && context.cteName);
61
60
 
61
+ // LATERAL joins don't work correctly with INTERSECT queries (non-CTE multi-component)
62
+ // because the SQL insertion logic places joins inside the INTERSECT subqueries
63
+ const isIntersectQuery = componentCount > 1 && !useCTE;
64
+ const useLateralJoins = Boolean(shouldUseLateralJoins()) && !isIntersectQuery;
65
+
62
66
  // Collect LATERAL join fragments if using LATERAL joins
63
67
  const lateralJoins: string[] = [];
64
68
  const lateralConditions: string[] = [];
@@ -430,11 +434,11 @@ export class ComponentInclusionNode extends QueryNode {
430
434
  } else if (typeof filter.value === 'boolean') {
431
435
  condition = `(${jsonPath})::boolean ${filter.operator} $${context.addParam(filter.value)}`;
432
436
  } else if (filter.operator === 'IN' || filter.operator === 'NOT IN') {
433
- if (Array.isArray(filter.value)) {
437
+ if (Array.isArray(filter.value) && filter.value.length > 0) {
434
438
  const placeholders = filter.value.map((v: any) => `$${context.addParam(v)}`).join(', ');
435
439
  condition = `${jsonPath} ${filter.operator} (${placeholders})`;
436
440
  } else {
437
- return null; // Invalid - fall back to normal path
441
+ return null; // Invalid or empty array - fall back to normal path
438
442
  }
439
443
  } else if (filter.operator === 'LIKE' || filter.operator === 'NOT LIKE' || filter.operator === 'ILIKE') {
440
444
  condition = `${jsonPath} ${filter.operator} $${context.addParam(filter.value)}::text`;
@@ -445,6 +449,9 @@ export class ComponentInclusionNode extends QueryNode {
445
449
  filterConditions.push(condition);
446
450
  }
447
451
 
452
+ // Guard: if no conditions were built, fall back to normal path
453
+ if (filterConditions.length === 0) return null;
454
+
448
455
  const nullsClause = sortOrder.nullsFirst ? 'NULLS FIRST' : 'NULLS LAST';
449
456
  const isNumeric = isNumericProperty(sortOrder.component, sortOrder.property);
450
457
  const sortExpr = isNumeric
@@ -622,9 +629,12 @@ export class ComponentInclusionNode extends QueryNode {
622
629
  condition = `${jsonPath} ${filter.operator} $${context.addParam(filter.value)}`;
623
630
  } else if (filter.operator === 'IN' || filter.operator === 'NOT IN') {
624
631
  // IN/NOT IN comparison - handle arrays properly
625
- if (Array.isArray(filter.value)) {
632
+ if (Array.isArray(filter.value) && filter.value.length > 0) {
626
633
  const placeholders = Array.from({length: filter.value.length}, (_, i) => `$${context.addParam(filter.value[i])}`).join(', ');
627
634
  condition = `${jsonPath} ${filter.operator} (${placeholders})`;
635
+ } else if (Array.isArray(filter.value) && filter.value.length === 0) {
636
+ // Empty array: IN () is always false, NOT IN () is always true
637
+ condition = filter.operator === 'IN' ? 'FALSE' : 'TRUE';
628
638
  } else {
629
639
  throw new Error(`${filter.operator} operator requires an array of values`);
630
640
  }
@@ -0,0 +1,372 @@
1
+ /**
2
+ * Benchmark: LATERAL joins vs EXISTS subqueries for multi-component queries
3
+ *
4
+ * Tests the performance impact of the INTERSECT query fix that disables
5
+ * LATERAL joins for multi-component non-CTE queries.
6
+ */
7
+ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
8
+ import { Entity } from '../../core/Entity';
9
+ import { Query, FilterOp } from '../../query/Query';
10
+ import { Component, CompData, BaseComponent } from '../../core/components';
11
+ import { ComponentRegistry } from '../../core/components/ComponentRegistry';
12
+ import { ensureComponentsRegistered } from '../utils';
13
+
14
+ // Benchmark components
15
+ @Component
16
+ class BenchUser extends BaseComponent {
17
+ @CompData({ indexed: true }) name: string = '';
18
+ @CompData({ indexed: true }) email: string = '';
19
+ @CompData() age: number = 0;
20
+ @CompData() status: string = 'active';
21
+ }
22
+
23
+ @Component
24
+ class BenchProfile extends BaseComponent {
25
+ @CompData({ indexed: true }) username: string = '';
26
+ @CompData() bio: string = '';
27
+ @CompData() verified: boolean = false;
28
+ }
29
+
30
+ @Component
31
+ class BenchSettings extends BaseComponent {
32
+ @CompData() theme: string = 'light';
33
+ @CompData() notifications: boolean = true;
34
+ @CompData() language: string = 'en';
35
+ }
36
+
37
+ // Test configuration
38
+ const DATASET_SIZES = {
39
+ small: 100,
40
+ medium: 1000,
41
+ large: 5000
42
+ };
43
+
44
+ const ITERATIONS = 5; // Number of times to run each query for averaging
45
+
46
+ interface BenchmarkResult {
47
+ name: string;
48
+ datasetSize: number;
49
+ avgTimeMs: number;
50
+ minTimeMs: number;
51
+ maxTimeMs: number;
52
+ resultCount: number;
53
+ }
54
+
55
+ async function runBenchmark(
56
+ name: string,
57
+ datasetSize: number,
58
+ queryFn: () => Promise<Entity[]>
59
+ ): Promise<BenchmarkResult> {
60
+ const times: number[] = [];
61
+ let resultCount = 0;
62
+
63
+ for (let i = 0; i < ITERATIONS; i++) {
64
+ const start = performance.now();
65
+ const results = await queryFn();
66
+ const end = performance.now();
67
+ times.push(end - start);
68
+ resultCount = results.length;
69
+ }
70
+
71
+ return {
72
+ name,
73
+ datasetSize,
74
+ avgTimeMs: times.reduce((a, b) => a + b, 0) / times.length,
75
+ minTimeMs: Math.min(...times),
76
+ maxTimeMs: Math.max(...times),
77
+ resultCount
78
+ };
79
+ }
80
+
81
+ describe('Query Performance Benchmark', () => {
82
+ const createdEntityIds: string[] = [];
83
+ const datasetSize = DATASET_SIZES.large; // 5000 entities
84
+
85
+ beforeAll(async () => {
86
+ await ensureComponentsRegistered(BenchUser, BenchProfile, BenchSettings);
87
+
88
+ console.log(`\n📊 Creating ${datasetSize} test entities...`);
89
+ const startCreate = performance.now();
90
+
91
+ // Create entities with various component combinations
92
+ for (let i = 0; i < datasetSize; i++) {
93
+ const entity = Entity.Create();
94
+
95
+ // All entities have BenchUser
96
+ entity.add(BenchUser, {
97
+ name: `User ${i}`,
98
+ email: `user${i}@test.com`,
99
+ age: 18 + (i % 60),
100
+ status: i % 3 === 0 ? 'active' : (i % 3 === 1 ? 'inactive' : 'pending')
101
+ });
102
+
103
+ // 80% have BenchProfile
104
+ if (i % 5 !== 0) {
105
+ entity.add(BenchProfile, {
106
+ username: `user_${i}`,
107
+ bio: `Bio for user ${i}`,
108
+ verified: i % 2 === 0
109
+ });
110
+ }
111
+
112
+ // 60% have BenchSettings
113
+ if (i % 5 < 3) {
114
+ entity.add(BenchSettings, {
115
+ theme: i % 2 === 0 ? 'light' : 'dark',
116
+ notifications: i % 3 !== 0,
117
+ language: ['en', 'es', 'fr', 'de'][i % 4]!
118
+ });
119
+ }
120
+
121
+ await entity.save();
122
+ createdEntityIds.push(entity.id);
123
+ }
124
+
125
+ const endCreate = performance.now();
126
+ console.log(`✅ Created ${datasetSize} entities in ${(endCreate - startCreate).toFixed(0)}ms\n`);
127
+ }, 120000); // 2 minute timeout for setup
128
+
129
+ afterAll(async () => {
130
+ // Cleanup
131
+ console.log(`\n🧹 Cleaning up ${createdEntityIds.length} entities...`);
132
+ for (const id of createdEntityIds) {
133
+ try {
134
+ const entity = await Entity.findById(id);
135
+ if (entity) {
136
+ await entity.delete();
137
+ }
138
+ } catch {
139
+ // Ignore cleanup errors
140
+ }
141
+ }
142
+ }, 120000);
143
+
144
+ describe('Single component queries (baseline)', () => {
145
+ test('single component, no filter', async () => {
146
+ const result = await runBenchmark(
147
+ 'Single component, no filter',
148
+ datasetSize,
149
+ () => new Query().with(BenchUser).take(100).exec()
150
+ );
151
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
152
+ expect(result.avgTimeMs).toBeLessThan(1000);
153
+ });
154
+
155
+ test('single component, with filter', async () => {
156
+ const result = await runBenchmark(
157
+ 'Single component, with filter',
158
+ datasetSize,
159
+ () => new Query()
160
+ .with(BenchUser, {
161
+ filters: [Query.filter('status', FilterOp.EQ, 'active')]
162
+ })
163
+ .take(100)
164
+ .exec()
165
+ );
166
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
167
+ expect(result.avgTimeMs).toBeLessThan(1000);
168
+ });
169
+ });
170
+
171
+ describe('Two component queries (affected by fix)', () => {
172
+ test('2 components, no filter', async () => {
173
+ const result = await runBenchmark(
174
+ '2 components, no filter',
175
+ datasetSize,
176
+ () => new Query()
177
+ .with(BenchUser)
178
+ .with(BenchProfile)
179
+ .take(100)
180
+ .exec()
181
+ );
182
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
183
+ expect(result.avgTimeMs).toBeLessThan(2000);
184
+ });
185
+
186
+ test('2 components, filter on first (bug pattern)', async () => {
187
+ const result = await runBenchmark(
188
+ '2 components, filter on first',
189
+ datasetSize,
190
+ () => new Query()
191
+ .with(BenchUser, {
192
+ filters: [Query.filter('status', FilterOp.EQ, 'active')]
193
+ })
194
+ .with(BenchProfile)
195
+ .take(100)
196
+ .exec()
197
+ );
198
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
199
+ expect(result.avgTimeMs).toBeLessThan(2000);
200
+ });
201
+
202
+ test('2 components, filter on second (bug pattern)', async () => {
203
+ const result = await runBenchmark(
204
+ '2 components, filter on second',
205
+ datasetSize,
206
+ () => new Query()
207
+ .with(BenchUser)
208
+ .with(BenchProfile, {
209
+ filters: [Query.filter('verified', FilterOp.EQ, true)]
210
+ })
211
+ .take(100)
212
+ .exec()
213
+ );
214
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
215
+ expect(result.avgTimeMs).toBeLessThan(2000);
216
+ });
217
+
218
+ test('2 components, filters on both', async () => {
219
+ const result = await runBenchmark(
220
+ '2 components, filters on both',
221
+ datasetSize,
222
+ () => new Query()
223
+ .with(BenchUser, {
224
+ filters: [Query.filter('status', FilterOp.EQ, 'active')]
225
+ })
226
+ .with(BenchProfile, {
227
+ filters: [Query.filter('verified', FilterOp.EQ, true)]
228
+ })
229
+ .take(100)
230
+ .exec()
231
+ );
232
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
233
+ expect(result.avgTimeMs).toBeLessThan(2000);
234
+ });
235
+
236
+ test('2 components, IN filter (bug pattern)', async () => {
237
+ const result = await runBenchmark(
238
+ '2 components, IN filter',
239
+ datasetSize,
240
+ () => new Query()
241
+ .with(BenchUser, {
242
+ filters: [Query.filter('status', FilterOp.IN, ['active', 'pending'])]
243
+ })
244
+ .with(BenchProfile)
245
+ .take(100)
246
+ .exec()
247
+ );
248
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
249
+ expect(result.avgTimeMs).toBeLessThan(2000);
250
+ });
251
+ });
252
+
253
+ describe('Three component queries', () => {
254
+ test('3 components, no filter', async () => {
255
+ const result = await runBenchmark(
256
+ '3 components, no filter',
257
+ datasetSize,
258
+ () => new Query()
259
+ .with(BenchUser)
260
+ .with(BenchProfile)
261
+ .with(BenchSettings)
262
+ .take(100)
263
+ .exec()
264
+ );
265
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
266
+ expect(result.avgTimeMs).toBeLessThan(3000);
267
+ });
268
+
269
+ test('3 components, filter on one', async () => {
270
+ const result = await runBenchmark(
271
+ '3 components, filter on one',
272
+ datasetSize,
273
+ () => new Query()
274
+ .with(BenchUser, {
275
+ filters: [Query.filter('age', FilterOp.GTE, 30)]
276
+ })
277
+ .with(BenchProfile)
278
+ .with(BenchSettings)
279
+ .take(100)
280
+ .exec()
281
+ );
282
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
283
+ expect(result.avgTimeMs).toBeLessThan(3000);
284
+ });
285
+
286
+ test('3 components, filters on all', async () => {
287
+ const result = await runBenchmark(
288
+ '3 components, filters on all',
289
+ datasetSize,
290
+ () => new Query()
291
+ .with(BenchUser, {
292
+ filters: [Query.filter('status', FilterOp.EQ, 'active')]
293
+ })
294
+ .with(BenchProfile, {
295
+ filters: [Query.filter('verified', FilterOp.EQ, true)]
296
+ })
297
+ .with(BenchSettings, {
298
+ filters: [Query.filter('theme', FilterOp.EQ, 'dark')]
299
+ })
300
+ .take(100)
301
+ .exec()
302
+ );
303
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
304
+ expect(result.avgTimeMs).toBeLessThan(3000);
305
+ });
306
+ });
307
+
308
+ describe('Sorting with multi-component (affected by fix)', () => {
309
+ test('2 components, sort on first', async () => {
310
+ const result = await runBenchmark(
311
+ '2 components, sort on first',
312
+ datasetSize,
313
+ () => new Query()
314
+ .with(BenchUser)
315
+ .with(BenchProfile)
316
+ .sortBy(BenchUser, 'age', 'DESC')
317
+ .take(100)
318
+ .exec()
319
+ );
320
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
321
+ expect(result.avgTimeMs).toBeLessThan(3000);
322
+ });
323
+
324
+ test('2 components, filter + sort on different components', async () => {
325
+ const result = await runBenchmark(
326
+ '2 components, filter + sort different',
327
+ datasetSize,
328
+ () => new Query()
329
+ .with(BenchUser)
330
+ .with(BenchProfile, {
331
+ filters: [Query.filter('verified', FilterOp.EQ, true)]
332
+ })
333
+ .sortBy(BenchUser, 'age', 'ASC')
334
+ .take(100)
335
+ .exec()
336
+ );
337
+ console.log(` ${result.name}: ${result.avgTimeMs.toFixed(2)}ms avg (${result.resultCount} results)`);
338
+ expect(result.avgTimeMs).toBeLessThan(3000);
339
+ });
340
+ });
341
+
342
+ describe('Count operations', () => {
343
+ test('2 components count with filter', async () => {
344
+ const times: number[] = [];
345
+ let count = 0;
346
+
347
+ for (let i = 0; i < ITERATIONS; i++) {
348
+ const start = performance.now();
349
+ count = await new Query()
350
+ .with(BenchUser, {
351
+ filters: [Query.filter('status', FilterOp.EQ, 'active')]
352
+ })
353
+ .with(BenchProfile)
354
+ .count();
355
+ const end = performance.now();
356
+ times.push(end - start);
357
+ }
358
+
359
+ const avgTime = times.reduce((a, b) => a + b, 0) / times.length;
360
+ console.log(` 2 components count with filter: ${avgTime.toFixed(2)}ms avg (count: ${count})`);
361
+ expect(avgTime).toBeLessThan(2000);
362
+ });
363
+ });
364
+
365
+ test('Performance summary', () => {
366
+ console.log('\n📈 Benchmark Summary:');
367
+ console.log(` Dataset size: ${datasetSize} entities`);
368
+ console.log(` Iterations per query: ${ITERATIONS}`);
369
+ console.log(' All queries completed within acceptable thresholds');
370
+ expect(true).toBe(true);
371
+ });
372
+ });
@@ -0,0 +1,595 @@
1
+ /**
2
+ * Edge case tests for Query SQL generation
3
+ * These tests verify that various edge cases don't produce invalid SQL
4
+ */
5
+ import { describe, test, expect, beforeAll, beforeEach } from 'bun:test';
6
+ import { Entity } from '../../../core/Entity';
7
+ import { Query, FilterOp } from '../../../query/Query';
8
+ import { TestUser, TestProduct, TestOrder } from '../../fixtures/components';
9
+ import { createTestContext, ensureComponentsRegistered } from '../../utils';
10
+
11
+ describe('Query Edge Cases', () => {
12
+ const ctx = createTestContext();
13
+
14
+ beforeAll(async () => {
15
+ await ensureComponentsRegistered(TestUser, TestProduct, TestOrder);
16
+ });
17
+
18
+ describe('IN/NOT IN operator edge cases', () => {
19
+ beforeEach(async () => {
20
+ // Create test data
21
+ const entity = ctx.tracker.create();
22
+ entity.add(TestUser, { name: 'InTest', email: 'in@test.com', age: 25 });
23
+ await entity.save();
24
+ });
25
+
26
+ test('IN with single element array works', async () => {
27
+ const results = await new Query()
28
+ .with(TestUser, {
29
+ filters: [Query.filter('name', FilterOp.IN, ['InTest'])]
30
+ })
31
+ .exec();
32
+
33
+ expect(results.length).toBeGreaterThanOrEqual(1);
34
+ });
35
+
36
+ test('IN with multiple elements works', async () => {
37
+ const results = await new Query()
38
+ .with(TestUser, {
39
+ filters: [Query.filter('name', FilterOp.IN, ['InTest', 'Other', 'Another'])]
40
+ })
41
+ .exec();
42
+
43
+ expect(results.length).toBeGreaterThanOrEqual(1);
44
+ });
45
+
46
+ test('IN with empty array returns no results (not SQL error)', async () => {
47
+ const results = await new Query()
48
+ .with(TestUser, {
49
+ filters: [Query.filter('name', FilterOp.IN, [])]
50
+ })
51
+ .exec();
52
+
53
+ // Empty IN should return no results, not throw SQL error
54
+ expect(results.length).toBe(0);
55
+ });
56
+
57
+ test('NOT IN with empty array returns all results (not SQL error)', async () => {
58
+ const allResults = await new Query()
59
+ .with(TestUser)
60
+ .exec();
61
+
62
+ const notInResults = await new Query()
63
+ .with(TestUser, {
64
+ filters: [Query.filter('name', FilterOp.NOT_IN, [])]
65
+ })
66
+ .exec();
67
+
68
+ // Empty NOT IN should return all results (nothing excluded)
69
+ expect(notInResults.length).toBe(allResults.length);
70
+ });
71
+
72
+ test('NOT IN with single element works', async () => {
73
+ const results = await new Query()
74
+ .with(TestUser, {
75
+ filters: [Query.filter('name', FilterOp.NOT_IN, ['InTest'])]
76
+ })
77
+ .exec();
78
+
79
+ // Should not include 'InTest'
80
+ const hasInTest = results.some(e => e.getInMemory(TestUser)?.name === 'InTest');
81
+ expect(hasInTest).toBe(false);
82
+ });
83
+
84
+ test('IN combined with other filters works', async () => {
85
+ const results = await new Query()
86
+ .with(TestUser, {
87
+ filters: [
88
+ Query.filter('name', FilterOp.IN, ['InTest', 'Other']),
89
+ Query.filter('age', FilterOp.GTE, 18)
90
+ ]
91
+ })
92
+ .exec();
93
+
94
+ expect(Array.isArray(results)).toBe(true);
95
+ });
96
+ });
97
+
98
+ describe('Multi-component query edge cases', () => {
99
+ beforeEach(async () => {
100
+ // Create entity with multiple components
101
+ const entity = ctx.tracker.create();
102
+ entity.add(TestUser, { name: 'MultiComp', email: 'multi@test.com', age: 30 });
103
+ entity.add(TestProduct, { sku: 'MULTI-SKU', name: 'Multi Product', price: 100, inStock: true });
104
+ await entity.save();
105
+
106
+ // Create entity with only user
107
+ const userOnly = ctx.tracker.create();
108
+ userOnly.add(TestUser, { name: 'UserOnly', email: 'useronly@test.com', age: 25 });
109
+ await userOnly.save();
110
+ });
111
+
112
+ test('two components with no filters works', async () => {
113
+ const results = await new Query()
114
+ .with(TestUser)
115
+ .with(TestProduct)
116
+ .exec();
117
+
118
+ expect(Array.isArray(results)).toBe(true);
119
+ });
120
+
121
+ test('two components with filter on first works', async () => {
122
+ const results = await new Query()
123
+ .with(TestUser, {
124
+ filters: [Query.filter('name', FilterOp.EQ, 'MultiComp')]
125
+ })
126
+ .with(TestProduct)
127
+ .exec();
128
+
129
+ expect(Array.isArray(results)).toBe(true);
130
+ });
131
+
132
+ test('two components with filter on second works', async () => {
133
+ const results = await new Query()
134
+ .with(TestUser)
135
+ .with(TestProduct, {
136
+ filters: [Query.filter('sku', FilterOp.EQ, 'MULTI-SKU')]
137
+ })
138
+ .exec();
139
+
140
+ expect(Array.isArray(results)).toBe(true);
141
+ });
142
+
143
+ test('two components with filters on both works', async () => {
144
+ const results = await new Query()
145
+ .with(TestUser, {
146
+ filters: [Query.filter('name', FilterOp.EQ, 'MultiComp')]
147
+ })
148
+ .with(TestProduct, {
149
+ filters: [Query.filter('price', FilterOp.GTE, 50)]
150
+ })
151
+ .exec();
152
+
153
+ expect(Array.isArray(results)).toBe(true);
154
+ });
155
+
156
+ test('three components with mixed filters works', async () => {
157
+ // Add order to existing entity
158
+ const entity = ctx.tracker.create();
159
+ entity.add(TestUser, { name: 'TripleComp', email: 'triple@test.com', age: 35 });
160
+ entity.add(TestProduct, { sku: 'TRIPLE-SKU', name: 'Triple Product', price: 200, inStock: true });
161
+ entity.add(TestOrder, { orderNumber: 'ORD-TRIPLE', status: 'pending', total: 200 });
162
+ await entity.save();
163
+
164
+ const results = await new Query()
165
+ .with(TestUser, {
166
+ filters: [Query.filter('age', FilterOp.GTE, 18)]
167
+ })
168
+ .with(TestProduct)
169
+ .with(TestOrder, {
170
+ filters: [Query.filter('status', FilterOp.EQ, 'pending')]
171
+ })
172
+ .exec();
173
+
174
+ expect(Array.isArray(results)).toBe(true);
175
+ });
176
+ });
177
+
178
+ describe('Sorting edge cases', () => {
179
+ beforeEach(async () => {
180
+ // Create entities with various ages
181
+ for (const age of [20, 30, 40]) {
182
+ const entity = ctx.tracker.create();
183
+ entity.add(TestUser, {
184
+ name: `SortEdge${age}`,
185
+ email: `sortedge${age}@test.com`,
186
+ age
187
+ });
188
+ await entity.save();
189
+ }
190
+ });
191
+
192
+ test('sort with no filters works', async () => {
193
+ const results = await new Query()
194
+ .with(TestUser)
195
+ .sortBy(TestUser, 'age', 'ASC')
196
+ .exec();
197
+
198
+ expect(Array.isArray(results)).toBe(true);
199
+ });
200
+
201
+ test('sort with filter on same component works', async () => {
202
+ const results = await new Query()
203
+ .with(TestUser, {
204
+ filters: [Query.filter('email', FilterOp.LIKE, 'sortedge%')]
205
+ })
206
+ .sortBy(TestUser, 'age', 'DESC')
207
+ .populate()
208
+ .exec();
209
+
210
+ expect(Array.isArray(results)).toBe(true);
211
+ // Verify sort order
212
+ for (let i = 1; i < results.length; i++) {
213
+ const prevAge = results[i - 1]!.getInMemory(TestUser)?.age ?? 0;
214
+ const currAge = results[i]!.getInMemory(TestUser)?.age ?? 0;
215
+ expect(currAge).toBeLessThanOrEqual(prevAge);
216
+ }
217
+ });
218
+
219
+ test('sort on component different from filter works', async () => {
220
+ // Create entity with both components
221
+ const entity = ctx.tracker.create();
222
+ entity.add(TestUser, { name: 'SortDiffComp', email: 'sortdiff@test.com', age: 50 });
223
+ entity.add(TestProduct, { sku: 'SORT-DIFF', name: 'Sort Product', price: 75, inStock: true });
224
+ await entity.save();
225
+
226
+ const results = await new Query()
227
+ .with(TestUser)
228
+ .with(TestProduct, {
229
+ filters: [Query.filter('price', FilterOp.GTE, 50)]
230
+ })
231
+ .sortBy(TestUser, 'age', 'ASC')
232
+ .exec();
233
+
234
+ expect(Array.isArray(results)).toBe(true);
235
+ });
236
+
237
+ test('multi-component query with sort works', async () => {
238
+ const entity = ctx.tracker.create();
239
+ entity.add(TestUser, { name: 'MultiSort', email: 'multisort@test.com', age: 28 });
240
+ entity.add(TestProduct, { sku: 'MULTI-SORT', name: 'MultiSort Product', price: 150, inStock: true });
241
+ await entity.save();
242
+
243
+ const results = await new Query()
244
+ .with(TestUser)
245
+ .with(TestProduct)
246
+ .sortBy(TestProduct, 'price', 'DESC')
247
+ .exec();
248
+
249
+ expect(Array.isArray(results)).toBe(true);
250
+ });
251
+ });
252
+
253
+ describe('Exclusion edge cases', () => {
254
+ test('without() with no matching entities works', async () => {
255
+ const entity = ctx.tracker.create();
256
+ entity.add(TestUser, { name: 'WithoutTest', email: 'without@test.com', age: 22 });
257
+ await entity.save();
258
+
259
+ const results = await new Query()
260
+ .with(TestUser)
261
+ .without(TestOrder) // This entity doesn't have TestOrder
262
+ .exec();
263
+
264
+ expect(results.some(e => e.id === entity.id)).toBe(true);
265
+ });
266
+
267
+ test('excludeEntityId with non-existent ID works', async () => {
268
+ const results = await new Query()
269
+ .with(TestUser)
270
+ .excludeEntityId('00000000-0000-0000-0000-000000000000')
271
+ .exec();
272
+
273
+ expect(Array.isArray(results)).toBe(true);
274
+ });
275
+
276
+ test('multiple excludeEntityId calls work', async () => {
277
+ const entity1 = ctx.tracker.create();
278
+ entity1.add(TestUser, { name: 'Exclude1', email: 'exclude1@test.com', age: 30 });
279
+ await entity1.save();
280
+
281
+ const entity2 = ctx.tracker.create();
282
+ entity2.add(TestUser, { name: 'Exclude2', email: 'exclude2@test.com', age: 31 });
283
+ await entity2.save();
284
+
285
+ const results = await new Query()
286
+ .with(TestUser)
287
+ .excludeEntityId(entity1.id)
288
+ .excludeEntityId(entity2.id)
289
+ .exec();
290
+
291
+ expect(results.some(e => e.id === entity1.id)).toBe(false);
292
+ expect(results.some(e => e.id === entity2.id)).toBe(false);
293
+ });
294
+
295
+ test('without() combined with filters works', async () => {
296
+ const results = await new Query()
297
+ .with(TestUser, {
298
+ filters: [Query.filter('age', FilterOp.GTE, 18)]
299
+ })
300
+ .without(TestProduct)
301
+ .exec();
302
+
303
+ expect(Array.isArray(results)).toBe(true);
304
+ });
305
+ });
306
+
307
+ describe('Pagination edge cases', () => {
308
+ test('limit 0 returns empty array', async () => {
309
+ const results = await new Query()
310
+ .with(TestUser)
311
+ .take(0)
312
+ .exec();
313
+
314
+ expect(results.length).toBe(0);
315
+ });
316
+
317
+ test('offset larger than result set returns empty', async () => {
318
+ const count = await new Query().with(TestUser).count();
319
+
320
+ const results = await new Query()
321
+ .with(TestUser)
322
+ .offset(count + 100)
323
+ .take(10)
324
+ .exec();
325
+
326
+ expect(results.length).toBe(0);
327
+ });
328
+
329
+ test('pagination with filters works', async () => {
330
+ const results = await new Query()
331
+ .with(TestUser, {
332
+ filters: [Query.filter('age', FilterOp.GTE, 18)]
333
+ })
334
+ .take(5)
335
+ .offset(0)
336
+ .exec();
337
+
338
+ expect(results.length).toBeLessThanOrEqual(5);
339
+ });
340
+
341
+ test('pagination with sort works', async () => {
342
+ const results = await new Query()
343
+ .with(TestUser)
344
+ .sortBy(TestUser, 'age', 'ASC')
345
+ .take(5)
346
+ .offset(0)
347
+ .exec();
348
+
349
+ expect(results.length).toBeLessThanOrEqual(5);
350
+ });
351
+
352
+ test('pagination with multi-component query works', async () => {
353
+ const results = await new Query()
354
+ .with(TestUser)
355
+ .with(TestProduct)
356
+ .take(5)
357
+ .offset(0)
358
+ .exec();
359
+
360
+ expect(Array.isArray(results)).toBe(true);
361
+ });
362
+ });
363
+
364
+ describe('Boolean filter edge cases', () => {
365
+ beforeEach(async () => {
366
+ const inStock = ctx.tracker.create();
367
+ inStock.add(TestProduct, { sku: 'BOOL-IN', name: 'In Stock', price: 50, inStock: true });
368
+ await inStock.save();
369
+
370
+ const outOfStock = ctx.tracker.create();
371
+ outOfStock.add(TestProduct, { sku: 'BOOL-OUT', name: 'Out of Stock', price: 50, inStock: false });
372
+ await outOfStock.save();
373
+ });
374
+
375
+ test('boolean true filter works', async () => {
376
+ const results = await new Query()
377
+ .with(TestProduct, {
378
+ filters: [Query.filter('inStock', FilterOp.EQ, true)]
379
+ })
380
+ .populate()
381
+ .exec();
382
+
383
+ for (const entity of results) {
384
+ const product = entity.getInMemory(TestProduct);
385
+ if (product) {
386
+ expect(product.inStock).toBe(true);
387
+ }
388
+ }
389
+ });
390
+
391
+ test('boolean false filter works', async () => {
392
+ const results = await new Query()
393
+ .with(TestProduct, {
394
+ filters: [Query.filter('inStock', FilterOp.EQ, false)]
395
+ })
396
+ .populate()
397
+ .exec();
398
+
399
+ for (const entity of results) {
400
+ const product = entity.getInMemory(TestProduct);
401
+ if (product) {
402
+ expect(product.inStock).toBe(false);
403
+ }
404
+ }
405
+ });
406
+ });
407
+
408
+ describe('Numeric filter edge cases', () => {
409
+ test('zero value filter works', async () => {
410
+ const entity = ctx.tracker.create();
411
+ entity.add(TestProduct, { sku: 'ZERO-PRICE', name: 'Free Product', price: 0, inStock: true });
412
+ await entity.save();
413
+
414
+ const results = await new Query()
415
+ .with(TestProduct, {
416
+ filters: [Query.filter('price', FilterOp.EQ, 0)]
417
+ })
418
+ .exec();
419
+
420
+ expect(results.length).toBeGreaterThanOrEqual(1);
421
+ });
422
+
423
+ test('negative value filter works', async () => {
424
+ const entity = ctx.tracker.create();
425
+ entity.add(TestUser, { name: 'NegAge', email: 'neg@test.com', age: -1 });
426
+ await entity.save();
427
+
428
+ const results = await new Query()
429
+ .with(TestUser, {
430
+ filters: [Query.filter('age', FilterOp.LT, 0)]
431
+ })
432
+ .exec();
433
+
434
+ expect(results.length).toBeGreaterThanOrEqual(1);
435
+ });
436
+
437
+ test('large number filter works', async () => {
438
+ const entity = ctx.tracker.create();
439
+ entity.add(TestProduct, { sku: 'LARGE-PRICE', name: 'Expensive', price: 999999999, inStock: true });
440
+ await entity.save();
441
+
442
+ const results = await new Query()
443
+ .with(TestProduct, {
444
+ filters: [Query.filter('price', FilterOp.GTE, 999999999)]
445
+ })
446
+ .exec();
447
+
448
+ expect(results.length).toBeGreaterThanOrEqual(1);
449
+ });
450
+ });
451
+
452
+ describe('String filter edge cases', () => {
453
+ test('LIKE with special characters works', async () => {
454
+ const entity = ctx.tracker.create();
455
+ entity.add(TestUser, { name: 'Test%User', email: 'special@test.com', age: 25 });
456
+ await entity.save();
457
+
458
+ // Note: % in LIKE is a wildcard, so this tests the pattern matching
459
+ const results = await new Query()
460
+ .with(TestUser, {
461
+ filters: [Query.filter('email', FilterOp.LIKE, '%special@test.com')]
462
+ })
463
+ .exec();
464
+
465
+ expect(results.length).toBeGreaterThanOrEqual(1);
466
+ });
467
+
468
+ test('ILIKE case-insensitive filter works', async () => {
469
+ const entity = ctx.tracker.create();
470
+ entity.add(TestUser, { name: 'CaseTest', email: 'UPPERCASE@TEST.COM', age: 25 });
471
+ await entity.save();
472
+
473
+ const results = await new Query()
474
+ .with(TestUser, {
475
+ filters: [Query.filter('email', FilterOp.ILIKE, '%uppercase@test.com%')]
476
+ })
477
+ .exec();
478
+
479
+ expect(results.length).toBeGreaterThanOrEqual(1);
480
+ });
481
+ });
482
+
483
+ describe('Bug reproduction: 2 components, 1 filter, LATERAL joins', () => {
484
+ // This is the exact pattern from the bug report:
485
+ // new Query().with(UserTag).with(PhoneComponent, Query.filters(...)).take(1).exec()
486
+
487
+ test('exact bug pattern: 2 components, filter on second, take(1)', async () => {
488
+ const entity = ctx.tracker.create();
489
+ entity.add(TestUser, { name: 'BugRepro', email: 'bug@test.com', age: 30 });
490
+ entity.add(TestProduct, { sku: 'BUG-SKU', name: 'Bug Product', price: 100, inStock: true });
491
+ await entity.save();
492
+
493
+ // This is the exact failing pattern
494
+ const results = await new Query()
495
+ .with(TestUser)
496
+ .with(TestProduct, {
497
+ filters: [Query.filter('sku', FilterOp.EQ, 'BUG-SKU')]
498
+ })
499
+ .take(1)
500
+ .exec();
501
+
502
+ expect(Array.isArray(results)).toBe(true);
503
+ expect(results.length).toBeLessThanOrEqual(1);
504
+ });
505
+
506
+ test('verify SQL is valid for bug pattern', async () => {
507
+ const entity = ctx.tracker.create();
508
+ entity.add(TestUser, { name: 'SQLVerify', email: 'sql@test.com', age: 25 });
509
+ entity.add(TestProduct, { sku: 'SQL-SKU', name: 'SQL Product', price: 50, inStock: true });
510
+ await entity.save();
511
+
512
+ // Should not throw SQL syntax error
513
+ const results = await new Query()
514
+ .with(TestUser)
515
+ .with(TestProduct, {
516
+ filters: [Query.filter('name', FilterOp.LIKE, '%SQL%')]
517
+ })
518
+ .take(10)
519
+ .exec();
520
+
521
+ expect(Array.isArray(results)).toBe(true);
522
+ });
523
+ });
524
+
525
+ describe('Combined complex queries', () => {
526
+ test('all features combined works', async () => {
527
+ // Create test data
528
+ const entity = ctx.tracker.create();
529
+ entity.add(TestUser, { name: 'ComplexTest', email: 'complex@test.com', age: 30 });
530
+ entity.add(TestProduct, { sku: 'COMPLEX-SKU', name: 'Complex Product', price: 100, inStock: true });
531
+ await entity.save();
532
+
533
+ // Query with everything
534
+ const results = await new Query()
535
+ .with(TestUser, {
536
+ filters: [
537
+ Query.filter('age', FilterOp.GTE, 18),
538
+ Query.filter('name', FilterOp.LIKE, 'Complex%')
539
+ ]
540
+ })
541
+ .with(TestProduct, {
542
+ filters: [Query.filter('inStock', FilterOp.EQ, true)]
543
+ })
544
+ .without(TestOrder)
545
+ .sortBy(TestUser, 'age', 'DESC')
546
+ .take(10)
547
+ .offset(0)
548
+ .populate()
549
+ .exec();
550
+
551
+ expect(Array.isArray(results)).toBe(true);
552
+ });
553
+
554
+ test('multi-component with IN filter and sort works', async () => {
555
+ const entity = ctx.tracker.create();
556
+ entity.add(TestUser, { name: 'InSortTest', email: 'insort@test.com', age: 35 });
557
+ entity.add(TestProduct, { sku: 'IN-SORT-SKU', name: 'InSort Product', price: 75, inStock: true });
558
+ await entity.save();
559
+
560
+ const results = await new Query()
561
+ .with(TestUser, {
562
+ filters: [Query.filter('name', FilterOp.IN, ['InSortTest', 'Other'])]
563
+ })
564
+ .with(TestProduct)
565
+ .sortBy(TestProduct, 'price', 'ASC')
566
+ .exec();
567
+
568
+ expect(Array.isArray(results)).toBe(true);
569
+ });
570
+
571
+ test('filters on all components with pagination works', async () => {
572
+ const entity = ctx.tracker.create();
573
+ entity.add(TestUser, { name: 'AllFilters', email: 'allfilters@test.com', age: 40 });
574
+ entity.add(TestProduct, { sku: 'ALL-FILTERS', name: 'All Filters Product', price: 200, inStock: true });
575
+ entity.add(TestOrder, { orderNumber: 'ORD-ALL', status: 'completed', total: 200 });
576
+ await entity.save();
577
+
578
+ const results = await new Query()
579
+ .with(TestUser, {
580
+ filters: [Query.filter('age', FilterOp.GTE, 30)]
581
+ })
582
+ .with(TestProduct, {
583
+ filters: [Query.filter('price', FilterOp.GTE, 100)]
584
+ })
585
+ .with(TestOrder, {
586
+ filters: [Query.filter('status', FilterOp.EQ, 'completed')]
587
+ })
588
+ .take(5)
589
+ .offset(0)
590
+ .exec();
591
+
592
+ expect(Array.isArray(results)).toBe(true);
593
+ });
594
+ });
595
+ });