@tstdl/base 0.92.142 → 0.92.144

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 (223) hide show
  1. package/ai/ai-file.service.js +1 -1
  2. package/ai/ai.service.js +3 -3
  3. package/ai/types.d.ts +1 -1
  4. package/api/client/client.d.ts +1 -1
  5. package/api/client/client.js +10 -4
  6. package/api/server/middlewares/content-type.middleware.js +8 -7
  7. package/api/types.js +1 -1
  8. package/authentication/client/authentication.service.js +3 -3
  9. package/authentication/server/authentication-ancillary.service.d.ts +11 -1
  10. package/authentication/server/authentication-ancillary.service.js +1 -1
  11. package/authentication/server/authentication-secret-requirements.validator.js +1 -1
  12. package/authentication/server/authentication.api-controller.js +22 -10
  13. package/authentication/server/authentication.service.d.ts +11 -5
  14. package/authentication/server/authentication.service.js +97 -49
  15. package/authentication/server/drizzle.config.js +2 -2
  16. package/authentication/server/module.js +1 -1
  17. package/cancellation/token.d.ts +2 -2
  18. package/cancellation/token.js +4 -4
  19. package/cookie/cookie.js +2 -2
  20. package/document-management/api/document-management.api.d.ts +122 -24
  21. package/document-management/api/document-management.api.js +17 -0
  22. package/document-management/{server/services → authorization}/document-management-authorization.service.d.ts +7 -7
  23. package/document-management/authorization/document-management-authorization.service.js +2 -0
  24. package/document-management/authorization/index.d.ts +2 -0
  25. package/document-management/authorization/index.js +2 -0
  26. package/document-management/authorization/policies.d.ts +38 -0
  27. package/document-management/authorization/policies.js +2 -0
  28. package/document-management/index.d.ts +1 -0
  29. package/document-management/index.js +1 -0
  30. package/document-management/models/document-assignment-scope.model.d.ts +1 -0
  31. package/document-management/models/document-assignment-scope.model.js +10 -3
  32. package/document-management/models/document-assignment-task.model.d.ts +1 -0
  33. package/document-management/models/document-assignment-task.model.js +8 -2
  34. package/document-management/models/document-category.model.d.ts +1 -0
  35. package/document-management/models/document-category.model.js +7 -1
  36. package/document-management/models/document-collection-assignment.model.d.ts +1 -0
  37. package/document-management/models/document-collection-assignment.model.js +12 -4
  38. package/document-management/models/document-collection.model.d.ts +2 -0
  39. package/document-management/models/document-collection.model.js +8 -2
  40. package/document-management/models/document-management-table.d.ts +3 -1
  41. package/document-management/models/document-management-table.js +2 -2
  42. package/document-management/models/document-property-value.model.d.ts +1 -0
  43. package/document-management/models/document-property-value.model.js +9 -3
  44. package/document-management/models/document-property.model.d.ts +1 -0
  45. package/document-management/models/document-property.model.js +8 -2
  46. package/document-management/models/document-request-collection-assignment.model.d.ts +1 -0
  47. package/document-management/models/document-request-collection-assignment.model.js +12 -4
  48. package/document-management/models/document-request-template.d.ts +1 -0
  49. package/document-management/models/document-request-template.js +6 -1
  50. package/document-management/models/document-request.model.d.ts +1 -0
  51. package/document-management/models/document-request.model.js +10 -1
  52. package/document-management/models/document-requests-template.d.ts +1 -0
  53. package/document-management/models/document-requests-template.js +7 -3
  54. package/document-management/models/document-tag-assignment.model.d.ts +8 -0
  55. package/document-management/models/document-tag-assignment.model.js +40 -0
  56. package/document-management/models/document-tag.model.d.ts +6 -0
  57. package/document-management/models/{document-request-submission.model.js → document-tag.model.js} +14 -18
  58. package/document-management/models/document-type-property.model.d.ts +1 -0
  59. package/document-management/models/document-type-property.model.js +7 -2
  60. package/document-management/models/document-type-validation.model.d.ts +1 -0
  61. package/document-management/models/document-type-validation.model.js +8 -2
  62. package/document-management/models/document-type.model.d.ts +1 -0
  63. package/document-management/models/document-type.model.js +7 -2
  64. package/document-management/models/document-validation-definition.model.d.ts +1 -0
  65. package/document-management/models/document-validation-definition.model.js +7 -2
  66. package/document-management/models/document-validation-execution-related-document.model.d.ts +1 -0
  67. package/document-management/models/document-validation-execution-related-document.model.js +10 -3
  68. package/document-management/models/document-validation-execution.model.d.ts +1 -0
  69. package/document-management/models/document-validation-execution.model.js +9 -3
  70. package/document-management/models/document-workflow.model.d.ts +4 -1
  71. package/document-management/models/document-workflow.model.js +16 -4
  72. package/document-management/models/document.model.d.ts +2 -2
  73. package/document-management/models/document.model.js +9 -8
  74. package/document-management/models/index.d.ts +2 -1
  75. package/document-management/models/index.js +2 -1
  76. package/document-management/server/api/document-management.api.d.ts +4 -1
  77. package/document-management/server/api/document-management.api.js +113 -22
  78. package/document-management/server/configure.d.ts +2 -2
  79. package/document-management/server/configure.js +7 -7
  80. package/document-management/server/drizzle/0000_parallel_mantis.sql +359 -0
  81. package/document-management/server/drizzle/meta/0000_snapshot.json +784 -260
  82. package/document-management/server/drizzle/meta/_journal.json +2 -2
  83. package/document-management/server/module.d.ts +2 -2
  84. package/document-management/server/module.js +2 -2
  85. package/document-management/server/schemas.d.ts +6 -5
  86. package/document-management/server/schemas.js +12 -11
  87. package/document-management/server/services/document-category-type.service.d.ts +19 -10
  88. package/document-management/server/services/document-category-type.service.js +34 -27
  89. package/document-management/server/services/document-collection.service.d.ts +13 -6
  90. package/document-management/server/services/document-collection.service.js +36 -12
  91. package/document-management/server/services/document-file.service.d.ts +8 -7
  92. package/document-management/server/services/document-file.service.js +28 -33
  93. package/document-management/server/services/document-management-ai.service.d.ts +5 -4
  94. package/document-management/server/services/document-management-ai.service.js +51 -28
  95. package/document-management/server/services/document-management-ancillary.service.d.ts +3 -21
  96. package/document-management/server/services/document-management-ancillary.service.js +0 -24
  97. package/document-management/server/services/document-management-observation.service.d.ts +15 -0
  98. package/document-management/server/services/document-management-observation.service.js +160 -0
  99. package/document-management/server/services/document-management.service.d.ts +6 -5
  100. package/document-management/server/services/document-management.service.js +112 -86
  101. package/document-management/server/services/document-property.service.d.ts +15 -7
  102. package/document-management/server/services/document-property.service.js +52 -20
  103. package/document-management/server/services/document-request.service.d.ts +13 -24
  104. package/document-management/server/services/document-request.service.js +39 -62
  105. package/document-management/server/services/document-tag.service.d.ts +10 -0
  106. package/document-management/server/services/document-tag.service.js +59 -0
  107. package/document-management/server/services/document-validation.service.d.ts +8 -8
  108. package/document-management/server/services/document-validation.service.js +41 -40
  109. package/document-management/server/services/document-workflow.service.d.ts +6 -5
  110. package/document-management/server/services/document-workflow.service.js +54 -43
  111. package/document-management/server/services/document.service.d.ts +12 -11
  112. package/document-management/server/services/document.service.js +66 -40
  113. package/document-management/server/services/index.d.ts +2 -1
  114. package/document-management/server/services/index.js +2 -1
  115. package/document-management/server/services/singleton.js +2 -2
  116. package/document-management/server/validators/ai-validation-executor.js +4 -4
  117. package/document-management/service-models/document-collection-metadata.service-model.d.ts +14 -0
  118. package/document-management/service-models/document-collection-metadata.service-model.js +1 -0
  119. package/document-management/service-models/document-folders.view-model.d.ts +1 -7
  120. package/document-management/service-models/document-folders.view-model.js +3 -15
  121. package/document-management/service-models/document-management.view-model.d.ts +20 -6
  122. package/document-management/service-models/document-management.view-model.js +62 -8
  123. package/document-management/service-models/document.service-model.d.ts +14 -11
  124. package/document-management/service-models/document.service-model.js +11 -2
  125. package/document-management/service-models/enriched/enriched-document-assignment.view.d.ts +1 -1
  126. package/document-management/service-models/enriched/enriched-document-assignment.view.js +0 -2
  127. package/document-management/service-models/enriched/enriched-document-category.view.d.ts +11 -1
  128. package/document-management/service-models/enriched/enriched-document-category.view.js +44 -1
  129. package/document-management/service-models/enriched/enriched-document-collection.view.d.ts +4 -2
  130. package/document-management/service-models/enriched/enriched-document-collection.view.js +13 -3
  131. package/document-management/service-models/enriched/enriched-document-management-data.view.d.ts +2 -0
  132. package/document-management/service-models/enriched/enriched-document-management-data.view.js +4 -2
  133. package/document-management/service-models/enriched/enriched-document-request.view.d.ts +1 -0
  134. package/document-management/service-models/enriched/enriched-document-request.view.js +2 -0
  135. package/document-management/service-models/enriched/enriched-document-type.view.d.ts +9 -1
  136. package/document-management/service-models/enriched/enriched-document-type.view.js +28 -1
  137. package/document-management/service-models/enriched/enriched-document.view.d.ts +7 -6
  138. package/document-management/service-models/enriched/enriched-document.view.js +29 -6
  139. package/document-management/service-models/{normalized-requests-template-data.model.d.ts → enriched/enriched-requests-template-data.model.d.ts} +6 -6
  140. package/document-management/service-models/{normalized-requests-template-data.model.js → enriched/enriched-requests-template-data.model.js} +1 -1
  141. package/document-management/service-models/enriched/index.d.ts +1 -0
  142. package/document-management/service-models/enriched/index.js +1 -0
  143. package/document-management/service-models/index.d.ts +2 -2
  144. package/document-management/service-models/index.js +2 -2
  145. package/examples/document-management/categories-and-types.d.ts +33 -31
  146. package/examples/document-management/categories-and-types.js +33 -0
  147. package/examples/document-management/main.d.ts +5 -4
  148. package/examples/document-management/main.js +13 -7
  149. package/function/log.js +2 -2
  150. package/http/server/node/module.d.ts +4 -1
  151. package/http/server/node/module.js +10 -1
  152. package/http/server/node/node-http-server.d.ts +3 -6
  153. package/http/server/node/node-http-server.js +68 -67
  154. package/injector/inject.js +6 -6
  155. package/injector/injector.js +3 -3
  156. package/jsx/is-component-class.js +1 -1
  157. package/key-value-store/key-value.store.d.ts +38 -7
  158. package/key-value-store/key-value.store.js +2 -1
  159. package/key-value-store/mongo/mongo-key-value.store.d.ts +1 -0
  160. package/key-value-store/mongo/mongo-key-value.store.js +14 -5
  161. package/key-value-store/postgres/drizzle/0000_shocking_slipstream.sql +12 -0
  162. package/key-value-store/postgres/drizzle/meta/0000_snapshot.json +97 -0
  163. package/key-value-store/postgres/drizzle/meta/_journal.json +13 -0
  164. package/key-value-store/postgres/drizzle.config.d.ts +2 -0
  165. package/key-value-store/postgres/drizzle.config.js +11 -0
  166. package/key-value-store/postgres/index.d.ts +2 -0
  167. package/key-value-store/postgres/index.js +2 -0
  168. package/key-value-store/postgres/key-value-store.service.d.ts +17 -0
  169. package/key-value-store/postgres/key-value-store.service.js +65 -0
  170. package/key-value-store/postgres/models/index.d.ts +2 -0
  171. package/key-value-store/postgres/models/index.js +2 -0
  172. package/key-value-store/postgres/models/key-value.model.d.ts +7 -0
  173. package/key-value-store/postgres/models/key-value.model.js +35 -0
  174. package/key-value-store/postgres/models/schemas.d.ts +3 -0
  175. package/key-value-store/postgres/models/schemas.js +4 -0
  176. package/key-value-store/postgres/module.d.ts +6 -0
  177. package/key-value-store/postgres/module.js +23 -0
  178. package/lock/web/web-lock.d.ts +0 -1
  179. package/lock/web/web-lock.js +6 -13
  180. package/orm/data-types/timestamp.js +1 -1
  181. package/orm/decorators.d.ts +37 -29
  182. package/orm/decorators.js +44 -24
  183. package/orm/entity.d.ts +1 -0
  184. package/orm/query.d.ts +10 -2
  185. package/orm/repository.types.d.ts +2 -1
  186. package/orm/schemas/json.d.ts +12 -6
  187. package/orm/schemas/json.js +12 -5
  188. package/orm/server/database.js +5 -2
  189. package/orm/server/drizzle/schema-converter.js +40 -11
  190. package/orm/server/query-converter.d.ts +2 -1
  191. package/orm/server/query-converter.js +57 -34
  192. package/orm/server/repository.d.ts +26 -43
  193. package/orm/server/repository.js +106 -39
  194. package/orm/server/transaction.d.ts +2 -1
  195. package/orm/server/transaction.js +3 -0
  196. package/orm/server/transactional.d.ts +5 -1
  197. package/orm/server/transactional.js +34 -4
  198. package/package.json +14 -11
  199. package/process/spawn.js +0 -1
  200. package/promise/deferred-promise.d.ts +4 -3
  201. package/promise/deferred-promise.js +13 -5
  202. package/queue/postgres/queue.js +8 -8
  203. package/reflection/utils.js +3 -3
  204. package/schema/decorators/class.js +0 -1
  205. package/schema/decorators/schema.js +1 -1
  206. package/schema/schemas/boolean.d.ts +1 -1
  207. package/schema/schemas/boolean.js +2 -2
  208. package/schema/schemas/number.js +3 -3
  209. package/schema/schemas/object.js +5 -6
  210. package/sse/server-sent-events-source.js +4 -1
  211. package/utils/compression.js +9 -9
  212. package/utils/date-time.d.ts +1 -0
  213. package/utils/date-time.js +18 -4
  214. package/utils/equals.d.ts +7 -0
  215. package/utils/equals.js +17 -2
  216. package/utils/function/memoize.js +10 -2
  217. package/utils/jwt.js +3 -3
  218. package/utils/object/property-name.d.ts +2 -2
  219. package/utils/timing.d.ts +2 -2
  220. package/utils/timing.js +12 -12
  221. package/document-management/models/document-request-submission.model.d.ts +0 -7
  222. package/document-management/server/drizzle/0000_moaning_luckman.sql +0 -305
  223. package/document-management/server/services/document-management-authorization.service.js +0 -28
@@ -1,5 +1,5 @@
1
1
  import { toCamelCase, toSnakeCase } from 'drizzle-orm/casing';
2
- import { boolean, check, doublePrecision, index, integer, jsonb, pgSchema, primaryKey, text, unique, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
2
+ import { boolean, check, doublePrecision, foreignKey, index, integer, jsonb, pgSchema, primaryKey, text, unique, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
3
3
  import { MultiKeyMap } from '../../../data-structures/multi-key-map.js';
4
4
  import { tryGetEnumName } from '../../../enumeration/enumeration.js';
5
5
  import { NotSupportedError } from '../../../errors/not-supported.error.js';
@@ -66,7 +66,7 @@ export function _getDrizzleTableFromType(type, fallbackSchemaName) {
66
66
  return column;
67
67
  });
68
68
  const indexFn = (data.options?.unique == true) ? uniqueIndex : index;
69
- let builder = indexFn(data.name ?? getIndexName(tableName, columns, { naming: data.options?.naming })).using(data.options?.using ?? 'btree', ...columns);
69
+ let builder = indexFn(data.options?.name ?? getIndexName(tableName, columns, { naming: data.options?.naming })).using(data.options?.using ?? 'btree', ...columns);
70
70
  if (isDefined(data.options?.where)) {
71
71
  const query = convertQuery(data.options.where(table), table, columnDefinitionsMap);
72
72
  builder = builder.where(query.inlineParams());
@@ -94,9 +94,19 @@ export function _getDrizzleTableFromType(type, fallbackSchemaName) {
94
94
  }
95
95
  return buildIndex(table, indexData, columnDefinition.name);
96
96
  }).filter(isDefined)),
97
+ ...tableReflectionDatas.flatMap((tableReflectionData) => {
98
+ return tableReflectionData.foreignKeys?.map((foreignKeyData) => {
99
+ const foreignTable = getDrizzleTableFromType(foreignKeyData.target(), dbSchema.schemaName);
100
+ return foreignKey({
101
+ name: foreignKeyData.options?.name ?? getForeignKeyName(tableName, foreignKeyData.columns, { naming: foreignKeyData.options?.naming }),
102
+ columns: foreignKeyData.columns.map((column) => getColumn(table, column)),
103
+ foreignColumns: foreignKeyData.foreignColumns.map((column) => getColumn(foreignTable, column)),
104
+ });
105
+ }) ?? [];
106
+ }),
97
107
  ...tableReflectionDatas.flatMap((tableReflectionData) => tableReflectionData.unique).filter(isDefined).map((data) => {
98
108
  const columns = data.columns?.map((column) => getColumn(table, column));
99
- let constraint = unique(data.name ?? getUniqueName(tableName, columns, { naming: data.options?.naming })).on(...columns);
109
+ let constraint = unique(data.options?.name ?? getUniqueName(tableName, columns, { naming: data.options?.naming })).on(...columns);
100
110
  if (data.options?.nulls == 'not distinct') {
101
111
  constraint = constraint.nullsNotDistinct();
102
112
  }
@@ -128,7 +138,7 @@ function getPostgresColumnEntries(type, dbSchema, tableName, path = new JsonPath
128
138
  const toDatabase = encrypted
129
139
  ? async (value, context) => {
130
140
  const bytes = encodeUtf8(value);
131
- return encryptBytes(bytes, context.encryptionKey);
141
+ return await encryptBytes(bytes, context.encryptionKey);
132
142
  }
133
143
  : (value) => value;
134
144
  const fromDatabase = encrypted
@@ -175,13 +185,18 @@ function getPostgresColumn(tableName, columnName, dbSchema, propertySchema, refl
175
185
  column = column.notNull();
176
186
  }
177
187
  if (isDefined(reflectionData.unique)) {
178
- column = column.unique(reflectionData.unique.name ?? getUniqueName(tableName, [columnName], { naming: reflectionData.unique.options?.naming }), isString(reflectionData.unique.options?.nulls) ? { nulls: reflectionData.unique.options.nulls } : undefined);
188
+ column = column.unique(reflectionData.unique.options?.name ?? getUniqueName(tableName, [columnName], { naming: reflectionData.unique.options?.naming }), isString(reflectionData.unique.options?.nulls) ? { nulls: reflectionData.unique.options.nulls } : undefined);
179
189
  }
180
190
  if ((reflectionData.primaryKey == true) && (options.skipPrimaryKey != true)) {
181
191
  column = column.primaryKey();
182
192
  }
193
+ for (const { target, targetColumn } of reflectionData.references ?? []) {
194
+ column = column.references(() => {
195
+ const targetTable = getDrizzleTableFromType(target(), dbSchema.schemaName);
196
+ return targetTable[(targetColumn ?? 'id')];
197
+ });
198
+ }
183
199
  if (isDefined(reflectionData.references)) {
184
- column = column.references(() => getDrizzleTableFromType(reflectionData.references(), dbSchema.schemaName).id);
185
200
  }
186
201
  return column;
187
202
  }
@@ -238,10 +253,11 @@ export function getPgEnum(schema, enumeration, context) {
238
253
  const dbSchema = isString(schema) ? getDbSchema(schema) : schema;
239
254
  const enumName = enumNames.get(enumeration) ?? tryGetEnumName(enumeration);
240
255
  if (isUndefined(enumName)) {
256
+ const errorMessage = 'Enum is not registered. Please register it using `databaseSchema.getEnum(MyEnum)` before use.';
241
257
  if (isDefined(context)) {
242
- throw new Error(`Enum is not registered. (type: ${context.type.name}, property: ${context.property})`);
258
+ throw new Error(`${errorMessage} (type: ${context.type.name}, property: ${context.property})`);
243
259
  }
244
- throw new Error('Enum is not registered.');
260
+ throw new Error(errorMessage);
245
261
  }
246
262
  const values = (isArray(enumeration) ? enumeration : enumValues(enumeration))
247
263
  .map((value) => value.toString());
@@ -255,13 +271,26 @@ function getDefaultTableName(type) {
255
271
  return toSnakeCase(isString(type.entityName) ? type.entityName : type.name.replace(/\d+$/u, ''));
256
272
  }
257
273
  function getPrimaryKeyName(tableName, columns, options) {
258
- return `${getTablePrefix(tableName, options?.naming)}_${getColumnNames(columns).join('_')}_pk`;
274
+ return getIdentifier(tableName, columns, 'pk', options);
259
275
  }
260
276
  function getIndexName(tableName, columns, options) {
261
- return `${getTablePrefix(tableName, options?.naming)}_${getColumnNames(columns).join('_')}_idx`;
277
+ return getIdentifier(tableName, columns, 'idx', options);
262
278
  }
263
279
  function getUniqueName(tableName, columns, options) {
264
- return `${getTablePrefix(tableName, options?.naming)}_${getColumnNames(columns).join('_')}_unique`;
280
+ return getIdentifier(tableName, columns, 'unique', options);
281
+ }
282
+ function getForeignKeyName(tableName, columns, options) {
283
+ return getIdentifier(tableName, columns, 'fkey', options);
284
+ }
285
+ function getIdentifier(tableName, columns, suffix, options) {
286
+ const identifier = `${getTablePrefix(tableName, options?.naming)}_${getColumnNames(columns).join('_')}_${suffix}`;
287
+ if (identifier.length > 63) {
288
+ if (options?.naming != 'abbreviated-table') {
289
+ return getIdentifier(tableName, columns, suffix, { naming: 'abbreviated-table' });
290
+ }
291
+ throw new Error(`Identifier "${identifier}" for table "${tableName}" is too long. Maximum length is 63 characters.`);
292
+ }
293
+ return identifier;
265
294
  }
266
295
  function getTablePrefix(tableName, naming) {
267
296
  return (naming == 'abbreviated-table') ? tableName.split('_').map((part) => part[0]).join('') : tableName;
@@ -10,11 +10,12 @@ import type { ColumnDefinition, PgTableFromType } from './types.js';
10
10
  /**
11
11
  * Converts a query object into a Drizzle SQL condition.
12
12
  * Recursively handles nested logical operators and maps property names to database columns.
13
+ * All top-level keys in the query object are implicitly joined with AND.
14
+ *
13
15
  * @param query The query object to convert. Can be a Drizzle SQL object, SQLWrapper, or a custom query object.
14
16
  * @param table The Drizzle table object.
15
17
  * @param columnDefinitionsMap A map from property names to column definitions.
16
18
  * @returns A Drizzle SQL condition representing the query.
17
- * @throws {Error} If multiple logical operators are used at the same level.
18
19
  * @throws {Error} If a property cannot be mapped to a column.
19
20
  * @throws {Error} If an unsupported query type is encountered.
20
21
  */
@@ -7,16 +7,17 @@
7
7
  import { and, eq, gt, gte, inArray, isNotNull, isNull, isSQLWrapper, lt, lte, ne, not, notInArray, or, SQL, sql } from 'drizzle-orm';
8
8
  import { NotSupportedError } from '../../errors/not-supported.error.js';
9
9
  import { hasOwnProperty, objectEntries } from '../../utils/object/object.js';
10
- import { assertDefinedPass, isPrimitive, isRegExp, isString, isUndefined } from '../../utils/type-guards.js';
10
+ import { assertDefinedPass, isDefined, isPrimitive, isRegExp, isString, isUndefined } from '../../utils/type-guards.js';
11
11
  const sqlTrue = sql `true`;
12
12
  /**
13
13
  * Converts a query object into a Drizzle SQL condition.
14
14
  * Recursively handles nested logical operators and maps property names to database columns.
15
+ * All top-level keys in the query object are implicitly joined with AND.
16
+ *
15
17
  * @param query The query object to convert. Can be a Drizzle SQL object, SQLWrapper, or a custom query object.
16
18
  * @param table The Drizzle table object.
17
19
  * @param columnDefinitionsMap A map from property names to column definitions.
18
20
  * @returns A Drizzle SQL condition representing the query.
19
- * @throws {Error} If multiple logical operators are used at the same level.
20
21
  * @throws {Error} If a property cannot be mapped to a column.
21
22
  * @throws {Error} If an unsupported query type is encountered.
22
23
  */
@@ -25,7 +26,7 @@ export function convertQuery(query, table, columnDefinitionsMap) {
25
26
  return query;
26
27
  }
27
28
  if (isSQLWrapper(query)) {
28
- return sql `${query}`;
29
+ return query.getSQL();
29
30
  }
30
31
  const queryEntries = objectEntries(query);
31
32
  if (queryEntries.length == 0) {
@@ -33,42 +34,43 @@ export function convertQuery(query, table, columnDefinitionsMap) {
33
34
  }
34
35
  const conditions = [];
35
36
  for (const [property, value] of queryEntries) {
36
- if (property == '$and') {
37
- if (queryEntries.length > 1) {
38
- throw new Error('only one logical operator per level allowed');
37
+ switch (property) {
38
+ case '$and': {
39
+ const subQueries = value.map((item) => convertQuery(item, table, columnDefinitionsMap));
40
+ const andCondition = and(...subQueries);
41
+ if (isDefined(andCondition)) {
42
+ conditions.push(andCondition);
43
+ }
44
+ break;
39
45
  }
40
- const andQuery = and(...query.$and.map((item) => convertQuery(item, table, columnDefinitionsMap)));
41
- if (isUndefined(andQuery)) {
42
- return sqlTrue;
46
+ case '$or': {
47
+ const subQueries = value.map((item) => convertQuery(item, table, columnDefinitionsMap));
48
+ const orCondition = or(...subQueries);
49
+ if (isDefined(orCondition)) {
50
+ conditions.push(orCondition);
51
+ }
52
+ break;
43
53
  }
44
- return andQuery;
45
- }
46
- if (property == '$or') {
47
- if (queryEntries.length > 1) {
48
- throw new Error('only one logical operator per level allowed');
54
+ case '$nor': {
55
+ const subQueries = value.map((item) => convertQuery(item, table, columnDefinitionsMap));
56
+ const orCondition = or(...subQueries);
57
+ if (isDefined(orCondition)) {
58
+ const norCondition = not(orCondition);
59
+ conditions.push(norCondition);
60
+ }
61
+ break;
49
62
  }
50
- const orQuery = or(...query.$or.map((item) => convertQuery(item, table, columnDefinitionsMap)));
51
- if (isUndefined(orQuery)) {
52
- return sqlTrue;
63
+ default: {
64
+ const columnDef = assertDefinedPass(columnDefinitionsMap.get(property), `Could not map property ${property} to column.`);
65
+ const column = table[columnDef.name];
66
+ const condition = getCondition(property, value, column);
67
+ conditions.push(condition);
68
+ break;
53
69
  }
54
- return orQuery;
55
70
  }
56
- if (property == '$nor') {
57
- if (queryEntries.length > 1) {
58
- throw new Error('only one logical operator per level allowed');
59
- }
60
- const orQuery = or(...query.$nor.map((item) => convertQuery(item, table, columnDefinitionsMap)));
61
- if (isUndefined(orQuery)) {
62
- return sqlTrue;
63
- }
64
- return not(orQuery);
65
- }
66
- const columnDef = assertDefinedPass(columnDefinitionsMap.get(property), `Could not map property ${property} to column.`);
67
- const column = table[columnDef.name];
68
- const condition = getCondition(property, value, column);
69
- conditions.push(condition);
70
71
  }
71
- return and(...conditions);
72
+ // Combine all collected conditions with AND. Return `true` if no conditions were generated.
73
+ return and(...conditions) ?? sqlTrue;
72
74
  }
73
75
  /**
74
76
  * Generates a Drizzle SQL condition based on a property, its value, and the corresponding column.
@@ -89,6 +91,26 @@ function getCondition(property, value, column) {
89
91
  }
90
92
  return eq(column, queryValue);
91
93
  }
94
+ if (hasOwnProperty(value, '$and')) {
95
+ const innerQueries = value.$and.map((query) => getCondition(property, query, column)); // eslint-disable-line @typescript-eslint/no-unsafe-argument
96
+ const andQuery = and(...innerQueries);
97
+ if (isUndefined(andQuery)) {
98
+ throw new Error(`No valid conditions in $and for property "${property}".`);
99
+ }
100
+ return andQuery;
101
+ }
102
+ if (hasOwnProperty(value, '$or')) {
103
+ const innerQueries = value.$or.map((query) => getCondition(property, query, column)); // eslint-disable-line @typescript-eslint/no-unsafe-argument
104
+ const orQuery = or(...innerQueries);
105
+ if (isUndefined(orQuery)) {
106
+ throw new Error(`No valid conditions in $or for property "${property}".`);
107
+ }
108
+ return orQuery;
109
+ }
110
+ if (hasOwnProperty(value, '$not')) {
111
+ const innerQuery = getCondition(property, value.$not, column); // eslint-disable-line @typescript-eslint/no-unsafe-argument
112
+ return not(innerQuery);
113
+ }
92
114
  if (hasOwnProperty(value, '$neq')) {
93
115
  const queryValue = value.$neq;
94
116
  if (queryValue === null) {
@@ -131,7 +153,8 @@ function getCondition(property, value, column) {
131
153
  : isRegExp(queryValue)
132
154
  ? ({ flags: queryValue.flags, value: queryValue.source })
133
155
  : ({ flags: queryValue.flags, value: queryValue.pattern });
134
- return sql `regexp_like(${column}, ${regexp.value}, ${regexp.flags})`;
156
+ const operator = (regexp.flags?.includes('i') ?? false) ? sql.raw('~*') : sql.raw('~');
157
+ return sql `${column} ${operator} ${regexp.value}`;
135
158
  }
136
159
  if (hasOwnProperty(value, '$text')) {
137
160
  throw new NotSupportedError('$text is not supported.');
@@ -1,12 +1,13 @@
1
1
  import { SQL } from 'drizzle-orm';
2
2
  import type { PgColumn, PgInsertValue, PgUpdateSetSource } from 'drizzle-orm/pg-core';
3
- import { type InjectOptions } from '../../injector/inject.js';
4
3
  import { type Resolvable, resolveArgumentType } from '../../injector/interfaces.js';
5
- import type { DeepPartial, OneOrMany, Paths, Type, TypedOmit } from '../../types.js';
4
+ import type { DeepPartial, OneOrMany, Paths, Type } from '../../types.js';
6
5
  import type { UntaggedDeep } from '../../types/index.js';
7
6
  import { Entity, type EntityMetadataAttributes, type EntityType, type EntityWithoutMetadata } from '../entity.js';
8
7
  import type { Query } from '../query.js';
9
8
  import type { EntityMetadataUpdate, EntityUpdate, LoadManyOptions, LoadOptions, NewEntity, Order, TargetColumnPaths } from '../repository.types.js';
9
+ import type { Database } from './database.js';
10
+ import type { PgTransaction } from './transaction.js';
10
11
  import { Transactional } from './transactional.js';
11
12
  import type { ColumnDefinition, PgTableFromType, TransformContext } from './types.js';
12
13
  export declare const repositoryType: unique symbol;
@@ -136,7 +137,7 @@ export declare class EntityRepository<T extends Entity | EntityWithoutMetadata =
136
137
  /**
137
138
  * Checks if all entities with the given IDs exist.
138
139
  * @param ids An array of entity IDs to check.
139
- * @returns A promise that resolves to `true` if all entities exist, `false` otherwise.
140
+ * @returns A promise that resolves to `true` if all entities exist, `false` otherwise. If `ids` is empty, returns `false`.
140
141
  */
141
142
  hasAll(ids: string[]): Promise<boolean>;
142
143
  /**
@@ -157,6 +158,20 @@ export declare class EntityRepository<T extends Entity | EntityWithoutMetadata =
157
158
  * @returns A promise that resolves to an array of the inserted entities.
158
159
  */
159
160
  insertMany(entities: NewEntity<T>[]): Promise<T[]>;
161
+ /**
162
+ * Inserts an entity if it does not already exist based on the target columns.
163
+ * @param target The column(s) to use for conflict detection.
164
+ * @param entity The entity to insert.
165
+ * @returns A promise that resolves to the inserted or existing entity.
166
+ */
167
+ insertIfNotExists(target: OneOrMany<Paths<UntaggedDeep<T>>>, entity: NewEntity<T>): Promise<T | undefined>;
168
+ /**
169
+ * Inserts many entities if they do not already exist based on the target columns.
170
+ * @param target The column(s) to use for conflict detection.
171
+ * @param entities The entities to insert.
172
+ * @returns A promise that resolves to the inserted or existing entities.
173
+ */
174
+ insertManyIfNotExists(target: OneOrMany<Paths<UntaggedDeep<T>>>, entities: NewEntity<T>[]): Promise<T[]>;
160
175
  /**
161
176
  * Inserts an entity or updates it if a conflict occurs based on the target columns.
162
177
  * @param target The column(s) to use for conflict detection.
@@ -430,45 +445,6 @@ export declare class EntityRepository<T extends Entity | EntityWithoutMetadata =
430
445
  protected _mapToInsertColumns(obj: DeepPartial<T> | NewEntity<T>, transformContext: TransformContext): Promise<PgInsertValue<PgTableFromType>>;
431
446
  protected _mapUpdate(update: EntityUpdate<T>, transformContext: TransformContext): Promise<PgUpdateSetSource<PgTableFromType>>;
432
447
  protected _getMetadataUpdate(update?: EntityUpdate<T>): PgUpdateSetSource<PgTableFromType<EntityType<Entity>>> | undefined;
433
- protected getIdLimitSelect(query: Query<T>): Omit<import("drizzle-orm/pg-core").PgSelectBase<string, {
434
- id: PgColumn<{
435
- name: string;
436
- tableName: string;
437
- dataType: "string";
438
- columnType: "PgUUID";
439
- data: string;
440
- driverParam: string;
441
- notNull: true;
442
- hasDefault: true;
443
- isPrimaryKey: true;
444
- isAutoincrement: false;
445
- hasRuntimeDefault: false;
446
- enumValues: undefined;
447
- baseColumn: never;
448
- identity: undefined;
449
- generated: undefined;
450
- }, {}, {}>;
451
- }, "partial", globalThis.Record<string, "not-null">, false, "where" | "limit", {
452
- id: string;
453
- }[], {
454
- id: PgColumn<{
455
- name: string;
456
- tableName: string;
457
- dataType: "string";
458
- columnType: "PgUUID";
459
- data: string;
460
- driverParam: string;
461
- notNull: true;
462
- hasDefault: true;
463
- isPrimaryKey: true;
464
- isAutoincrement: false;
465
- hasRuntimeDefault: false;
466
- enumValues: undefined;
467
- baseColumn: never;
468
- identity: undefined;
469
- generated: undefined;
470
- }, {}, {}>;
471
- }>, "where" | "limit">;
472
448
  protected getTransformContext(): Promise<TransformContext>;
473
449
  }
474
450
  /**
@@ -477,7 +453,14 @@ export declare class EntityRepository<T extends Entity | EntityWithoutMetadata =
477
453
  * @param type The entity type.
478
454
  * @returns An EntityRepository instance for the specified type.
479
455
  */
480
- export declare function injectRepository<T extends Entity | EntityWithoutMetadata>(type: EntityType<T>, options?: TypedOmit<InjectOptions<EntityRepository<T>, undefined>, 'optional'>): EntityRepository<T>;
456
+ export declare function injectRepository<T extends Entity | EntityWithoutMetadata>(type: EntityType<T>, session?: Database | PgTransaction | null): EntityRepository<T>;
457
+ /**
458
+ * Injects an EntityRepository instance for the specified entity type.
459
+ * @template T The entity type.
460
+ * @param type The entity type.
461
+ * @returns An EntityRepository instance for the specified type.
462
+ */
463
+ export declare function injectRepositoryAsync<T extends Entity | EntityWithoutMetadata>(type: EntityType<T>, session?: Database | PgTransaction | null): Promise<EntityRepository<T>>;
481
464
  /**
482
465
  * Gets or creates a singleton EntityRepository class for the specified entity type.
483
466
  * @template T The entity type.