@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,121 @@
1
+ import { readFile, fileExists } from '@stonyx/utils/file';
2
+ import path from 'path';
3
+ import fs from 'fs/promises';
4
+ import type { Pool, PoolConnection } from 'mysql2/promise';
5
+ import { validateIdentifier } from './query-builder.js';
6
+
7
+ interface ParsedMigration {
8
+ up: string;
9
+ down: string;
10
+ }
11
+
12
+ export async function ensureMigrationsTable(pool: Pool, tableName: string = '__migrations'): Promise<void> {
13
+ validateIdentifier(tableName, 'migration table name');
14
+ await pool.execute(`
15
+ CREATE TABLE IF NOT EXISTS \`${tableName}\` (
16
+ id INT AUTO_INCREMENT PRIMARY KEY,
17
+ filename VARCHAR(255) NOT NULL UNIQUE,
18
+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
19
+ )
20
+ `);
21
+ }
22
+
23
+ export async function getAppliedMigrations(pool: Pool, tableName: string = '__migrations'): Promise<string[]> {
24
+ validateIdentifier(tableName, 'migration table name');
25
+ const [rows] = await pool.execute(
26
+ `SELECT filename FROM \`${tableName}\` ORDER BY id ASC`
27
+ ) as [Array<{ filename: string }>, unknown];
28
+
29
+ return rows.map(row => row.filename);
30
+ }
31
+
32
+ export async function getMigrationFiles(migrationsDir: string): Promise<string[]> {
33
+ const exists = await fileExists(migrationsDir);
34
+ if (!exists) return [];
35
+
36
+ const entries = await fs.readdir(migrationsDir);
37
+
38
+ return entries
39
+ .filter(f => f.endsWith('.sql'))
40
+ .sort();
41
+ }
42
+
43
+ export function parseMigrationFile(content: string): ParsedMigration {
44
+ const upMarker = '-- UP';
45
+ const downMarker = '-- DOWN';
46
+ const upIndex = content.indexOf(upMarker);
47
+ const downIndex = content.indexOf(downMarker);
48
+
49
+ if (upIndex === -1) {
50
+ return { up: content.trim(), down: '' };
51
+ }
52
+
53
+ const upStart = upIndex + upMarker.length;
54
+ const upEnd = downIndex !== -1 ? downIndex : content.length;
55
+ const up = content.slice(upStart, upEnd).trim();
56
+ const down = downIndex !== -1 ? content.slice(downIndex + downMarker.length).trim() : '';
57
+
58
+ return { up, down };
59
+ }
60
+
61
+ export async function applyMigration(pool: Pool, filename: string, upSql: string, tableName: string = '__migrations'): Promise<void> {
62
+ validateIdentifier(tableName, 'migration table name');
63
+ const connection = await pool.getConnection();
64
+
65
+ try {
66
+ await connection.beginTransaction();
67
+
68
+ // Execute each statement separately (split on semicolons)
69
+ const statements = splitStatements(upSql);
70
+
71
+ for (const stmt of statements) {
72
+ await connection.execute(stmt);
73
+ }
74
+
75
+ await connection.execute(
76
+ `INSERT INTO \`${tableName}\` (filename) VALUES (?)`,
77
+ [filename]
78
+ );
79
+
80
+ await connection.commit();
81
+ } catch (error) {
82
+ await connection.rollback();
83
+ throw error;
84
+ } finally {
85
+ connection.release();
86
+ }
87
+ }
88
+
89
+ export async function rollbackMigration(pool: Pool, filename: string, downSql: string, tableName: string = '__migrations'): Promise<void> {
90
+ validateIdentifier(tableName, 'migration table name');
91
+ const connection = await pool.getConnection();
92
+
93
+ try {
94
+ await connection.beginTransaction();
95
+
96
+ const statements = splitStatements(downSql);
97
+
98
+ for (const stmt of statements) {
99
+ await connection.execute(stmt);
100
+ }
101
+
102
+ await connection.execute(
103
+ `DELETE FROM \`${tableName}\` WHERE filename = ?`,
104
+ [filename]
105
+ );
106
+
107
+ await connection.commit();
108
+ } catch (error) {
109
+ await connection.rollback();
110
+ throw error;
111
+ } finally {
112
+ connection.release();
113
+ }
114
+ }
115
+
116
+ function splitStatements(sql: string): string[] {
117
+ return sql
118
+ .split(';')
119
+ .map(s => s.trim())
120
+ .filter(s => s.length > 0 && !s.startsWith('--'));
121
+ }
@@ -0,0 +1,543 @@
1
+ import { getPool, closePool } from './connection.js';
2
+ import type { MysqlConfig } from './connection.js';
3
+ import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
4
+ import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
5
+ import type { ModelSchema, ViewSchema, SnapshotEntry } from './schema-introspector.js';
6
+ import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
7
+ import { buildInsert, buildUpdate, buildDelete, buildSelect } from './query-builder.js';
8
+ import { store } from '@stonyx/orm';
9
+ import { createRecord } from '../manage-record.js';
10
+ import { confirm } from '@stonyx/utils/prompt';
11
+ import { readFile } from '@stonyx/utils/file';
12
+ import { getPluralName } from '../plural-registry.js';
13
+ import { isDbError } from '../utils.js';
14
+ import config from 'stonyx/config';
15
+ import log from 'stonyx/log';
16
+ import path from 'path';
17
+ import type { Pool } from 'mysql2/promise';
18
+ import type { OrmRecord } from '../types/orm-types.js';
19
+
20
+ interface PersistContext {
21
+ record?: OrmRecord;
22
+ recordId?: unknown;
23
+ oldState?: Record<string, unknown>;
24
+ }
25
+
26
+ interface PersistResponse {
27
+ data?: { id?: unknown };
28
+ }
29
+
30
+ interface ExecuteResult {
31
+ insertId?: number;
32
+ }
33
+
34
+ interface OrmStore {
35
+ get(key: string): Map<number | string, unknown> | undefined;
36
+ get(key: string, id: number | string): unknown;
37
+ _memoryResolver?: (modelName: string) => boolean;
38
+ data?: Map<string, Map<number | string, unknown>>;
39
+ }
40
+
41
+ interface MysqlDBDeps {
42
+ getPool: typeof getPool;
43
+ closePool: typeof closePool;
44
+ ensureMigrationsTable: typeof ensureMigrationsTable;
45
+ getAppliedMigrations: typeof getAppliedMigrations;
46
+ getMigrationFiles: typeof getMigrationFiles;
47
+ applyMigration: typeof applyMigration;
48
+ parseMigrationFile: typeof parseMigrationFile;
49
+ introspectModels: typeof introspectModels;
50
+ introspectViews: typeof introspectViews;
51
+ getTopologicalOrder: typeof getTopologicalOrder;
52
+ schemasToSnapshot: typeof schemasToSnapshot;
53
+ loadLatestSnapshot: typeof loadLatestSnapshot;
54
+ detectSchemaDrift: typeof detectSchemaDrift;
55
+ buildInsert: typeof buildInsert;
56
+ buildUpdate: typeof buildUpdate;
57
+ buildDelete: typeof buildDelete;
58
+ buildSelect: typeof buildSelect;
59
+ createRecord: typeof createRecord;
60
+ store: OrmStore;
61
+ confirm: typeof confirm;
62
+ readFile: typeof readFile;
63
+ getPluralName: typeof getPluralName;
64
+ config: typeof config;
65
+ log: Record<string, ((...args: unknown[]) => void) | undefined>;
66
+ path: typeof path;
67
+ }
68
+
69
+ const defaultDeps: MysqlDBDeps = {
70
+ getPool, closePool, ensureMigrationsTable, getAppliedMigrations,
71
+ getMigrationFiles, applyMigration, parseMigrationFile,
72
+ introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
73
+ loadLatestSnapshot, detectSchemaDrift,
74
+ buildInsert, buildUpdate, buildDelete, buildSelect,
75
+ createRecord, store: store as OrmStore, confirm, readFile, getPluralName,
76
+ config, log, path
77
+ };
78
+
79
+ export default class MysqlDB {
80
+ static instance: MysqlDB | undefined;
81
+
82
+ deps!: MysqlDBDeps;
83
+ pool!: Pool | null;
84
+ mysqlConfig!: MysqlConfig;
85
+
86
+ constructor(deps: Partial<MysqlDBDeps> = {}) {
87
+ if (MysqlDB.instance) return MysqlDB.instance;
88
+ MysqlDB.instance = this;
89
+
90
+ this.deps = { ...defaultDeps, ...deps } as MysqlDBDeps;
91
+ this.pool = null;
92
+ const mysqlConfig = this.deps.config.orm.mysql;
93
+ if (!mysqlConfig) throw new Error('MySQL configuration (config.orm.mysql) is required');
94
+ this.mysqlConfig = mysqlConfig;
95
+ }
96
+
97
+ private requirePool(): Pool {
98
+ if (!this.pool) throw new Error('MysqlDB pool not initialized — call init() first');
99
+ return this.pool;
100
+ }
101
+
102
+ async init(): Promise<void> {
103
+ this.pool = await this.deps.getPool(this.mysqlConfig);
104
+ await this.deps.ensureMigrationsTable(this.pool, this.mysqlConfig.migrationsTable);
105
+ await this.loadMemoryRecords();
106
+ }
107
+
108
+ async startup(): Promise<void> {
109
+ if (!this.mysqlConfig.migrationsDir) throw new Error('MySQL migrationsDir is required in config');
110
+ const migrationsPath = this.deps.path.resolve(this.deps.config.rootPath, this.mysqlConfig.migrationsDir);
111
+
112
+ // Check for pending migrations
113
+ const applied = await this.deps.getAppliedMigrations(this.requirePool(), this.mysqlConfig.migrationsTable);
114
+ const files = await this.deps.getMigrationFiles(migrationsPath);
115
+ const pending = files.filter(f => !applied.includes(f));
116
+
117
+ if (pending.length > 0) {
118
+ this.deps.log.db?.(`${pending.length} pending migration(s) found.`);
119
+
120
+ const shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
121
+
122
+ if (shouldApply) {
123
+ for (const filename of pending) {
124
+ const content = await this.deps.readFile(this.deps.path.join(migrationsPath, filename)) as string;
125
+ const { up } = this.deps.parseMigrationFile(content);
126
+
127
+ await this.deps.applyMigration(this.requirePool(), filename, up, this.mysqlConfig.migrationsTable);
128
+ this.deps.log.db?.(`Applied migration: ${filename}`);
129
+ }
130
+
131
+ // Reload records after applying migrations
132
+ await this.loadMemoryRecords();
133
+ } else {
134
+ this.deps.log.warn?.('Skipping pending migrations. Schema may be outdated.');
135
+ }
136
+ } else if (files.length === 0) {
137
+ const schemas = this.deps.introspectModels();
138
+ const modelCount = Object.keys(schemas).length;
139
+
140
+ if (modelCount > 0) {
141
+ const shouldGenerate = await this.deps.confirm(
142
+ `No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`
143
+ );
144
+
145
+ if (shouldGenerate) {
146
+ const { generateMigration } = await import('./migration-generator.js');
147
+ const result = await generateMigration('initial_setup');
148
+
149
+ if (result) {
150
+ const { up } = this.deps.parseMigrationFile(result.content);
151
+ await this.deps.applyMigration(this.requirePool(), result.filename, up, this.mysqlConfig.migrationsTable);
152
+ this.deps.log.db?.(`Applied migration: ${result.filename}`);
153
+ await this.loadMemoryRecords();
154
+ }
155
+ } else {
156
+ this.deps.log.warn?.('Skipping initial migration. Tables may not exist.');
157
+ }
158
+ }
159
+ }
160
+
161
+ // Check for schema drift
162
+ const schemas = this.deps.introspectModels();
163
+ if (!this.mysqlConfig.migrationsDir) throw new Error('MySQL migrationsDir is required in config');
164
+ const snapshot = await this.deps.loadLatestSnapshot(this.deps.path.resolve(this.deps.config.rootPath, this.mysqlConfig.migrationsDir)) as Record<string, SnapshotEntry>;
165
+
166
+ if (Object.keys(snapshot).length > 0) {
167
+ const drift = this.deps.detectSchemaDrift(schemas, snapshot);
168
+
169
+ if (drift.hasChanges) {
170
+ this.deps.log.warn?.('Schema drift detected: models have changed since the last migration.');
171
+ this.deps.log.warn?.('Run `stonyx db:generate-migration` to create a new migration.');
172
+ }
173
+ }
174
+ }
175
+
176
+ async shutdown(): Promise<void> {
177
+ await this.deps.closePool();
178
+ this.pool = null;
179
+ }
180
+
181
+ async save(): Promise<void> {
182
+ // No-op: MySQL persists data immediately via persist()
183
+ }
184
+
185
+ /**
186
+ * Loads only models with memory: true into the in-memory store on startup.
187
+ * Models with memory: false are skipped — accessed on-demand via find()/findAll().
188
+ */
189
+ async loadMemoryRecords(): Promise<void> {
190
+ const schemas = this.deps.introspectModels();
191
+ const order = this.deps.getTopologicalOrder(schemas);
192
+ const Orm = (await import('@stonyx/orm')).default;
193
+
194
+ for (const modelName of order) {
195
+ // Check the model's memory flag — skip non-memory models
196
+ const { modelClass } = Orm.instance.getRecordClasses(modelName) as { modelClass?: { memory?: boolean } };
197
+ if (modelClass?.memory === false) {
198
+ this.deps.log.db?.(`Skipping memory load for '${modelName}' (memory: false)`);
199
+ continue;
200
+ }
201
+
202
+ const schema = schemas[modelName];
203
+ const { sql, values } = this.deps.buildSelect(schema.table);
204
+
205
+ try {
206
+ const result = await this.requirePool().execute(sql, values);
207
+ const rows = result[0] as Record<string, unknown>[];
208
+
209
+ for (const row of rows) {
210
+ const rawData = this._rowToRawData(row, schema);
211
+ this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
212
+ }
213
+ } catch (error) {
214
+ // Table may not exist yet (pre-migration) — skip gracefully
215
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') {
216
+ this.deps.log.db?.(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
217
+ continue;
218
+ }
219
+
220
+ throw error;
221
+ }
222
+ }
223
+
224
+ // Load views with memory: true
225
+ const viewSchemas = this.deps.introspectViews();
226
+
227
+ for (const [viewName, viewSchema] of Object.entries(viewSchemas)) {
228
+ const { modelClass: viewClass } = Orm.instance.getRecordClasses(viewName) as { modelClass?: { memory?: boolean } };
229
+ if (viewClass?.memory !== true) {
230
+ this.deps.log.db?.(`Skipping memory load for view '${viewName}' (memory: false)`);
231
+ continue;
232
+ }
233
+
234
+ const schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
235
+ const { sql, values } = this.deps.buildSelect(schema.table);
236
+
237
+ try {
238
+ const result = await this.requirePool().execute(sql, values);
239
+ const rows = result[0] as Record<string, unknown>[];
240
+
241
+ for (const row of rows) {
242
+ const rawData = this._rowToRawData(row, schema);
243
+ this.deps.createRecord(viewName, rawData, { isDbRecord: true, serialize: false, transform: false });
244
+ }
245
+ } catch (error) {
246
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') {
247
+ this.deps.log.db?.(`View '${viewSchema.viewName}' does not exist yet. Skipping load for '${viewName}'.`);
248
+ continue;
249
+ }
250
+ throw error;
251
+ }
252
+ }
253
+ }
254
+
255
+ /**
256
+ * @deprecated Use loadMemoryRecords() instead. Kept for backward compatibility.
257
+ */
258
+ async loadAllRecords(): Promise<void> {
259
+ return this.loadMemoryRecords();
260
+ }
261
+
262
+ /**
263
+ * Find a single record by ID from MySQL.
264
+ * Does NOT cache the result in the store for memory: false models.
265
+ */
266
+ async findRecord(modelName: string, id: string | number): Promise<OrmRecord | undefined> {
267
+ const schemas = this.deps.introspectModels();
268
+ let schema: { table: string; columns: Record<string, string>; foreignKeys: Record<string, unknown> } | undefined = schemas[modelName];
269
+
270
+ // Check views if not found in models
271
+ if (!schema) {
272
+ const viewSchemas = this.deps.introspectViews();
273
+ const viewSchema = viewSchemas[modelName];
274
+ if (viewSchema) {
275
+ schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
276
+ }
277
+ }
278
+
279
+ if (!schema) return undefined;
280
+
281
+ const { sql, values } = this.deps.buildSelect(schema.table, { id });
282
+
283
+ try {
284
+ const result = await this.requirePool().execute(sql, values);
285
+ const rows = result[0] as Record<string, unknown>[];
286
+
287
+ if (rows.length === 0) return undefined;
288
+
289
+ const rawData = this._rowToRawData(rows[0], schema);
290
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
291
+
292
+ // Don't let memory:false records accumulate in the store
293
+ // The caller keeps the reference; the store doesn't retain it
294
+ this._evictIfNotMemory(modelName, record);
295
+
296
+ return record;
297
+ } catch (error) {
298
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') return undefined;
299
+ throw error;
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Find all records of a model from MySQL, with optional conditions.
305
+ */
306
+ async findAll(modelName: string, conditions?: Record<string, unknown>): Promise<OrmRecord[]> {
307
+ const schemas = this.deps.introspectModels();
308
+ let schema: { table: string; columns: Record<string, string>; foreignKeys: Record<string, unknown> } | undefined = schemas[modelName];
309
+
310
+ // Check views if not found in models
311
+ if (!schema) {
312
+ const viewSchemas = this.deps.introspectViews();
313
+ const viewSchema = viewSchemas[modelName];
314
+ if (viewSchema) {
315
+ schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
316
+ }
317
+ }
318
+
319
+ if (!schema) return [];
320
+
321
+ const resolvedSchema = schema;
322
+ const { sql, values } = this.deps.buildSelect(resolvedSchema.table, conditions);
323
+
324
+ try {
325
+ const result = await this.requirePool().execute(sql, values);
326
+ const rows = result[0] as Record<string, unknown>[];
327
+
328
+ const records = rows.map(row => {
329
+ const rawData = this._rowToRawData(row, resolvedSchema);
330
+ return this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
331
+ });
332
+
333
+ // Don't let memory:false records accumulate in the store
334
+ for (const record of records) {
335
+ this._evictIfNotMemory(modelName, record);
336
+ }
337
+
338
+ return records;
339
+ } catch (error) {
340
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') return [];
341
+ throw error;
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Remove a record from the in-memory store if its model has memory: false.
347
+ * The record object itself survives — the caller retains the reference.
348
+ * This prevents on-demand queries from leaking records into the store.
349
+ */
350
+ private _evictIfNotMemory(modelName: string, record: OrmRecord): void {
351
+ const storeRef = this.deps.store;
352
+
353
+ // Use the memory resolver if available (set by Orm.init)
354
+ if (storeRef._memoryResolver && !storeRef._memoryResolver(modelName)) {
355
+ const modelStore = (storeRef.get?.(modelName) ?? storeRef.data?.get(modelName)) as Map<unknown, unknown> | undefined;
356
+ if (modelStore) modelStore.delete(record.id);
357
+ }
358
+ }
359
+
360
+ private _rowToRawData(row: Record<string, unknown>, schema: { columns: Record<string, string>; foreignKeys: Record<string, unknown> }): Record<string, unknown> {
361
+ const rawData: Record<string, unknown> = { ...row };
362
+
363
+ for (const [col, mysqlType] of Object.entries(schema.columns)) {
364
+ if (rawData[col] == null) continue;
365
+
366
+ // Convert boolean columns from MySQL TINYINT(1) 0/1 to false/true
367
+ if (mysqlType === 'TINYINT(1)') {
368
+ rawData[col] = !!rawData[col];
369
+ }
370
+
371
+ // Parse JSON columns back to JS values (custom transforms stored as JSON)
372
+ if (mysqlType === 'JSON' && typeof rawData[col] === 'string') {
373
+ try { rawData[col] = JSON.parse(rawData[col] as string); } catch { /* keep raw string */ }
374
+ }
375
+ }
376
+
377
+ // Map FK columns back to relationship keys
378
+ // e.g., owner_id -> owner (the belongsTo handler expects the id value under the relationship key name)
379
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
380
+ const relName = fkCol.replace(/_id$/, '');
381
+
382
+ if (rawData[fkCol] !== undefined) {
383
+ rawData[relName] = rawData[fkCol];
384
+ delete rawData[fkCol];
385
+ }
386
+ }
387
+
388
+ // Remove timestamp columns — managed by MySQL
389
+ delete rawData.created_at;
390
+ delete rawData.updated_at;
391
+
392
+ return rawData;
393
+ }
394
+
395
+ async persist(operation: string, modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
396
+ // Views are read-only — no-op for all write operations
397
+ const Orm = (await import('@stonyx/orm')).default;
398
+ if ((Orm as unknown as { instance?: { isView?: (name: string) => boolean } }).instance?.isView?.(modelName)) return;
399
+
400
+ switch (operation) {
401
+ case 'create':
402
+ return this._persistCreate(modelName, context, response);
403
+ case 'update':
404
+ return this._persistUpdate(modelName, context, response);
405
+ case 'delete':
406
+ return this._persistDelete(modelName, context);
407
+ }
408
+ }
409
+
410
+ private async _persistCreate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
411
+ const schemas = this.deps.introspectModels();
412
+ const schema = schemas[modelName];
413
+
414
+ if (!schema) return;
415
+
416
+ const recordId = response?.data?.id;
417
+ const record = recordId != null ? this.deps.store.get(modelName, (isNaN(recordId as number) ? recordId : parseInt(recordId as string)) as number | string) as OrmRecord | null : null;
418
+
419
+ if (!record) return;
420
+
421
+ const insertData = this._recordToRow(record, schema);
422
+
423
+ // For auto-increment models, remove the pending ID
424
+ const isPendingId = record.__data.__pendingSqlId;
425
+
426
+ if (isPendingId) {
427
+ delete insertData.id;
428
+ } else if (insertData.id !== undefined) {
429
+ // Keep user-provided ID (string IDs or explicit numeric IDs)
430
+ }
431
+
432
+ const { sql, values } = this.deps.buildInsert(schema.table, insertData);
433
+
434
+ const [result] = await this.requirePool().execute(sql, values) as [ExecuteResult, unknown];
435
+
436
+ // Re-key the record in the store if MySQL generated the ID
437
+ if (isPendingId && result.insertId) {
438
+ const pendingId = record.id;
439
+ const realId = result.insertId;
440
+ const modelStore = this.deps.store.get(modelName);
441
+ if (!modelStore) throw new Error(`Model "${modelName}" not found in store during ID re-key`);
442
+
443
+ modelStore.delete(pendingId as number | string);
444
+ record.__data.id = realId;
445
+ record.id = realId;
446
+ modelStore.set(realId as number | string, record);
447
+
448
+ // Update the response data with the real ID
449
+ if (response?.data) {
450
+ response.data.id = realId;
451
+ }
452
+
453
+ delete record.__data.__pendingSqlId;
454
+ }
455
+ }
456
+
457
+ private async _persistUpdate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
458
+ const schemas = this.deps.introspectModels();
459
+ const schema = schemas[modelName];
460
+
461
+ if (!schema) return;
462
+
463
+ const record = context.record;
464
+ if (!record) return;
465
+
466
+ const id = record.id;
467
+ const oldState = context.oldState || {};
468
+ const currentData = record.__data;
469
+
470
+ // Build a diff of changed columns
471
+ const changedData: Record<string, unknown> = {};
472
+
473
+ for (const [col] of Object.entries(schema.columns)) {
474
+ if (currentData[col] !== oldState[col]) {
475
+ changedData[col] = currentData[col] ?? null;
476
+ }
477
+ }
478
+
479
+ // Check FK changes too
480
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
481
+ const relName = fkCol.replace(/_id$/, '');
482
+ const currentFkValue = (record.__relationships[relName] as { id: unknown } | undefined)?.id ?? null;
483
+ const oldFkValue = oldState[relName] ?? null;
484
+
485
+ if (currentFkValue !== oldFkValue) {
486
+ changedData[fkCol] = currentFkValue;
487
+ }
488
+ }
489
+
490
+ if (Object.keys(changedData).length === 0) return;
491
+
492
+ const { sql, values } = this.deps.buildUpdate(schema.table, id, changedData);
493
+ await this.requirePool().execute(sql, values);
494
+ }
495
+
496
+ private async _persistDelete(modelName: string, context: PersistContext): Promise<void> {
497
+ const schemas = this.deps.introspectModels();
498
+ const schema = schemas[modelName];
499
+
500
+ if (!schema) return;
501
+
502
+ const id = context.recordId;
503
+ if (id == null) return;
504
+
505
+ const { sql, values } = this.deps.buildDelete(schema.table, id);
506
+ await this.requirePool().execute(sql, values);
507
+ }
508
+
509
+ private _recordToRow(record: OrmRecord, schema: ModelSchema): Record<string, unknown> {
510
+ const row: Record<string, unknown> = {};
511
+ const data = record.__data;
512
+
513
+ // ID
514
+ if (data.id !== undefined) {
515
+ row.id = data.id;
516
+ }
517
+
518
+ // Attribute columns
519
+ for (const [col, mysqlType] of Object.entries(schema.columns)) {
520
+ if (data[col] !== undefined) {
521
+ // JSON columns: stringify non-string values for MySQL JSON storage
522
+ row[col] = mysqlType === 'JSON' && typeof data[col] !== 'string'
523
+ ? JSON.stringify(data[col])
524
+ : data[col];
525
+ }
526
+ }
527
+
528
+ // FK columns from relationships
529
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
530
+ const relName = fkCol.replace(/_id$/, '');
531
+ const related = record.__relationships[relName];
532
+
533
+ if (related) {
534
+ row[fkCol] = (related as { id: unknown }).id;
535
+ } else if (data[relName] !== undefined) {
536
+ // Raw FK value (e.g., from create payload)
537
+ row[fkCol] = data[relName];
538
+ }
539
+ }
540
+
541
+ return row;
542
+ }
543
+ }