@stonyx/orm 0.2.5-alpha.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +482 -15
  2. package/config/environment.js +63 -6
  3. package/dist/aggregates.d.ts +21 -0
  4. package/dist/aggregates.js +93 -0
  5. package/dist/attr.d.ts +2 -0
  6. package/dist/attr.js +22 -0
  7. package/dist/belongs-to.d.ts +11 -0
  8. package/dist/belongs-to.js +59 -0
  9. package/dist/cli.d.ts +22 -0
  10. package/dist/cli.js +148 -0
  11. package/dist/commands.d.ts +7 -0
  12. package/dist/commands.js +146 -0
  13. package/dist/db.d.ts +21 -0
  14. package/dist/db.js +180 -0
  15. package/dist/exports/db.d.ts +7 -0
  16. package/{src → dist}/exports/db.js +2 -4
  17. package/dist/has-many.d.ts +11 -0
  18. package/dist/has-many.js +58 -0
  19. package/dist/hooks.d.ts +75 -0
  20. package/dist/hooks.js +110 -0
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.js +34 -0
  23. package/dist/main.d.ts +46 -0
  24. package/dist/main.js +181 -0
  25. package/dist/manage-record.d.ts +13 -0
  26. package/dist/manage-record.js +123 -0
  27. package/dist/meta-request.d.ts +6 -0
  28. package/dist/meta-request.js +52 -0
  29. package/dist/migrate.d.ts +2 -0
  30. package/dist/migrate.js +57 -0
  31. package/dist/model-property.d.ts +9 -0
  32. package/dist/model-property.js +29 -0
  33. package/dist/model.d.ts +15 -0
  34. package/dist/model.js +18 -0
  35. package/dist/mysql/connection.d.ts +14 -0
  36. package/dist/mysql/connection.js +24 -0
  37. package/dist/mysql/migration-generator.d.ts +45 -0
  38. package/dist/mysql/migration-generator.js +254 -0
  39. package/dist/mysql/migration-runner.d.ts +12 -0
  40. package/dist/mysql/migration-runner.js +88 -0
  41. package/dist/mysql/mysql-db.d.ts +100 -0
  42. package/dist/mysql/mysql-db.js +425 -0
  43. package/dist/mysql/query-builder.d.ts +10 -0
  44. package/dist/mysql/query-builder.js +44 -0
  45. package/dist/mysql/schema-introspector.d.ts +19 -0
  46. package/dist/mysql/schema-introspector.js +257 -0
  47. package/dist/mysql/type-map.d.ts +21 -0
  48. package/dist/mysql/type-map.js +36 -0
  49. package/dist/orm-request.d.ts +38 -0
  50. package/dist/orm-request.js +475 -0
  51. package/dist/plural-registry.d.ts +4 -0
  52. package/dist/plural-registry.js +9 -0
  53. package/dist/postgres/connection.d.ts +15 -0
  54. package/dist/postgres/connection.js +32 -0
  55. package/dist/postgres/migration-generator.d.ts +45 -0
  56. package/dist/postgres/migration-generator.js +280 -0
  57. package/dist/postgres/migration-runner.d.ts +10 -0
  58. package/dist/postgres/migration-runner.js +87 -0
  59. package/dist/postgres/postgres-db.d.ts +119 -0
  60. package/dist/postgres/postgres-db.js +477 -0
  61. package/dist/postgres/query-builder.d.ts +27 -0
  62. package/dist/postgres/query-builder.js +98 -0
  63. package/dist/postgres/schema-introspector.d.ts +29 -0
  64. package/dist/postgres/schema-introspector.js +296 -0
  65. package/dist/postgres/type-map.d.ts +23 -0
  66. package/dist/postgres/type-map.js +56 -0
  67. package/dist/record.d.ts +75 -0
  68. package/dist/record.js +129 -0
  69. package/dist/relationships.d.ts +10 -0
  70. package/dist/relationships.js +41 -0
  71. package/dist/schema-helpers.d.ts +20 -0
  72. package/dist/schema-helpers.js +48 -0
  73. package/dist/serializer.d.ts +17 -0
  74. package/dist/serializer.js +136 -0
  75. package/dist/setup-rest-server.d.ts +1 -0
  76. package/dist/setup-rest-server.js +52 -0
  77. package/dist/standalone-db.d.ts +58 -0
  78. package/dist/standalone-db.js +142 -0
  79. package/dist/store.d.ts +62 -0
  80. package/dist/store.js +286 -0
  81. package/dist/timescale/query-builder.d.ts +43 -0
  82. package/dist/timescale/query-builder.js +115 -0
  83. package/dist/timescale/timescale-db.d.ts +45 -0
  84. package/dist/timescale/timescale-db.js +84 -0
  85. package/dist/transforms.d.ts +2 -0
  86. package/dist/transforms.js +17 -0
  87. package/dist/types/orm-types.d.ts +153 -0
  88. package/dist/types/orm-types.js +1 -0
  89. package/dist/utils.d.ts +7 -0
  90. package/dist/utils.js +17 -0
  91. package/dist/view-resolver.d.ts +8 -0
  92. package/dist/view-resolver.js +171 -0
  93. package/dist/view.d.ts +11 -0
  94. package/dist/view.js +18 -0
  95. package/package.json +64 -11
  96. package/src/aggregates.ts +109 -0
  97. package/src/{attr.js → attr.ts} +2 -2
  98. package/src/belongs-to.ts +90 -0
  99. package/src/cli.ts +183 -0
  100. package/src/commands.ts +179 -0
  101. package/src/db.ts +232 -0
  102. package/src/exports/db.ts +7 -0
  103. package/src/has-many.ts +92 -0
  104. package/src/hooks.ts +151 -0
  105. package/src/{index.js → index.ts} +12 -2
  106. package/src/main.ts +229 -0
  107. package/src/manage-record.ts +161 -0
  108. package/src/{meta-request.js → meta-request.ts} +17 -14
  109. package/src/migrate.ts +72 -0
  110. package/src/model-property.ts +35 -0
  111. package/src/model.ts +21 -0
  112. package/src/mysql/connection.ts +43 -0
  113. package/src/mysql/migration-generator.ts +337 -0
  114. package/src/mysql/migration-runner.ts +121 -0
  115. package/src/mysql/mysql-db.ts +543 -0
  116. package/src/mysql/query-builder.ts +69 -0
  117. package/src/mysql/schema-introspector.ts +310 -0
  118. package/src/mysql/type-map.ts +42 -0
  119. package/src/orm-request.ts +582 -0
  120. package/src/plural-registry.ts +12 -0
  121. package/src/postgres/connection.ts +48 -0
  122. package/src/postgres/migration-generator.ts +370 -0
  123. package/src/postgres/migration-runner.ts +115 -0
  124. package/src/postgres/postgres-db.ts +616 -0
  125. package/src/postgres/query-builder.ts +148 -0
  126. package/src/postgres/schema-introspector.ts +360 -0
  127. package/src/postgres/type-map.ts +61 -0
  128. package/src/record.ts +186 -0
  129. package/src/relationships.ts +54 -0
  130. package/src/schema-helpers.ts +59 -0
  131. package/src/serializer.ts +161 -0
  132. package/src/setup-rest-server.ts +62 -0
  133. package/src/standalone-db.ts +185 -0
  134. package/src/store.ts +373 -0
  135. package/src/timescale/query-builder.ts +174 -0
  136. package/src/timescale/timescale-db.ts +119 -0
  137. package/src/transforms.ts +20 -0
  138. package/src/types/mysql2.d.ts +49 -0
  139. package/src/types/orm-types.ts +158 -0
  140. package/src/types/pg.d.ts +32 -0
  141. package/src/types/stonyx-cron.d.ts +5 -0
  142. package/src/types/stonyx-events.d.ts +4 -0
  143. package/src/types/stonyx-rest-server.d.ts +16 -0
  144. package/src/types/stonyx-utils.d.ts +33 -0
  145. package/src/types/stonyx.d.ts +21 -0
  146. package/src/utils.ts +22 -0
  147. package/src/view-resolver.ts +211 -0
  148. package/src/view.ts +22 -0
  149. package/.claude/project-structure.md +0 -578
  150. package/.github/workflows/ci.yml +0 -36
  151. package/.github/workflows/publish.yml +0 -143
  152. package/src/belongs-to.js +0 -63
  153. package/src/db.js +0 -80
  154. package/src/has-many.js +0 -61
  155. package/src/main.js +0 -119
  156. package/src/manage-record.js +0 -103
  157. package/src/model-property.js +0 -29
  158. package/src/model.js +0 -9
  159. package/src/orm-request.js +0 -249
  160. package/src/record.js +0 -100
  161. package/src/relationships.js +0 -43
  162. package/src/serializer.js +0 -138
  163. package/src/setup-rest-server.js +0 -57
  164. package/src/store.js +0 -211
  165. package/src/transforms.js +0 -20
  166. package/stonyx-bootstrap.cjs +0 -30
@@ -0,0 +1,616 @@
1
+ import { getPool, closePool } from './connection.js';
2
+ import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
3
+ import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
4
+ import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
5
+ import { buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch } from './query-builder.js';
6
+ import { store } from '@stonyx/orm';
7
+ import { createRecord } from '../manage-record.js';
8
+ import { confirm } from '@stonyx/utils/prompt';
9
+ import { readFile } from '@stonyx/utils/file';
10
+ import { getPluralName } from '../plural-registry.js';
11
+ import { isDbError } from '../utils.js';
12
+ import config from 'stonyx/config';
13
+ import log from 'stonyx/log';
14
+ import path from 'path';
15
+ import type { Pool } from 'pg';
16
+ import type { ForeignKeyDef, ModelSchema, OrmRecord } from '../types/orm-types.js';
17
+
18
+ interface PersistContext {
19
+ record?: OrmRecord;
20
+ recordId?: unknown;
21
+ oldState?: Record<string, unknown>;
22
+ }
23
+
24
+ interface PersistResponse {
25
+ data?: { id: unknown };
26
+ }
27
+
28
+ interface SearchResult {
29
+ record: OrmRecord;
30
+ distance: number;
31
+ }
32
+
33
+ interface VectorSearchOptions {
34
+ limit?: number;
35
+ where?: Record<string, unknown>;
36
+ }
37
+
38
+ interface PostgresDeps {
39
+ getPool: typeof getPool;
40
+ closePool: typeof closePool;
41
+ ensureMigrationsTable: typeof ensureMigrationsTable;
42
+ getAppliedMigrations: typeof getAppliedMigrations;
43
+ getMigrationFiles: typeof getMigrationFiles;
44
+ applyMigration: typeof applyMigration;
45
+ parseMigrationFile: typeof parseMigrationFile;
46
+ introspectModels: typeof introspectModels;
47
+ introspectViews: typeof introspectViews;
48
+ getTopologicalOrder: typeof getTopologicalOrder;
49
+ schemasToSnapshot: typeof schemasToSnapshot;
50
+ loadLatestSnapshot: typeof loadLatestSnapshot;
51
+ detectSchemaDrift: typeof detectSchemaDrift;
52
+ buildInsert: typeof buildInsert;
53
+ buildUpdate: typeof buildUpdate;
54
+ buildDelete: typeof buildDelete;
55
+ buildSelect: typeof buildSelect;
56
+ buildVectorSearch: typeof buildVectorSearch;
57
+ buildHybridSearch: typeof buildHybridSearch;
58
+ createRecord: typeof createRecord;
59
+ store: typeof store;
60
+ confirm: typeof confirm;
61
+ readFile: typeof readFile;
62
+ getPluralName: typeof getPluralName;
63
+ config: typeof config;
64
+ log: typeof log;
65
+ path: typeof path;
66
+ [key: string]: unknown;
67
+ }
68
+
69
+ const defaultDeps: PostgresDeps = {
70
+ getPool, closePool, ensureMigrationsTable, getAppliedMigrations,
71
+ getMigrationFiles, applyMigration, parseMigrationFile,
72
+ introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
73
+ loadLatestSnapshot, detectSchemaDrift,
74
+ buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch,
75
+ createRecord, store, confirm, readFile, getPluralName, config, log, path
76
+ };
77
+
78
+ export default class PostgresDB {
79
+ /** PostgreSQL extensions to enable on pool init. Subclasses can override. */
80
+ static extensions: string[] = ['vector'];
81
+
82
+ /** Config key under config.orm for this adapter. Subclasses can override. */
83
+ static configKey: string = 'postgres';
84
+
85
+ /** Singleton instance, set by subclass constructor name. */
86
+ static instance: PostgresDB | undefined;
87
+
88
+ deps!: PostgresDeps;
89
+ pool!: Pool | null;
90
+ pgConfig!: Record<string, unknown>;
91
+
92
+ constructor(deps: Partial<PostgresDeps> = {}) {
93
+ const Ctor = this.constructor as typeof PostgresDB;
94
+ if (Ctor.instance) return Ctor.instance;
95
+ Ctor.instance = this;
96
+
97
+ this.deps = { ...defaultDeps, ...deps } as PostgresDeps;
98
+ this.pool = null;
99
+ this.pgConfig = this.deps.config.orm[Ctor.configKey] as Record<string, unknown>;
100
+ }
101
+
102
+ protected requirePool(): Pool {
103
+ if (!this.pool) throw new Error('PostgresDB pool not initialized — call init() first');
104
+ return this.pool;
105
+ }
106
+
107
+ async init(): Promise<void> {
108
+ this.pool = await this.deps.getPool(
109
+ this.pgConfig as unknown as Parameters<typeof getPool>[0],
110
+ (this.constructor as typeof PostgresDB).extensions
111
+ );
112
+ await this.deps.ensureMigrationsTable(this.pool, this.pgConfig.migrationsTable as string | undefined);
113
+ await this.loadMemoryRecords();
114
+ }
115
+
116
+ async startup(): Promise<void> {
117
+ const migrationsPath = this.deps.path.resolve(this.deps.config.rootPath, this.pgConfig.migrationsDir as string);
118
+
119
+ // Check for pending migrations
120
+ const applied = await this.deps.getAppliedMigrations(this.requirePool(), this.pgConfig.migrationsTable as string | undefined);
121
+ const files = await this.deps.getMigrationFiles(migrationsPath);
122
+ const pending = files.filter(f => !applied.includes(f));
123
+
124
+ if (pending.length > 0) {
125
+ this.deps.log.db?.(`${pending.length} pending migration(s) found.`);
126
+
127
+ const shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
128
+
129
+ if (shouldApply) {
130
+ for (const filename of pending) {
131
+ const content = await this.deps.readFile(this.deps.path.join(migrationsPath, filename)) as string;
132
+ const { up } = this.deps.parseMigrationFile(content);
133
+
134
+ await this.deps.applyMigration(this.requirePool(), filename, up, this.pgConfig.migrationsTable as string | undefined);
135
+ this.deps.log.db?.(`Applied migration: ${filename}`);
136
+ }
137
+
138
+ // Reload records after applying migrations
139
+ await this.loadMemoryRecords();
140
+ } else {
141
+ this.deps.log.warn?.('Skipping pending migrations. Schema may be outdated.');
142
+ }
143
+ } else if (files.length === 0) {
144
+ const schemas = this.deps.introspectModels();
145
+ const modelCount = Object.keys(schemas).length;
146
+
147
+ if (modelCount > 0) {
148
+ const shouldGenerate = await this.deps.confirm(
149
+ `No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`
150
+ );
151
+
152
+ if (shouldGenerate) {
153
+ const { generateMigration } = await import('./migration-generator.js');
154
+ const result = await generateMigration('initial_setup');
155
+
156
+ if (result) {
157
+ const { up } = this.deps.parseMigrationFile(result.content);
158
+ await this.deps.applyMigration(this.requirePool(), result.filename, up, this.pgConfig.migrationsTable as string | undefined);
159
+ this.deps.log.db?.(`Applied migration: ${result.filename}`);
160
+ await this.loadMemoryRecords();
161
+ }
162
+ } else {
163
+ this.deps.log.warn?.('Skipping initial migration. Tables may not exist.');
164
+ }
165
+ }
166
+ }
167
+
168
+ // Check for schema drift
169
+ const schemas = this.deps.introspectModels();
170
+ const snapshot = await this.deps.loadLatestSnapshot(this.deps.path.resolve(this.deps.config.rootPath, this.pgConfig.migrationsDir as string));
171
+
172
+ if (Object.keys(snapshot).length > 0) {
173
+ const drift = this.deps.detectSchemaDrift(schemas, snapshot as Parameters<typeof detectSchemaDrift>[1]);
174
+
175
+ if (drift.hasChanges) {
176
+ this.deps.log.warn?.('Schema drift detected: models have changed since the last migration.');
177
+ this.deps.log.warn?.('Run `stonyx db:generate-migration` to create a new migration.');
178
+ }
179
+ }
180
+ }
181
+
182
+ async shutdown(): Promise<void> {
183
+ await this.deps.closePool();
184
+ this.pool = null;
185
+ }
186
+
187
+ async save(): Promise<void> {
188
+ // No-op: PostgreSQL persists data immediately via persist()
189
+ }
190
+
191
+ /**
192
+ * Loads only models with memory: true into the in-memory store on startup.
193
+ * Models with memory: false are skipped -- accessed on-demand via find()/findAll().
194
+ */
195
+ async loadMemoryRecords(): Promise<void> {
196
+ const schemas = this.deps.introspectModels();
197
+ const order = this.deps.getTopologicalOrder(schemas);
198
+ const Orm = (await import('@stonyx/orm')).default;
199
+
200
+ for (const modelName of order) {
201
+ const { modelClass } = Orm.instance.getRecordClasses(modelName) as { modelClass: { memory?: boolean } };
202
+ if (modelClass?.memory === false) {
203
+ this.deps.log.db?.(`Skipping memory load for '${modelName}' (memory: false)`);
204
+ continue;
205
+ }
206
+
207
+ const schema = schemas[modelName];
208
+ const { sql, values } = this.deps.buildSelect(schema.table);
209
+
210
+ try {
211
+ const result = await this.requirePool().query(sql, values);
212
+
213
+ for (const row of result.rows) {
214
+ const rawData = this._rowToRawData(row, schema);
215
+ this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
216
+ }
217
+ } catch (error) {
218
+ // 42P01 = undefined_table (PG equivalent of ER_NO_SUCH_TABLE)
219
+ if (isDbError(error) && error.code === '42P01') {
220
+ this.deps.log.db?.(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
221
+ continue;
222
+ }
223
+
224
+ throw error;
225
+ }
226
+ }
227
+
228
+ // Load views with memory: true
229
+ const viewSchemas = this.deps.introspectViews();
230
+
231
+ for (const [viewName, viewSchema] of Object.entries(viewSchemas)) {
232
+ const { modelClass: viewClass } = Orm.instance.getRecordClasses(viewName) as { modelClass: { memory?: boolean } };
233
+ if (viewClass?.memory !== true) {
234
+ this.deps.log.db?.(`Skipping memory load for view '${viewName}' (memory: false)`);
235
+ continue;
236
+ }
237
+
238
+ const sourceIdType = schemas[viewSchema.source]?.idType || 'number';
239
+ const schema: ModelSchema = {
240
+ table: viewSchema.viewName,
241
+ idType: sourceIdType,
242
+ columns: viewSchema.columns || {},
243
+ foreignKeys: (viewSchema.foreignKeys || {}) as Record<string, ForeignKeyDef>,
244
+ relationships: { belongsTo: {}, hasMany: {} },
245
+ vectorColumns: {},
246
+ memory: false,
247
+ };
248
+ const { sql, values } = this.deps.buildSelect(schema.table);
249
+
250
+ try {
251
+ const result = await this.requirePool().query(sql, values);
252
+
253
+ for (const row of result.rows) {
254
+ const rawData = this._rowToRawData(row, schema);
255
+ this.deps.createRecord(viewName, rawData, { isDbRecord: true, serialize: false, transform: false });
256
+ }
257
+ } catch (error) {
258
+ if (isDbError(error) && error.code === '42P01') {
259
+ this.deps.log.db?.(`View '${viewSchema.viewName}' does not exist yet. Skipping load for '${viewName}'.`);
260
+ continue;
261
+ }
262
+ throw error;
263
+ }
264
+ }
265
+ }
266
+
267
+ /**
268
+ * @deprecated Use loadMemoryRecords() instead. Kept for backward compatibility.
269
+ */
270
+ async loadAllRecords(): Promise<void> {
271
+ return this.loadMemoryRecords();
272
+ }
273
+
274
+ /**
275
+ * Find a single record by ID from PostgreSQL.
276
+ * Does NOT cache the result in the store for memory: false models.
277
+ */
278
+ async findRecord(modelName: string, id: string | number): Promise<OrmRecord | undefined> {
279
+ const schemas = this.deps.introspectModels();
280
+ let schema: ModelSchema | undefined = schemas[modelName];
281
+
282
+ // Check views if not found in models
283
+ if (!schema) {
284
+ const viewSchemas = this.deps.introspectViews();
285
+ const viewSchema = viewSchemas[modelName];
286
+ if (viewSchema) {
287
+ const sourceIdType = schemas[viewSchema.source]?.idType || 'number';
288
+ schema = {
289
+ table: viewSchema.viewName,
290
+ idType: sourceIdType,
291
+ columns: viewSchema.columns || {},
292
+ foreignKeys: (viewSchema.foreignKeys || {}) as Record<string, ForeignKeyDef>,
293
+ relationships: { belongsTo: {}, hasMany: {} },
294
+ vectorColumns: {},
295
+ memory: false,
296
+ };
297
+ }
298
+ }
299
+
300
+ if (!schema) return undefined;
301
+
302
+ const { sql, values } = this.deps.buildSelect(schema.table, { id });
303
+
304
+ try {
305
+ const result = await this.requirePool().query(sql, values);
306
+
307
+ if (result.rows.length === 0) return undefined;
308
+
309
+ const rawData = this._rowToRawData(result.rows[0], schema);
310
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
311
+
312
+ this._evictIfNotMemory(modelName, record);
313
+
314
+ return record;
315
+ } catch (error) {
316
+ if (isDbError(error) && error.code === '42P01') return undefined;
317
+ throw error;
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Find all records of a model from PostgreSQL, with optional conditions.
323
+ */
324
+ async findAll(modelName: string, conditions?: Record<string, unknown>): Promise<OrmRecord[]> {
325
+ const schemas = this.deps.introspectModels();
326
+ let schema: ModelSchema | undefined = schemas[modelName];
327
+
328
+ // Check views if not found in models
329
+ if (!schema) {
330
+ const viewSchemas = this.deps.introspectViews();
331
+ const viewSchema = viewSchemas[modelName];
332
+ if (viewSchema) {
333
+ const sourceIdType = schemas[viewSchema.source]?.idType || 'number';
334
+ schema = {
335
+ table: viewSchema.viewName,
336
+ idType: sourceIdType,
337
+ columns: viewSchema.columns || {},
338
+ foreignKeys: (viewSchema.foreignKeys || {}) as Record<string, ForeignKeyDef>,
339
+ relationships: { belongsTo: {}, hasMany: {} },
340
+ vectorColumns: {},
341
+ memory: false,
342
+ };
343
+ }
344
+ }
345
+
346
+ if (!schema) return [];
347
+
348
+ const resolvedSchema = schema;
349
+ const { sql, values } = this.deps.buildSelect(resolvedSchema.table, conditions);
350
+
351
+ try {
352
+ const result = await this.requirePool().query(sql, values);
353
+
354
+ const records = result.rows.map(row => {
355
+ const rawData = this._rowToRawData(row, resolvedSchema);
356
+ return this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
357
+ });
358
+
359
+ for (const record of records) {
360
+ this._evictIfNotMemory(modelName, record);
361
+ }
362
+
363
+ return records;
364
+ } catch (error) {
365
+ if (isDbError(error) && error.code === '42P01') return [];
366
+ throw error;
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Perform a vector similarity search using cosine distance.
372
+ */
373
+ async vectorSearch(modelName: string, vectorColumn: string, queryVector: number[], options: VectorSearchOptions = {}): Promise<SearchResult[]> {
374
+ const schemas = this.deps.introspectModels();
375
+ const schema = schemas[modelName];
376
+ if (!schema) return [];
377
+
378
+ const { sql, values } = this.deps.buildVectorSearch(schema.table, vectorColumn, queryVector, options);
379
+
380
+ try {
381
+ const result = await this.requirePool().query(sql, values);
382
+
383
+ return result.rows.map(row => {
384
+ const distance = row.distance as number;
385
+ delete row.distance;
386
+ const rawData = this._rowToRawData(row, schema);
387
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
388
+ this._evictIfNotMemory(modelName, record);
389
+ return { record, distance };
390
+ });
391
+ } catch (error) {
392
+ if (isDbError(error) && error.code === '42P01') return [];
393
+ throw error;
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Perform a hybrid search combining vector similarity with text filtering.
399
+ */
400
+ async hybridSearch(modelName: string, vectorColumn: string, queryVector: number[], textColumn: string, textQuery: string, options: VectorSearchOptions = {}): Promise<SearchResult[]> {
401
+ const schemas = this.deps.introspectModels();
402
+ const schema = schemas[modelName];
403
+ if (!schema) return [];
404
+
405
+ const { sql, values } = this.deps.buildHybridSearch(schema.table, vectorColumn, queryVector, textColumn, textQuery, options);
406
+
407
+ try {
408
+ const result = await this.requirePool().query(sql, values);
409
+
410
+ return result.rows.map(row => {
411
+ const distance = row.distance as number;
412
+ delete row.distance;
413
+ const rawData = this._rowToRawData(row, schema);
414
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
415
+ this._evictIfNotMemory(modelName, record);
416
+ return { record, distance };
417
+ });
418
+ } catch (error) {
419
+ if (isDbError(error) && error.code === '42P01') return [];
420
+ throw error;
421
+ }
422
+ }
423
+
424
+ /**
425
+ * Remove a record from the in-memory store if its model has memory: false.
426
+ * The record object itself survives -- the caller retains the reference.
427
+ * @private
428
+ */
429
+ private _evictIfNotMemory(modelName: string, record: OrmRecord): void {
430
+ const storeRef = this.deps.store as {
431
+ _memoryResolver?: (name: string) => boolean;
432
+ get?: (name: string) => Map<unknown, unknown> | undefined;
433
+ data?: { get(name: string): Map<unknown, unknown> | undefined };
434
+ };
435
+
436
+ if (storeRef._memoryResolver && !storeRef._memoryResolver(modelName)) {
437
+ const modelStore = storeRef.get?.(modelName) ?? storeRef.data?.get(modelName);
438
+ if (modelStore) modelStore.delete(record.id);
439
+ }
440
+ }
441
+
442
+ private _rowToRawData(row: Record<string, unknown>, schema: ModelSchema): Record<string, unknown> {
443
+ const rawData: Record<string, unknown> = { ...row };
444
+
445
+ // PostgreSQL returns native booleans and parsed JSONB -- no manual conversion needed.
446
+ // Only FK remapping and timestamp stripping required.
447
+
448
+ // Map FK columns back to relationship keys
449
+ for (const [fkCol] of Object.entries(schema.foreignKeys)) {
450
+ const relName = fkCol.replace(/_id$/, '');
451
+
452
+ if (rawData[fkCol] !== undefined) {
453
+ rawData[relName] = rawData[fkCol];
454
+ delete rawData[fkCol];
455
+ }
456
+ }
457
+
458
+ // Remove timestamp columns -- managed by PostgreSQL
459
+ delete rawData.created_at;
460
+ delete rawData.updated_at;
461
+
462
+ return rawData;
463
+ }
464
+
465
+ async persist(operation: string, modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
466
+ // Views are read-only -- no-op for all write operations
467
+ const Orm = (await import('@stonyx/orm')).default;
468
+ if ((Orm.instance as { isView?: (name: string) => boolean })?.isView?.(modelName)) return;
469
+
470
+ switch (operation) {
471
+ case 'create':
472
+ return this._persistCreate(modelName, context, response);
473
+ case 'update':
474
+ return this._persistUpdate(modelName, context, response);
475
+ case 'delete':
476
+ return this._persistDelete(modelName, context);
477
+ }
478
+ }
479
+
480
+ private async _persistCreate(modelName: string, _context: PersistContext, response: PersistResponse): Promise<void> {
481
+ const schemas = this.deps.introspectModels();
482
+ const schema = schemas[modelName];
483
+
484
+ if (!schema) return;
485
+
486
+ const recordId = response?.data?.id;
487
+ const storeRef = this.deps.store as unknown as {
488
+ get(name: string, id: unknown): OrmRecord | null;
489
+ };
490
+ const record = recordId != null ? storeRef.get(modelName, isNaN(recordId as number) ? recordId : parseInt(recordId as string)) : null;
491
+
492
+ if (!record) return;
493
+
494
+ const insertData = this._recordToRow(record, schema);
495
+
496
+ // For auto-increment models, remove the pending ID
497
+ const isPendingId = record.__data.__pendingSqlId;
498
+
499
+ if (isPendingId) {
500
+ delete insertData.id;
501
+ }
502
+
503
+ const { sql, values } = this.deps.buildInsert(schema.table, insertData);
504
+
505
+ const result = await this.requirePool().query(sql, values);
506
+
507
+ // Re-key the record in the store if PostgreSQL generated the ID (via RETURNING)
508
+ if (isPendingId && result.rows.length > 0) {
509
+ const pendingId = record.id;
510
+ const realId = result.rows[0].id as string | number;
511
+ const modelStore = (this.deps.store as unknown as { get(name: string): Map<unknown, unknown> }).get(modelName);
512
+
513
+ modelStore.delete(pendingId);
514
+ record.__data.id = realId;
515
+ record.id = realId;
516
+ modelStore.set(realId, record);
517
+
518
+ // Update the response data with the real ID
519
+ if (response?.data) {
520
+ response.data.id = realId;
521
+ }
522
+
523
+ delete record.__data.__pendingSqlId;
524
+ }
525
+ }
526
+
527
+ private async _persistUpdate(modelName: string, context: PersistContext, _response: PersistResponse): Promise<void> {
528
+ const schemas = this.deps.introspectModels();
529
+ const schema = schemas[modelName];
530
+
531
+ if (!schema) return;
532
+
533
+ const record = context.record;
534
+ if (!record) return;
535
+
536
+ const id = record.id;
537
+ const oldState = context.oldState || {};
538
+ const currentData = record.__data;
539
+
540
+ // Build a diff of changed columns
541
+ const changedData: Record<string, unknown> = {};
542
+
543
+ for (const [col] of Object.entries(schema.columns)) {
544
+ if (currentData[col] !== oldState[col]) {
545
+ changedData[col] = currentData[col] ?? null;
546
+ }
547
+ }
548
+
549
+ // Check FK changes too
550
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
551
+ const relName = fkCol.replace(/_id$/, '');
552
+ const currentFkValue = (record.__relationships[relName] as { id: unknown } | undefined)?.id ?? null;
553
+ const oldFkValue = oldState[relName] ?? null;
554
+
555
+ if (currentFkValue !== oldFkValue) {
556
+ changedData[fkCol] = currentFkValue;
557
+ }
558
+ }
559
+
560
+ if (Object.keys(changedData).length === 0) return;
561
+
562
+ // PostgreSQL doesn't have ON UPDATE CURRENT_TIMESTAMP -- set updated_at manually
563
+ changedData.updated_at = new Date();
564
+
565
+ const { sql, values } = this.deps.buildUpdate(schema.table, id, changedData);
566
+ await this.requirePool().query(sql, values);
567
+ }
568
+
569
+ private async _persistDelete(modelName: string, context: PersistContext): Promise<void> {
570
+ const schemas = this.deps.introspectModels();
571
+ const schema = schemas[modelName];
572
+
573
+ if (!schema) return;
574
+
575
+ const id = context.recordId;
576
+ if (id == null) return;
577
+
578
+ const { sql, values } = this.deps.buildDelete(schema.table, id);
579
+ await this.requirePool().query(sql, values);
580
+ }
581
+
582
+ private _recordToRow(record: OrmRecord, schema: ModelSchema): Record<string, unknown> {
583
+ const row: Record<string, unknown> = {};
584
+ const data = record.__data;
585
+
586
+ // ID
587
+ if (data.id !== undefined) {
588
+ row.id = data.id;
589
+ }
590
+
591
+ // Attribute columns
592
+ for (const [col, pgType] of Object.entries(schema.columns)) {
593
+ if (data[col] !== undefined) {
594
+ // JSONB columns: stringify non-string values for PostgreSQL JSONB storage
595
+ row[col] = pgType === 'JSONB' && typeof data[col] !== 'string'
596
+ ? JSON.stringify(data[col])
597
+ : data[col];
598
+ }
599
+ }
600
+
601
+ // FK columns from relationships
602
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
603
+ const relName = fkCol.replace(/_id$/, '');
604
+ const related = record.__relationships[relName];
605
+
606
+ if (related) {
607
+ row[fkCol] = (related as { id: unknown }).id;
608
+ } else if (data[relName] !== undefined) {
609
+ // Raw FK value (e.g., from create payload)
610
+ row[fkCol] = data[relName];
611
+ }
612
+ }
613
+
614
+ return row;
615
+ }
616
+ }