@stonyx/orm 0.3.2-beta.33 → 0.3.2-beta.330

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 (71) hide show
  1. package/README.md +377 -30
  2. package/config/environment.js +111 -12
  3. package/dist/column-conversion.d.ts +34 -0
  4. package/dist/column-conversion.js +34 -0
  5. package/dist/commands.js +34 -0
  6. package/dist/dynamodb/connection.d.ts +31 -0
  7. package/dist/dynamodb/connection.js +28 -0
  8. package/dist/dynamodb/dynamodb-db.d.ts +142 -0
  9. package/dist/dynamodb/dynamodb-db.js +596 -0
  10. package/dist/dynamodb/operation-builder.d.ts +76 -0
  11. package/dist/dynamodb/operation-builder.js +116 -0
  12. package/dist/dynamodb/type-map.d.ts +31 -0
  13. package/dist/dynamodb/type-map.js +48 -0
  14. package/dist/index.d.ts +4 -2
  15. package/dist/index.js +3 -2
  16. package/dist/main.d.ts +1 -0
  17. package/dist/main.js +29 -1
  18. package/dist/manage-record.d.ts +4 -0
  19. package/dist/manage-record.js +95 -34
  20. package/dist/mysql/connection.d.ts +3 -0
  21. package/dist/mysql/mysql-db.d.ts +32 -2
  22. package/dist/mysql/mysql-db.js +239 -45
  23. package/dist/mysql/query-builder.d.ts +1 -0
  24. package/dist/mysql/query-builder.js +17 -0
  25. package/dist/normalize-record-id.d.ts +67 -0
  26. package/dist/normalize-record-id.js +88 -0
  27. package/dist/orm-request.d.ts +17 -1
  28. package/dist/orm-request.js +77 -19
  29. package/dist/postgres/column-rules.d.ts +33 -0
  30. package/dist/postgres/column-rules.js +34 -0
  31. package/dist/postgres/connection.d.ts +1 -0
  32. package/dist/postgres/connection.js +8 -6
  33. package/dist/postgres/postgres-db.d.ts +36 -2
  34. package/dist/postgres/postgres-db.js +244 -45
  35. package/dist/postgres/query-builder.d.ts +1 -0
  36. package/dist/postgres/query-builder.js +17 -0
  37. package/dist/record.js +7 -5
  38. package/dist/relationships.js +1 -1
  39. package/dist/serializer.js +38 -2
  40. package/dist/store.d.ts +13 -1
  41. package/dist/store.js +65 -6
  42. package/dist/timescale/query-builder.d.ts +1 -1
  43. package/dist/timescale/query-builder.js +1 -2
  44. package/dist/types/orm-types.d.ts +11 -0
  45. package/package.json +19 -7
  46. package/src/column-conversion.ts +53 -0
  47. package/src/commands.ts +43 -0
  48. package/src/dynamodb/connection.ts +50 -0
  49. package/src/dynamodb/dynamodb-db.ts +811 -0
  50. package/src/dynamodb/operation-builder.ts +202 -0
  51. package/src/dynamodb/type-map.ts +54 -0
  52. package/src/index.ts +4 -2
  53. package/src/main.ts +30 -1
  54. package/src/manage-record.ts +112 -33
  55. package/src/mysql/connection.ts +3 -0
  56. package/src/mysql/mysql-db.ts +264 -46
  57. package/src/mysql/query-builder.ts +21 -0
  58. package/src/normalize-record-id.ts +88 -0
  59. package/src/orm-request.ts +109 -18
  60. package/src/postgres/column-rules.ts +37 -0
  61. package/src/postgres/connection.ts +10 -6
  62. package/src/postgres/postgres-db.ts +277 -49
  63. package/src/postgres/query-builder.ts +21 -0
  64. package/src/record.ts +8 -5
  65. package/src/relationships.ts +1 -1
  66. package/src/serializer.ts +39 -2
  67. package/src/store.ts +68 -6
  68. package/src/timescale/query-builder.ts +1 -2
  69. package/src/types/orm-types.ts +12 -0
  70. package/src/types/stonyx.d.ts +7 -1
  71. package/config/environment.ts +0 -91
@@ -5,6 +5,7 @@ import { getPluralName } from './plural-registry.js';
5
5
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
6
6
  import config from 'stonyx/config';
7
7
  import { isOrmRecord } from './utils.js';
8
+ import normalizeRecordId from './normalize-record-id.js';
8
9
  const methodAccessMap = {
9
10
  GET: 'read',
10
11
  POST: 'create',
@@ -42,19 +43,46 @@ function getModelRelationships(modelName) {
42
43
  }
43
44
  return relationships;
44
45
  }
45
- // Helper to build base URL from request
46
- function getBaseUrl(request) {
46
+ /**
47
+ * Build the absolute base URL that every advertised link hangs off — origin
48
+ * plus the prefix the ORM's routes are actually mounted at.
49
+ *
50
+ * The prefix is derived from the *request*, not from
51
+ * `config.orm.restServer.route`. Express sets `request.baseUrl` to the real
52
+ * mountpath registered by `RestServer.mountRoute`, which for this module is
53
+ * always `<prefix>/<pluralizedModel>` (see setup-rest-server.ts). Stripping the
54
+ * trailing model segment therefore yields the prefix by construction, and the
55
+ * link builder cannot drift from the mount registrar the way a second,
56
+ * independent normalisation of `route` would.
57
+ *
58
+ * When `request.baseUrl` is absent or does not end in the model segment the
59
+ * prefix is empty, which reproduces the previous origin-only behaviour.
60
+ */
61
+ function getBaseUrl(request, pluralizedModel) {
47
62
  const protocol = request.protocol || 'http';
48
63
  const host = request.get('host');
49
- return `${protocol}://${host}`;
64
+ const modelSegment = `/${pluralizedModel}`;
65
+ const mountPath = request.baseUrl ?? '';
66
+ const prefix = mountPath.endsWith(modelSegment) ? mountPath.slice(0, -modelSegment.length) : '';
67
+ return `${protocol}://${host}${prefix}`;
50
68
  }
69
+ // Kept as a name because twelve `getId(...)` call sites read it. It is now a
70
+ // thin delegate: there is exactly ONE normalisation of a URL id in the repo,
71
+ // and it is the exported one a consumer can import.
72
+ //
73
+ // "of a URL id" is the load-bearing qualifier, and it is the same one
74
+ // src/normalize-record-id.ts:18 carries. Three copies of the coercion survive
75
+ // at this head — src/orm-request.ts (the create-response path),
76
+ // src/postgres/postgres-db.ts and src/mysql/mysql-db.ts — but each normalises a
77
+ // RESPONSE id (`response?.data?.id`), not a URL id, and each omits this
78
+ // function's `if (!id) return ''` guard. They are tracked as
79
+ // abofs/stonyx-orm#282 and enumerated by name in AC-5's allowlist
80
+ // (test/integration/readme-sample-test.ts).
81
+ //
82
+ // A second implementation of the URL-id normalisation here is the defect
83
+ // abofs/stonyx-orm#270 exists to remove — see src/normalize-record-id.ts.
51
84
  function getId(params) {
52
- const id = params.id;
53
- if (!id)
54
- return '';
55
- if (isNaN(id))
56
- return id;
57
- return parseInt(id);
85
+ return normalizeRecordId(params.id);
58
86
  }
59
87
  function buildResponse(data, includeParam, recordOrRecords, options = {}) {
60
88
  const { links, baseUrl } = options;
@@ -209,7 +237,7 @@ export default class OrmRequest extends Request {
209
237
  recordsToReturn = recordsToReturn.filter(accessFilter);
210
238
  if (queryFilterPredicate)
211
239
  recordsToReturn = recordsToReturn.filter(queryFilterPredicate);
212
- const baseUrl = getBaseUrl(request);
240
+ const baseUrl = getBaseUrl(request, pluralizedModel);
213
241
  const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl }));
214
242
  return buildResponse(data, request.query?.include, recordsToReturn, {
215
243
  links: { self: `${baseUrl}/${pluralizedModel}` },
@@ -222,7 +250,7 @@ export default class OrmRequest extends Request {
222
250
  return 404;
223
251
  const fieldsMap = parseFields(request.query);
224
252
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
225
- const baseUrl = getBaseUrl(request);
253
+ const baseUrl = getBaseUrl(request, pluralizedModel);
226
254
  return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl }), request.query?.include, record, {
227
255
  links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
228
256
  baseUrl
@@ -289,7 +317,7 @@ export default class OrmRequest extends Request {
289
317
  return { data: record.toJSON?.() };
290
318
  };
291
319
  const deleteHandler = ({ params }) => {
292
- store.remove(model, getId(params));
320
+ store.remove(model, getId(params), { _skipAutoPersist: true });
293
321
  return 204;
294
322
  };
295
323
  // Wrap handlers with hooks
@@ -348,9 +376,13 @@ export default class OrmRequest extends Request {
348
376
  }
349
377
  // Execute main handler
350
378
  const response = await handler(request, state);
351
- // Persist to SQL database for create/update (delete is handled by store.remove auto-persist)
379
+ // Set context.record for update BEFORE persist so SQL drivers can read it
380
+ if (operation === 'update' && response?.data) {
381
+ context.record = store.get(this.model, getId(request.params));
382
+ }
383
+ // Persist to SQL database for all write operations (create/update/delete)
352
384
  const sqlDb = Orm.instance.sqlDb;
353
- if (sqlDb && (operation === 'create' || operation === 'update')) {
385
+ if (sqlDb && WRITE_OPERATIONS.has(operation)) {
354
386
  await sqlDb.persist(operation, this.model, context, response);
355
387
  }
356
388
  // Add response and relevant records to context
@@ -367,9 +399,6 @@ export default class OrmRequest extends Request {
367
399
  const recordId = isNaN(responseData.id) ? responseData.id : parseInt(responseData.id);
368
400
  context.record = store.get(this.model, recordId);
369
401
  }
370
- else if (operation === 'update' && response?.data) {
371
- context.record = store.get(this.model, getId(request.params));
372
- }
373
402
  else if (operation === 'delete') {
374
403
  // For delete, the record may no longer exist, but we have oldState
375
404
  context.recordId = getId(request.params);
@@ -396,7 +425,7 @@ export default class OrmRequest extends Request {
396
425
  if (!record)
397
426
  return 404;
398
427
  const relatedData = record.__relationships[relationshipName];
399
- const baseUrl = getBaseUrl(request);
428
+ const baseUrl = getBaseUrl(request, pluralizedModel);
400
429
  let data;
401
430
  if (info.isArray) {
402
431
  // hasMany - return array
@@ -418,7 +447,7 @@ export default class OrmRequest extends Request {
418
447
  if (!record)
419
448
  return 404;
420
449
  const relatedData = record.__relationships[relationshipName];
421
- const baseUrl = getBaseUrl(request);
450
+ const baseUrl = getBaseUrl(request, pluralizedModel);
422
451
  let data;
423
452
  if (info.isArray) {
424
453
  // hasMany - return array of linkage objects
@@ -463,6 +492,35 @@ export default class OrmRequest extends Request {
463
492
  return routes;
464
493
  }
465
494
  auth(request, state) {
495
+ // abofs/stonyx-orm#270 — hand the predicate the value the record is
496
+ // ACTUALLY resolved by, rather than the raw text it was parsed from.
497
+ //
498
+ // This is the default path precisely because it requires the consumer to
499
+ // remember nothing. Exporting `normalizeRecordId` alone would leave the
500
+ // framework owning resolution while asking every consumer to call one
501
+ // function, with no signal when they forget — the same silent fail-open,
502
+ // one step over. The export is the escape hatch for hooks and custom
503
+ // handlers; this line is the contract.
504
+ //
505
+ // `request.params` is deliberately NOT mutated. Twelve `getId(...)` call
506
+ // sites read it, and `_withHooks` assigns `params: request.params` onto the
507
+ // hook context, so every consumer hook reads the same object. Changing
508
+ // `params.id` from string to number underneath them is a silent behaviour
509
+ // change on paths this issue is not about.
510
+ //
511
+ // Synchronous by necessity: @stonyx/rest-server calls auth() without
512
+ // awaiting it.
513
+ //
514
+ // The `undefined` branch is a PRESENCE check, not a second normalisation:
515
+ // it answers "does this route carry an :id at all", which is how both
516
+ // documented samples tell a collection request from a record request. It
517
+ // cannot be folded into normalizeRecordId, because that function must keep
518
+ // returning '' for a falsy id — `store.get(key, undefined)` returns the
519
+ // whole model Map rather than a record (abofs/stonyx-orm#167, pinned by
520
+ // test/unit/store-get-falsy-id-test.ts), so the resolution path depends on
521
+ // the '' it returns today.
522
+ const rawId = request.params?.id;
523
+ request.recordId = rawId === undefined ? undefined : normalizeRecordId(rawId);
466
524
  const access = this.access(request);
467
525
  if (!access)
468
526
  return 403;
@@ -0,0 +1,33 @@
1
+ import type { ColumnRule } from '../column-conversion.js';
2
+ /**
3
+ * PostgreSQL's write-path conversion rule (#292).
4
+ *
5
+ * JSONB columns must receive a JSON *string*. node-pg's `prepareValue`
6
+ * (`pg/lib/utils.js`) checks `Array.isArray` before its object fallback, so a
7
+ * raw array is rendered as a Postgres array literal (`{"1","2","3"}`) rather
8
+ * than JSON. `[]` becomes `{}`, which is valid JSON, so it lands silently
9
+ * corrupted with no error.
10
+ *
11
+ * Two behaviours this rule must keep:
12
+ *
13
+ * - `typeof value === 'string'` passes through untouched. A JSONB column
14
+ * already holding a JSON string (`'{"a":1}'`) must store the object it
15
+ * describes; an unconditional `JSON.stringify` would double-encode it.
16
+ * - An `undefined` column type is a no-op. `updated_at`, `id` and FK columns
17
+ * are added outside the attribute loop and are absent from
18
+ * `schema.columns`.
19
+ *
20
+ * The `'JSONB'` sentinel is the exact literal emitted by
21
+ * `src/postgres/type-map.ts`, the only module that produces the values in
22
+ * `schema.columns`. The two producing functions are `getPgType` and
23
+ * `getVectorType` (`src/postgres/schema-introspector.ts` writes `columns[key]`
24
+ * at exactly three sites, all routed through those two); `mysqlTypeToPg` is not
25
+ * exported and is reachable only from inside `getPgType`.
26
+ *
27
+ * One documented gap: `getPgType` returns a consumer transform's declared
28
+ * `pgType` verbatim, so a consumer writing `pgType: 'jsonb'` puts a value in
29
+ * `schema.columns` that type-map never authored and this exact-match sentinel
30
+ * misses. It misses identically on the create path, pre-fix and post-fix --
31
+ * pre-existing and symmetric, not introduced here.
32
+ */
33
+ export declare const postgresJsonRule: ColumnRule;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * PostgreSQL's write-path conversion rule (#292).
3
+ *
4
+ * JSONB columns must receive a JSON *string*. node-pg's `prepareValue`
5
+ * (`pg/lib/utils.js`) checks `Array.isArray` before its object fallback, so a
6
+ * raw array is rendered as a Postgres array literal (`{"1","2","3"}`) rather
7
+ * than JSON. `[]` becomes `{}`, which is valid JSON, so it lands silently
8
+ * corrupted with no error.
9
+ *
10
+ * Two behaviours this rule must keep:
11
+ *
12
+ * - `typeof value === 'string'` passes through untouched. A JSONB column
13
+ * already holding a JSON string (`'{"a":1}'`) must store the object it
14
+ * describes; an unconditional `JSON.stringify` would double-encode it.
15
+ * - An `undefined` column type is a no-op. `updated_at`, `id` and FK columns
16
+ * are added outside the attribute loop and are absent from
17
+ * `schema.columns`.
18
+ *
19
+ * The `'JSONB'` sentinel is the exact literal emitted by
20
+ * `src/postgres/type-map.ts`, the only module that produces the values in
21
+ * `schema.columns`. The two producing functions are `getPgType` and
22
+ * `getVectorType` (`src/postgres/schema-introspector.ts` writes `columns[key]`
23
+ * at exactly three sites, all routed through those two); `mysqlTypeToPg` is not
24
+ * exported and is reachable only from inside `getPgType`.
25
+ *
26
+ * One documented gap: `getPgType` returns a consumer transform's declared
27
+ * `pgType` verbatim, so a consumer writing `pgType: 'jsonb'` puts a value in
28
+ * `schema.columns` that type-map never authored and this exact-match sentinel
29
+ * misses. It misses identically on the create path, pre-fix and post-fix --
30
+ * pre-existing and symmetric, not introduced here.
31
+ */
32
+ export const postgresJsonRule = (value, columnType) => columnType === 'JSONB' && typeof value !== 'string'
33
+ ? JSON.stringify(value)
34
+ : value;
@@ -6,6 +6,7 @@ interface PgConfig {
6
6
  password: string;
7
7
  database: string;
8
8
  connectionLimit: number;
9
+ [key: string]: unknown;
9
10
  }
10
11
  /**
11
12
  * Create or return the singleton pg Pool.
@@ -7,15 +7,17 @@ export async function getPool(pgConfig, extensions = ['vector']) {
7
7
  if (pool)
8
8
  return pool;
9
9
  const { default: pg } = await import('pg');
10
+ const { host, port, user, password, database, connectionLimit, migrationsDir, migrationsTable, autoMigrate, writeBatchSize, writeQueueLimit, ...poolOpts } = pgConfig;
10
11
  pool = new pg.Pool({
11
- host: pgConfig.host,
12
- port: pgConfig.port,
13
- user: pgConfig.user,
14
- password: pgConfig.password,
15
- database: pgConfig.database,
16
- max: pgConfig.connectionLimit,
12
+ host,
13
+ port,
14
+ user,
15
+ password,
16
+ database,
17
+ max: connectionLimit,
17
18
  idleTimeoutMillis: 30000,
18
19
  connectionTimeoutMillis: 10000,
20
+ ...poolOpts,
19
21
  });
20
22
  // Enable requested PostgreSQL extensions
21
23
  for (const ext of extensions) {
@@ -2,12 +2,14 @@ import { getPool, closePool } from './connection.js';
2
2
  import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
3
3
  import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
4
4
  import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
5
- import { buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch } from './query-builder.js';
5
+ import { buildInsert, buildInsertMany, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch } from './query-builder.js';
6
6
  import { store } from '@stonyx/orm';
7
7
  import { createRecord } from '../manage-record.js';
8
8
  import { confirm } from '@stonyx/utils/prompt';
9
9
  import { readFile } from '@stonyx/utils/file';
10
10
  import { getPluralName } from '../plural-registry.js';
11
+ import { convertRow } from '../column-conversion.js';
12
+ import { postgresJsonRule } from './column-rules.js';
11
13
  import config from 'stonyx/config';
12
14
  import log from 'stonyx/log';
13
15
  import path from 'path';
@@ -24,6 +26,13 @@ interface PersistResponse {
24
26
  id: unknown;
25
27
  };
26
28
  }
29
+ type ExitEmitter = Pick<NodeJS.Process, 'once' | 'removeListener'>;
30
+ export declare class WriteQueueFullError extends Error {
31
+ constructor(limit: number);
32
+ }
33
+ export declare class WriteQueueClosedError extends Error {
34
+ constructor();
35
+ }
27
36
  interface SearchResult {
28
37
  record: OrmRecord;
29
38
  distance: number;
@@ -47,6 +56,7 @@ interface PostgresDeps {
47
56
  loadLatestSnapshot: typeof loadLatestSnapshot;
48
57
  detectSchemaDrift: typeof detectSchemaDrift;
49
58
  buildInsert: typeof buildInsert;
59
+ buildInsertMany: typeof buildInsertMany;
50
60
  buildUpdate: typeof buildUpdate;
51
61
  buildDelete: typeof buildDelete;
52
62
  buildSelect: typeof buildSelect;
@@ -57,9 +67,12 @@ interface PostgresDeps {
57
67
  confirm: typeof confirm;
58
68
  readFile: typeof readFile;
59
69
  getPluralName: typeof getPluralName;
70
+ convertRow: typeof convertRow;
71
+ postgresJsonRule: typeof postgresJsonRule;
60
72
  config: typeof config;
61
73
  log: typeof log;
62
74
  path: typeof path;
75
+ process: ExitEmitter;
63
76
  [key: string]: unknown;
64
77
  }
65
78
  export default class PostgresDB {
@@ -72,11 +85,23 @@ export default class PostgresDB {
72
85
  deps: PostgresDeps;
73
86
  pool: Pool | null;
74
87
  pgConfig: Record<string, unknown>;
88
+ readonly persistResolvesAfterWrite = true;
89
+ private _queuedWrites;
90
+ private _inFlightWrites;
91
+ private _drainingWrites;
92
+ private _acceptingWrites;
93
+ private _exitReport;
75
94
  constructor(deps?: Partial<PostgresDeps>);
76
95
  protected requirePool(): Pool;
77
96
  init(): Promise<void>;
97
+ get writeBatchSize(): number;
98
+ get writeQueueLimit(): number;
99
+ get pendingWriteCount(): number;
78
100
  startup(): Promise<void>;
79
101
  shutdown(): Promise<void>;
102
+ private _registerExitReport;
103
+ private _unregisterExitReport;
104
+ private _reportUnpersistedWrites;
80
105
  save(): Promise<void>;
81
106
  /**
82
107
  * Loads only models with memory: true into the in-memory store on startup.
@@ -112,7 +137,16 @@ export default class PostgresDB {
112
137
  private _evictIfNotMemory;
113
138
  private _rowToRawData;
114
139
  persist(operation: string, modelName: string, context: PersistContext, response: PersistResponse): Promise<void>;
115
- private _persistCreate;
140
+ private _drainWritesInBackground;
141
+ private _drainQueuedWrites;
142
+ private _takeNextWriteGroup;
143
+ private _executeWriteGroup;
144
+ private _persistCreates;
145
+ private _prepareCreate;
146
+ private _chunkWithinBindParameterLimit;
147
+ private _insertCreates;
148
+ private _insertCreatesOneByOne;
149
+ private _adoptGeneratedId;
116
150
  private _persistUpdate;
117
151
  private _persistDelete;
118
152
  private _recordToRow;