akanjs 3.0.0-alpha.71 → 3.0.0-alpha.73

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 (188) hide show
  1. package/client/cookie.ts +21 -34
  2. package/client/csrTypes.ts +0 -12
  3. package/client/frameConfig.ts +13 -0
  4. package/common/Logger.ts +13 -6
  5. package/common/TrustedProxy.ts +134 -0
  6. package/common/clamp.ts +2 -0
  7. package/common/dynamicRecord.ts +12 -0
  8. package/common/index.ts +5 -1
  9. package/common/isValidDate.ts +1 -1
  10. package/common/requestOrigin.ts +32 -0
  11. package/common/{httpClient.ts → restClient.ts} +16 -9
  12. package/constant/types.ts +22 -0
  13. package/dictionary/base.dictionary.ts +4 -0
  14. package/dictionary/trans.ts +24 -5
  15. package/document/dataLoader.ts +0 -4
  16. package/document/filterMeta.ts +2 -2
  17. package/document/loaderInfo.ts +4 -1
  18. package/fetch/client/fetchClient.ts +65 -88
  19. package/fetch/client/fetchHandle.ts +57 -0
  20. package/fetch/client/httpClient.ts +42 -14
  21. package/fetch/client/sliceInitHandle.ts +101 -0
  22. package/fetch/fetchType/appliedReturn.type.ts +64 -1
  23. package/fetch/fetchType/sliceFetch.type.ts +5 -5
  24. package/fetch/requestStorage.ts +19 -5
  25. package/index.ts +16 -2
  26. package/local/apps/serverLifecycle/serverLifecycle-local.db-shm +0 -0
  27. package/local/apps/serverLifecycle/serverLifecycle-local_solid.db-shm +0 -0
  28. package/package.json +1 -1
  29. package/server/akanApp.ts +3 -19
  30. package/server/akanAppHeaders.ts +10 -4
  31. package/server/akanOption.ts +14 -1
  32. package/server/akanServer.ts +3 -0
  33. package/server/cachePolicy.ts +2 -11
  34. package/server/decorators.ts +12 -3
  35. package/server/devtools/constantSerializer.ts +8 -1
  36. package/server/di/diLifecycle.ts +21 -1
  37. package/server/di/resolveHierarchy.ts +3 -3
  38. package/server/imageOptimizer.ts +2 -17
  39. package/server/mcp/McpDispatcher.ts +8 -2
  40. package/server/resolver/database.resolver.ts +13 -8
  41. package/server/resolver/signal.resolver.ts +3 -3
  42. package/server/routeTreeBuilder.ts +1 -15
  43. package/server/routing/apiRouter.ts +4 -5
  44. package/server/routing/appWsData.ts +9 -6
  45. package/server/staticPath.ts +34 -0
  46. package/server/webRouter.ts +35 -41
  47. package/service/adapt.ts +1 -5
  48. package/service/predefinedAdaptor/cache.adaptor.ts +8 -4
  49. package/service/predefinedAdaptor/database.adaptor.ts +37 -1766
  50. package/service/predefinedAdaptor/sql/PendingStoreEnsures.ts +22 -0
  51. package/service/predefinedAdaptor/sql/QueryCompiler.ts +225 -0
  52. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +812 -0
  53. package/service/predefinedAdaptor/sql/UpdateCompiler.ts +67 -0
  54. package/service/predefinedAdaptor/sql/dialect/postgres.ts +151 -0
  55. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +134 -0
  56. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +29 -0
  57. package/service/predefinedAdaptor/sql/driver/libsql.ts +37 -0
  58. package/service/predefinedAdaptor/sql/driver/postgres.ts +42 -0
  59. package/service/predefinedAdaptor/sql/types.ts +251 -0
  60. package/service/predefinedAdaptor/sql/values.ts +91 -0
  61. package/signal/CrossSiteGuard.ts +71 -0
  62. package/signal/SignalFailure.ts +51 -0
  63. package/signal/endpoint.ts +2 -2
  64. package/signal/exception.ts +43 -6
  65. package/signal/index.ts +2 -0
  66. package/signal/intercept.ts +5 -2
  67. package/signal/internal.ts +10 -2
  68. package/signal/serializer/fetch.serializer.ts +11 -1
  69. package/signal/signalContext.ts +25 -28
  70. package/signal/slice.ts +1 -1
  71. package/store/SliceRequest.ts +23 -0
  72. package/store/action.ts +177 -114
  73. package/store/agent/AgentBridge.ts +3 -1
  74. package/store/agentic/StExposeBuilder.ts +7 -4
  75. package/store/agentic/StStateBuilder.ts +9 -4
  76. package/store/agentic/StToolBuilder.ts +21 -7
  77. package/store/store.ts +1 -1
  78. package/store/storeInstance.ts +3 -3
  79. package/store/storeRegistry.ts +1 -1
  80. package/types/client/cookie.d.ts +13 -2
  81. package/types/client/csrTypes.d.ts +0 -1
  82. package/types/client/frameConfig.d.ts +1 -0
  83. package/types/common/TrustedProxy.d.ts +24 -0
  84. package/types/common/clamp.d.ts +2 -0
  85. package/types/common/dynamicRecord.d.ts +14 -0
  86. package/types/common/index.d.ts +5 -1
  87. package/types/common/requestOrigin.d.ts +14 -0
  88. package/types/common/restClient.d.ts +27 -0
  89. package/types/constant/types.d.ts +13 -0
  90. package/types/dictionary/base.dictionary.d.ts +1 -1
  91. package/types/dictionary/dictionary.d.ts +8 -8
  92. package/types/document/dataLoader.d.ts +0 -3
  93. package/types/document/filterMeta.d.ts +2 -2
  94. package/types/document/loaderInfo.d.ts +2 -2
  95. package/types/fetch/client/fetchHandle.d.ts +24 -0
  96. package/types/fetch/client/httpClient.d.ts +2 -0
  97. package/types/fetch/client/sliceInitHandle.d.ts +29 -0
  98. package/types/fetch/fetchType/appliedReturn.type.d.ts +38 -1
  99. package/types/fetch/fetchType/sliceFetch.type.d.ts +5 -5
  100. package/types/fetch/requestStorage.d.ts +14 -0
  101. package/types/index.d.ts +17 -2
  102. package/types/server/akanOption.d.ts +8 -1
  103. package/types/server/decorators.d.ts +12 -2
  104. package/types/server/di/diLifecycle.d.ts +9 -1
  105. package/types/server/routeTreeBuilder.d.ts +1 -2
  106. package/types/server/routing/appWsData.d.ts +7 -3
  107. package/types/server/staticPath.d.ts +17 -0
  108. package/types/service/adapt.d.ts +1 -1
  109. package/types/service/predefinedAdaptor/database.adaptor.d.ts +15 -407
  110. package/types/service/predefinedAdaptor/sql/PendingStoreEnsures.d.ts +6 -0
  111. package/types/service/predefinedAdaptor/sql/QueryCompiler.d.ts +28 -0
  112. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +127 -0
  113. package/types/service/predefinedAdaptor/sql/UpdateCompiler.d.ts +17 -0
  114. package/types/service/predefinedAdaptor/sql/dialect/postgres.d.ts +27 -0
  115. package/types/service/predefinedAdaptor/sql/dialect/sqlite.d.ts +27 -0
  116. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +16 -0
  117. package/types/service/predefinedAdaptor/sql/driver/libsql.d.ts +17 -0
  118. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +17 -0
  119. package/types/service/predefinedAdaptor/sql/types.d.ts +226 -0
  120. package/types/service/predefinedAdaptor/sql/values.d.ts +13 -0
  121. package/types/signal/CrossSiteGuard.d.ts +44 -0
  122. package/types/signal/SignalFailure.d.ts +28 -0
  123. package/types/signal/exception.d.ts +38 -54774
  124. package/types/signal/index.d.ts +2 -0
  125. package/types/signal/intercept.d.ts +3 -3
  126. package/types/signal/internal.d.ts +5 -1
  127. package/types/signal/serializer/fetch.serializer.d.ts +7 -1
  128. package/types/store/SliceRequest.d.ts +16 -0
  129. package/types/store/agentic/StToolBuilder.d.ts +10 -1
  130. package/types/ui/Agent/Menu.d.ts +1 -1
  131. package/types/ui/Field/Choice.d.ts +52 -0
  132. package/types/ui/Field/Collection.d.ts +51 -0
  133. package/types/ui/Field/DateField.d.ts +32 -0
  134. package/types/ui/Field/Label.d.ts +9 -0
  135. package/types/ui/Field/NumberField.d.ts +43 -0
  136. package/types/ui/Field/Relation.d.ts +80 -0
  137. package/types/ui/Field/Text.d.ts +101 -0
  138. package/types/ui/Field/index.d.ts +50 -0
  139. package/types/ui/Field.d.ts +1 -412
  140. package/types/ui/Load/Edit_Client.d.ts +3 -1
  141. package/types/ui/Load/Stream.d.ts +22 -0
  142. package/types/ui/Load/index.d.ts +2 -0
  143. package/types/ui/System/Root.d.ts +4 -0
  144. package/types/ui/index.d.ts +1 -1
  145. package/types/ui/recipe/badgeRecipe.d.ts +2 -2
  146. package/types/ui/recipe/buttonRecipe.d.ts +2 -2
  147. package/types/webkit/useCamera.d.ts +10 -1
  148. package/types/webkit/usePurchase.d.ts +4 -0
  149. package/ui/Agent/Menu.tsx +2 -2
  150. package/ui/Data/TableList.tsx +1 -1
  151. package/ui/DraggableList.tsx +1 -2
  152. package/ui/Field/Choice.tsx +172 -0
  153. package/ui/Field/Collection.tsx +293 -0
  154. package/ui/Field/DateField.tsx +138 -0
  155. package/ui/Field/Label.tsx +31 -0
  156. package/ui/Field/NumberField.tsx +169 -0
  157. package/ui/Field/Relation.tsx +387 -0
  158. package/ui/Field/Text.tsx +360 -0
  159. package/ui/Field/index.tsx +70 -0
  160. package/ui/Input.tsx +3 -3
  161. package/ui/Load/Edit.tsx +2 -2
  162. package/ui/Load/Edit_Client.tsx +11 -3
  163. package/ui/Load/Pagination.tsx +25 -25
  164. package/ui/Load/Stream.tsx +38 -0
  165. package/ui/Load/Units.tsx +50 -37
  166. package/ui/Load/View.tsx +25 -17
  167. package/ui/Load/index.ts +2 -0
  168. package/ui/Model/EditModal.tsx +7 -7
  169. package/ui/Signal/Message.tsx +7 -7
  170. package/ui/Signal/PubSub.tsx +4 -1
  171. package/ui/System/Client.tsx +0 -2
  172. package/ui/System/Gtag.tsx +1 -1
  173. package/ui/System/Root.tsx +4 -0
  174. package/ui/index.ts +1 -1
  175. package/ui/overlayPosition.ts +1 -2
  176. package/webkit/useCamera.tsx +22 -6
  177. package/webkit/useCodepush.tsx +2 -2
  178. package/webkit/useCsrValues.ts +1 -3
  179. package/webkit/useFetch.ts +4 -3
  180. package/webkit/useFrameRuntime.ts +14 -7
  181. package/webkit/usePurchase.tsx +4 -1
  182. package/fetch/serializer/fetch.serializer.ts +0 -142
  183. package/fetch/serializer/index.ts +0 -1
  184. package/types/common/httpClient.d.ts +0 -20
  185. package/types/fetch/serializer/fetch.serializer.d.ts +0 -14
  186. package/types/fetch/serializer/index.d.ts +0 -1
  187. package/types/fetch/serializer.d.ts +0 -1
  188. package/ui/Field.tsx +0 -1639
@@ -1,1787 +1,58 @@
1
- import { Database, type SQLQueryBindings, type Statement } from "bun:sqlite";
1
+ import { Database } from "bun:sqlite";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { mkdir } from "node:fs/promises";
4
4
  import path from "node:path";
5
- import type { InArgs, InValue, Client as LibsqlClient } from "@libsql/client";
6
- import { DEFAULT_VALUE, dayjs, FIELD_META, getEnv, type PromiseOrObject } from "akanjs/base";
7
- import { type ConstantModel, getDefault } from "akanjs/constant";
8
- import {
9
- createDocumentId,
10
- type DatabaseModel,
11
- type DocumentQuery,
12
- type DocumentQueryNode,
13
- type DocumentSchema,
14
- type DocumentUpdate,
15
- type DocumentUpdateInput,
16
- type DocumentUpdateNode,
17
- type DocumentUpdateOperator,
18
- type DocumentUpdateOptions,
19
- documentQueryHelper,
20
- encodeDocumentValue,
21
- isDocumentId,
22
- isDocumentUpdateNode,
23
- NoDocumentError,
24
- resolveDocumentUpdate,
25
- type SchemaOf,
26
- sanitizeJson,
27
- searchColumns,
28
- } from "akanjs/document";
29
- import type { Sql } from "postgres";
5
+ import { getEnv, type PromiseOrObject } from "akanjs/base";
6
+ import type { ConstantModel } from "akanjs/constant";
7
+ import type { DatabaseModel, DocumentSchema, SchemaOf } from "akanjs/document";
30
8
  import { adapt } from "../adapt";
31
9
  import { ScheduleAdaptorRole } from "./role.adaptor";
32
10
  import {
33
- DEFAULT_SEARCH_WEIGHTS,
34
11
  DEFAULT_TOKENIZER,
35
- DOC_TABLE,
36
- FTS_TABLE,
37
12
  OPTIMIZE_CRON,
38
13
  OPTIMIZE_CRON_KEY,
39
14
  parseSearchEnabled,
40
15
  RETRY_INTERVAL_KEY,
41
16
  RETRY_INTERVAL_MS,
42
17
  SearchIndex,
43
- toMatchExpression,
44
18
  } from "./searchIndex";
45
- import { descriptorHash, jsonPath, quoteIdent, stableJson } from "./sqlDescriptor";
19
+ import { PostgresDialect } from "./sql/dialect/postgres";
20
+ import { BunSqliteClient } from "./sql/driver/bunSqlite";
21
+ import { LibsqlAkanClient } from "./sql/driver/libsql";
22
+ import { PostgresAkanClient } from "./sql/driver/postgres";
23
+ import { PendingStoreEnsures } from "./sql/PendingStoreEnsures";
24
+ import { SqlDocumentStore } from "./sql/SqlDocumentStore";
25
+ import type {
26
+ DatabaseAdaptor,
27
+ LibsqlDatabaseConfig,
28
+ PostgresDatabaseConfig,
29
+ SearchConfig,
30
+ SqliteDatabaseConfig,
31
+ SqliteEnv,
32
+ TransactionContext,
33
+ } from "./sql/types";
46
34
  import { resolveDefaultSqliteFile } from "./sqlitePath";
47
35
 
48
- export interface SqliteDatabaseConfig {
49
- filePath?: string;
50
- journalMode?: "WAL" | "DELETE" | "TRUNCATE" | "PERSIST" | "MEMORY" | "OFF";
51
- busyTimeoutMs?: number;
52
- synchronous?: "OFF" | "NORMAL" | "FULL" | "EXTRA";
53
- foreignKeys?: boolean;
54
- cacheSize?: number;
55
- tempStore?: "DEFAULT" | "FILE" | "MEMORY";
56
- }
57
-
58
- export interface LibsqlDatabaseConfig {
59
- url?: string;
60
- authToken?: string;
61
- }
62
-
63
- export interface PostgresDatabaseConfig {
64
- url?: string;
65
- host?: string;
66
- port?: number;
67
- database?: string;
68
- user?: string;
69
- password?: string;
70
- }
71
-
72
- export interface SearchConfig {
73
- enabled?: boolean;
74
- tokenizer?: string;
75
- }
76
-
77
- export interface DatabaseConfig {
78
- driver?: "sqlite" | "libsql" | "postgres";
79
- sqlite?: SqliteDatabaseConfig;
80
- libsql?: LibsqlDatabaseConfig;
81
- postgres?: PostgresDatabaseConfig;
82
- search?: SearchConfig;
83
- }
84
-
85
- export interface DocumentStore {
86
- ensure(): Promise<void>;
87
- create(data: DocumentRecord): Promise<any>;
88
- clone(data: DocumentRecord & { id: string }): Promise<any>;
89
- update(id: string, patch: DocumentRecord): Promise<any>;
90
- remove(id: string): Promise<any>;
91
- updateOneByQuery(
92
- query: DocumentQuery,
93
- update: DocumentUpdateInput,
94
- options?: DocumentUpdateOptions,
95
- ): Promise<{ acknowledged: boolean; matchedCount: number; modifiedCount: number; upsertedId: string | null }>;
96
- updateManyByQuery(
97
- query: DocumentQuery,
98
- update: DocumentUpdateInput,
99
- ): Promise<{ acknowledged: boolean; matchedCount: number; modifiedCount: number }>;
100
- removeManyByQuery(
101
- query: DocumentQuery,
102
- ): Promise<{ acknowledged: boolean; matchedCount: number; modifiedCount: number }>;
103
- removeOneByQuery(
104
- query: DocumentQuery,
105
- ): Promise<{ acknowledged: boolean; matchedCount: number; modifiedCount: number; upsertedId: string | null }>;
106
- bulkWrite(
107
- operations: { updateOne: { filter: DocumentQuery; update: DocumentUpdateInput; upsert?: boolean } }[],
108
- ): Promise<{ acknowledged: boolean; matchedCount: number; modifiedCount: number; upsertedId: string | null }>;
109
- find(query?: DocumentQuery, options?: FindManyOptions): Promise<any[]>;
110
- findIds(
111
- query?: DocumentQuery,
112
- options?: { sort?: SortOption; skip?: number | null; limit?: number | null; sample?: number },
113
- ): Promise<string[]>;
114
- findOne(query?: DocumentQuery, options?: FindOneOptions): Promise<any | null>;
115
- findId(
116
- query?: DocumentQuery,
117
- options?: { sort?: SortOption; skip?: number | null; sample?: boolean },
118
- ): Promise<string | null>;
119
- pickOne(query?: DocumentQuery, options?: FindOneOptions): Promise<any>;
120
- pickById(id: string): Promise<any>;
121
- exists(query?: DocumentQuery): Promise<string | null>;
122
- count(query?: DocumentQuery): Promise<number>;
123
- insight(query?: DocumentQuery): Promise<any>;
124
- hydrate(data: DocumentRecord, originalData?: DocumentRecord, options?: { track?: boolean }): any;
125
- }
126
-
127
- export interface SqlResultRows<Row = Record<string, unknown>> {
128
- rows: Row[];
129
- }
130
-
131
- export interface AkanSqlStatement {
132
- run(...params: unknown[]): Promise<unknown>;
133
- get<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row | null>;
134
- all<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row[]>;
135
- }
136
-
137
- export interface AkanSqlClient {
138
- execute(sql: string, params?: unknown[] | Record<string, unknown>): Promise<unknown>;
139
- prepare(sql: string): AkanSqlStatement;
140
- close(): Promise<void>;
141
- }
142
-
143
- export interface DatabaseAdaptor {
144
- getConnection(): AkanSqlClient;
145
- getStore(constant: ConstantModel, database: DatabaseModel, schema: DocumentSchema): DocumentStore;
146
- transaction<T>(fn: () => PromiseOrObject<T>): Promise<T>;
147
-
148
- getSearchIndex(): SearchIndex | null;
149
- }
150
-
151
- interface SqliteEnv {
152
- workspaceRoot?: string;
153
- database?: DatabaseConfig;
154
- }
155
-
156
- interface TransactionContext {
157
- afterCommit: (() => PromiseOrObject<void>)[];
158
- }
159
-
160
- const BASE_COLUMNS = new Set(["id", "createdAt", "updatedAt", "removedAt"]);
161
- const RESERVED_RE = /^sqlite_|^_akan_meta$|^search_doc$|^search_fts$/i;
162
- const REF_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
163
- const toSafeRefName = (value: string) => value.replace(/[^A-Za-z0-9_]+/g, "_").replace(/_+/g, "_");
164
- type DocumentRecord = Record<string, unknown>;
165
- type MutableDocumentRecord = Record<string, unknown>;
166
- type FieldMap = Record<string, { getProps: () => Record<string, unknown>; [key: string]: unknown }>;
167
- type SortOption = Record<string, 1 | -1> | null | undefined;
168
- type ProjectionOption = Partial<Record<string, boolean>> | null | undefined;
169
- type FindManyOptions = {
170
- sort?: SortOption;
171
- skip?: number | null;
172
- limit?: number | null;
173
- sample?: number;
174
- select?: ProjectionOption;
175
- };
176
- type FindOneOptions = { sort?: SortOption; skip?: number | null; sample?: boolean; select?: ProjectionOption };
177
- type WriteHookOptions = { runSaveHooks?: boolean; crudType?: "update" | "remove" };
178
- type QueryOperatorName = Extract<DocumentQueryNode, { kind: "op" }>["op"];
179
- interface SqliteDocumentRow {
180
- id: string;
181
- createdAt: number | string;
182
- updatedAt: number | string;
183
- removedAt?: number | string | null;
184
- _doc: string;
185
- }
186
- type ProjectedSqliteDocumentRow = Omit<SqliteDocumentRow, "_doc"> & Record<string, unknown>;
187
-
188
- interface DocumentDatabaseOwner {
189
- getConnection(): AkanSqlClient;
190
- getSearchIndex(): SearchIndex | null;
191
- getMeta(key: string): Promise<string | undefined> | string | undefined;
192
- setMeta(key: string, value: string): Promise<void>;
193
- afterCommit(fn: () => PromiseOrObject<void>): Promise<void>;
194
- }
195
-
196
- class BunSqliteStatement implements AkanSqlStatement {
197
- constructor(private readonly statement: Statement) {}
198
- async run(...params: unknown[]) {
199
- return this.statement.run(...(params as SQLQueryBindings[]));
200
- }
201
- async get<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row | null> {
202
- return (this.statement.get(...(params as SQLQueryBindings[])) as Row | null) ?? null;
203
- }
204
- async all<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row[]> {
205
- return this.statement.all(...(params as SQLQueryBindings[])) as Row[];
206
- }
207
- }
208
-
209
- class BunSqliteClient implements AkanSqlClient {
210
- constructor(readonly db: Database) {}
211
- async execute(sql: string, params: unknown[] | Record<string, unknown> = []) {
212
- const values = Array.isArray(params) ? params : Object.values(params);
213
- return this.db.query(sql).run(...(values as SQLQueryBindings[]));
214
- }
215
- prepare(sql: string): AkanSqlStatement {
216
- return new BunSqliteStatement(this.db.query(sql));
217
- }
218
- async close() {
219
- this.db.close();
220
- }
221
- }
222
-
223
- class LibsqlStatement implements AkanSqlStatement {
224
- constructor(
225
- private readonly client: LibsqlClient,
226
- private readonly sql: string,
227
- ) {}
228
- async run(...params: unknown[]) {
229
- const args = toLibsqlArgs(params);
230
- return await this.client.execute({ sql: this.sql, args });
231
- }
232
- async get<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row | null> {
233
- const args = toLibsqlArgs(params);
234
- const result = await this.client.execute({ sql: this.sql, args });
235
- return (result.rows[0] as Row | undefined) ?? null;
236
- }
237
- async all<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row[]> {
238
- const args = toLibsqlArgs(params);
239
- const result = await this.client.execute({ sql: this.sql, args });
240
- return result.rows as Row[];
241
- }
242
- }
243
-
244
- class LibsqlAkanClient implements AkanSqlClient {
245
- constructor(readonly client: LibsqlClient) {}
246
- async execute(sql: string, params: unknown[] | Record<string, unknown> = []) {
247
- return await this.client.execute({ sql, args: toLibsqlArgs(Array.isArray(params) ? params : [params]) });
248
- }
249
- prepare(sql: string): AkanSqlStatement {
250
- return new LibsqlStatement(this.client, sql);
251
- }
252
- async close() {
253
- this.client.close();
254
- }
255
- }
256
-
257
- class PostgresStatement implements AkanSqlStatement {
258
- constructor(
259
- private readonly client: Sql,
260
- private readonly sql: string,
261
- ) {}
262
- async run(...params: unknown[]) {
263
- const { sql, params: positionalParams } = toPostgresSql(this.sql, params);
264
- return await this.client.unsafe(sql, positionalParams as any[]);
265
- }
266
- async get<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row | null> {
267
- const rows = await this.all<Row>(...params);
268
- return rows[0] ?? null;
269
- }
270
- async all<Row = Record<string, unknown>>(...params: unknown[]): Promise<Row[]> {
271
- const { sql, params: positionalParams } = toPostgresSql(this.sql, params);
272
- return (await this.client.unsafe(sql, positionalParams as any[])) as Row[];
273
- }
274
- }
275
-
276
- class PostgresAkanClient implements AkanSqlClient {
277
- constructor(readonly client: Sql) {}
278
- async execute(sql: string, params: unknown[] | Record<string, unknown> = []) {
279
- return await this.client.unsafe(sql, Array.isArray(params) ? (params as any[]) : Object.values(params));
280
- }
281
- prepare(sql: string): AkanSqlStatement {
282
- return new PostgresStatement(this.client, sql);
283
- }
284
- async close() {
285
- await this.client.end();
286
- }
287
- }
288
-
289
- const isPlainObject = (value: unknown): value is Record<string, unknown> =>
290
- !!value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Buffer);
291
- const toLibsqlValue = (value: unknown): InValue => {
292
- if (
293
- value === null ||
294
- typeof value === "string" ||
295
- typeof value === "number" ||
296
- typeof value === "bigint" ||
297
- typeof value === "boolean" ||
298
- value instanceof Date ||
299
- value instanceof Uint8Array ||
300
- value instanceof ArrayBuffer
301
- ) {
302
- return value;
303
- }
304
- if (value instanceof Buffer) return new Uint8Array(value);
305
- return JSON.stringify(value);
306
- };
307
- const toLibsqlArgs = (params: unknown[]): InArgs => {
308
- if (params.length === 1 && isPlainObject(params[0])) {
309
- return Object.fromEntries(Object.entries(params[0]).map(([key, value]) => [key, toLibsqlValue(value)]));
310
- }
311
- return params.map(toLibsqlValue);
312
- };
313
- const toPostgresSql = (sql: string, params: unknown[]) => {
314
- if (params.length === 1 && isPlainObject(params[0])) {
315
- const named = params[0];
316
- const values: unknown[] = [];
317
- const text = sql.replace(/\$[A-Za-z_][A-Za-z0-9_]*/g, (token) => {
318
- values.push(named[token.slice(1)]);
319
- return `$${values.length}`;
320
- });
321
- return { sql: text, params: values };
322
- }
323
- let index = 0;
324
- return {
325
- sql: sql.replace(/\?/g, () => `$${++index}`),
326
- params,
327
- };
328
- };
329
- const encodeSqlValue = (value: unknown) => encodeDocumentValue(value);
330
-
331
- const decodeDateValue = (value: unknown) => {
332
- if (value === null || value === undefined) return value;
333
- if (typeof value === "number") return dayjs(value);
334
- const epoch = Number(value);
335
- return Number.isNaN(epoch) ? dayjs(value as never) : dayjs(epoch);
336
- };
337
- const QUERY_OPERATOR_KEYS = new Set([
338
- "eq",
339
- "ne",
340
- "oneOf",
341
- "notOneOf",
342
- "gt",
343
- "gte",
344
- "lt",
345
- "lte",
346
- "between",
347
- "exists",
348
- "missing",
349
- "empty",
350
- "has",
351
- "contains",
352
- ]);
353
-
354
- interface SqlFrag {
355
- sql: string;
356
- params: unknown[];
357
- }
358
-
359
- interface SearchJoinProps {
360
- alias: string;
361
- ref: string;
362
- match: string;
363
- weights: number[];
364
- }
365
-
366
- interface SearchJoin extends SqlFrag {
367
- alias: string;
368
- }
369
-
370
- interface CompiledQuery {
371
- where: string;
372
- params: unknown[];
373
- joins: SearchJoin[];
374
- }
375
-
376
- interface CompileContext {
377
- joins: SearchJoin[];
378
- conjunctive: boolean;
379
- }
380
-
381
- interface SqlDialect {
382
- readonly name: "sqlite" | "postgres";
383
- timestampType(): string;
384
- docColumnType(): string;
385
- docColumn(): string;
386
- docValuePlaceholder(): string;
387
- extract(path: string): string;
388
- projectExpr(path: string): string;
389
- decodeProjected(value: unknown): unknown;
390
- eq(path: string, value: unknown): SqlFrag;
391
- ne(path: string, value: unknown): SqlFrag;
392
- compare(path: string, op: "gt" | "gte" | "lt" | "lte", value: unknown): SqlFrag;
393
- between(path: string, from: unknown, to: unknown): SqlFrag;
394
- inList(path: string, values: unknown[]): SqlFrag;
395
- notInList(path: string, values: unknown[]): SqlFrag;
396
- exists(path: string): SqlFrag;
397
- missing(path: string): SqlFrag;
398
- empty(path: string): SqlFrag;
399
- arrayHas(path: string, value: unknown): SqlFrag;
400
- contains(path: string, value: unknown): SqlFrag;
401
- searchJoin(props: SearchJoinProps): SqlFrag;
402
- applyUpdate(acc: string, op: DocumentUpdateOperator, path: string, value: unknown): SqlFrag;
403
- affectedRows(result: unknown): number;
404
- }
405
-
406
- const jsonStr = (value: unknown) => JSON.stringify(sanitizeJson(value) ?? null);
407
-
408
- export class SqliteDialect implements SqlDialect {
409
- readonly name = "sqlite" as const;
410
- timestampType() {
411
- return "INTEGER";
412
- }
413
- docColumnType() {
414
- return "TEXT";
415
- }
416
- docColumn() {
417
- return quoteIdent("_doc");
418
- }
419
- docValuePlaceholder() {
420
- return "?";
421
- }
422
- #path(path: string) {
423
- return `'${jsonPath(path).replaceAll("'", "''")}'`;
424
- }
425
- extract(path: string) {
426
- return `json_extract(${this.docColumn()}, ${this.#path(path)})`;
427
- }
428
-
429
- projectExpr(path: string) {
430
- return `${this.docColumn()} -> ${this.#path(path)}`;
431
- }
432
- decodeProjected(value: unknown) {
433
- return typeof value === "string" ? JSON.parse(value) : value;
434
- }
435
- eq(path: string, value: unknown): SqlFrag {
436
- return value === null
437
- ? { sql: `${this.extract(path)} IS NULL`, params: [] }
438
- : { sql: `${this.extract(path)} = ?`, params: [encodeSqlValue(value)] };
439
- }
440
- ne(path: string, value: unknown): SqlFrag {
441
- return value === null
442
- ? { sql: `${this.extract(path)} IS NOT NULL`, params: [] }
443
- : { sql: `${this.extract(path)} != ?`, params: [encodeSqlValue(value)] };
444
- }
445
- compare(path: string, op: "gt" | "gte" | "lt" | "lte", value: unknown): SqlFrag {
446
- const operators = { gt: ">", gte: ">=", lt: "<", lte: "<=" } as const;
447
- return { sql: `${this.extract(path)} ${operators[op]} ?`, params: [encodeSqlValue(value)] };
448
- }
449
- between(path: string, from: unknown, to: unknown): SqlFrag {
450
- return {
451
- sql: `(${this.extract(path)} >= ? AND ${this.extract(path)} <= ?)`,
452
- params: [encodeSqlValue(from), encodeSqlValue(to)],
453
- };
454
- }
455
- inList(path: string, values: unknown[]): SqlFrag {
456
- return {
457
- sql: `${this.extract(path)} IN (${values.map(() => "?").join(", ")})`,
458
- params: values.map(encodeSqlValue),
459
- };
460
- }
461
- notInList(path: string, values: unknown[]): SqlFrag {
462
- return {
463
- sql: `${this.extract(path)} NOT IN (${values.map(() => "?").join(", ")})`,
464
- params: values.map(encodeSqlValue),
465
- };
466
- }
467
- exists(path: string): SqlFrag {
468
- return { sql: `json_type(${this.docColumn()}, ${this.#path(path)}) IS NOT NULL`, params: [] };
469
- }
470
- missing(path: string): SqlFrag {
471
- return { sql: `json_type(${this.docColumn()}, ${this.#path(path)}) IS NULL`, params: [] };
472
- }
473
- empty(path: string): SqlFrag {
474
- const type = `json_type(${this.docColumn()}, ${this.#path(path)})`;
475
- return { sql: `(${type} IS NULL OR ${type} = 'null')`, params: [] };
476
- }
477
- arrayHas(path: string, value: unknown): SqlFrag {
478
- return {
479
- sql: `EXISTS (SELECT 1 FROM json_each(${this.extract(path)}) WHERE json_each.value = ?)`,
480
- params: [encodeSqlValue(value)],
481
- };
482
- }
483
- contains(path: string, value: unknown): SqlFrag {
484
- return { sql: `${this.extract(path)} LIKE ?`, params: [`%${String(value)}%`] };
485
- }
486
- searchJoin({ alias, ref, match, weights }: SearchJoinProps): SqlFrag {
487
-
488
- return {
489
- sql:
490
- `JOIN (SELECT d."refId" AS rid, bm25(${FTS_TABLE}, ${weights.join(", ")}) AS score ` +
491
- `FROM ${FTS_TABLE} JOIN ${DOC_TABLE} d ON d."fid" = ${FTS_TABLE}."rowid" ` +
492
- `WHERE ${FTS_TABLE} MATCH ? AND d."ref" = ?) ${alias} ON ${alias}."rid" = ${quoteIdent(ref)}."id"`,
493
- params: [match, ref],
494
- };
495
- }
496
- applyUpdate(acc: string, op: DocumentUpdateOperator, path: string, value: unknown): SqlFrag {
497
- const p = this.#path(path);
498
-
499
- const cur = `json_extract(${this.docColumn()}, ${p})`;
500
- const arr = `COALESCE(${cur}, json('[]'))`;
501
-
502
- switch (op) {
503
- case "set":
504
- return { sql: `json_set(${acc}, ${p}, json(?))`, params: [jsonStr(value)] };
505
- case "unset":
506
- return { sql: `json_remove(${acc}, ${p})`, params: [] };
507
- case "inc":
508
- return { sql: `json_set(${acc}, ${p}, COALESCE(${cur}, 0) + ?)`, params: [Number(value)] };
509
- case "mul":
510
- return { sql: `json_set(${acc}, ${p}, COALESCE(${cur}, 0) * ?)`, params: [Number(value)] };
511
- case "min":
512
- return { sql: `json_set(${acc}, ${p}, MIN(COALESCE(${cur}, ?), ?))`, params: [Number(value), Number(value)] };
513
- case "max":
514
- return { sql: `json_set(${acc}, ${p}, MAX(COALESCE(${cur}, ?), ?))`, params: [Number(value), Number(value)] };
515
- case "push":
516
- return { sql: `json_set(${acc}, ${p}, json_insert(${arr}, '$[#]', json(?)))`, params: [jsonStr(value)] };
517
- case "addToSet":
518
- return {
519
- sql: `json_set(${acc}, ${p}, CASE WHEN EXISTS (SELECT 1 FROM json_each(${arr}) WHERE json_each.value = ?) THEN ${arr} ELSE json_insert(${arr}, '$[#]', json(?)) END)`,
520
- params: [encodeSqlValue(value), jsonStr(value)],
521
- };
522
- case "pull":
523
- return {
524
- sql: `json_set(${acc}, ${p}, (SELECT json_group_array(json_each.value) FROM json_each(${arr}) WHERE json_each.value <> ?))`,
525
- params: [encodeSqlValue(value)],
526
- };
527
- case "setOnInsert":
528
- return { sql: acc, params: [] };
529
- }
530
- }
531
- affectedRows(result: unknown): number {
532
- const row = result as { changes?: number | bigint; rowsAffected?: number } | null;
533
- return Number(row?.changes ?? row?.rowsAffected ?? 0);
534
- }
535
- }
536
-
537
- export class PostgresDialect implements SqlDialect {
538
- readonly name = "postgres" as const;
539
- timestampType() {
540
- return "BIGINT";
541
- }
542
- docColumnType() {
543
- return "jsonb";
544
- }
545
- docColumn() {
546
- return quoteIdent("_doc");
547
- }
548
- docValuePlaceholder() {
549
- return "?::jsonb";
550
- }
551
- #path(path: string) {
552
- return `'{${path
553
- .split(".")
554
- .map((part) => part.replaceAll("'", "''"))
555
- .join(",")}}'`;
556
- }
557
- #jsonb(path: string) {
558
- return `(${this.docColumn()} #> ${this.#path(path)})`;
559
- }
560
- #text(path: string) {
561
- return `(${this.docColumn()} #>> ${this.#path(path)})`;
562
- }
563
- extract(path: string) {
564
- return this.#jsonb(path);
565
- }
566
-
567
- projectExpr(path: string) {
568
- return this.#jsonb(path);
569
- }
570
- decodeProjected(value: unknown) {
571
- return value;
572
- }
573
- eq(path: string, value: unknown): SqlFrag {
574
- return value === null
575
- ? { sql: `${this.#jsonb(path)} IS NULL`, params: [] }
576
- : { sql: `${this.#jsonb(path)} = ?::jsonb`, params: [jsonStr(value)] };
577
- }
578
- ne(path: string, value: unknown): SqlFrag {
579
- return value === null
580
- ? { sql: `${this.#jsonb(path)} IS NOT NULL`, params: [] }
581
- : { sql: `${this.#jsonb(path)} <> ?::jsonb`, params: [jsonStr(value)] };
582
- }
583
- compare(path: string, op: "gt" | "gte" | "lt" | "lte", value: unknown): SqlFrag {
584
- const operators = { gt: ">", gte: ">=", lt: "<", lte: "<=" } as const;
585
- return { sql: `${this.#jsonb(path)} ${operators[op]} ?::jsonb`, params: [jsonStr(value)] };
586
- }
587
- between(path: string, from: unknown, to: unknown): SqlFrag {
588
- return {
589
- sql: `(${this.#jsonb(path)} >= ?::jsonb AND ${this.#jsonb(path)} <= ?::jsonb)`,
590
- params: [jsonStr(from), jsonStr(to)],
591
- };
592
- }
593
- inList(path: string, values: unknown[]): SqlFrag {
594
- return {
595
- sql: `${this.#jsonb(path)} IN (${values.map(() => "?::jsonb").join(", ")})`,
596
- params: values.map(jsonStr),
597
- };
598
- }
599
- notInList(path: string, values: unknown[]): SqlFrag {
600
- return {
601
- sql: `${this.#jsonb(path)} NOT IN (${values.map(() => "?::jsonb").join(", ")})`,
602
- params: values.map(jsonStr),
603
- };
604
- }
605
- exists(path: string): SqlFrag {
606
- return { sql: `${this.#jsonb(path)} IS NOT NULL`, params: [] };
607
- }
608
- missing(path: string): SqlFrag {
609
- return { sql: `${this.#jsonb(path)} IS NULL`, params: [] };
610
- }
611
- empty(path: string): SqlFrag {
612
- return { sql: `(${this.#jsonb(path)} IS NULL OR jsonb_typeof(${this.#jsonb(path)}) = 'null')`, params: [] };
613
- }
614
- arrayHas(path: string, value: unknown): SqlFrag {
615
- return { sql: `${this.#jsonb(path)} @> ?::jsonb`, params: [jsonStr(value)] };
616
- }
617
- contains(path: string, value: unknown): SqlFrag {
618
- return { sql: `${this.#text(path)} LIKE ?`, params: [`%${String(value)}%`] };
619
- }
620
- searchJoin({ ref }: SearchJoinProps): SqlFrag {
621
-
622
- throw new Error(
623
- `Text search on "${ref}" requires the sqlite or libsql database; Postgres has no fts5 index to join.`,
624
- );
625
- }
626
- applyUpdate(acc: string, op: DocumentUpdateOperator, path: string, value: unknown): SqlFrag {
627
- const p = this.#path(path);
628
-
629
- const jsonbAt = `(${this.docColumn()}) #> ${p}`;
630
- const textAt = `(${this.docColumn()}) #>> ${p}`;
631
- const arr = `COALESCE(${jsonbAt}, '[]'::jsonb)`;
632
-
633
- switch (op) {
634
- case "set":
635
- return { sql: `jsonb_set(${acc}, ${p}, ?::jsonb, true)`, params: [jsonStr(value)] };
636
- case "unset":
637
- return { sql: `(${acc}) #- ${p}`, params: [] };
638
- case "inc":
639
- return {
640
- sql: `jsonb_set(${acc}, ${p}, to_jsonb(COALESCE((${textAt})::numeric, 0) + ?), true)`,
641
- params: [Number(value)],
642
- };
643
- case "mul":
644
- return {
645
- sql: `jsonb_set(${acc}, ${p}, to_jsonb(COALESCE((${textAt})::numeric, 0) * ?), true)`,
646
- params: [Number(value)],
647
- };
648
- case "min":
649
- return {
650
- sql: `jsonb_set(${acc}, ${p}, to_jsonb(LEAST(COALESCE((${textAt})::numeric, ?), ?)), true)`,
651
- params: [Number(value), Number(value)],
652
- };
653
- case "max":
654
- return {
655
- sql: `jsonb_set(${acc}, ${p}, to_jsonb(GREATEST(COALESCE((${textAt})::numeric, ?), ?)), true)`,
656
- params: [Number(value), Number(value)],
657
- };
658
- case "push":
659
- return {
660
- sql: `jsonb_set(${acc}, ${p}, ${arr} || jsonb_build_array(?::jsonb), true)`,
661
- params: [jsonStr(value)],
662
- };
663
- case "addToSet":
664
- return {
665
- sql: `jsonb_set(${acc}, ${p}, CASE WHEN ${arr} @> jsonb_build_array(?::jsonb) THEN ${arr} ELSE ${arr} || jsonb_build_array(?::jsonb) END, true)`,
666
- params: [jsonStr(value), jsonStr(value)],
667
- };
668
- case "pull":
669
- return {
670
- sql: `jsonb_set(${acc}, ${p}, COALESCE((SELECT jsonb_agg(elem) FROM jsonb_array_elements(${arr}) elem WHERE elem <> ?::jsonb), '[]'::jsonb), true)`,
671
- params: [jsonStr(value)],
672
- };
673
- case "setOnInsert":
674
- return { sql: acc, params: [] };
675
- }
676
- }
677
- affectedRows(result: unknown): number {
678
- const row = result as { count?: number } | Array<unknown> | null;
679
- if (Array.isArray(row)) return (row as { count?: number }).count ?? row.length;
680
- return Number(row?.count ?? 0);
681
- }
682
- }
683
-
684
- type QueryLeafOps = Pick<
685
- SqlDialect,
686
- | "eq"
687
- | "ne"
688
- | "compare"
689
- | "between"
690
- | "inList"
691
- | "notInList"
692
- | "exists"
693
- | "missing"
694
- | "empty"
695
- | "arrayHas"
696
- | "contains"
697
- >;
698
-
699
- const BASE_COLUMN_LEAF: QueryLeafOps = {
700
- eq: (path, value) =>
701
- value === null
702
- ? { sql: `${quoteIdent(path)} IS NULL`, params: [] }
703
- : { sql: `${quoteIdent(path)} = ?`, params: [encodeSqlValue(value)] },
704
- ne: (path, value) =>
705
- value === null
706
- ? { sql: `${quoteIdent(path)} IS NOT NULL`, params: [] }
707
- : { sql: `${quoteIdent(path)} != ?`, params: [encodeSqlValue(value)] },
708
- compare: (path, op, value) => {
709
- const operators = { gt: ">", gte: ">=", lt: "<", lte: "<=" } as const;
710
- return { sql: `${quoteIdent(path)} ${operators[op]} ?`, params: [encodeSqlValue(value)] };
711
- },
712
- between: (path, from, to) => ({
713
- sql: `(${quoteIdent(path)} >= ? AND ${quoteIdent(path)} <= ?)`,
714
- params: [encodeSqlValue(from), encodeSqlValue(to)],
715
- }),
716
- inList: (path, values) => ({
717
- sql: `${quoteIdent(path)} IN (${values.map(() => "?").join(", ")})`,
718
- params: values.map(encodeSqlValue),
719
- }),
720
- notInList: (path, values) => ({
721
- sql: `${quoteIdent(path)} NOT IN (${values.map(() => "?").join(", ")})`,
722
- params: values.map(encodeSqlValue),
723
- }),
724
- exists: (path) => ({ sql: `${quoteIdent(path)} IS NOT NULL`, params: [] }),
725
- missing: (path) => ({ sql: `${quoteIdent(path)} IS NULL`, params: [] }),
726
- empty: (path) => ({ sql: `${quoteIdent(path)} IS NULL`, params: [] }),
727
- arrayHas: (path, value) => ({
728
- sql: `EXISTS (SELECT 1 FROM json_each(${quoteIdent(path)}) WHERE json_each.value = ?)`,
729
- params: [encodeSqlValue(value)],
730
- }),
731
- contains: (path, value) => ({ sql: `${quoteIdent(path)} LIKE ?`, params: [`%${String(value)}%`] }),
732
- };
733
-
734
- class QueryCompiler {
735
- constructor(
736
- private readonly fields: FieldMap,
737
- private readonly dialect: SqlDialect,
738
- private readonly ref: string,
739
- private readonly searchEnabled: () => boolean,
740
- ) {}
741
-
742
- #leaf(path: string): QueryLeafOps {
743
- return BASE_COLUMNS.has(path) ? BASE_COLUMN_LEAF : this.dialect;
744
- }
745
-
746
- compile(query?: DocumentQuery): CompiledQuery {
747
- const joins: SearchJoin[] = [];
748
- if (!query || (typeof query === "object" && !Array.isArray(query) && Object.keys(query).length === 0)) {
749
- return { where: "1 = 1", params: [], joins };
750
- }
751
- const compiled = this.compileNode(query, { joins, conjunctive: true });
752
- return { where: compiled.sql || "1 = 1", params: compiled.params, joins };
753
- }
754
-
755
- orderBy(sort: Record<string, 1 | -1> = { createdAt: -1 }) {
756
- return Object.entries(sort)
757
- .map(([path, direction]) => `${this.fieldExpr(path)} ${direction === 1 ? "ASC" : "DESC"}`)
758
- .join(", ");
759
- }
760
-
761
- fieldExpr(path: string) {
762
- this.assertPath(path);
763
- return BASE_COLUMNS.has(path) ? quoteIdent(path) : this.dialect.extract(path);
764
- }
765
-
766
- projectExpr(path: string) {
767
- this.assertPath(path);
768
- return BASE_COLUMNS.has(path) ? quoteIdent(path) : this.dialect.projectExpr(path);
769
- }
770
-
771
- private compileNode(query: DocumentQuery, ctx: CompileContext): { sql: string; params: unknown[] } {
772
- if (this.isQueryNode(query)) {
773
- if (query.kind === "search") {
774
- if (!ctx.conjunctive)
775
- throw new Error(
776
- `Text search on "${this.ref}" must sit at an AND position; q.search() cannot be nested under q.any() or q.not().`,
777
- );
778
- const join = this.#searchJoin(query, ctx.joins.length);
779
- if (join) ctx.joins.push(join);
780
- return { sql: join ? "" : "0 = 1", params: [] };
781
- }
782
- if (query.kind === "all" || query.kind === "any") {
783
- const subCtx = query.kind === "all" ? ctx : { ...ctx, conjunctive: false };
784
- const parts = query.queries.map((sub) => this.compileNode(sub, subCtx)).filter((part) => part.sql);
785
- if (!parts.length) return { sql: "1 = 1", params: [] };
786
- const joiner = query.kind === "all" ? " AND " : " OR ";
787
- return {
788
- sql: `(${parts.map((part) => part.sql).join(joiner)})`,
789
- params: parts.flatMap((part) => part.params),
790
- };
791
- }
792
- if (query.kind === "not") {
793
- const part = this.compileNode(query.query, { ...ctx, conjunctive: false });
794
- return { sql: `NOT (${part.sql})`, params: part.params };
795
- }
796
- if (query.kind === "raw") {
797
- if (/[;]/.test(query.sql)) throw new Error("Raw SQL query fragments must be a single statement fragment");
798
- return { sql: `(${query.sql})`, params: query.params };
799
- }
800
- throw new Error("Operator nodes must be attached to a document path");
801
- }
802
- const parts = Object.entries(query).flatMap(([path, value]) => {
803
- if (value === undefined) throw new Error(`Undefined query value is not allowed: ${path}`);
804
- return [this.compileField(path, value, ctx)];
805
- });
806
- if (!parts.length) return { sql: "1 = 1", params: [] };
807
- return {
808
- sql: `(${parts.map((part) => part.sql).join(" AND ")})`,
809
- params: parts.flatMap((part) => part.params),
810
- };
811
- }
812
-
813
- #searchJoin(node: Extract<DocumentQueryNode, { kind: "search" }>, index: number): SearchJoin | null {
814
- if (!this.searchEnabled())
815
- throw new Error(
816
- `Text search on "${this.ref}" is unavailable because the search index is switched off (AKAN_SEARCH_ENABLED).`,
817
- );
818
- const columns = node.columns?.filter((column) => searchColumns.includes(column));
819
- if (node.columns?.length && !columns?.length)
820
- throw new Error(`Unknown search column on "${this.ref}": ${node.columns.join(", ")}`);
821
- const match = toMatchExpression(node.text, { prefix: node.prefix, columns });
822
-
823
- if (!match) return null;
824
- const weights = node.weights ?? DEFAULT_SEARCH_WEIGHTS;
825
-
826
- if (weights.length !== searchColumns.length || weights.some((weight) => !Number.isFinite(weight)))
827
- throw new Error(
828
- `Search weights on "${this.ref}" must be ${searchColumns.length} finite numbers: ${JSON.stringify(node.weights)}`,
829
- );
830
- const alias = `__s${index}`;
831
- return { alias, ...this.dialect.searchJoin({ alias, ref: this.ref, match, weights }) };
832
- }
833
-
834
- private compileField(path: string, value: unknown, ctx: CompileContext): { sql: string; params: unknown[] } {
835
- this.assertPath(path);
836
- const field = this.fields[path]?.getProps?.() ?? this.fields[path];
837
- const leaf = this.#leaf(path);
838
- if (this.isQueryNode(value)) {
839
- if (value.kind !== "op") return this.compileNode({ [path]: value } as DocumentQuery, ctx);
840
- switch (value.op) {
841
- case "eq":
842
- return leaf.eq(path, value.value);
843
- case "ne":
844
- return leaf.ne(path, value.value);
845
- case "oneOf": {
846
- const values = (value.value as unknown[]) ?? [];
847
- if (!values.length) return { sql: "0 = 1", params: [] };
848
- if (field?.isArray) {
849
- const parts = values.map((item) => leaf.arrayHas(path, item));
850
- return {
851
- sql: `(${parts.map((part) => part.sql).join(" OR ")})`,
852
- params: parts.flatMap((part) => part.params),
853
- };
854
- }
855
- return leaf.inList(path, values);
856
- }
857
- case "notOneOf": {
858
- const values = (value.value as unknown[]) ?? [];
859
- if (!values.length) return { sql: "1 = 1", params: [] };
860
- if (field?.isArray) {
861
- const parts = values.map((item) => leaf.arrayHas(path, item));
862
- return {
863
- sql: `NOT (${parts.map((part) => part.sql).join(" OR ")})`,
864
- params: parts.flatMap((part) => part.params),
865
- };
866
- }
867
- return leaf.notInList(path, values);
868
- }
869
- case "gt":
870
- case "gte":
871
- case "lt":
872
- case "lte":
873
- return leaf.compare(path, value.op, value.value);
874
- case "between": {
875
- const [from, to] = value.value as [unknown, unknown];
876
- return leaf.between(path, from, to);
877
- }
878
- case "exists":
879
- return leaf.exists(path);
880
- case "missing":
881
- return leaf.missing(path);
882
- case "empty":
883
- return leaf.empty(path);
884
- case "has":
885
- return leaf.arrayHas(path, value.value);
886
- case "contains":
887
- return leaf.contains(path, value.value);
888
- }
889
- }
890
- if (value && typeof value === "object" && !Array.isArray(value)) {
891
- const operators = value as Record<string, unknown>;
892
- const keys = Object.keys(operators);
893
- if (keys.some((key) => QUERY_OPERATOR_KEYS.has(key))) {
894
- const parts = keys.flatMap((key) => {
895
- if (!QUERY_OPERATOR_KEYS.has(key)) return [];
896
- if (key === "exists")
897
- return [this.compileField(path, { kind: "op", op: operators.exists ? "exists" : "missing" }, ctx)];
898
- if (key === "missing")
899
- return [this.compileField(path, { kind: "op", op: operators.missing ? "missing" : "exists" }, ctx)];
900
- if (key === "empty")
901
- return [this.compileField(path, { kind: "op", op: operators.empty ? "empty" : "exists" }, ctx)];
902
- return [this.compileField(path, { kind: "op", op: key as QueryOperatorName, value: operators[key] }, ctx)];
903
- });
904
- return {
905
- sql: `(${parts.map((part) => part.sql).join(" AND ")})`,
906
- params: parts.flatMap((part) => part.params),
907
- };
908
- }
909
- }
910
- if (field?.isArray && !Array.isArray(value)) return leaf.arrayHas(path, value);
911
- return leaf.eq(path, value);
912
- }
913
-
914
- private assertPath(path: string) {
915
- const root = path.split(".")[0];
916
- if (BASE_COLUMNS.has(root)) return;
917
- if (!this.fields[root]) {
918
-
919
- if (/^\d+$/.test(root))
920
- throw new Error(
921
- `Query received an array instead of a query object (field path "${path}"). ` +
922
- `A query must be a descriptor object; a slice exec must return queryBy...(...), not an executed list.`,
923
- );
924
- throw new Error(`Unknown document field path: ${path}`);
925
- }
926
- }
927
-
928
- private isQueryNode(value: unknown): value is DocumentQueryNode {
929
- return !!value && typeof value === "object" && "kind" in value;
930
- }
931
- }
932
-
933
- class UpdateCompiler {
934
- constructor(
935
- private readonly fields: FieldMap,
936
- private readonly dialect: SqlDialect,
937
- ) {}
938
-
939
- compile(update: DocumentUpdate): { assignments: string[]; params: unknown[]; setOnInsert: Record<string, unknown> } {
940
- const baseAssignments: string[] = [];
941
- const baseParams: unknown[] = [];
942
- const setOnInsert: Record<string, unknown> = {};
943
- const jsonOps: { op: DocumentUpdateOperator; path: string; value: unknown }[] = [];
944
- for (const [path, raw] of Object.entries(update)) {
945
- if (raw === undefined) continue;
946
- const node: DocumentUpdateNode = isDocumentUpdateNode(raw) ? raw : { kind: "update", op: "set", value: raw };
947
- this.#assertPath(path);
948
- if (node.op === "setOnInsert") {
949
- setOnInsert[path] = node.value;
950
- continue;
951
- }
952
- if (BASE_COLUMNS.has(path)) {
953
- if (node.op === "set") {
954
- baseAssignments.push(`${quoteIdent(path)} = ?`);
955
- baseParams.push(encodeSqlValue(node.value));
956
- } else if (node.op === "unset") {
957
- baseAssignments.push(`${quoteIdent(path)} = NULL`);
958
- } else {
959
- throw new Error(`Unsupported update operator '${node.op}' on base column: ${path}`);
960
- }
961
- continue;
962
- }
963
- jsonOps.push({ op: node.op, path, value: node.value });
964
- }
965
- const assignments = [...baseAssignments];
966
- const params = [...baseParams];
967
- if (jsonOps.length) {
968
- let acc = this.dialect.docColumn();
969
- for (const { op, path, value } of jsonOps) {
970
- const frag = this.dialect.applyUpdate(acc, op, path, value);
971
- acc = frag.sql;
972
- params.push(...frag.params);
973
- }
974
- assignments.push(`${this.dialect.docColumn()} = ${acc}`);
975
- }
976
- return { assignments, params, setOnInsert };
977
- }
978
-
979
- #assertPath(path: string) {
980
- const root = path.split(".")[0];
981
- if (BASE_COLUMNS.has(root)) return;
982
- if (!this.fields[root]) throw new Error(`Unknown document field path: ${path}`);
983
- }
984
- }
985
-
36
+ export { PostgresDialect } from "./sql/dialect/postgres";
37
+ export { SqliteDialect } from "./sql/dialect/sqlite";
38
+ export { SqlDocumentStore } from "./sql/SqlDocumentStore";
986
39
  /**
987
- * Per-document modification state, attached only when a document is hydrated for writing.
988
- * Non-enumerable so `{ ...doc }` in `toRow` and `Object.entries` in `sanitizeJson` never see it.
40
+ * The three SQL databases an app can mount, and nothing else. The layer underneath them — drivers, dialects,
41
+ * the query and update compilers, and the document store they all share — lives in .
989
42
  */
990
- const MODIFICATION_STATE = Symbol("akan.document.modificationState");
991
-
992
- interface ModificationState {
993
- isNew: boolean;
994
- original: Record<string, unknown>;
995
- }
996
-
997
- export class SqlDocumentStore {
998
- readonly schema: DocumentSchema;
999
- readonly table: string;
1000
- readonly compiler: QueryCompiler;
1001
- readonly updateCompiler: UpdateCompiler;
1002
- #insertStmt: AkanSqlStatement | null = null;
1003
- #readStmtCache = new Map<string, AkanSqlStatement>();
1004
- #docPrototype: object | null = null;
1005
- #immutableKeys: string[] | null = null;
1006
-
1007
- constructor(
1008
- private readonly owner: DocumentDatabaseOwner,
1009
- readonly constant: ConstantModel,
1010
- readonly database: DatabaseModel,
1011
- schema: DocumentSchema,
1012
- private readonly dialect: SqlDialect = new SqliteDialect(),
1013
- ) {
1014
- this.schema = schema;
1015
- this.table = database.refName;
1016
- const fields = database.doc[FIELD_META] as unknown as FieldMap;
1017
-
1018
- this.compiler = new QueryCompiler(fields, dialect, this.table, () => !!this.owner.getSearchIndex()?.enabled);
1019
- this.updateCompiler = new UpdateCompiler(fields, dialect);
1020
- }
1021
-
1022
- async ensure() {
1023
- this.assertValidRefName(this.table);
1024
- const db = this.owner.getConnection();
1025
- const ts = this.dialect.timestampType();
1026
- await db.execute(
1027
- `CREATE TABLE IF NOT EXISTS ${quoteIdent(this.table)} (
1028
- "id" TEXT PRIMARY KEY NOT NULL,
1029
- "createdAt" ${ts} NOT NULL,
1030
- "updatedAt" ${ts} NOT NULL,
1031
- "removedAt" ${ts},
1032
- "_doc" ${this.dialect.docColumnType()} NOT NULL
1033
- )`,
1034
- );
1035
- await this.owner.setMeta(
1036
- `table:${this.table}`,
1037
- await descriptorHash({ table: this.table, columns: ["id", "createdAt", "updatedAt", "removedAt", "_doc"] }),
1038
- );
1039
- for (const [idx, index] of this.schema.indexes.entries()) {
1040
- const name = index.name ?? `${this.table}_${Object.keys(index.fields).map(toSafeRefName).join("_")}_${idx}`;
1041
- this.assertValidRefName(name);
1042
- const hash = await descriptorHash(index);
1043
- const metaKey = `index:${this.table}:${name}`;
1044
- const existing = await this.owner.getMeta(metaKey);
1045
- if (existing && existing !== hash) throw new Error(`Index descriptor mismatch: ${name}`);
1046
- const expressions = Object.keys(index.fields).map((field) => this.compiler.fieldExpr(field));
1047
- const unique = index.unique ? "UNIQUE " : "";
1048
- await db.execute(
1049
- `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdent(name)} ON ${quoteIdent(this.table)} (${expressions.join(", ")})`,
1050
- );
1051
- await this.owner.setMeta(metaKey, hash);
1052
- }
1053
- await this.owner.getSearchIndex()?.ensureRef(this.constant, this.database);
1054
- }
1055
-
1056
- async create(data: DocumentRecord, { runSaveHooks = true }: WriteHookOptions = {}) {
1057
- const now = Date.now();
1058
- const id = data.id ?? createDocumentId(now);
1059
- if (!isDocumentId(id)) throw new Error(`Invalid ID value: ${id}`);
1060
- const doc = this.hydrate(
1061
- this.prepareDocument({
1062
- ...data,
1063
- id,
1064
- createdAt: data.createdAt ?? dayjs(now),
1065
- updatedAt: data.updatedAt ?? dayjs(now),
1066
- }),
1067
- );
1068
- if (runSaveHooks) await this.runHooks("save", "create", doc, "pre");
1069
- await this.runHooks("create", "create", doc, "pre");
1070
- const row = this.toRow(doc);
1071
- await this.insertStmt().run(row.id, row.createdAt, row.updatedAt, row.removedAt, row._doc);
1072
- await this.runHooks("create", "create", doc, "post");
1073
- if (runSaveHooks) await this.runHooks("save", "create", doc, "post");
1074
- return doc;
1075
- }
1076
-
1077
- async clone(data: DocumentRecord & { id: string }) {
1078
- return this.create(data);
1079
- }
1080
-
1081
- async update(id: string, patch: DocumentRecord, options: WriteHookOptions = {}) {
1082
- const current = await this.pickByIdForWrite(id);
1083
- return await this.writeUpdatedDocument(id, { ...current, ...patch, id, updatedAt: dayjs() }, current, options);
1084
- }
1085
-
1086
- async remove(id: string) {
1087
-
1088
- return this.update(id, { removedAt: dayjs() }, { runSaveHooks: false, crudType: "remove" });
1089
- }
1090
-
1091
- async updateOneByQuery(query: DocumentQuery, update: DocumentUpdateInput, options: DocumentUpdateOptions = {}) {
1092
- const resolved = resolveDocumentUpdate(update);
1093
- const { assignments, params } = this.compiledUpdate(resolved);
1094
- const { where, params: whereParams } = this.writeQuery(query, "updateOneByQuery");
1095
- const subquery = `SELECT ${quoteIdent("id")} FROM ${quoteIdent(this.table)} WHERE ${where} ORDER BY ${this.compiler.orderBy()} LIMIT 1`;
1096
- const sql = `UPDATE ${quoteIdent(this.table)} SET ${assignments.join(", ")} WHERE ${quoteIdent("id")} IN (${subquery})`;
1097
- const changes = this.dialect.affectedRows(
1098
- await this.owner
1099
- .getConnection()
1100
- .prepare(sql)
1101
- .run(...params, ...whereParams),
1102
- );
1103
- if (changes > 0) return { acknowledged: true, matchedCount: 1, modifiedCount: 1, upsertedId: null };
1104
- if (!options.upsert) return { acknowledged: true, matchedCount: 0, modifiedCount: 0, upsertedId: null };
1105
- const inserted = await this.create(this.applyInsertUpdate(this.extractInsertBase(query), resolved), {
1106
- runSaveHooks: false,
1107
- });
1108
- return { acknowledged: true, matchedCount: 0, modifiedCount: 1, upsertedId: inserted.id };
1109
- }
1110
-
1111
- async updateManyByQuery(query: DocumentQuery, update: DocumentUpdateInput) {
1112
- const { assignments, params } = this.compiledUpdate(resolveDocumentUpdate(update));
1113
- const { where, params: whereParams } = this.writeQuery(query, "updateManyByQuery");
1114
- const sql = `UPDATE ${quoteIdent(this.table)} SET ${assignments.join(", ")} WHERE ${where}`;
1115
- const changes = this.dialect.affectedRows(
1116
- await this.owner
1117
- .getConnection()
1118
- .prepare(sql)
1119
- .run(...params, ...whereParams),
1120
- );
1121
- return { acknowledged: true, matchedCount: changes, modifiedCount: changes };
1122
- }
1123
-
1124
- async removeManyByQuery(query: DocumentQuery) {
1125
-
1126
- return this.updateManyByQuery(query, { removedAt: dayjs() });
1127
- }
1128
-
1129
- async removeOneByQuery(query: DocumentQuery) {
1130
-
1131
- return this.updateOneByQuery(query, { removedAt: dayjs() });
1132
- }
1133
-
1134
- private compiledUpdate(update: DocumentUpdate) {
1135
- const compiled = this.updateCompiler.compile(update);
1136
- return {
1137
- assignments: [`${quoteIdent("updatedAt")} = ?`, ...compiled.assignments],
1138
- params: [Date.now(), ...compiled.params],
1139
- };
1140
- }
1141
-
1142
- async bulkWrite(
1143
- operations: { updateOne: { filter: DocumentQuery; update: DocumentUpdateInput; upsert?: boolean } }[],
1144
- ) {
1145
- let matchedCount = 0;
1146
- let modifiedCount = 0;
1147
- let upsertedId: string | null = null;
1148
- for (const operation of operations) {
1149
- const result = await this.updateOneByQuery(operation.updateOne.filter, operation.updateOne.update, {
1150
- upsert: operation.updateOne.upsert,
1151
- });
1152
- matchedCount += result.matchedCount;
1153
- modifiedCount += result.modifiedCount;
1154
- upsertedId ??= result.upsertedId ?? null;
1155
- }
1156
- return { acknowledged: true, matchedCount, modifiedCount, upsertedId };
1157
- }
1158
-
1159
- async find(query?: DocumentQuery, options: FindManyOptions = {}) {
1160
- const { where, params, joins } = this.safeQuery(query);
1161
- const limitValue = Number(options.limit ?? 0);
1162
- const skipValue = Number(options.skip ?? 0);
1163
- const limit = limitValue ? ` LIMIT ${limitValue}` : "";
1164
- const offset = skipValue ? ` OFFSET ${skipValue}` : "";
1165
- const join = this.joinSql(joins);
1166
- const order = options.sample ? "ORDER BY random()" : `ORDER BY ${this.orderBy(options.sort, joins)}`;
1167
- const args = [...this.joinParams(joins), ...params];
1168
- const projection = this.resolveProjection(options.select);
1169
- if (projection) {
1170
- const rows = await this.prepareReadStmt(
1171
- `SELECT ${this.projectionSql(projection)} FROM ${quoteIdent(this.table)}${join} WHERE ${where} ${order}${limit}${offset}`,
1172
- ).all<ProjectedSqliteDocumentRow>(...args);
1173
- return rows.map((row) => this.hydrate(this.fromProjectedRow(row, projection), undefined, { track: false }));
1174
- }
1175
-
1176
- const star = joins.length ? `${quoteIdent(this.table)}.*` : "*";
1177
- const rows = await this.prepareReadStmt(
1178
- `SELECT ${star} FROM ${quoteIdent(this.table)}${join} WHERE ${where} ${order}${limit}${offset}`,
1179
- ).all<SqliteDocumentRow>(...args);
1180
- return rows.map((row) => this.hydrate(this.fromRow(row), undefined, { track: false }));
1181
- }
1182
-
1183
- async findIds(
1184
- query?: DocumentQuery,
1185
- options: { sort?: SortOption; skip?: number | null; limit?: number | null; sample?: number } = {},
1186
- ) {
1187
- const { where, params, joins } = this.safeQuery(query);
1188
- const limitValue = Number(options.limit ?? 0);
1189
- const skipValue = Number(options.skip ?? 0);
1190
- const limit = limitValue ? ` LIMIT ${limitValue}` : "";
1191
- const offset = skipValue ? ` OFFSET ${skipValue}` : "";
1192
- const join = this.joinSql(joins);
1193
- const order = options.sample ? "ORDER BY random()" : `ORDER BY ${this.orderBy(options.sort, joins)}`;
1194
- const rows = await this.prepareReadStmt(
1195
- `SELECT ${quoteIdent(this.table)}."id" FROM ${quoteIdent(this.table)}${join} WHERE ${where} ${order}${limit}${offset}`,
1196
- ).all<{ id: string }>(...this.joinParams(joins), ...params);
1197
- return rows.map((row) => row.id);
1198
- }
1199
-
1200
- async findOne(query?: DocumentQuery, options: FindOneOptions = {}) {
1201
- return (await this.find(query, { ...options, limit: 1, sample: options.sample ? 1 : undefined })).at(0) ?? null;
1202
- }
1203
-
1204
- async findId(query?: DocumentQuery, options: { sort?: SortOption; skip?: number | null; sample?: boolean } = {}) {
1205
- return (await this.findIds(query, { ...options, limit: 1, sample: options.sample ? 1 : undefined })).at(0) ?? null;
1206
- }
1207
-
1208
- async pickOne(query?: DocumentQuery, options: FindOneOptions = {}) {
1209
- const doc = await this.findOne(query, options);
1210
- if (!doc) throw new NoDocumentError(`No Document (${this.table}): ${JSON.stringify(query)}`);
1211
- return doc;
1212
- }
1213
-
1214
- async pickById(id: string) {
1215
- const doc = await this.findOne({ id } as DocumentQuery);
1216
- if (!doc) throw new NoDocumentError(`No Document (${this.table}): ${id}`);
1217
- return doc;
1218
- }
1219
-
1220
- async exists(query?: DocumentQuery) {
1221
- return this.findId(query);
1222
- }
1223
-
1224
- async count(query?: DocumentQuery) {
1225
- const { where, params, joins } = this.safeQuery(query);
1226
- const row = await this.prepareReadStmt(
1227
- `SELECT count(*) as count FROM ${quoteIdent(this.table)}${this.joinSql(joins)} WHERE ${where}`,
1228
- ).get<{ count: number }>(...this.joinParams(joins), ...params);
1229
- return row?.count ?? 0;
1230
- }
1231
-
1232
- async insight(query?: DocumentQuery) {
1233
- const insightFields = this.constant.insight[FIELD_META] as unknown as FieldMap;
1234
- const result: DocumentRecord = {};
1235
- for (const [key, field] of Object.entries(insightFields)) {
1236
- const props = field.getProps();
1237
- if (!props.accumulate) {
1238
- result[key] = props.default;
1239
- } else if (
1240
- typeof props.accumulate === "object" &&
1241
- !Object.keys(props.accumulate as Record<string, unknown>).some((key) => key.startsWith("$"))
1242
- ) {
1243
- result[key] = await this.count(documentQueryHelper.all(query ?? {}, props.accumulate as DocumentQuery));
1244
- } else {
1245
- result[key] = await this.count(query);
1246
- }
1247
- }
1248
- return result;
1249
- }
1250
-
1251
- private safeQuery(query?: DocumentQuery) {
1252
- return this.compiler.compile(documentQueryHelper.all(documentQueryHelper.empty("removedAt"), query ?? {}));
1253
- }
1254
-
1255
- private writeQuery(query: DocumentQuery | undefined, operation: string) {
1256
- const compiled = this.safeQuery(query);
1257
- if (compiled.joins.length)
1258
- throw new Error(`q.search() cannot be used in ${operation} on "${this.table}"; query-level writes take no join.`);
1259
- return compiled;
1260
- }
1261
-
1262
- private joinSql(joins: SearchJoin[]) {
1263
- return joins.length ? ` ${joins.map((join) => join.sql).join(" ")}` : "";
1264
- }
1265
-
1266
- private joinParams(joins: SearchJoin[]) {
1267
- return joins.flatMap((join) => join.params);
1268
- }
1269
-
1270
- private orderBy(sort: SortOption, joins: SearchJoin[]) {
1271
- const explicit = sort && Object.keys(sort).length ? sort : null;
1272
- if (!explicit && joins.length) return `${joins[0].alias}."score", ${quoteIdent(this.table)}."id" DESC`;
1273
- return this.compiler.orderBy(explicit ?? undefined);
1274
- }
1275
-
1276
- private prepareDocument(data: DocumentRecord) {
1277
- const fields = this.database.doc[FIELD_META] as unknown as FieldMap;
1278
- const doc: MutableDocumentRecord = {};
1279
- for (const [key, field] of Object.entries(fields)) {
1280
- const props = field.getProps();
1281
- const value = data[key];
1282
- if (value === undefined) {
1283
- if (props.default !== undefined && props.default !== null) {
1284
- doc[key] = typeof props.default === "function" ? props.default(data) : props.default;
1285
- } else if (!props.nullable && !["removedAt"].includes(key)) {
1286
- if (["id", "createdAt", "updatedAt"].includes(key)) continue;
1287
- throw new Error(`Missing required field: ${key}`);
1288
- }
1289
- } else if (value === null && !props.nullable) {
1290
- throw new Error(`Field is not nullable: ${key}`);
1291
- } else {
1292
- doc[key] = value;
1293
- }
1294
- if (doc[key] !== undefined && doc[key] !== null) {
1295
- doc[key] = this.normalizeWriteValue(doc[key], props);
1296
- }
1297
- if (props.enum && doc[key] !== undefined && doc[key] !== null) {
1298
- const values = Array.isArray(doc[key]) ? doc[key] : [doc[key]];
1299
- const fieldEnum = props.enum as { has: (value: unknown) => boolean } | undefined;
1300
- const invalidValue = fieldEnum ? values.find((value: unknown) => !fieldEnum.has(value)) : undefined;
1301
- if (invalidValue !== undefined) throw new Error(`Invalid enum value for ${key}: ${invalidValue}`);
1302
- }
1303
- const validate = props.validate as ((value: unknown, doc: MutableDocumentRecord) => boolean) | undefined;
1304
- if (validate && doc[key] !== undefined && doc[key] !== null && !validate(doc[key], doc)) {
1305
- throw new Error(`Invalid field value: ${key}`);
1306
- }
1307
- }
1308
- return { ...data, ...doc };
1309
- }
1310
-
1311
- private extractInsertBase(query: DocumentQuery): Record<string, unknown> {
1312
- if (!query || typeof query !== "object" || Array.isArray(query) || "kind" in query) return {};
1313
- return Object.fromEntries(
1314
- Object.entries(query).flatMap(([key, value]) => {
1315
- if (["all", "any"].includes(key) || key.startsWith("$")) return [];
1316
- if (value === null || ["string", "number", "boolean"].includes(typeof value)) return [[key, value]];
1317
- return [];
1318
- }),
1319
- );
1320
- }
1321
-
1322
- private applyInsertUpdate(base: DocumentRecord, update: DocumentUpdate) {
1323
- const doc: MutableDocumentRecord = { ...base };
1324
- const setPath = (path: string, value: unknown) => {
1325
- const parts = path.split(".");
1326
- let target: MutableDocumentRecord = doc;
1327
- for (const part of parts.slice(0, -1)) {
1328
- target[part] ??= {};
1329
- target = target[part] as MutableDocumentRecord;
1330
- }
1331
- target[parts.at(-1) as string] = value;
1332
- };
1333
- const getPath = (path: string) =>
1334
- path.split(".").reduce<unknown>((obj, key) => (obj as DocumentRecord | undefined)?.[key], doc);
1335
- for (const [path, raw] of Object.entries(update)) {
1336
- if (raw === undefined) continue;
1337
- const node: DocumentUpdateNode = isDocumentUpdateNode(raw) ? raw : { kind: "update", op: "set", value: raw };
1338
- const current = getPath(path);
1339
- switch (node.op) {
1340
- case "set":
1341
- case "setOnInsert":
1342
- setPath(path, node.value);
1343
- break;
1344
- case "unset": {
1345
- const parts = path.split(".");
1346
- let target: MutableDocumentRecord | undefined = doc;
1347
- for (const part of parts.slice(0, -1)) {
1348
- target = target?.[part] as MutableDocumentRecord | undefined;
1349
- if (!target || typeof target !== "object") break;
1350
- }
1351
- if (target) delete target[parts.at(-1) as string];
1352
- break;
1353
- }
1354
- case "inc":
1355
- setPath(path, Number(current ?? 0) + Number(node.value));
1356
- break;
1357
- case "mul":
1358
- setPath(path, Number(current ?? 0) * Number(node.value));
1359
- break;
1360
- case "min":
1361
- setPath(path, current === undefined ? node.value : Math.min(Number(current), Number(node.value)));
1362
- break;
1363
- case "max":
1364
- setPath(path, current === undefined ? node.value : Math.max(Number(current), Number(node.value)));
1365
- break;
1366
- case "push":
1367
- setPath(path, [...(Array.isArray(current) ? current : []), node.value]);
1368
- break;
1369
- case "addToSet": {
1370
- const arr = Array.isArray(current) ? current : [];
1371
- if (!arr.some((item) => stableJson(item) === stableJson(node.value))) setPath(path, [...arr, node.value]);
1372
- break;
1373
- }
1374
- case "pull":
1375
- if (Array.isArray(current))
1376
- setPath(
1377
- path,
1378
- current.filter((item) => stableJson(item) !== stableJson(node.value)),
1379
- );
1380
- break;
1381
- }
1382
- }
1383
- return doc;
1384
- }
1385
-
1386
- private toRow(doc: DocumentRecord) {
1387
- const payload = { ...doc };
1388
- delete payload.id;
1389
- delete payload.createdAt;
1390
- delete payload.updatedAt;
1391
- delete payload.removedAt;
1392
- return {
1393
- id: doc.id,
1394
- createdAt: Number(encodeSqlValue(doc.createdAt ?? dayjs())),
1395
- updatedAt: Number(encodeSqlValue(doc.updatedAt ?? dayjs())),
1396
- removedAt: doc.removedAt ? Number(encodeSqlValue(doc.removedAt)) : null,
1397
- _doc: JSON.stringify(sanitizeJson(payload)),
1398
- };
1399
- }
1400
-
1401
- private fromRow(row: SqliteDocumentRow) {
1402
-
1403
- const rawDoc: unknown = row._doc;
1404
- const raw = typeof rawDoc === "string" ? JSON.parse(rawDoc) : (rawDoc as Record<string, unknown>);
1405
- const payload = this.decodeDocumentPayload(raw);
1406
- return {
1407
- id: row.id,
1408
- createdAt: dayjs(Number(row.createdAt)),
1409
- updatedAt: dayjs(Number(row.updatedAt)),
1410
- removedAt: row.removedAt ? dayjs(Number(row.removedAt)) : undefined,
1411
- ...payload,
1412
- };
1413
- }
1414
-
1415
- private normalizeProjection(select: ProjectionOption): string[] | null {
1416
- if (!select) return null;
1417
- const fields = Object.entries(select)
1418
- .filter(([, included]) => included)
1419
- .map(([field]) => field);
1420
- return [...new Set(fields.filter((field) => field !== "_doc"))];
1421
- }
1422
-
1423
- private resolveProjection(select: ProjectionOption): string[] | null {
1424
- const projection = this.normalizeProjection(select);
1425
- if (projection !== null) return projection;
1426
- return this.defaultProjection();
1427
- }
1428
-
1429
- private defaultProjection(): string[] | null {
1430
- const fields = this.database.doc[FIELD_META] as unknown as FieldMap;
1431
- const entries = Object.entries(fields).filter(([key]) => !BASE_COLUMNS.has(key));
1432
- if (!entries.some(([, field]) => field.getProps().select === false)) return null;
1433
- return entries.flatMap(([key, field]) => (field.getProps().select === false ? [] : [key]));
1434
- }
1435
-
1436
- private projectionSql(fields: string[]) {
1437
- const jsonFields = fields.filter((field) => !BASE_COLUMNS.has(field));
1438
- const baseColumns = [...BASE_COLUMNS].map((field) => quoteIdent(field));
1439
- const jsonColumns = jsonFields.map(
1440
- (field, idx) => `${this.compiler.projectExpr(field)} AS ${quoteIdent(this.projectionAlias(idx))}`,
1441
- );
1442
- return [...baseColumns, ...jsonColumns].join(", ");
1443
- }
1444
-
1445
- private projectionAlias(idx: number) {
1446
- return `__akan_projection_${idx}`;
1447
- }
1448
-
1449
- private fromProjectedRow(row: ProjectedSqliteDocumentRow, fields: string[]) {
1450
- const doc: DocumentRecord = {
1451
- id: row.id,
1452
- createdAt: dayjs(Number(row.createdAt)),
1453
- updatedAt: dayjs(Number(row.updatedAt)),
1454
- removedAt: row.removedAt ? dayjs(Number(row.removedAt)) : undefined,
1455
- };
1456
- const jsonFields = fields.filter((field) => !BASE_COLUMNS.has(field));
1457
- for (const [idx, field] of jsonFields.entries()) {
1458
- const value = this.dialect.decodeProjected(row[this.projectionAlias(idx)]);
1459
- const props = (this.database.doc[FIELD_META] as unknown as FieldMap)[field]?.getProps?.();
1460
- if (value === null && !props?.nullable) {
1461
- if (props?.default != null) {
1462
- doc[field] =
1463
- typeof props.default === "function" ? (props.default as (data: unknown) => unknown)(doc) : props.default;
1464
- } else {
1465
- doc[field] =
1466
- ((props as Record<string, unknown>).modelRef as { [DEFAULT_VALUE]?: unknown })?.[DEFAULT_VALUE] ?? null;
1467
- }
1468
- } else {
1469
- doc[field] = props ? this.decodeFieldValue(value, props) : value;
1470
- }
1471
- }
1472
- return doc;
1473
- }
1474
-
1475
- private async findForWrite(query?: DocumentQuery, options: FindManyOptions = {}) {
1476
- const { where, params, joins } = this.safeQuery(query);
1477
- const limitValue = Number(options.limit ?? 0);
1478
- const skipValue = Number(options.skip ?? 0);
1479
- const limit = limitValue ? ` LIMIT ${limitValue}` : "";
1480
- const offset = skipValue ? ` OFFSET ${skipValue}` : "";
1481
- const join = this.joinSql(joins);
1482
- const order = options.sample ? "ORDER BY random()" : `ORDER BY ${this.orderBy(options.sort, joins)}`;
1483
- const star = joins.length ? `${quoteIdent(this.table)}.*` : "*";
1484
- const rows = await this.prepareReadStmt(
1485
- `SELECT ${star} FROM ${quoteIdent(this.table)}${join} WHERE ${where} ${order}${limit}${offset}`,
1486
- ).all<SqliteDocumentRow>(...this.joinParams(joins), ...params);
1487
- return rows.map((row) => this.hydrate(this.fromRow(row)));
1488
- }
1489
-
1490
- private async findOneForWrite(query?: DocumentQuery, options: FindOneOptions = {}) {
1491
- return (
1492
- (await this.findForWrite(query, { ...options, limit: 1, sample: options.sample ? 1 : undefined })).at(0) ?? null
1493
- );
1494
- }
1495
-
1496
- private async pickByIdForWrite(id: string) {
1497
- const doc = await this.findOneForWrite({ id } as DocumentQuery);
1498
- if (!doc) throw new NoDocumentError(`No Document (${this.table}): ${id}`);
1499
- return doc;
1500
- }
1501
-
1502
- private async writeUpdatedDocument(
1503
- id: string,
1504
- data: DocumentRecord,
1505
- originalData: DocumentRecord,
1506
- { runSaveHooks = true, crudType = "update" }: WriteHookOptions = {},
1507
- ) {
1508
- const prepared = this.prepareDocument({ ...data, id, updatedAt: dayjs() });
1509
- this.#assertImmutableUnchanged(prepared, originalData);
1510
- const doc = this.hydrate(prepared, originalData);
1511
- if (runSaveHooks) await this.runHooks("save", crudType, doc, "pre");
1512
- await this.runHooks(crudType, crudType, doc, "pre");
1513
- const row = this.toRow(doc);
1514
- await this.owner
1515
- .getConnection()
1516
- .prepare(
1517
- `UPDATE ${quoteIdent(this.table)} SET "createdAt" = ?, "updatedAt" = ?, "removedAt" = ?, "_doc" = ${this.dialect.docValuePlaceholder()} WHERE "id" = ?`,
1518
- )
1519
- .run(row.createdAt, row.updatedAt, row.removedAt, row._doc, id);
1520
- await this.runHooks(crudType, crudType, doc, "post");
1521
- if (runSaveHooks) await this.runHooks("save", crudType, doc, "post");
1522
- return doc;
1523
- }
1524
-
1525
- #assertImmutableUnchanged(prepared: DocumentRecord, originalData: DocumentRecord) {
1526
- this.#immutableKeys ??= Object.entries(this.database.doc[FIELD_META] as unknown as FieldMap)
1527
- .filter(([, fieldMeta]) => fieldMeta.getProps().immutable)
1528
- .map(([key]) => key);
1529
- if (!this.#immutableKeys.length) return;
1530
- const changed = this.#immutableKeys.filter((key) => jsonStr(prepared[key]) !== jsonStr(originalData[key]));
1531
- if (!changed.length) return;
1532
-
1533
- throw new Error(
1534
- `Cannot modify immutable field${changed.length > 1 ? "s" : ""} on ${this.table} (${String(prepared.id)}): ${changed.join(", ")}`,
1535
- );
1536
- }
1537
-
1538
- private decodeDocumentPayload(payload: Record<string, unknown>) {
1539
- const fields = this.database.doc[FIELD_META] as unknown as FieldMap;
1540
- const result: Record<string, unknown> = {};
1541
- for (const [key, fieldMeta] of Object.entries(fields)) {
1542
- if (BASE_COLUMNS.has(key)) continue;
1543
- const props = fieldMeta.getProps();
1544
- const value = payload[key];
1545
- if (value === undefined) {
1546
- const def = props.default;
1547
- if (def != null) {
1548
- result[key] = typeof def === "function" ? (def as (data: unknown) => unknown)(payload) : def;
1549
- } else if (props.nullable) {
1550
- result[key] = null;
1551
- } else {
1552
- result[key] =
1553
- ((props as Record<string, unknown>).modelRef as { [DEFAULT_VALUE]?: unknown })?.[DEFAULT_VALUE] ?? null;
1554
- }
1555
- } else {
1556
- result[key] = this.decodeFieldValue(value, props);
1557
- }
1558
- }
1559
- for (const [key, value] of Object.entries(payload)) {
1560
- if (key in result || BASE_COLUMNS.has(key)) continue;
1561
- const props = fields[key]?.getProps?.();
1562
- result[key] = props ? this.decodeFieldValue(value, props) : value;
1563
- }
1564
- return result;
1565
- }
1566
-
1567
- private decodeFieldValue(value: unknown, props: Record<string, unknown>): unknown {
1568
- if (value === undefined || value === null) return value;
1569
- if (props.isMap) {
1570
- const entries = value instanceof Map ? [...value.entries()] : Object.entries(value as Record<string, unknown>);
1571
- return new Map(entries.map(([key, item]) => [key, this.decodeMapValue(item, props)]));
1572
- }
1573
- if (props.modelRef === Date) {
1574
- if (Array.isArray(value)) return value.map((item) => (item === null ? item : decodeDateValue(item)));
1575
- return decodeDateValue(value);
1576
- }
1577
- if (Array.isArray(value)) return value.map((item) => this.decodeNestedValue(item, props));
1578
- return this.decodeNestedValue(value, props);
1579
- }
1580
-
1581
- private decodeMapValue(value: unknown, props: Record<string, unknown>) {
1582
- if (value === undefined || value === null) return value;
1583
- if (props.of === Date) return decodeDateValue(value);
1584
- return value;
1585
- }
1586
-
1587
- private decodeNestedValue(value: unknown, props: Record<string, unknown>): unknown {
1588
- if (!value || typeof value !== "object") return value;
1589
- if (!props.isClass || !props.isScalar) return value;
1590
- const scalarFields = (props.modelRef as { [FIELD_META]?: FieldMap } | undefined)?.[FIELD_META];
1591
- if (!scalarFields) return value;
1592
- const source = value as Record<string, unknown>;
1593
- const defaults = getDefault(scalarFields as never) as Record<string, unknown>;
1594
- const result: Record<string, unknown> = {};
1595
- for (const [key, fieldMeta] of Object.entries(scalarFields)) {
1596
- const nestedProps = fieldMeta.getProps();
1597
- const nested = source[key];
1598
- result[key] = nested === undefined ? defaults[key] : this.decodeFieldValue(nested, nestedProps);
1599
- }
1600
- for (const [key, nested] of Object.entries(source)) {
1601
- if (!(key in result)) result[key] = nested;
1602
- }
1603
- return result;
1604
- }
1605
-
1606
- private normalizeWriteValue(value: unknown, props: Record<string, unknown>): unknown {
1607
- if (value === undefined || value === null) return value;
1608
- if (props.modelRef === Date) {
1609
- if (Array.isArray(value))
1610
- return value.map((item) => (item === null || item === undefined ? item : dayjs(item as never)));
1611
- return dayjs(value as never);
1612
- }
1613
- if (!props.isClass || !props.isScalar) return value;
1614
- if (Array.isArray(value)) return value.map((item) => this.fillScalarDefaults(item, props));
1615
- return this.fillScalarDefaults(value, props);
1616
- }
1617
-
1618
- private fillScalarDefaults(value: unknown, props: Record<string, unknown>): unknown {
1619
- if (!value || typeof value !== "object") return value;
1620
- const scalarFields = (props.modelRef as { [FIELD_META]?: FieldMap } | undefined)?.[FIELD_META];
1621
- if (!scalarFields) return value;
1622
- const defaults = getDefault(scalarFields as never) as Record<string, unknown>;
1623
- const result = { ...(value as Record<string, unknown>) };
1624
- for (const [key, fieldMeta] of Object.entries(scalarFields)) {
1625
- const nestedProps = fieldMeta.getProps();
1626
- if (result[key] === undefined) result[key] = defaults[key];
1627
- else result[key] = this.normalizeWriteValue(result[key], nestedProps);
1628
- }
1629
- return result;
1630
- }
1631
-
1632
- /**
1633
- * `track` buys `isModified()` and costs a deep clone of the row, so it is decided per call site rather than
1634
- * paid everywhere. Only the read paths (`find`, and the projected read behind it) opt out — that clone was 42%
1635
- * of a list query, and a listed document is never the one a save hook runs on. Everything else keeps it, so an
1636
- * external caller of `hydrate` sees no change.
1637
- */
1638
- hydrate(data: DocumentRecord, originalData: DocumentRecord = data, { track = true }: { track?: boolean } = {}) {
1639
- const isNew = !originalData.id;
1640
- const hydratedData = isNew ? this.prepareDocument(data) : data;
1641
- const doc = Object.assign(Object.create(this.#documentPrototype()), hydratedData);
1642
- if (!track) return doc;
1643
- Object.defineProperty(doc, MODIFICATION_STATE, {
1644
- value: {
1645
- isNew,
1646
-
1647
- original: JSON.parse(JSON.stringify(sanitizeJson(originalData) ?? {})) as Record<string, unknown>,
1648
- } satisfies ModificationState,
1649
- });
1650
- return doc;
1651
- }
1652
-
1653
- /**
1654
- * One prototype per store instead of six closures per document. It extends the model's own document prototype,
1655
- * so declared chain methods and `instanceof` are unaffected, and every method here is non-enumerable exactly as
1656
- * the previous per-document `defineProperties` made them.
1657
- */
1658
- #documentPrototype() {
1659
- if (this.#docPrototype) return this.#docPrototype;
1660
- const store = this;
1661
- this.#docPrototype = Object.create(this.database.doc.prototype, {
1662
- set: {
1663
- value(this: DocumentRecord, patch: DocumentRecord) {
1664
- Object.assign(this, patch);
1665
- return this;
1666
- },
1667
- },
1668
- save: {
1669
- async value(this: DocumentRecord) {
1670
- return this.id ? store.update(this.id as string, this) : store.create(this);
1671
- },
1672
- },
1673
- refresh: {
1674
- async value(this: DocumentRecord) {
1675
- Object.assign(this, await store.pickById(this.id as string));
1676
- return this;
1677
- },
1678
- },
1679
- isModified: {
1680
- value(this: DocumentRecord & { [MODIFICATION_STATE]?: ModificationState }, field?: string) {
1681
- const state = this[MODIFICATION_STATE];
1682
- if (!state) throw new Error(SqlDocumentStore.#untrackedModificationMessage(store.table));
1683
- if (state.isNew) return true;
1684
- if (!field) return JSON.stringify(sanitizeJson(this)) !== JSON.stringify(state.original);
1685
- return JSON.stringify(sanitizeJson(this[field])) !== JSON.stringify(state.original[field]);
1686
- },
1687
- },
1688
- toJSON: {
1689
- value(this: DocumentRecord) {
1690
- return sanitizeJson(this);
1691
- },
1692
- },
1693
- toObject: {
1694
- value(this: DocumentRecord) {
1695
- return sanitizeJson(this);
1696
- },
1697
- },
1698
- }) as object;
1699
- return this.#docPrototype;
1700
- }
1701
-
1702
- static #untrackedModificationMessage(table: string) {
1703
- return (
1704
- `isModified() is unavailable on this ${table} document: it was loaded through a read query, which does not ` +
1705
- `snapshot the row. Call it inside a save hook, or re-load the document through the write path (\`save()\`, ` +
1706
- `\`update()\`) before comparing.`
1707
- );
1708
- }
1709
-
1710
- private async runHooks(
1711
- saveType: "save" | "create" | "update" | "remove",
1712
- crudType: "create" | "update" | "remove",
1713
- doc: DocumentRecord,
1714
- phase: "pre" | "post",
1715
- ) {
1716
- const hooks = phase === "pre" ? this.schema.preHooks.get(saveType) : this.schema.postHooks.get(saveType);
1717
- for (const hook of hooks ?? []) {
1718
- const run = () => hook.call(doc, () => undefined, crudType);
1719
- if (phase === "post") await this.owner.afterCommit(run);
1720
- else await run();
1721
- }
1722
- }
1723
-
1724
- private insertStmt() {
1725
- this.#insertStmt ??= this.owner
1726
- .getConnection()
1727
- .prepare(
1728
- `INSERT INTO ${quoteIdent(this.table)} ("id", "createdAt", "updatedAt", "removedAt", "_doc") VALUES (?, ?, ?, ?, ${this.dialect.docValuePlaceholder()})`,
1729
- );
1730
- return this.#insertStmt;
1731
- }
1732
-
1733
- private prepareReadStmt(sql: string) {
1734
- const cached = this.#readStmtCache.get(sql);
1735
- if (cached) return cached;
1736
-
1737
- if (this.#readStmtCache.size >= 128) {
1738
- const oldest = this.#readStmtCache.keys().next().value;
1739
- if (oldest) this.#readStmtCache.delete(oldest);
1740
- }
1741
- const stmt = this.owner.getConnection().prepare(sql);
1742
- this.#readStmtCache.set(sql, stmt);
1743
- return stmt;
1744
- }
1745
-
1746
- private assertValidRefName(refName: string) {
1747
- if (!REF_NAME_RE.test(refName) || RESERVED_RE.test(refName))
1748
- throw new Error(`Invalid database identifier: ${refName}`);
1749
- }
1750
- }
1751
-
1752
- /**
1753
- * The schema setups `getStore` starts but nobody awaits.
1754
- *
1755
- * `getStore` returns a store synchronously while `ensure()` goes on creating tables and indexes, so
1756
- * the connection could be closed out from under one — a server shutting down, or a test tearing its
1757
- * fixture down. That surfaced as an unhandled `Cannot use a closed database` blamed on whatever ran
1758
- * next, which made it look like a flaky test rather than a race at shutdown.
1759
- *
1760
- * Every statement `ensure()` runs is `IF NOT EXISTS`, so one cut short is simply redone on the next
1761
- * boot; a failure *before* the close is still a real problem and still surfaces.
1762
- */
1763
- class PendingStoreEnsures {
1764
- readonly #pending = new Set<Promise<void>>();
1765
- #closed = false;
1766
-
1767
- track(ensure: Promise<void>): void {
1768
- const tracked = ensure
1769
- .catch((error: unknown) => {
1770
- if (this.#closed) return;
1771
- throw error;
1772
- })
1773
- .finally(() => {
1774
- this.#pending.delete(tracked);
1775
- });
1776
- this.#pending.add(tracked);
1777
- }
1778
-
1779
- /** Let them finish against a live connection. Call before closing it. */
1780
- async settle(): Promise<void> {
1781
- this.#closed = true;
1782
- await Promise.allSettled([...this.#pending]);
1783
- }
1784
- }
43
+ export type {
44
+ AkanSqlClient,
45
+ AkanSqlStatement,
46
+ DatabaseAdaptor,
47
+ DatabaseConfig,
48
+ DocumentDatabaseOwner,
49
+ DocumentStore,
50
+ LibsqlDatabaseConfig,
51
+ PostgresDatabaseConfig,
52
+ SearchConfig,
53
+ SqliteDatabaseConfig,
54
+ SqlResultRows,
55
+ } from "./sql/types";
1785
56
 
1786
57
  export class SqliteDatabase
1787
58
  extends adapt("sqliteDatabase", ({ env, plug }) => ({