@stonyx/orm 0.2.1-beta.86 → 0.2.1-beta.88

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 (47) hide show
  1. package/dist/aggregates.js +9 -6
  2. package/dist/db.js +4 -4
  3. package/dist/hooks.js +6 -2
  4. package/dist/main.js +3 -1
  5. package/dist/manage-record.js +6 -2
  6. package/dist/mysql/migration-generator.js +15 -6
  7. package/dist/mysql/migration-runner.js +5 -0
  8. package/dist/mysql/mysql-db.js +24 -14
  9. package/dist/mysql/schema-introspector.js +11 -6
  10. package/dist/orm-request.js +19 -11
  11. package/dist/postgres/connection.js +3 -1
  12. package/dist/postgres/migration-generator.js +9 -5
  13. package/dist/postgres/migration-runner.js +5 -0
  14. package/dist/postgres/postgres-db.js +14 -13
  15. package/dist/postgres/schema-introspector.js +11 -6
  16. package/dist/postgres/type-map.js +3 -0
  17. package/dist/relationships.js +2 -0
  18. package/dist/setup-rest-server.js +4 -6
  19. package/dist/store.js +2 -0
  20. package/dist/timescale/query-builder.d.ts +2 -0
  21. package/dist/timescale/query-builder.js +30 -2
  22. package/dist/utils.js +2 -1
  23. package/dist/view-resolver.js +3 -1
  24. package/package.json +1 -1
  25. package/src/aggregates.ts +9 -7
  26. package/src/belongs-to.ts +1 -1
  27. package/src/db.ts +4 -4
  28. package/src/hooks.ts +4 -2
  29. package/src/main.ts +3 -2
  30. package/src/manage-record.ts +5 -2
  31. package/src/mysql/migration-generator.ts +12 -7
  32. package/src/mysql/migration-runner.ts +5 -0
  33. package/src/mysql/mysql-db.ts +23 -17
  34. package/src/mysql/schema-introspector.ts +10 -7
  35. package/src/orm-request.ts +19 -12
  36. package/src/postgres/connection.ts +3 -1
  37. package/src/postgres/migration-generator.ts +7 -5
  38. package/src/postgres/migration-runner.ts +5 -0
  39. package/src/postgres/postgres-db.ts +14 -13
  40. package/src/postgres/schema-introspector.ts +10 -7
  41. package/src/postgres/type-map.ts +4 -0
  42. package/src/relationships.ts +3 -2
  43. package/src/setup-rest-server.ts +7 -10
  44. package/src/store.ts +2 -1
  45. package/src/timescale/query-builder.ts +39 -2
  46. package/src/utils.ts +2 -1
  47. package/src/view-resolver.ts +2 -1
@@ -56,20 +56,20 @@ export default class PostgresDB {
56
56
  const files = await this.deps.getMigrationFiles(migrationsPath);
57
57
  const pending = files.filter(f => !applied.includes(f));
58
58
  if (pending.length > 0) {
59
- this.deps.log.db(`${pending.length} pending migration(s) found.`);
59
+ this.deps.log.db?.(`${pending.length} pending migration(s) found.`);
60
60
  const shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
61
61
  if (shouldApply) {
62
62
  for (const filename of pending) {
63
63
  const content = await this.deps.readFile(this.deps.path.join(migrationsPath, filename));
64
64
  const { up } = this.deps.parseMigrationFile(content);
65
65
  await this.deps.applyMigration(this.requirePool(), filename, up, this.pgConfig.migrationsTable);
66
- this.deps.log.db(`Applied migration: ${filename}`);
66
+ this.deps.log.db?.(`Applied migration: ${filename}`);
67
67
  }
68
68
  // Reload records after applying migrations
69
69
  await this.loadMemoryRecords();
70
70
  }
71
71
  else {
72
- this.deps.log.warn('Skipping pending migrations. Schema may be outdated.');
72
+ this.deps.log.warn?.('Skipping pending migrations. Schema may be outdated.');
73
73
  }
74
74
  }
75
75
  else if (files.length === 0) {
@@ -83,12 +83,12 @@ export default class PostgresDB {
83
83
  if (result) {
84
84
  const { up } = this.deps.parseMigrationFile(result.content);
85
85
  await this.deps.applyMigration(this.requirePool(), result.filename, up, this.pgConfig.migrationsTable);
86
- this.deps.log.db(`Applied migration: ${result.filename}`);
86
+ this.deps.log.db?.(`Applied migration: ${result.filename}`);
87
87
  await this.loadMemoryRecords();
88
88
  }
89
89
  }
90
90
  else {
91
- this.deps.log.warn('Skipping initial migration. Tables may not exist.');
91
+ this.deps.log.warn?.('Skipping initial migration. Tables may not exist.');
92
92
  }
93
93
  }
94
94
  }
@@ -98,8 +98,8 @@ export default class PostgresDB {
98
98
  if (Object.keys(snapshot).length > 0) {
99
99
  const drift = this.deps.detectSchemaDrift(schemas, snapshot);
100
100
  if (drift.hasChanges) {
101
- this.deps.log.warn('Schema drift detected: models have changed since the last migration.');
102
- this.deps.log.warn('Run `stonyx db:generate-migration` to create a new migration.');
101
+ this.deps.log.warn?.('Schema drift detected: models have changed since the last migration.');
102
+ this.deps.log.warn?.('Run `stonyx db:generate-migration` to create a new migration.');
103
103
  }
104
104
  }
105
105
  }
@@ -121,7 +121,7 @@ export default class PostgresDB {
121
121
  for (const modelName of order) {
122
122
  const { modelClass } = Orm.instance.getRecordClasses(modelName);
123
123
  if (modelClass?.memory === false) {
124
- this.deps.log.db(`Skipping memory load for '${modelName}' (memory: false)`);
124
+ this.deps.log.db?.(`Skipping memory load for '${modelName}' (memory: false)`);
125
125
  continue;
126
126
  }
127
127
  const schema = schemas[modelName];
@@ -136,7 +136,7 @@ export default class PostgresDB {
136
136
  catch (error) {
137
137
  // 42P01 = undefined_table (PG equivalent of ER_NO_SUCH_TABLE)
138
138
  if (isDbError(error) && error.code === '42P01') {
139
- this.deps.log.db(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
139
+ this.deps.log.db?.(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
140
140
  continue;
141
141
  }
142
142
  throw error;
@@ -147,7 +147,7 @@ export default class PostgresDB {
147
147
  for (const [viewName, viewSchema] of Object.entries(viewSchemas)) {
148
148
  const { modelClass: viewClass } = Orm.instance.getRecordClasses(viewName);
149
149
  if (viewClass?.memory !== true) {
150
- this.deps.log.db(`Skipping memory load for view '${viewName}' (memory: false)`);
150
+ this.deps.log.db?.(`Skipping memory load for view '${viewName}' (memory: false)`);
151
151
  continue;
152
152
  }
153
153
  const sourceIdType = schemas[viewSchema.source]?.idType || 'number';
@@ -170,7 +170,7 @@ export default class PostgresDB {
170
170
  }
171
171
  catch (error) {
172
172
  if (isDbError(error) && error.code === '42P01') {
173
- this.deps.log.db(`View '${viewSchema.viewName}' does not exist yet. Skipping load for '${viewName}'.`);
173
+ this.deps.log.db?.(`View '${viewSchema.viewName}' does not exist yet. Skipping load for '${viewName}'.`);
174
174
  continue;
175
175
  }
176
176
  throw error;
@@ -250,11 +250,12 @@ export default class PostgresDB {
250
250
  }
251
251
  if (!schema)
252
252
  return [];
253
- const { sql, values } = this.deps.buildSelect(schema.table, conditions);
253
+ const resolvedSchema = schema;
254
+ const { sql, values } = this.deps.buildSelect(resolvedSchema.table, conditions);
254
255
  try {
255
256
  const result = await this.requirePool().query(sql, values);
256
257
  const records = result.rows.map(row => {
257
- const rawData = this._rowToRawData(row, schema);
258
+ const rawData = this._rowToRawData(row, resolvedSchema);
258
259
  return this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
259
260
  });
260
261
  for (const record of records) {
@@ -60,6 +60,8 @@ export function introspectModels() {
60
60
  }
61
61
  // Build foreign keys from belongsTo relationships
62
62
  for (const [relName, targetModelName] of Object.entries(relationships.belongsTo)) {
63
+ if (!targetModelName)
64
+ continue;
63
65
  const fkColumn = `${relName}_id`;
64
66
  foreignKeys[fkColumn] = {
65
67
  references: sanitizeTableName(getPluralName(targetModelName)),
@@ -139,7 +141,8 @@ export function getTopologicalOrder(schemas) {
139
141
  return;
140
142
  // Visit dependencies (belongsTo targets) first
141
143
  for (const targetModelName of Object.values(schema.relationships.belongsTo)) {
142
- visit(targetModelName);
144
+ if (targetModelName)
145
+ visit(targetModelName);
143
146
  }
144
147
  order.push(name);
145
148
  }
@@ -175,11 +178,13 @@ export function introspectViews() {
175
178
  const relInfo = getRelationshipInfo(property);
176
179
  if (relInfo?.type === 'belongsTo') {
177
180
  relationships.belongsTo[key] = relInfo.modelName;
178
- const fkColumn = `${key}_id`;
179
- foreignKeys[fkColumn] = {
180
- references: sanitizeTableName(getPluralName(relInfo.modelName)),
181
- column: 'id',
182
- };
181
+ if (relInfo.modelName) {
182
+ const fkColumn = `${key}_id`;
183
+ foreignKeys[fkColumn] = {
184
+ references: sanitizeTableName(getPluralName(relInfo.modelName)),
185
+ column: 'id',
186
+ };
187
+ }
183
188
  }
184
189
  else if (relInfo?.type === 'hasMany') {
185
190
  relationships.hasMany[key] = relInfo.modelName;
@@ -36,6 +36,9 @@ export function getPgType(attrType, transformFn) {
36
36
  * Returns a vector column type for the given dimensions.
37
37
  */
38
38
  export function getVectorType(dimensions) {
39
+ if (!Number.isInteger(dimensions) || dimensions < 1 || dimensions > 16000) {
40
+ throw new Error(`Invalid vector dimensions: ${dimensions}. Must be an integer between 1 and 16000.`);
41
+ }
39
42
  return `vector(${dimensions})`;
40
43
  }
41
44
  function mysqlTypeToPg(mysqlType) {
@@ -10,6 +10,8 @@ export function getRelationships(type, sourceModel, targetModel, relationshipId)
10
10
  if (!allRelationships.has(sourceModel))
11
11
  allRelationships.set(sourceModel, new Map());
12
12
  const modelRelationship = allRelationships.get(sourceModel);
13
+ if (!modelRelationship)
14
+ return undefined;
13
15
  if (!modelRelationship.has(targetModel))
14
16
  modelRelationship.set(targetModel, new Map());
15
17
  const relationship = modelRelationship.get(targetModel);
@@ -8,7 +8,7 @@ import { dbKey } from './db.js';
8
8
  import { getPluralName } from './plural-registry.js';
9
9
  import log from 'stonyx/log';
10
10
  export default async function (route, accessPath, metaRoute) {
11
- let accessFiles = {};
11
+ const accessFiles = {};
12
12
  try {
13
13
  await forEachFileImport(accessPath, (accessClass) => {
14
14
  const accessInstance = new accessClass();
@@ -32,8 +32,8 @@ export default async function (route, accessPath, metaRoute) {
32
32
  });
33
33
  }
34
34
  catch (error) {
35
- log.error(error instanceof Error ? error.message : String(error));
36
- log.warn('You must define a valid access configuration file in order to access ORM generated REST endpoints.');
35
+ log.error?.(error instanceof Error ? error.message : String(error));
36
+ log.warn?.('You must define a valid access configuration file in order to access ORM generated REST endpoints.');
37
37
  }
38
38
  await waitForModule('rest-server');
39
39
  // Remove "/" prefix and name mount point accordingly
@@ -46,9 +46,7 @@ export default async function (route, accessPath, metaRoute) {
46
46
  }
47
47
  // Mount the meta route when metaRoute config is enabled
48
48
  if (metaRoute) {
49
- log.warn('SECURITY RISK! - Meta route is enabled via metaRoute config. This feature is intended for development purposes only!');
49
+ log.warn?.('SECURITY RISK! - Meta route is enabled via metaRoute config. This feature is intended for development purposes only!');
50
50
  RestServer.instance.mountRoute(MetaRequest, { name });
51
51
  }
52
- // Cleanup references
53
- accessFiles = null;
54
52
  }
package/dist/store.js CHANGED
@@ -245,6 +245,8 @@ export default class Store {
245
245
  }];
246
246
  while (queue.length > 0) {
247
247
  const item = queue.shift();
248
+ if (!item)
249
+ break;
248
250
  const key = `${item.modelName}:${item.recordId}`;
249
251
  if (visited.has(key))
250
252
  continue;
@@ -1,4 +1,6 @@
1
1
  export { validateIdentifier, buildInsert, buildUpdate, buildDelete, buildSelect } from '../postgres/query-builder.js';
2
+ export declare function validateInterval(interval: string, context?: string): string;
3
+ export declare function validateAggregate(expr: string, context?: string): string;
2
4
  interface QueryResult {
3
5
  sql: string;
4
6
  values: unknown[];
@@ -1,6 +1,20 @@
1
1
  // Re-export all base PostgreSQL query builders
2
2
  export { validateIdentifier, buildInsert, buildUpdate, buildDelete, buildSelect } from '../postgres/query-builder.js';
3
3
  import { validateIdentifier } from '../postgres/query-builder.js';
4
+ const SAFE_INTERVAL = /^\d+\s+(microsecond|millisecond|second|minute|hour|day|week|month|year)s?$/i;
5
+ export function validateInterval(interval, context = 'interval') {
6
+ if (!interval || typeof interval !== 'string' || !SAFE_INTERVAL.test(interval.trim())) {
7
+ throw new Error(`Invalid SQL ${context}: "${interval}". Intervals must match pattern like "7 days", "1 hour", "30 minutes".`);
8
+ }
9
+ return interval.trim();
10
+ }
11
+ const SAFE_AGGREGATE = /^(COUNT|SUM|AVG|MIN|MAX|FIRST|LAST)\s*\(\s*("?[a-zA-Z_][a-zA-Z0-9_]*"?|\*)\s*\)\s*(AS\s+"?[a-zA-Z_][a-zA-Z0-9_]*"?)?$/i;
12
+ export function validateAggregate(expr, context = 'aggregate') {
13
+ if (!expr || typeof expr !== 'string' || !SAFE_AGGREGATE.test(expr.trim())) {
14
+ throw new Error(`Invalid SQL ${context}: "${expr}". Aggregates must be simple function calls like "AVG(value) AS avg_value".`);
15
+ }
16
+ return expr.trim();
17
+ }
4
18
  /**
5
19
  * Build a CREATE TABLE + hypertable conversion statement.
6
20
  * TimescaleDB hypertables are regular tables converted via create_hypertable().
@@ -9,6 +23,7 @@ export function buildCreateHypertable(table, timeColumn, options = {}) {
9
23
  validateIdentifier(table, 'table name');
10
24
  validateIdentifier(timeColumn, 'column name');
11
25
  const { chunkInterval = '7 days' } = options;
26
+ validateInterval(chunkInterval, 'chunk interval');
12
27
  const sql = `SELECT create_hypertable('"${table}"', '${timeColumn}', chunk_time_interval => INTERVAL '${chunkInterval}', if_not_exists => TRUE)`;
13
28
  return { sql, values: [] };
14
29
  }
@@ -24,7 +39,7 @@ export function buildTimeBucket(table, timeColumn, bucketSize, options = {}) {
24
39
  const selectCols = [`time_bucket($${paramIndex++}, "${timeColumn}") AS bucket`];
25
40
  values.push(bucketSize);
26
41
  for (const agg of aggregates) {
27
- selectCols.push(agg);
42
+ selectCols.push(validateAggregate(agg));
28
43
  }
29
44
  const whereClauses = [];
30
45
  if (where) {
@@ -35,7 +50,17 @@ export function buildTimeBucket(table, timeColumn, bucketSize, options = {}) {
35
50
  }
36
51
  }
37
52
  const whereStr = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
38
- const orderStr = orderBy ? ` ORDER BY ${orderBy}` : '';
53
+ let orderStr = '';
54
+ if (orderBy) {
55
+ const parts = orderBy.trim().split(/\s+/);
56
+ const col = parts[0];
57
+ const dir = parts[1]?.toUpperCase();
58
+ validateIdentifier(col, 'ORDER BY column');
59
+ if (dir && dir !== 'ASC' && dir !== 'DESC') {
60
+ throw new Error(`Invalid ORDER BY direction: "${dir}". Must be ASC or DESC.`);
61
+ }
62
+ orderStr = ` ORDER BY "${col}"${dir ? ` ${dir}` : ''}`;
63
+ }
39
64
  let limitStr = '';
40
65
  if (limit != null) {
41
66
  limitStr = ` LIMIT $${paramIndex++}`;
@@ -52,6 +77,8 @@ export function buildContinuousAggregate(viewName, table, timeColumn, bucketSize
52
77
  validateIdentifier(table, 'table name');
53
78
  validateIdentifier(timeColumn, 'column name');
54
79
  const { withNoData = false } = options;
80
+ validateInterval(bucketSize, 'bucket size');
81
+ aggregates.forEach(agg => validateAggregate(agg));
55
82
  const selectCols = [
56
83
  `time_bucket('${bucketSize}', "${timeColumn}") AS bucket`,
57
84
  ...aggregates,
@@ -65,6 +92,7 @@ export function buildContinuousAggregate(viewName, table, timeColumn, bucketSize
65
92
  */
66
93
  export function buildCompressionPolicy(table, compressAfter) {
67
94
  validateIdentifier(table, 'table name');
95
+ validateInterval(compressAfter, 'compress after interval');
68
96
  const sql = `SELECT add_compression_policy('"${table}"', INTERVAL '${compressAfter}', if_not_exists => TRUE)`;
69
97
  return { sql };
70
98
  }
package/dist/utils.js CHANGED
@@ -6,7 +6,8 @@ export function isDbError(error) {
6
6
  export function pluralize(word) {
7
7
  if (word.includes('-')) {
8
8
  const parts = word.split('-');
9
- const pluralizedLast = basePluralize(parts.pop());
9
+ const last = parts.pop();
10
+ const pluralizedLast = basePluralize(last);
10
11
  return [...parts, pluralizedLast].join('-');
11
12
  }
12
13
  return basePluralize(word);
@@ -101,7 +101,9 @@ export default class ViewResolver {
101
101
  if (!groups.has(key)) {
102
102
  groups.set(key, []);
103
103
  }
104
- groups.get(key).push(record);
104
+ const group = groups.get(key);
105
+ if (group)
106
+ group.push(record);
105
107
  }
106
108
  const results = [];
107
109
  for (const [groupKey, groupRecords] of groups) {
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "stonyx-async",
5
5
  "stonyx-module"
6
6
  ],
7
- "version": "0.2.1-beta.86",
7
+ "version": "0.2.1-beta.88",
8
8
  "description": "",
9
9
  "main": "dist/index.js",
10
10
  "type": "module",
package/src/aggregates.ts CHANGED
@@ -27,13 +27,15 @@ export class AggregateProperty {
27
27
  return 0;
28
28
  }
29
29
 
30
- switch (this.aggregateType) {
31
- case 'count':
32
- return relatedRecords.length;
30
+ if (this.aggregateType === 'count') return relatedRecords.length;
31
+
32
+ const field = this.field;
33
+ if (!field) return null;
33
34
 
35
+ switch (this.aggregateType) {
34
36
  case 'sum':
35
37
  return relatedRecords.reduce((acc, record) => {
36
- const val = parseFloat(record?.__data?.[this.field!] as string ?? record?.[this.field!] as string);
38
+ const val = parseFloat(record?.__data?.[field] as string ?? record?.[field] as string);
37
39
  return acc + (isNaN(val) ? 0 : val);
38
40
  }, 0);
39
41
 
@@ -41,7 +43,7 @@ export class AggregateProperty {
41
43
  let sum = 0;
42
44
  let count = 0;
43
45
  for (const record of relatedRecords) {
44
- const val = parseFloat(record?.__data?.[this.field!] as string ?? record?.[this.field!] as string);
46
+ const val = parseFloat(record?.__data?.[field] as string ?? record?.[field] as string);
45
47
  if (!isNaN(val)) {
46
48
  sum += val;
47
49
  count++;
@@ -53,7 +55,7 @@ export class AggregateProperty {
53
55
  case 'min': {
54
56
  let min: number | null = null;
55
57
  for (const record of relatedRecords) {
56
- const val = parseFloat(record?.__data?.[this.field!] as string ?? record?.[this.field!] as string);
58
+ const val = parseFloat(record?.__data?.[field] as string ?? record?.[field] as string);
57
59
  if (!isNaN(val) && (min === null || val < min)) min = val;
58
60
  }
59
61
  return min;
@@ -62,7 +64,7 @@ export class AggregateProperty {
62
64
  case 'max': {
63
65
  let max: number | null = null;
64
66
  for (const record of relatedRecords) {
65
- const val = parseFloat(record?.__data?.[this.field!] as string ?? record?.[this.field!] as string);
67
+ const val = parseFloat(record?.__data?.[field] as string ?? record?.[field] as string);
66
68
  if (!isNaN(val) && (max === null || val > max)) max = val;
67
69
  }
68
70
  return max;
package/src/belongs-to.ts CHANGED
@@ -4,7 +4,7 @@ import type { SourceRecord } from './types/orm-types.js';
4
4
 
5
5
  function getOrSet<K, V>(map: Map<K, V>, key: K, defaultValue: V): V {
6
6
  if (!map.has(key)) map.set(key, defaultValue);
7
- return map.get(key)!;
7
+ return map.get(key) as V;
8
8
  }
9
9
 
10
10
  interface BelongsToOptions {
package/src/db.ts CHANGED
@@ -84,7 +84,7 @@ export default class DB {
84
84
  const hasData = collectionKeys.some(key => Array.isArray(data[key]) && data[key].length > 0);
85
85
 
86
86
  if (hasData) {
87
- log.error!(`DB mode mismatch: db.json contains data but mode is set to 'directory'. Run migration first:\n\n stonyx db:migrate-to-directory\n`);
87
+ log.error?.(`DB mode mismatch: db.json contains data but mode is set to 'directory'. Run migration first:\n\n stonyx db:migrate-to-directory\n`);
88
88
  process.exit(1);
89
89
  }
90
90
  }
@@ -97,7 +97,7 @@ export default class DB {
97
97
  )).some(Boolean);
98
98
 
99
99
  if (hasCollectionFiles) {
100
- log.error!(`DB mode mismatch: directory '${config.orm.db.directory}/' contains collection files but mode is set to 'file'. Run migration first:\n\n stonyx db:migrate-to-file\n`);
100
+ log.error?.(`DB mode mismatch: directory '${config.orm.db.directory}/' contains collection files but mode is set to 'file'. Run migration first:\n\n stonyx db:migrate-to-file\n`);
101
101
  process.exit(1);
102
102
  }
103
103
  }
@@ -176,13 +176,13 @@ export default class DB {
176
176
  if (dbFileExists) await updateFile(dbFilePath, skeleton, { json: true });
177
177
  else await createFile(dbFilePath, skeleton, { json: true });
178
178
 
179
- log.db!(`DB has been successfully saved to ${config.orm.db.directory}/ directory`);
179
+ log.db?.(`DB has been successfully saved to ${config.orm.db.directory}/ directory`);
180
180
  return;
181
181
  }
182
182
 
183
183
  await updateFile(`${config.rootPath}/${file}`, jsonData, { json: true });
184
184
 
185
- log.db!(`DB has been successfully saved to ${file}`);
185
+ log.db?.(`DB has been successfully saved to ${file}`);
186
186
  }
187
187
 
188
188
  async getRecord(): Promise<DBRecord> {
package/src/hooks.ts CHANGED
@@ -40,7 +40,8 @@ export function beforeHook(operation: string, model: string, handler: HookHandle
40
40
  if (!beforeHooks.has(key)) {
41
41
  beforeHooks.set(key, []);
42
42
  }
43
- beforeHooks.get(key)!.push(handler);
43
+ const hooks = beforeHooks.get(key);
44
+ if (hooks) hooks.push(handler);
44
45
 
45
46
  // Return unsubscribe function
46
47
  return () => {
@@ -66,7 +67,8 @@ export function afterHook(operation: string, model: string, handler: HookHandler
66
67
  if (!afterHooks.has(key)) {
67
68
  afterHooks.set(key, []);
68
69
  }
69
- afterHooks.get(key)!.push(handler);
70
+ const hooks = afterHooks.get(key);
71
+ if (hooks) hooks.push(handler);
70
72
 
71
73
  // Return unsubscribe function
72
74
  return () => {
package/src/main.ts CHANGED
@@ -187,7 +187,8 @@ export default class Orm {
187
187
  static get db(): OrmDB | SqlDb {
188
188
  if (!Orm.initialized) throw new Error('ORM has not been initialized yet');
189
189
 
190
- return Orm.instance.db!;
190
+ if (!Orm.instance.db) throw new Error('ORM database has not been initialized');
191
+ return Orm.instance.db;
191
192
  }
192
193
 
193
194
  getRecordClasses(modelName: string): { modelClass: unknown; serializerClass: unknown } {
@@ -218,7 +219,7 @@ export default class Orm {
218
219
  this.warnings.add(message);
219
220
 
220
221
  setTimeout(() => {
221
- this.warnings.forEach(warning => log.warn!(warning));
222
+ this.warnings.forEach(warning => log.warn?.(warning));
222
223
  this.warnings.clear();
223
224
  }, 0);
224
225
  }
@@ -142,8 +142,11 @@ function assignRecordId(modelName: string, rawData: { [key: string]: unknown }):
142
142
  return;
143
143
  }
144
144
 
145
- const modelStore = Array.from(store.get(modelName)!.values()) as OrmRecord[];
146
- rawData.id = modelStore.length ? (modelStore.at(-1)!.id as number) + 1 : 1;
145
+ const storeMap = store.get(modelName);
146
+ if (!storeMap) throw new Error(`Cannot assign record ID: model "${modelName}" not found in store`);
147
+ const modelStore = Array.from(storeMap.values()) as OrmRecord[];
148
+ const lastRecord = modelStore.at(-1);
149
+ rawData.id = lastRecord ? (lastRecord.id as number) + 1 : 1;
147
150
  }
148
151
 
149
152
  function isStringIdModel(modelName: string): boolean {
@@ -51,9 +51,12 @@ interface GeneratedMigration {
51
51
  type Snapshot = Record<string, SnapshotEntry & { isView?: boolean; viewName?: string; viewQuery?: string; source?: string }>;
52
52
 
53
53
  export async function generateMigration(description: string = 'migration'): Promise<GeneratedMigration | null> {
54
- const { migrationsDir } = config.orm.mysql!;
54
+ const mysqlConfig = config.orm.mysql;
55
+ if (!mysqlConfig) throw new Error('MySQL configuration (config.orm.mysql) is required for migration generation');
56
+ const { migrationsDir } = mysqlConfig;
57
+ if (!migrationsDir) throw new Error('MySQL migrationsDir is required in config');
55
58
  const rootPath = config.rootPath;
56
- const migrationsPath = path.resolve(rootPath, migrationsDir!);
59
+ const migrationsPath = path.resolve(rootPath, migrationsDir);
57
60
 
58
61
  await createDirectory(migrationsPath);
59
62
 
@@ -71,7 +74,7 @@ export async function generateMigration(description: string = 'migration'): Prom
71
74
  const viewDiffPrelim = diffViewSnapshots(previousViewSnapshotPrelim, currentViewSnapshotPrelim);
72
75
 
73
76
  if (!viewDiffPrelim.hasChanges) {
74
- log.db!('No schema changes detected.');
77
+ log.db?.('No schema changes detected.');
75
78
  return null;
76
79
  }
77
80
  }
@@ -104,7 +107,8 @@ export async function generateMigration(description: string = 'migration'): Prom
104
107
 
105
108
  // Removed columns
106
109
  for (const { model, column, type } of diff.removedColumns) {
107
- const table = previousSnapshot[model].table!;
110
+ const table = previousSnapshot[model]?.table;
111
+ if (!table) throw new Error(`Missing table name in snapshot for model "${model}"`);
108
112
  upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
109
113
  downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
110
114
  }
@@ -130,7 +134,8 @@ export async function generateMigration(description: string = 'migration'): Prom
130
134
 
131
135
  // Removed foreign keys
132
136
  for (const { model, column, references } of diff.removedForeignKeys) {
133
- const table = previousSnapshot[model].table!;
137
+ const table = previousSnapshot[model]?.table;
138
+ if (!table) throw new Error(`Missing table name in snapshot for model "${model}"`);
134
139
  // Resolve FK column type from the referenced table's PK type in previous snapshot
135
140
  const refModel = Object.entries(previousSnapshot).find(([, s]) => s.table === references.references);
136
141
  const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
@@ -184,7 +189,7 @@ export async function generateMigration(description: string = 'migration'): Prom
184
189
  const combinedHasChanges = diff.hasChanges || viewDiff.hasChanges;
185
190
 
186
191
  if (!combinedHasChanges) {
187
- log.db!('No schema changes detected.');
192
+ log.db?.('No schema changes detected.');
188
193
  return null;
189
194
  }
190
195
 
@@ -202,7 +207,7 @@ export async function generateMigration(description: string = 'migration'): Prom
202
207
  await createFile(path.join(migrationsPath, filename), content);
203
208
  await createFile(path.join(migrationsPath, '.snapshot.json'), JSON.stringify(combinedSnapshot, null, 2));
204
209
 
205
- log.db!(`Migration generated: ${filename}`);
210
+ log.db?.(`Migration generated: ${filename}`);
206
211
 
207
212
  return { filename, content, snapshot: combinedSnapshot };
208
213
  }
@@ -2,6 +2,7 @@ import { readFile, fileExists } from '@stonyx/utils/file';
2
2
  import path from 'path';
3
3
  import fs from 'fs/promises';
4
4
  import type { Pool, PoolConnection } from 'mysql2/promise';
5
+ import { validateIdentifier } from './query-builder.js';
5
6
 
6
7
  interface ParsedMigration {
7
8
  up: string;
@@ -9,6 +10,7 @@ interface ParsedMigration {
9
10
  }
10
11
 
11
12
  export async function ensureMigrationsTable(pool: Pool, tableName: string = '__migrations'): Promise<void> {
13
+ validateIdentifier(tableName, 'migration table name');
12
14
  await pool.execute(`
13
15
  CREATE TABLE IF NOT EXISTS \`${tableName}\` (
14
16
  id INT AUTO_INCREMENT PRIMARY KEY,
@@ -19,6 +21,7 @@ export async function ensureMigrationsTable(pool: Pool, tableName: string = '__m
19
21
  }
20
22
 
21
23
  export async function getAppliedMigrations(pool: Pool, tableName: string = '__migrations'): Promise<string[]> {
24
+ validateIdentifier(tableName, 'migration table name');
22
25
  const [rows] = await pool.execute(
23
26
  `SELECT filename FROM \`${tableName}\` ORDER BY id ASC`
24
27
  ) as [Array<{ filename: string }>, unknown];
@@ -56,6 +59,7 @@ export function parseMigrationFile(content: string): ParsedMigration {
56
59
  }
57
60
 
58
61
  export async function applyMigration(pool: Pool, filename: string, upSql: string, tableName: string = '__migrations'): Promise<void> {
62
+ validateIdentifier(tableName, 'migration table name');
59
63
  const connection = await pool.getConnection();
60
64
 
61
65
  try {
@@ -83,6 +87,7 @@ export async function applyMigration(pool: Pool, filename: string, upSql: string
83
87
  }
84
88
 
85
89
  export async function rollbackMigration(pool: Pool, filename: string, downSql: string, tableName: string = '__migrations'): Promise<void> {
90
+ validateIdentifier(tableName, 'migration table name');
86
91
  const connection = await pool.getConnection();
87
92
 
88
93
  try {