bunsane 0.1.0 → 0.1.1

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.
Files changed (85) hide show
  1. package/.github/workflows/deploy-docs.yml +57 -0
  2. package/LICENSE.md +1 -1
  3. package/README.md +2 -28
  4. package/TODO.md +8 -1
  5. package/bun.lock +3 -0
  6. package/config/upload.config.ts +135 -0
  7. package/core/App.ts +119 -4
  8. package/core/ArcheType.ts +122 -0
  9. package/core/BatchLoader.ts +100 -0
  10. package/core/ComponentRegistry.ts +4 -3
  11. package/core/Components.ts +2 -2
  12. package/core/Decorators.ts +15 -8
  13. package/core/Entity.ts +159 -12
  14. package/core/EntityCache.ts +15 -0
  15. package/core/EntityHookManager.ts +855 -0
  16. package/core/EntityManager.ts +12 -2
  17. package/core/ErrorHandler.ts +64 -7
  18. package/core/FileValidator.ts +284 -0
  19. package/core/Query.ts +453 -85
  20. package/core/RequestContext.ts +24 -0
  21. package/core/RequestLoaders.ts +65 -0
  22. package/core/SchedulerManager.ts +710 -0
  23. package/core/UploadManager.ts +261 -0
  24. package/core/components/UploadComponent.ts +206 -0
  25. package/core/decorators/EntityHooks.ts +190 -0
  26. package/core/decorators/ScheduledTask.ts +83 -0
  27. package/core/events/EntityLifecycleEvents.ts +177 -0
  28. package/core/processors/ImageProcessor.ts +423 -0
  29. package/core/storage/LocalStorageProvider.ts +290 -0
  30. package/core/storage/StorageProvider.ts +112 -0
  31. package/database/DatabaseHelper.ts +183 -58
  32. package/database/index.ts +1 -1
  33. package/database/sqlHelpers.ts +7 -0
  34. package/docs/README.md +149 -0
  35. package/docs/_coverpage.md +36 -0
  36. package/docs/_sidebar.md +23 -0
  37. package/docs/api/core.md +568 -0
  38. package/docs/api/hooks.md +554 -0
  39. package/docs/api/index.md +222 -0
  40. package/docs/api/query.md +678 -0
  41. package/docs/api/service.md +744 -0
  42. package/docs/core-concepts/archetypes.md +512 -0
  43. package/docs/core-concepts/components.md +498 -0
  44. package/docs/core-concepts/entity.md +314 -0
  45. package/docs/core-concepts/hooks.md +683 -0
  46. package/docs/core-concepts/query.md +588 -0
  47. package/docs/core-concepts/services.md +647 -0
  48. package/docs/examples/code-examples.md +425 -0
  49. package/docs/getting-started.md +337 -0
  50. package/docs/index.html +97 -0
  51. package/examples/hooks/README.md +228 -0
  52. package/examples/hooks/audit-logger.ts +495 -0
  53. package/gql/Generator.ts +56 -34
  54. package/gql/decorators/Upload.ts +176 -0
  55. package/gql/helpers.ts +67 -0
  56. package/gql/index.ts +55 -31
  57. package/gql/types.ts +1 -1
  58. package/index.ts +79 -11
  59. package/package.json +5 -4
  60. package/rest/Generator.ts +3 -0
  61. package/rest/index.ts +22 -0
  62. package/service/Service.ts +1 -1
  63. package/service/ServiceRegistry.ts +10 -6
  64. package/service/index.ts +12 -1
  65. package/tests/bench/insert.bench.ts +59 -0
  66. package/tests/bench/relations.bench.ts +269 -0
  67. package/tests/bench/sorting.bench.ts +415 -0
  68. package/tests/component-hooks.test.ts +1409 -0
  69. package/tests/component.test.ts +205 -0
  70. package/tests/errorHandling.test.ts +155 -0
  71. package/tests/hooks.test.ts +666 -0
  72. package/tests/query-sorting.test.ts +101 -0
  73. package/tests/relations.test.ts +169 -0
  74. package/tests/scheduler.test.ts +724 -0
  75. package/tsconfig.json +35 -34
  76. package/types/graphql.types.ts +87 -0
  77. package/types/hooks.types.ts +141 -0
  78. package/types/scheduler.types.ts +165 -0
  79. package/types/upload.types.ts +184 -0
  80. package/upload/index.ts +140 -0
  81. package/utils/UploadHelper.ts +305 -0
  82. package/utils/cronParser.ts +366 -0
  83. package/utils/errorMessages.ts +151 -0
  84. package/validate-docs.sh +90 -0
  85. package/core/Events.ts +0 -0
package/core/Query.ts CHANGED
@@ -1,31 +1,56 @@
1
- import type { BaseComponent } from "./Components";
1
+ import type { BaseComponent, ComponentDataType } from "./Components";
2
2
  import { Entity } from "./Entity";
3
3
  import ComponentRegistry from "./ComponentRegistry";
4
4
  import { logger } from "./Logger";
5
5
  import { sql } from "bun";
6
6
  import db from "database";
7
7
  import { timed } from "./Decorators";
8
+ import { inList } from "../database/sqlHelpers";
8
9
 
9
10
  export type FilterOperator = "=" | ">" | "<" | ">=" | "<=" | "!=" | "LIKE" | "IN" | "NOT IN";
11
+
12
+ export const FilterOp = {
13
+ EQ: "=" as FilterOperator,
14
+ GT: ">" as FilterOperator,
15
+ LT: "<" as FilterOperator,
16
+ GTE: ">=" as FilterOperator,
17
+ LTE: "<=" as FilterOperator,
18
+ NEQ: "!=" as FilterOperator,
19
+ LIKE: "LIKE" as FilterOperator,
20
+ IN: "IN" as FilterOperator,
21
+ NOT_IN: "NOT IN" as FilterOperator
22
+ }
10
23
  export interface QueryFilter {
11
24
  field: string;
12
25
  operator: FilterOperator;
13
26
  value: any;
14
27
  }
15
28
 
16
- export type QueryFilterOptions = {
17
- filters?: QueryFilter[];
18
- };
29
+ export interface QueryFilterOptions {
30
+ filters: QueryFilter[];
31
+ }
32
+
33
+ export type SortDirection = "ASC" | "DESC";
19
34
 
20
- function wrapLog(str: string) {
21
- // console.log(str);
35
+ export interface SortOrder {
36
+ component: string;
37
+ property: string;
38
+ direction: SortDirection;
39
+ nullsFirst?: boolean;
22
40
  }
41
+
23
42
  class Query {
24
43
  private requiredComponents: Set<string> = new Set<string>();
25
44
  private excludedComponents: Set<string> = new Set<string>();
26
45
  private componentFilters: Map<string, QueryFilter[]> = new Map();
27
46
  private populateComponents: boolean = false;
28
47
  private withId: string | null = null;
48
+ private limit: number | null = null;
49
+ private offsetValue: number = 0;
50
+ private eagerComponents: Set<string> = new Set<string>();
51
+ private sortOrders: SortOrder[] = [];
52
+
53
+ static filterOp = FilterOp;
29
54
 
30
55
  public findById(id: string) {
31
56
  this.withId = id;
@@ -51,16 +76,46 @@ class Query {
51
76
  return this;
52
77
  }
53
78
 
54
-
79
+ public eagerLoad<T extends BaseComponent>(ctors: (new (...args: any[]) => T)[]): this {
80
+ for (const ctor of ctors) {
81
+ const type_id = ComponentRegistry.getComponentId(ctor.name);
82
+ if (!type_id) {
83
+ throw new Error(`Component ${ctor.name} is not registered.`);
84
+ }
85
+ this.eagerComponents.add(type_id);
86
+ }
87
+ return this;
88
+ }
89
+
90
+ public eagerLoadComponents(ctors: Array<new () => BaseComponent>): this {
91
+ for (const ctor of ctors) {
92
+ const type_id = ComponentRegistry.getComponentId(ctor.name);
93
+ if (!type_id) {
94
+ throw new Error(`Component ${ctor.name} is not registered.`);
95
+ }
96
+ this.eagerComponents.add(type_id);
97
+ }
98
+ return this;
99
+ }
100
+
55
101
  public static filter(field: string, operator: FilterOperator, value: any): QueryFilter {
56
102
  return { field, operator, value };
57
103
  }
58
104
 
105
+ public static typedFilter<T extends BaseComponent>(
106
+ componentCtor: new (...args: any[]) => T,
107
+ field: keyof ComponentDataType<T>,
108
+ operator: FilterOperator,
109
+ value: any
110
+ ): QueryFilter {
111
+ return { field: field as string, operator, value };
112
+ }
113
+
59
114
  public static filters(...filters: QueryFilter[]): QueryFilterOptions {
60
115
  return { filters };
61
116
  }
62
117
 
63
- private buildFilterCondition(filter: QueryFilter): string {
118
+ private buildFilterCondition(filter: QueryFilter, alias: string, paramIndex: number): { sql: string, params: any[], newParamIndex: number } {
64
119
  const { field, operator, value } = filter;
65
120
  switch (operator) {
66
121
  case "=":
@@ -70,22 +125,22 @@ class Query {
70
125
  case "<=":
71
126
  case "!=":
72
127
  if (typeof value === "string") {
73
- return `data->>'${field}' ${operator} '${value}'`;
128
+ return { sql: `${alias}.data->>'${field}' ${operator} $${paramIndex}`, params: [value], newParamIndex: paramIndex + 1 };
74
129
  } else {
75
- return `(data->>'${field}')::numeric ${operator} ${value}`;
130
+ return { sql: `(${alias}.data->>'${field}')::numeric ${operator} $${paramIndex}`, params: [value], newParamIndex: paramIndex + 1 };
76
131
  }
77
132
  case "LIKE":
78
- return `data->>'${field}' LIKE '${value}'`;
133
+ return { sql: `${alias}.data->>'${field}' LIKE $${paramIndex}`, params: [value], newParamIndex: paramIndex + 1 };
79
134
  case "IN":
80
135
  if (Array.isArray(value)) {
81
- const valueList = value.map(v => typeof v === "string" ? `'${v}'` : v).join(", ");
82
- return `data->>'${field}' IN (${valueList})`;
136
+ const placeholders = Array.from({length: value.length}, (_, i) => `$${paramIndex + i}`).join(', ');
137
+ return { sql: `${alias}.data->>'${field}' IN (${placeholders})`, params: value, newParamIndex: paramIndex + value.length };
83
138
  }
84
139
  throw new Error("IN operator requires an array of values");
85
140
  case "NOT IN":
86
141
  if (Array.isArray(value)) {
87
- const valueList = value.map(v => typeof v === "string" ? `'${v}'` : v).join(", ");
88
- return `data->>'${field}' NOT IN (${valueList})`;
142
+ const placeholders = Array.from({length: value.length}, (_, i) => `$${paramIndex + i}`).join(', ');
143
+ return { sql: `${alias}.data->>'${field}' NOT IN (${placeholders})`, params: value, newParamIndex: paramIndex + value.length };
89
144
  }
90
145
  throw new Error("NOT IN operator requires an array of values");
91
146
  default:
@@ -93,11 +148,20 @@ class Query {
93
148
  }
94
149
  }
95
150
 
96
- private buildFilterWhereClause(typeId: string, filters: QueryFilter[]): string {
97
- if (filters.length === 0) return "";
151
+ private buildFilterWhereClause(typeId: string, filters: QueryFilter[], alias: string, paramIndex: number): { sql: string, params: any[], newParamIndex: number } {
152
+ if (filters.length === 0) return { sql: '', params: [], newParamIndex: paramIndex };
98
153
 
99
- const conditions = filters.map(filter => this.buildFilterCondition(filter));
100
- return conditions.join(" AND ");
154
+ const conditions: string[] = [];
155
+ const allParams: any[] = [];
156
+ let currentIndex = paramIndex;
157
+ for (const filter of filters) {
158
+ const { sql, params, newParamIndex } = this.buildFilterCondition(filter, alias, currentIndex);
159
+ conditions.push(sql);
160
+ allParams.push(...params);
161
+ currentIndex = newParamIndex;
162
+ }
163
+ const sql = conditions.join(' AND ');
164
+ return { sql, params: allParams, newParamIndex: currentIndex };
101
165
  }
102
166
 
103
167
 
@@ -115,7 +179,61 @@ class Query {
115
179
  return this;
116
180
  }
117
181
 
118
- @timed
182
+ public take(limit: number): this {
183
+ this.limit = limit;
184
+ return this;
185
+ }
186
+
187
+ public offset(offset: number): this {
188
+ this.offsetValue = offset;
189
+ return this;
190
+ }
191
+
192
+ public sortBy<T extends BaseComponent>(
193
+ componentCtor: new (...args: any[]) => T,
194
+ property: keyof ComponentDataType<T>,
195
+ direction: SortDirection = "ASC",
196
+ nullsFirst: boolean = false
197
+ ): this {
198
+ const componentName = componentCtor.name;
199
+ const typeId = ComponentRegistry.getComponentId(componentName);
200
+
201
+ if (!typeId) {
202
+ throw new Error(`Component ${componentName} is not registered.`);
203
+ }
204
+
205
+ // Validate that the component is required in this query
206
+ if (!this.requiredComponents.has(typeId)) {
207
+ throw new Error(`Cannot sort by component ${componentName} that is not included in the query. Use .with(${componentName}) first.`);
208
+ }
209
+
210
+ this.sortOrders.push({
211
+ component: componentName,
212
+ property: property as string,
213
+ direction,
214
+ nullsFirst
215
+ });
216
+
217
+ return this;
218
+ }
219
+
220
+ public orderBy(orders: SortOrder[]): this {
221
+ // Validate each sort order
222
+ for (const order of orders) {
223
+ const typeId = ComponentRegistry.getComponentId(order.component);
224
+ if (!typeId) {
225
+ throw new Error(`Component ${order.component} is not registered.`);
226
+ }
227
+ if (!this.requiredComponents.has(typeId)) {
228
+ throw new Error(`Cannot sort by component ${order.component} that is not included in the query. Use .with(${order.component}) first.`);
229
+ }
230
+ }
231
+
232
+ this.sortOrders = orders;
233
+ return this;
234
+ }
235
+
236
+ @timed("Query.exec")
119
237
  public async exec(): Promise<Entity[]> {
120
238
  const componentIds = Array.from(this.requiredComponents);
121
239
  const excludedIds = Array.from(this.excludedComponents);
@@ -131,67 +249,120 @@ class Query {
131
249
  case !hasRequired && !hasExcluded && !hasWithId:
132
250
  return [];
133
251
  case !hasRequired && !hasExcluded && hasWithId:
134
- const result = await db`SELECT id FROM entities WHERE id = ${this.withId!}`;
252
+ let query = db`SELECT id FROM entities WHERE id = ${this.withId} AND deleted_at IS NULL ORDER BY id`;
253
+ if (this.limit !== null) {
254
+ query = db`${query} LIMIT ${this.limit}`;
255
+ }
256
+ if (this.offsetValue > 0) {
257
+ query = db`${query} OFFSET ${this.offsetValue}`;
258
+ }
259
+ const result = await query;
135
260
  ids = result.map((row: any) => row.id);
136
261
  break;
137
262
  case hasRequired && hasExcluded && hasFilters:
138
- ids = await this.getIdsWithFiltersAndExclusions(componentIds, excludedIds, componentCount);
263
+ ids = await this.getIdsWithFiltersAndExclusions(componentIds, excludedIds, componentCount, this.limit, this.offsetValue);
139
264
  break;
140
265
  case hasRequired && hasExcluded:
141
- const componentIdsString = componentIds.map(id => `'${id}'`).join(', ');
142
- const excludedIdsString = excludedIds.map(id => `'${id}'`).join(', ');
143
- const excludedQuery = `
266
+ const componentIdsString = inList(componentIds, 1);
267
+ const excludedIdsString = inList(excludedIds, componentIdsString.newParamIndex);
268
+ let excludedQuery = db`
144
269
  SELECT ec.entity_id as id
145
270
  FROM entity_components ec
146
- WHERE ec.type_id IN (${componentIdsString})
147
- ${this.withId ? `AND ec.entity_id = '${this.withId}'` : ''}
271
+ WHERE ec.type_id IN ${db.unsafe(componentIdsString.sql, componentIdsString.params)} AND ec.deleted_at IS NULL
272
+ ${this.withId ? db`AND ec.entity_id = ${this.withId}` : db``}
148
273
  AND NOT EXISTS (
149
274
  SELECT 1 FROM entity_components ec_ex
150
- WHERE ec_ex.entity_id = ec.entity_id AND ec_ex.type_id IN (${excludedIdsString})
275
+ WHERE ec_ex.entity_id = ec.entity_id AND ec_ex.type_id IN ${db.unsafe(excludedIdsString.sql, excludedIdsString.params)} AND ec_ex.deleted_at IS NULL
151
276
  )
152
277
  GROUP BY ec.entity_id
153
278
  HAVING COUNT(DISTINCT ec.type_id) = ${componentCount}
279
+ ORDER BY ec.entity_id
154
280
  `;
155
- wrapLog(`Executing query: ${excludedQuery}`);
156
- const excludedQueryResult = await db.unsafe(excludedQuery);
281
+ if (this.limit !== null) {
282
+ excludedQuery = db`${excludedQuery} LIMIT ${this.limit}`;
283
+ }
284
+ if (this.offsetValue > 0) {
285
+ excludedQuery = db`${excludedQuery} OFFSET ${this.offsetValue}`;
286
+ }
287
+ const excludedQueryResult = await excludedQuery;
157
288
  ids = excludedQueryResult.map((row: any) => row.id);
158
289
  break;
159
290
  case hasRequired && hasFilters:
160
- ids = await this.getIdsWithFilters(componentIds, componentCount);
291
+ ids = await this.getIdsWithFilters(componentIds, componentCount, this.limit, this.offsetValue);
161
292
  break;
162
293
  case hasRequired:
163
- let queryStr: string;
294
+ let queryStr: any;
164
295
  let requiredOnlyQueryResult: any;
165
296
  if (componentCount === 1) {
166
- // Optimize for single component: no need for GROUP BY, HAVING, or DISTINCT
167
- queryStr = `SELECT entity_id as id FROM entity_components WHERE type_id = '${componentIds[0]}' ${this.withId ? `AND entity_id = '${this.withId}'` : ''}`;
168
- wrapLog(`Executing optimized query: ${queryStr}`);
169
- requiredOnlyQueryResult = await db.unsafe(queryStr);
297
+ // Phase 2A: Optimize single component sorting with JOIN
298
+ if (this.sortOrders.length > 0) {
299
+ const typeId = componentIds[0]!;
300
+ const sortExpression = this.buildSortExpressionForSingleComponent(typeId, "c");
301
+ queryStr = db`SELECT DISTINCT ec.entity_id as id ${db.unsafe(sortExpression.select)} FROM entity_components ec JOIN components c ON ec.entity_id = c.entity_id AND c.type_id = ${typeId} AND c.deleted_at IS NULL WHERE ec.type_id = ${typeId} ${this.withId ? db`AND ec.entity_id = ${this.withId}` : db``} AND ec.deleted_at IS NULL ${db.unsafe(sortExpression.orderBy)}`;
302
+ } else {
303
+ queryStr = db`SELECT entity_id as id FROM entity_components WHERE type_id = ${componentIds[0]} ${this.withId ? db`AND entity_id = ${this.withId}` : db``} AND deleted_at IS NULL ORDER BY entity_id`;
304
+ }
305
+ if (this.limit !== null) {
306
+ queryStr = db`${queryStr} LIMIT ${this.limit}`;
307
+ }
308
+ if (this.offsetValue > 0) {
309
+ queryStr = db`${queryStr} OFFSET ${this.offsetValue}`;
310
+ }
311
+ requiredOnlyQueryResult = await queryStr;
170
312
  } else {
171
- queryStr = `SELECT DISTINCT entity_id as id FROM entity_components WHERE type_id IN (${componentIds.map(id => `'${id}'`).join(', ')}) ${this.withId ? `AND entity_id = '${this.withId}'` : ''} GROUP BY entity_id HAVING COUNT(DISTINCT type_id) = ${componentCount}`;
172
- wrapLog(`Executing query: ${queryStr}`);
173
- requiredOnlyQueryResult = await db`
174
- SELECT DISTINCT entity_id as id FROM entity_components
175
- WHERE type_id IN ${sql(componentIds)}
176
- ${this.withId ? sql`AND entity_id = ${this.withId}` : sql``}
177
- GROUP BY entity_id
178
- HAVING COUNT(DISTINCT type_id) = ${componentCount}
179
- `;
313
+ // Phase 2A: Optimize multi-component sorting with JOINs instead of subqueries
314
+ if (this.sortOrders.length > 0) {
315
+ const compIds = inList(componentIds, 1);
316
+ let orderByClause = "ORDER BY ";
317
+ const orderClauses: string[] = [];
318
+
319
+ for (const order of this.sortOrders) {
320
+ const typeId = ComponentRegistry.getComponentId(order.component);
321
+ if (typeId && componentIds.includes(typeId)) {
322
+ const direction = order.direction.toUpperCase();
323
+ const nullsClause = order.nullsFirst ? "NULLS FIRST" : "NULLS LAST";
324
+ // Use JOIN-based sorting instead of subquery
325
+ const subquery = `(SELECT (c.data->>'${order.property}')::numeric FROM components c WHERE c.entity_id = base_query.id AND c.type_id = '${typeId}' AND c.deleted_at IS NULL LIMIT 1)`;
326
+ orderClauses.push(`${subquery} ${direction} ${nullsClause}`);
327
+ }
328
+ }
329
+ orderClauses.push("base_query.id ASC");
330
+ orderByClause += orderClauses.join(", ");
331
+
332
+ queryStr = db`SELECT * FROM (SELECT DISTINCT entity_id as id FROM entity_components WHERE type_id IN ${db.unsafe(compIds.sql, compIds.params)} ${this.withId ? db`AND entity_id = ${this.withId}` : db``} AND deleted_at IS NULL GROUP BY entity_id HAVING COUNT(DISTINCT type_id) = ${componentCount}) base_query ${db.unsafe(orderByClause)}`;
333
+ } else {
334
+ const compIds = inList(componentIds, 1);
335
+ queryStr = db`SELECT DISTINCT entity_id as id FROM entity_components WHERE type_id IN ${db.unsafe(compIds.sql, compIds.params)} ${this.withId ? db`AND entity_id = ${this.withId}` : db``} AND deleted_at IS NULL GROUP BY entity_id HAVING COUNT(DISTINCT type_id) = ${componentCount} ORDER BY entity_id`;
336
+ }
337
+ if (this.limit !== null) {
338
+ queryStr = db`${queryStr} LIMIT ${this.limit}`;
339
+ }
340
+ if (this.offsetValue > 0) {
341
+ queryStr = db`${queryStr} OFFSET ${this.offsetValue}`;
342
+ }
343
+ requiredOnlyQueryResult = await queryStr;
180
344
  }
181
345
  ids = requiredOnlyQueryResult.map((row: any) => row.id);
182
346
  break;
183
347
  case hasExcluded:
184
- const onlyExcludedIdsString = excludedIds.map(id => `'${id}'`).join(', ');
185
- const onlyExcludedQuery = `
348
+ const onlyExcludedIdsString = inList(excludedIds, 1);
349
+ let onlyExcludedQuery = db`
186
350
  SELECT DISTINCT ec.entity_id as id
187
- FROM entity_components ec
188
- WHERE ${this.withId ? `ec.entity_id = '${this.withId}' AND ` : ''} NOT EXISTS (
351
+ FROM entity_components ec
352
+ WHERE ${this.withId ? db`ec.entity_id = ${this.withId} AND ` : db``} NOT EXISTS (
189
353
  SELECT 1 FROM entity_components ec_ex
190
- WHERE ec_ex.entity_id = ec.entity_id AND ec_ex.type_id IN (${onlyExcludedIdsString})
354
+ WHERE ec_ex.entity_id = ec.entity_id AND ec_ex.type_id IN ${db.unsafe(onlyExcludedIdsString.sql, onlyExcludedIdsString.params)} AND ec_ex.deleted_at IS NULL
191
355
  )
356
+ AND ec.deleted_at IS NULL
357
+ ORDER BY ec.entity_id
192
358
  `;
193
- wrapLog(`Executing query: ${onlyExcludedQuery}`);
194
- const onlyExcludedQueryResult = await db.unsafe(onlyExcludedQuery);
359
+ if (this.limit !== null) {
360
+ onlyExcludedQuery = db`${onlyExcludedQuery} LIMIT ${this.limit}`;
361
+ }
362
+ if (this.offsetValue > 0) {
363
+ onlyExcludedQuery = db`${onlyExcludedQuery} OFFSET ${this.offsetValue}`;
364
+ }
365
+ const onlyExcludedQueryResult = await onlyExcludedQuery;
195
366
  ids = onlyExcludedQueryResult.map((row: any) => row.id);
196
367
  break;
197
368
  default:
@@ -229,66 +400,263 @@ class Query {
229
400
  entities[i + 3] = entity;
230
401
  }
231
402
  }
403
+ if (this.eagerComponents.size > 0) {
404
+ await Entity.LoadComponents(entities, Array.from(this.eagerComponents));
405
+ }
232
406
  return entities;
233
407
  }
234
408
  }
235
409
 
236
- private async getIdsWithFilters(componentIds: string[], componentCount: number): Promise<string[]> {
237
- let query = `
238
- SELECT DISTINCT ec.entity_id as id
239
- FROM entity_components ec
240
- `;
241
-
242
- const joins: string[] = [];
243
- const whereConditions: string[] = [`ec.type_id IN (${componentIds.map(id => `'${id}'`).join(', ')})`];
244
- if (this.withId) {
245
- whereConditions.push(`ec.entity_id = '${this.withId}'`);
410
+ private buildOrderByClause(): string {
411
+ if (this.sortOrders.length === 0) {
412
+ return 'ORDER BY ec.entity_id';
246
413
  }
247
-
414
+
415
+ const orderClauses: string[] = [];
416
+ for (const order of this.sortOrders) {
417
+ const typeId = ComponentRegistry.getComponentId(order.component);
418
+ if (!typeId) continue;
419
+
420
+ // For now, assume we have a component alias. In practice, we'd need to map component types to aliases
421
+ // This is a simplified implementation - in a full implementation, we'd need to track aliases per component
422
+ const componentAlias = `c_${typeId}`;
423
+ const direction = order.direction.toUpperCase();
424
+ const nulls = order.nullsFirst ? 'NULLS FIRST' : 'NULLS LAST';
425
+ orderClauses.push(`(${componentAlias}.data->>'${order.property}')::text ${direction} ${nulls}`);
426
+ }
427
+
428
+ // Always include entity_id as final tiebreaker for consistent ordering
429
+ orderClauses.push('ec.entity_id ASC');
430
+
431
+ return `ORDER BY ${orderClauses.join(', ')}`;
432
+ }
433
+
434
+ private buildOrderByClauseWithJoinData(componentIds: string[], joinCount: number): string {
435
+ if (this.sortOrders.length === 0) {
436
+ return `ORDER BY id`;
437
+ }
438
+
439
+ const orderClauses: string[] = [];
440
+
441
+ for (let i = 0; i < this.sortOrders.length; i++) {
442
+ const order = this.sortOrders[i];
443
+ if (!order) continue;
444
+
445
+ const typeId = ComponentRegistry.getComponentId(order.component);
446
+ if (!typeId || !componentIds.includes(typeId)) {
447
+ continue; // Skip if component not in query
448
+ }
449
+
450
+ const direction = order.direction.toUpperCase();
451
+ const nullsClause = order.nullsFirst ? "NULLS FIRST" : "NULLS LAST";
452
+
453
+ // For subquery approach, use correlated subquery for sorting
454
+ const sortExpression = `(SELECT (c.data->>'${order.property}')::numeric FROM components c WHERE c.entity_id = filtered_entities.id AND c.type_id = '${typeId}' AND c.deleted_at IS NULL LIMIT 1)`;
455
+
456
+ orderClauses.push(`${sortExpression} ${direction} ${nullsClause}`);
457
+ }
458
+
459
+ // Always include entity_id as final tiebreaker for consistent ordering
460
+ orderClauses.push(`id ASC`);
461
+
462
+ return `ORDER BY ${orderClauses.join(", ")}`;
463
+ }
464
+
465
+ private buildSortExpressionForSingleComponent(typeId: string, alias: string): { select: string, orderBy: string } {
466
+ if (this.sortOrders.length === 0) {
467
+ return { select: "", orderBy: "ORDER BY ec.entity_id" };
468
+ }
469
+
470
+ const order = this.sortOrders[0]; // For single component, we only support single sort
471
+ if (!order) {
472
+ return { select: "", orderBy: "ORDER BY ec.entity_id" };
473
+ }
474
+
475
+ const direction = order.direction.toUpperCase();
476
+ const nullsClause = order.nullsFirst ? "NULLS FIRST" : "NULLS LAST";
477
+
478
+ const selectExpr = `, (${alias}.data->>'${order.property}')::numeric as sort_val`;
479
+ const orderByExpr = `ORDER BY sort_val ${direction} ${nullsClause}, ec.entity_id ASC`;
480
+
481
+ return { select: selectExpr, orderBy: orderByExpr };
482
+ }
483
+
484
+ private async getIdsWithFilters(componentIds: string[], componentCount: number, limit?: number | null, offset?: number): Promise<string[]> {
485
+ let params: any[] = [];
486
+ let paramIndex = 1;
487
+ const compIds = inList(componentIds, paramIndex);
488
+ params.push(...compIds.params);
489
+ paramIndex = compIds.newParamIndex;
490
+
491
+ const joins: string[] = [];
248
492
  let joinIndex = 0;
249
493
  for (const [typeId, filters] of this.componentFilters.entries()) {
250
494
  if (componentIds.includes(typeId)) {
251
495
  const alias = `c${joinIndex}`;
252
- joins.push(`JOIN components ${alias} ON ec.entity_id = ${alias}.entity_id AND ${alias}.type_id = '${typeId}'`);
253
-
254
- const filterCondition = this.buildFilterWhereClause(typeId, filters);
255
- if (filterCondition) {
256
- whereConditions.push(filterCondition.replace(/data->/g, `${alias}.data->`));
257
- }
496
+ joins.push(`JOIN components ${alias} ON ec.entity_id = ${alias}.entity_id AND ${alias}.type_id = $${paramIndex} AND ${alias}.deleted_at IS NULL`);
497
+ params.push(typeId);
498
+ paramIndex++;
258
499
  joinIndex++;
259
500
  }
260
501
  }
261
-
262
- query += joins.join(' ');
263
- query += ` WHERE ${whereConditions.join(' AND ')}`;
264
- query += ` GROUP BY ec.entity_id HAVING COUNT(DISTINCT ec.type_id) = ${componentCount}`;
265
-
266
- wrapLog(`Executing filtered query: ${query}`);
267
- const filteredResult = await db.unsafe(query);
268
- return filteredResult.map((row: any) => row.id);
269
- }
270
502
 
271
- private async getIdsWithFiltersAndExclusions(componentIds: string[], excludedIds: string[], componentCount: number): Promise<string[]> {
503
+ let sql: string;
504
+
505
+ // For sorting, use a CTE approach to avoid GROUP BY conflicts
506
+ if (this.sortOrders.length > 0) {
507
+ let selectColumns = `ec.entity_id as id`;
508
+
509
+ // Add sort columns using window functions
510
+ const sortColumns: string[] = [];
511
+ for (let i = 0; i < this.sortOrders.length; i++) {
512
+ const order = this.sortOrders[i];
513
+ if (!order) continue;
514
+
515
+ const typeId = ComponentRegistry.getComponentId(order.component);
516
+ if (!typeId || !componentIds.includes(typeId)) {
517
+ continue; // Skip if component not in query
518
+ }
519
+
520
+ // Find the join alias for this component
521
+ let sortAlias = '';
522
+ let aliasIndex = 0;
523
+ for (const [filterTypeId, filters] of Array.from(this.componentFilters.entries())) {
524
+ if (componentIds.includes(filterTypeId) && filterTypeId === typeId) {
525
+ sortAlias = `c${aliasIndex}`;
526
+ break;
527
+ }
528
+ if (componentIds.includes(filterTypeId)) {
529
+ aliasIndex++;
530
+ }
531
+ }
532
+
533
+ if (sortAlias) {
534
+ sortColumns.push(`FIRST_VALUE((${sortAlias}.data->>'${order.property}')::numeric) OVER (PARTITION BY ec.entity_id ORDER BY ${sortAlias}.created_at DESC) as sort_val_${i}`);
535
+ }
536
+ }
537
+ if (sortColumns.length > 0) {
538
+ selectColumns += `, ${sortColumns.join(', ')}`;
539
+ }
540
+
541
+ // Use CTE to get filtered entities with sort values
542
+ sql = `WITH filtered_entities AS (
543
+ SELECT ${selectColumns}
544
+ FROM entity_components ec ${joins.join(' ')}
545
+ WHERE ec.type_id IN ${compIds.sql} AND ec.deleted_at IS NULL`;
546
+
547
+ if (this.withId) {
548
+ sql += ` AND ec.entity_id = $${paramIndex}`;
549
+ params.push(this.withId);
550
+ paramIndex++;
551
+ }
552
+
553
+ joinIndex = 0;
554
+ for (const [typeId, filters] of this.componentFilters.entries()) {
555
+ if (componentIds.includes(typeId)) {
556
+ const alias = `c${joinIndex}`;
557
+ const filterConditions = this.buildFilterWhereClause(typeId, filters, alias, paramIndex);
558
+ if (filterConditions.sql) {
559
+ sql += ` AND ${filterConditions.sql}`;
560
+ params.push(...filterConditions.params);
561
+ paramIndex = filterConditions.newParamIndex;
562
+ }
563
+ joinIndex++;
564
+ }
565
+ }
566
+
567
+ sql += `
568
+ )
569
+ SELECT DISTINCT fe.id, ${sortColumns.length > 0 ? sortColumns.map((_, i) => `fe.sort_val_${i}`).join(', ') : ''}
570
+ FROM filtered_entities fe
571
+ WHERE (SELECT COUNT(DISTINCT ec.type_id) FROM entity_components ec WHERE ec.entity_id = fe.id AND ec.deleted_at IS NULL) = $${paramIndex}`;
572
+
573
+ params.push(componentCount);
574
+ paramIndex++;
575
+
576
+ // Build ORDER BY clause using the selected sort values
577
+ const orderClauses: string[] = [];
578
+ for (let i = 0; i < this.sortOrders.length; i++) {
579
+ const order = this.sortOrders[i];
580
+ if (!order) continue;
581
+
582
+ const direction = order.direction.toUpperCase();
583
+ const nullsClause = order.nullsFirst ? "NULLS FIRST" : "NULLS LAST";
584
+ orderClauses.push(`sort_val_${i} ${direction} ${nullsClause}`);
585
+ }
586
+ // Always include entity_id as final tiebreaker for consistent ordering
587
+ orderClauses.push(`id ASC`);
588
+ sql += ` ORDER BY ${orderClauses.join(", ")}`;
589
+ } else {
590
+ // No sorting - use simpler approach
591
+ sql = `SELECT DISTINCT ec.entity_id as id FROM entity_components ec ${joins.join(' ')} WHERE ec.type_id IN ${compIds.sql} AND ec.deleted_at IS NULL`;
592
+
593
+ if (this.withId) {
594
+ sql += ` AND ec.entity_id = $${paramIndex}`;
595
+ params.push(this.withId);
596
+ paramIndex++;
597
+ }
598
+
599
+ joinIndex = 0;
600
+ for (const [typeId, filters] of this.componentFilters.entries()) {
601
+ if (componentIds.includes(typeId)) {
602
+ const alias = `c${joinIndex}`;
603
+ const filterConditions = this.buildFilterWhereClause(typeId, filters, alias, paramIndex);
604
+ if (filterConditions.sql) {
605
+ sql += ` AND ${filterConditions.sql}`;
606
+ params.push(...filterConditions.params);
607
+ paramIndex = filterConditions.newParamIndex;
608
+ }
609
+ joinIndex++;
610
+ }
611
+ }
612
+
613
+ sql += ` GROUP BY ec.entity_id HAVING COUNT(DISTINCT ec.type_id) = $${paramIndex}`;
614
+ params.push(componentCount);
615
+ paramIndex++;
616
+ sql += ` ORDER BY ec.entity_id`;
617
+ }
618
+
619
+ if (limit !== null && limit !== undefined) {
620
+ sql += ` LIMIT $${paramIndex}`;
621
+ params.push(limit);
622
+ paramIndex++;
623
+ }
624
+ if (offset && offset > 0) {
625
+ sql += ` OFFSET $${paramIndex}`;
626
+ params.push(offset);
627
+ paramIndex++;
628
+ }
629
+
630
+ const filteredResult = await db.unsafe(sql, params);
631
+ return filteredResult.map((row: any) => row.id);
632
+ } private async getIdsWithFiltersAndExclusions(componentIds: string[], excludedIds: string[], componentCount: number, limit?: number | null, offset?: number): Promise<string[]> {
272
633
  const entityIds = await this.getIdsWithFilters(componentIds, componentCount);
273
634
 
274
635
  if (entityIds.length === 0) {
275
636
  return [];
276
637
  }
277
638
 
278
- const idsString = entityIds.map(id => `'${id}'`).join(', ');
279
- const excludedString = excludedIds.map(id => `'${id}'`).join(', ');
280
- const query = `
639
+ const idsList = sql(entityIds);
640
+ const excludedList = inList(excludedIds, 1);
641
+ let query = db`
281
642
  WITH entity_list AS (
282
- SELECT unnest(ARRAY[${idsString}]) as id
643
+ SELECT unnest(${idsList}) as id
283
644
  )
284
645
  SELECT el.id
285
646
  FROM entity_list el
286
647
  WHERE NOT EXISTS (
287
648
  SELECT 1 FROM entity_components ec
288
- WHERE ec.entity_id = el.id AND ec.type_id IN (${excludedString})
649
+ WHERE ec.entity_id = el.id AND ec.type_id IN ${db.unsafe(excludedList.sql, excludedList.params)} AND ec.deleted_at IS NULL
289
650
  )
651
+ ORDER BY el.id
290
652
  `;
291
- const exclusionResult = await db.unsafe(query);
653
+ if (limit !== null && limit !== undefined) {
654
+ query = db`${query} LIMIT ${limit}`;
655
+ }
656
+ if (offset && offset > 0) {
657
+ query = db`${query} OFFSET ${offset}`;
658
+ }
659
+ const exclusionResult = await query;
292
660
  return exclusionResult.map((row: any) => row.id);
293
661
  }
294
662
  }