@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.
- package/README.md +377 -30
- package/config/environment.js +111 -12
- package/dist/column-conversion.d.ts +34 -0
- package/dist/column-conversion.js +34 -0
- package/dist/commands.js +34 -0
- package/dist/dynamodb/connection.d.ts +31 -0
- package/dist/dynamodb/connection.js +28 -0
- package/dist/dynamodb/dynamodb-db.d.ts +142 -0
- package/dist/dynamodb/dynamodb-db.js +596 -0
- package/dist/dynamodb/operation-builder.d.ts +76 -0
- package/dist/dynamodb/operation-builder.js +116 -0
- package/dist/dynamodb/type-map.d.ts +31 -0
- package/dist/dynamodb/type-map.js +48 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +3 -2
- package/dist/main.d.ts +1 -0
- package/dist/main.js +29 -1
- package/dist/manage-record.d.ts +4 -0
- package/dist/manage-record.js +95 -34
- package/dist/mysql/connection.d.ts +3 -0
- package/dist/mysql/mysql-db.d.ts +32 -2
- package/dist/mysql/mysql-db.js +239 -45
- package/dist/mysql/query-builder.d.ts +1 -0
- package/dist/mysql/query-builder.js +17 -0
- package/dist/normalize-record-id.d.ts +67 -0
- package/dist/normalize-record-id.js +88 -0
- package/dist/orm-request.d.ts +17 -1
- package/dist/orm-request.js +77 -19
- package/dist/postgres/column-rules.d.ts +33 -0
- package/dist/postgres/column-rules.js +34 -0
- package/dist/postgres/connection.d.ts +1 -0
- package/dist/postgres/connection.js +8 -6
- package/dist/postgres/postgres-db.d.ts +36 -2
- package/dist/postgres/postgres-db.js +244 -45
- package/dist/postgres/query-builder.d.ts +1 -0
- package/dist/postgres/query-builder.js +17 -0
- package/dist/record.js +7 -5
- package/dist/relationships.js +1 -1
- package/dist/serializer.js +38 -2
- package/dist/store.d.ts +13 -1
- package/dist/store.js +65 -6
- package/dist/timescale/query-builder.d.ts +1 -1
- package/dist/timescale/query-builder.js +1 -2
- package/dist/types/orm-types.d.ts +11 -0
- package/package.json +19 -7
- package/src/column-conversion.ts +53 -0
- package/src/commands.ts +43 -0
- package/src/dynamodb/connection.ts +50 -0
- package/src/dynamodb/dynamodb-db.ts +811 -0
- package/src/dynamodb/operation-builder.ts +202 -0
- package/src/dynamodb/type-map.ts +54 -0
- package/src/index.ts +4 -2
- package/src/main.ts +30 -1
- package/src/manage-record.ts +112 -33
- package/src/mysql/connection.ts +3 -0
- package/src/mysql/mysql-db.ts +264 -46
- package/src/mysql/query-builder.ts +21 -0
- package/src/normalize-record-id.ts +88 -0
- package/src/orm-request.ts +109 -18
- package/src/postgres/column-rules.ts +37 -0
- package/src/postgres/connection.ts +10 -6
- package/src/postgres/postgres-db.ts +277 -49
- package/src/postgres/query-builder.ts +21 -0
- package/src/record.ts +8 -5
- package/src/relationships.ts +1 -1
- package/src/serializer.ts +39 -2
- package/src/store.ts +68 -6
- package/src/timescale/query-builder.ts +1 -2
- package/src/types/orm-types.ts +12 -0
- package/src/types/stonyx.d.ts +7 -1
- package/config/environment.ts +0 -91
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DynamoDB operation parameter builders.
|
|
3
|
+
*
|
|
4
|
+
* Each function returns a plain-object "params" bag that can be passed
|
|
5
|
+
* directly to the corresponding DocumentClient command
|
|
6
|
+
* (PutCommand, GetCommand, UpdateCommand, DeleteCommand, ScanCommand, QueryCommand).
|
|
7
|
+
*
|
|
8
|
+
* All functions are pure — no SDK imports here; the caller wraps params
|
|
9
|
+
* in the appropriate Command class.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export interface PutItemParams {
|
|
13
|
+
TableName: string;
|
|
14
|
+
Item: Record<string, unknown>;
|
|
15
|
+
ConditionExpression?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface GetItemParams {
|
|
19
|
+
TableName: string;
|
|
20
|
+
Key: Record<string, unknown>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface UpdateItemParams {
|
|
24
|
+
TableName: string;
|
|
25
|
+
Key: Record<string, unknown>;
|
|
26
|
+
UpdateExpression: string;
|
|
27
|
+
ExpressionAttributeNames: Record<string, string>;
|
|
28
|
+
ExpressionAttributeValues: Record<string, unknown>;
|
|
29
|
+
ReturnValues: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DeleteItemParams {
|
|
33
|
+
TableName: string;
|
|
34
|
+
Key: Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ScanParams {
|
|
38
|
+
TableName: string;
|
|
39
|
+
FilterExpression?: string;
|
|
40
|
+
ExpressionAttributeNames?: Record<string, string>;
|
|
41
|
+
ExpressionAttributeValues?: Record<string, unknown>;
|
|
42
|
+
ExclusiveStartKey?: Record<string, unknown>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface QueryParams {
|
|
46
|
+
TableName: string;
|
|
47
|
+
IndexName: string;
|
|
48
|
+
KeyConditionExpression: string;
|
|
49
|
+
ExpressionAttributeNames: Record<string, string>;
|
|
50
|
+
ExpressionAttributeValues: Record<string, unknown>;
|
|
51
|
+
ExclusiveStartKey?: Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* PutItem — optionally with a condition expression.
|
|
56
|
+
*
|
|
57
|
+
* Pass conditionExpression = 'attribute_not_exists(id)' to enforce uniqueness.
|
|
58
|
+
*/
|
|
59
|
+
export function buildPutItem(
|
|
60
|
+
tableName: string,
|
|
61
|
+
item: Record<string, unknown>,
|
|
62
|
+
conditionExpression?: string,
|
|
63
|
+
): PutItemParams {
|
|
64
|
+
const params: PutItemParams = { TableName: tableName, Item: item };
|
|
65
|
+
if (conditionExpression) params.ConditionExpression = conditionExpression;
|
|
66
|
+
return params;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* GetItem by primary key.
|
|
71
|
+
*/
|
|
72
|
+
export function buildGetItem(
|
|
73
|
+
tableName: string,
|
|
74
|
+
key: Record<string, unknown>,
|
|
75
|
+
): GetItemParams {
|
|
76
|
+
return { TableName: tableName, Key: key };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* UpdateItem with a SET expression built from the `updates` object.
|
|
81
|
+
* Only the supplied attributes are updated (diff-based call site).
|
|
82
|
+
*/
|
|
83
|
+
export function buildUpdateItem(
|
|
84
|
+
tableName: string,
|
|
85
|
+
key: Record<string, unknown>,
|
|
86
|
+
updates: Record<string, unknown>,
|
|
87
|
+
): UpdateItemParams {
|
|
88
|
+
const names: Record<string, string> = {};
|
|
89
|
+
const values: Record<string, unknown> = {};
|
|
90
|
+
const setClauses: string[] = [];
|
|
91
|
+
|
|
92
|
+
for (const [attr, val] of Object.entries(updates)) {
|
|
93
|
+
const nameAlias = `#${attr}`;
|
|
94
|
+
const valAlias = `:${attr}`;
|
|
95
|
+
names[nameAlias] = attr;
|
|
96
|
+
values[valAlias] = val;
|
|
97
|
+
setClauses.push(`${nameAlias} = ${valAlias}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
TableName: tableName,
|
|
102
|
+
Key: key,
|
|
103
|
+
UpdateExpression: `SET ${setClauses.join(', ')}`,
|
|
104
|
+
ExpressionAttributeNames: names,
|
|
105
|
+
ExpressionAttributeValues: values,
|
|
106
|
+
ReturnValues: 'NONE',
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* DeleteItem by primary key.
|
|
112
|
+
*/
|
|
113
|
+
export function buildDeleteItem(
|
|
114
|
+
tableName: string,
|
|
115
|
+
key: Record<string, unknown>,
|
|
116
|
+
): DeleteItemParams {
|
|
117
|
+
return { TableName: tableName, Key: key };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* ScanCommand params.
|
|
122
|
+
* If conditions are supplied they are rendered as a FilterExpression using AND.
|
|
123
|
+
*/
|
|
124
|
+
export function buildScan(
|
|
125
|
+
tableName: string,
|
|
126
|
+
conditions?: Record<string, unknown>,
|
|
127
|
+
exclusiveStartKey?: Record<string, unknown>,
|
|
128
|
+
): ScanParams {
|
|
129
|
+
const params: ScanParams = { TableName: tableName };
|
|
130
|
+
|
|
131
|
+
if (exclusiveStartKey) params.ExclusiveStartKey = exclusiveStartKey;
|
|
132
|
+
|
|
133
|
+
if (conditions && Object.keys(conditions).length > 0) {
|
|
134
|
+
const validEntries = Object.entries(conditions).filter(
|
|
135
|
+
([, val]) => val !== undefined && val !== null,
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
if (validEntries.length > 0) {
|
|
139
|
+
const names: Record<string, string> = {};
|
|
140
|
+
const values: Record<string, unknown> = {};
|
|
141
|
+
const clauses: string[] = [];
|
|
142
|
+
|
|
143
|
+
for (const [attr, val] of validEntries) {
|
|
144
|
+
const nameAlias = `#${attr}`;
|
|
145
|
+
const valAlias = `:${attr}`;
|
|
146
|
+
names[nameAlias] = attr;
|
|
147
|
+
values[valAlias] = val;
|
|
148
|
+
clauses.push(`${nameAlias} = ${valAlias}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
params.FilterExpression = clauses.join(' AND ');
|
|
152
|
+
params.ExpressionAttributeNames = names;
|
|
153
|
+
params.ExpressionAttributeValues = values;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return params;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* QueryCommand params for a GSI.
|
|
162
|
+
* keyConditions must be in the form { attrName: value } and will be rendered
|
|
163
|
+
* as equality expressions joined by AND.
|
|
164
|
+
*/
|
|
165
|
+
export function buildQuery(
|
|
166
|
+
tableName: string,
|
|
167
|
+
indexName: string,
|
|
168
|
+
keyConditions: Record<string, unknown>,
|
|
169
|
+
exclusiveStartKey?: Record<string, unknown>,
|
|
170
|
+
): QueryParams {
|
|
171
|
+
const validEntries = Object.entries(keyConditions).filter(
|
|
172
|
+
([, val]) => val !== undefined && val !== null,
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
if (validEntries.length === 0) {
|
|
176
|
+
throw new Error('buildQuery: all keyCondition values are undefined/null');
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const names: Record<string, string> = {};
|
|
180
|
+
const values: Record<string, unknown> = {};
|
|
181
|
+
const clauses: string[] = [];
|
|
182
|
+
|
|
183
|
+
for (const [attr, val] of validEntries) {
|
|
184
|
+
const nameAlias = `#${attr}`;
|
|
185
|
+
const valAlias = `:${attr}`;
|
|
186
|
+
names[nameAlias] = attr;
|
|
187
|
+
values[valAlias] = val;
|
|
188
|
+
clauses.push(`${nameAlias} = ${valAlias}`);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const params: QueryParams = {
|
|
192
|
+
TableName: tableName,
|
|
193
|
+
IndexName: indexName,
|
|
194
|
+
KeyConditionExpression: clauses.join(' AND '),
|
|
195
|
+
ExpressionAttributeNames: names,
|
|
196
|
+
ExpressionAttributeValues: values,
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
if (exclusiveStartKey) params.ExclusiveStartKey = exclusiveStartKey;
|
|
200
|
+
|
|
201
|
+
return params;
|
|
202
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps ORM attribute types to DynamoDB scalar attribute types.
|
|
3
|
+
* DynamoDB DocumentClient auto-marshalls JS objects, so most values
|
|
4
|
+
* are sent as their native JS types. This map is used by the
|
|
5
|
+
* schema-introspector and startup provisioner for table/GSI creation.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type DynamoScalarType = 'S' | 'N' | 'BOOL';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* DynamoDB attribute-type string for a given ORM attr type.
|
|
12
|
+
* - string → S
|
|
13
|
+
* - number / float → N (stored as Number; DocumentClient handles it)
|
|
14
|
+
* - boolean → BOOL
|
|
15
|
+
* - date → S (ISO-8601 string — enables range queries)
|
|
16
|
+
* - timestamp → N (milliseconds since epoch)
|
|
17
|
+
* - passthrough/trim/etc → S (safe default)
|
|
18
|
+
*
|
|
19
|
+
* For key schema declarations only `S` and `N` are valid; BOOL
|
|
20
|
+
* is legal for attributes but never for a PK/SK.
|
|
21
|
+
*/
|
|
22
|
+
const typeMap: Record<string, DynamoScalarType> = {
|
|
23
|
+
string: 'S',
|
|
24
|
+
number: 'N',
|
|
25
|
+
float: 'N',
|
|
26
|
+
boolean: 'BOOL',
|
|
27
|
+
date: 'S',
|
|
28
|
+
timestamp: 'N',
|
|
29
|
+
passthrough: 'S',
|
|
30
|
+
trim: 'S',
|
|
31
|
+
uppercase: 'S',
|
|
32
|
+
ceil: 'N',
|
|
33
|
+
floor: 'N',
|
|
34
|
+
round: 'N',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Returns the DynamoDB attribute type for a given ORM type string.
|
|
39
|
+
* Defaults to 'S' for any unknown/custom type.
|
|
40
|
+
*/
|
|
41
|
+
export function getDynamoType(attrType: string): DynamoScalarType {
|
|
42
|
+
return typeMap[attrType] ?? 'S';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Returns the DynamoDB key type ('S' | 'N') for use in KeySchema.
|
|
47
|
+
* BOOL cannot be a key attribute; anything that maps to BOOL falls back to 'S'.
|
|
48
|
+
*/
|
|
49
|
+
export function getDynamoKeyType(attrType: string): 'S' | 'N' {
|
|
50
|
+
const t = getDynamoType(attrType);
|
|
51
|
+
return t === 'N' ? 'N' : 'S';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export default typeMap;
|
package/src/index.ts
CHANGED
|
@@ -21,15 +21,17 @@ import Serializer from './serializer.js';
|
|
|
21
21
|
import attr from './attr.js';
|
|
22
22
|
import belongsTo from './belongs-to.js';
|
|
23
23
|
import hasMany from './has-many.js';
|
|
24
|
-
import { createRecord, updateRecord } from './manage-record.js';
|
|
24
|
+
import { createRecord, updateRecord, createRecordAndPersist, updateRecordAndPersist } from './manage-record.js';
|
|
25
25
|
import { count, avg, sum, min, max } from './aggregates.js';
|
|
26
26
|
|
|
27
27
|
export { default } from './main.js';
|
|
28
28
|
export { store, relationships } from './main.js';
|
|
29
29
|
export type { PersistErrorDetail } from './main.js';
|
|
30
30
|
export { Model, View, Serializer }; // base classes
|
|
31
|
-
export { attr, belongsTo, hasMany, createRecord, updateRecord };
|
|
31
|
+
export { attr, belongsTo, hasMany, createRecord, updateRecord, createRecordAndPersist, updateRecordAndPersist };
|
|
32
32
|
export { count, avg, sum, min, max }; // aggregate helpers
|
|
33
|
+
export { default as normalizeRecordId } from './normalize-record-id.js'; // canonical URL-id -> record-id resolution (#270)
|
|
34
|
+
export type { OrmRequest$ as OrmAccessRequest } from './orm-request.js'; // the request access() is handed, incl. recordId (#270)
|
|
33
35
|
export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js'; // middleware hooks
|
|
34
36
|
|
|
35
37
|
// Store API:
|
package/src/main.ts
CHANGED
|
@@ -20,7 +20,6 @@ import log from 'stonyx/log';
|
|
|
20
20
|
import { forEachFileImport } from '@stonyx/utils/file';
|
|
21
21
|
import { kebabCaseToPascalCase, pluralize } from '@stonyx/utils/string';
|
|
22
22
|
import { registerPluralName } from './plural-registry.js';
|
|
23
|
-
import setupRestServer from './setup-rest-server.js';
|
|
24
23
|
import baseTransforms from './transforms.js';
|
|
25
24
|
import Store from './store.js';
|
|
26
25
|
import Serializer from './serializer.js';
|
|
@@ -35,6 +34,7 @@ export interface SqlDb {
|
|
|
35
34
|
startup(): Promise<void>;
|
|
36
35
|
shutdown(): Promise<void>;
|
|
37
36
|
persist(operation: string, model: string, context: unknown, response: unknown): Promise<void>;
|
|
37
|
+
persistResolvesAfterWrite?: boolean;
|
|
38
38
|
findRecord(modelName: string, id: unknown): Promise<unknown>;
|
|
39
39
|
findAll(modelName: string, conditions?: Record<string, unknown>): Promise<unknown[]>;
|
|
40
40
|
}
|
|
@@ -90,6 +90,11 @@ export default class Orm {
|
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
async init(): Promise<void> {
|
|
93
|
+
// Self-register so log.db works even when @stonyx/orm is in the
|
|
94
|
+
// consumer's `dependencies` (stonyx loader only merges devDependencies).
|
|
95
|
+
const { logColor = 'white', logMethod = 'db' } = config.orm;
|
|
96
|
+
log.defineType(logMethod, logColor);
|
|
97
|
+
|
|
93
98
|
const { paths, restServer } = config.orm;
|
|
94
99
|
|
|
95
100
|
const promises: Promise<unknown>[] = ['Model', 'Serializer', 'Transform'].map(type => {
|
|
@@ -159,6 +164,11 @@ export default class Orm {
|
|
|
159
164
|
this.sqlDb = new MysqlDB() as SqlDb;
|
|
160
165
|
this.db = this.sqlDb;
|
|
161
166
|
promises.push(this.sqlDb.init());
|
|
167
|
+
} else if (config.orm.dynamodb) {
|
|
168
|
+
const { default: DynamoDBDB } = await import('./dynamodb/dynamodb-db.js');
|
|
169
|
+
this.sqlDb = new DynamoDBDB() as SqlDb;
|
|
170
|
+
this.db = this.sqlDb;
|
|
171
|
+
promises.push(this.sqlDb.init());
|
|
162
172
|
} else if (this.options.dbType !== 'none') {
|
|
163
173
|
const db = new DB();
|
|
164
174
|
this.db = db;
|
|
@@ -167,6 +177,25 @@ export default class Orm {
|
|
|
167
177
|
}
|
|
168
178
|
|
|
169
179
|
if (restServer.enabled === 'true') {
|
|
180
|
+
// MUST stay dynamic. setup-rest-server.js names the optional
|
|
181
|
+
// '@stonyx/rest-server' peer in its own static graph — directly, and
|
|
182
|
+
// through orm-request.ts / meta-request.ts, which import `Request` at
|
|
183
|
+
// module scope because they extend it (correctly: an `extends` base
|
|
184
|
+
// class cannot be awaited). Node links a module's entire static graph
|
|
185
|
+
// before evaluating any of it, so a static import here puts that
|
|
186
|
+
// specifier on the entry graph and `import('@stonyx/orm')` throws
|
|
187
|
+
// ERR_MODULE_NOT_FOUND for an ORM-only consumer that never installed the
|
|
188
|
+
// optional peer.
|
|
189
|
+
//
|
|
190
|
+
// NOT the same reason the SQL/DynamoDB drivers above are lazy: those
|
|
191
|
+
// modules carry no static peer specifier that survives to `dist/`
|
|
192
|
+
// (postgres-db.ts:15 and mysql-db.ts:17 are `import type`, erased by
|
|
193
|
+
// tsc), so the `await import()` there is not what isolates pg / mysql2 /
|
|
194
|
+
// @aws-sdk — that happens one layer down, in src/*/connection.ts (and
|
|
195
|
+
// src/dynamodb/dynamodb-db.ts).
|
|
196
|
+
// setup-rest-server.js is the only dist module whose laziness is
|
|
197
|
+
// load-bearing for peer resolution. (#280)
|
|
198
|
+
const { default: setupRestServer } = await import('./setup-rest-server.js');
|
|
170
199
|
promises.push(setupRestServer(restServer.route, paths.access, restServer.metaRoute));
|
|
171
200
|
}
|
|
172
201
|
|
package/src/manage-record.ts
CHANGED
|
@@ -28,7 +28,73 @@ const defaultOptions: CreateRecordOptions = {
|
|
|
28
28
|
|
|
29
29
|
let pendingIdCounter = 0;
|
|
30
30
|
|
|
31
|
+
interface RecordWrite<Result> {
|
|
32
|
+
result: Result;
|
|
33
|
+
written: Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type AwaitedOperation = 'create' | 'update';
|
|
37
|
+
|
|
38
|
+
const writeNotRequested = Promise.resolve();
|
|
39
|
+
|
|
40
|
+
function ignoreReportedFailure(): void {}
|
|
41
|
+
|
|
42
|
+
function persistRequested(options: CreateRecordOptions, userOptions: CreateRecordOptions): boolean {
|
|
43
|
+
return !options.isDbRecord && !userOptions._relationshipKey && !options._skipAutoPersist;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function reportPersistFailure(operation: AwaitedOperation, modelName: string, recordId: unknown, failure: unknown): Error {
|
|
47
|
+
const error = failure instanceof Error ? failure : new Error(String(failure));
|
|
48
|
+
Orm.instance.emitPersistError({ operation, modelName, recordId, error });
|
|
49
|
+
return error;
|
|
50
|
+
}
|
|
51
|
+
|
|
31
52
|
export function createRecord(modelName: string, rawData: { [key: string]: unknown } = {}, userOptions: CreateRecordOptions = {}): OrmRecord {
|
|
53
|
+
const { result: record, written } = createRecordWrite(modelName, rawData, userOptions);
|
|
54
|
+
written.catch(ignoreReportedFailure);
|
|
55
|
+
return record;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function updateRecord(record: OrmRecord, rawData: unknown, userOptions: CreateRecordOptions = {}): void {
|
|
59
|
+
updateRecordWrite(record, rawData, userOptions).written.catch(ignoreReportedFailure);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function createRecordAndPersist(modelName: string, rawData: { [key: string]: unknown } = {}, userOptions: CreateRecordOptions = {}): Promise<OrmRecord> {
|
|
63
|
+
assertWriteCanBeAwaited();
|
|
64
|
+
const { result: record, written } = createRecordWrite(modelName, rawData, userOptions);
|
|
65
|
+
await written;
|
|
66
|
+
await saveJsonDatabase('create', modelName, record.id, { ...defaultOptions, ...userOptions }, userOptions);
|
|
67
|
+
return record;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function updateRecordAndPersist(record: OrmRecord, rawData: unknown, userOptions: CreateRecordOptions = {}): Promise<void> {
|
|
71
|
+
assertWriteCanBeAwaited();
|
|
72
|
+
await updateRecordWrite(record, rawData, userOptions).written;
|
|
73
|
+
await saveJsonDatabase('update', record?.__model?.__name ?? '', record.id, { ...defaultOptions, ...userOptions }, userOptions);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function assertWriteCanBeAwaited(): void {
|
|
77
|
+
const sqlDb = Orm.instance?.sqlDb as { persistResolvesAfterWrite?: boolean } | undefined;
|
|
78
|
+
if (sqlDb && sqlDb.persistResolvesAfterWrite !== true) {
|
|
79
|
+
throw new Error('The configured database adapter cannot confirm a write has landed, so createRecordAndPersist/updateRecordAndPersist are unavailable for it (DynamoDB: abofs/stonyx-orm#299)');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function saveJsonDatabase(operation: AwaitedOperation, modelName: string, recordId: unknown, options: CreateRecordOptions, userOptions: CreateRecordOptions): Promise<void> {
|
|
84
|
+
const orm = Orm.instance;
|
|
85
|
+
if (orm.sqlDb || !persistRequested(options, userOptions)) return;
|
|
86
|
+
|
|
87
|
+
const jsonDatabase = orm.db as { save?: () => Promise<void> } | undefined;
|
|
88
|
+
if (!jsonDatabase?.save) return;
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
await jsonDatabase.save();
|
|
92
|
+
} catch (failure) {
|
|
93
|
+
throw reportPersistFailure(operation, modelName, recordId, failure);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function createRecordWrite(modelName: string, rawData: { [key: string]: unknown }, userOptions: CreateRecordOptions): RecordWrite<OrmRecord> {
|
|
32
98
|
const orm = Orm.instance;
|
|
33
99
|
const { initialized } = Orm;
|
|
34
100
|
const options = { ...defaultOptions, ...userOptions };
|
|
@@ -50,9 +116,7 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
|
|
|
50
116
|
const existingRecord = modelStore.get(rawData.id as number | string);
|
|
51
117
|
|
|
52
118
|
if (existingRecord instanceof OrmRecord) {
|
|
53
|
-
|
|
54
|
-
updateRecord(existingRecord, rawData, { ...options, update: true });
|
|
55
|
-
return existingRecord;
|
|
119
|
+
return { result: existingRecord, written: updateRecordWrite(existingRecord, rawData, { ...options, update: true }).written };
|
|
56
120
|
}
|
|
57
121
|
|
|
58
122
|
const recordClasses = orm.getRecordClasses(modelName);
|
|
@@ -79,6 +143,28 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
|
|
|
79
143
|
pendingHasMany.splice(0);
|
|
80
144
|
}
|
|
81
145
|
|
|
146
|
+
// FK-based inverse hasMany wiring — when a child record is created with a
|
|
147
|
+
// foreign-key field (e.g. `owner: 'owner-1'` on an animal), find any parent
|
|
148
|
+
// whose hasMany registry targets this model and push the child into the
|
|
149
|
+
// parent's shared array. This covers edge cases where the child is created
|
|
150
|
+
// in a separate async frame without a belongsTo handler firing.
|
|
151
|
+
const hasManyReg = getHasManyRegistry();
|
|
152
|
+
if (hasManyReg) {
|
|
153
|
+
for (const [parentModelName, targetMap] of hasManyReg) {
|
|
154
|
+
const childArrayMap = targetMap.get(modelName);
|
|
155
|
+
if (!childArrayMap) continue;
|
|
156
|
+
|
|
157
|
+
// Check if rawData contains a FK field matching the parent model name
|
|
158
|
+
const fkValue = rawData[parentModelName];
|
|
159
|
+
if (fkValue === undefined || fkValue === null) continue;
|
|
160
|
+
|
|
161
|
+
const parentArray = childArrayMap.get(fkValue);
|
|
162
|
+
if (parentArray && !parentArray.includes(record)) {
|
|
163
|
+
parentArray.push(record);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
82
168
|
// Fulfill pending belongsTo relationships
|
|
83
169
|
const pendingBelongsToQueue = getPendingBelongsToRegistry();
|
|
84
170
|
const pendingBelongsToRaw = pendingBelongsToQueue.get(modelName)?.get(record.id);
|
|
@@ -86,7 +172,7 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
|
|
|
86
172
|
|
|
87
173
|
if (pendingBelongsTo) {
|
|
88
174
|
const belongsToReg = getBelongsToRegistry();
|
|
89
|
-
const
|
|
175
|
+
const pendingHasManyReg = getHasManyRegistry();
|
|
90
176
|
|
|
91
177
|
for (const { sourceRecord, sourceModelName, relationshipKey, relationshipId } of pendingBelongsTo) {
|
|
92
178
|
// Update the belongsTo relationship on the source record
|
|
@@ -103,7 +189,7 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
|
|
|
103
189
|
}
|
|
104
190
|
|
|
105
191
|
// Wire inverse hasMany if it exists
|
|
106
|
-
const inverseHasMany =
|
|
192
|
+
const inverseHasMany = pendingHasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
|
|
107
193
|
|
|
108
194
|
if (inverseHasMany && !inverseHasMany.includes(sourceRecord)) {
|
|
109
195
|
inverseHasMany.push(sourceRecord);
|
|
@@ -114,27 +200,26 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
|
|
|
114
200
|
pendingBelongsTo.length = 0;
|
|
115
201
|
}
|
|
116
202
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
203
|
+
if (!orm?.sqlDb || !persistRequested(options, userOptions)) return { result: record, written: writeNotRequested };
|
|
204
|
+
|
|
205
|
+
const registryIdBeforePersist = record.id;
|
|
206
|
+
const response = { data: { id: record.id } };
|
|
207
|
+
const written = orm.sqlDb.persist('create', modelName, { rawData }, response)
|
|
208
|
+
.catch((failure: unknown) => {
|
|
209
|
+
throw reportPersistFailure('create', modelName, record.id, failure);
|
|
210
|
+
})
|
|
211
|
+
.finally(() => {
|
|
212
|
+
if (store._memoryResolver && !store._memoryResolver(modelName)) {
|
|
213
|
+
store.evictRecord(modelName, record.id, registryIdBeforePersist);
|
|
214
|
+
}
|
|
128
215
|
});
|
|
129
|
-
}
|
|
130
216
|
|
|
131
|
-
return record;
|
|
217
|
+
return { result: record, written };
|
|
132
218
|
}
|
|
133
219
|
|
|
134
|
-
|
|
220
|
+
function updateRecordWrite(record: OrmRecord, rawData: unknown, userOptions: CreateRecordOptions): RecordWrite<void> {
|
|
135
221
|
if (!rawData) throw new Error('rawData must be passed in to updateRecord call');
|
|
136
222
|
|
|
137
|
-
// Guard: read-only views cannot be updated
|
|
138
223
|
const modelName = record?.__model?.__name;
|
|
139
224
|
if (modelName && Orm.instance?.isView?.(modelName)) {
|
|
140
225
|
throw new Error(`Cannot update records for read-only view '${modelName}'`);
|
|
@@ -142,24 +227,18 @@ export function updateRecord(record: OrmRecord, rawData: unknown, userOptions: C
|
|
|
142
227
|
|
|
143
228
|
const options = { ...defaultOptions, ...userOptions, update: true };
|
|
144
229
|
|
|
145
|
-
// Capture old state before update for SQL diff
|
|
146
230
|
const oldState = record.__data ? JSON.parse(JSON.stringify(record.__data)) : {};
|
|
147
231
|
|
|
148
232
|
record.serialize(rawData, options);
|
|
149
233
|
|
|
150
|
-
// Auto-persist to SQL — skip for DB loads (isDbRecord) and relationship resolution (_relationshipKey)
|
|
151
234
|
const orm = Orm.instance;
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
error: err instanceof Error ? err : new Error(String(err)),
|
|
160
|
-
});
|
|
161
|
-
});
|
|
162
|
-
}
|
|
235
|
+
if (!orm?.sqlDb || !modelName || !persistRequested(options, userOptions)) return { result: undefined, written: writeNotRequested };
|
|
236
|
+
|
|
237
|
+
const written = orm.sqlDb.persist('update', modelName, { record, oldState }, {}).catch((failure: unknown) => {
|
|
238
|
+
throw reportPersistFailure('update', modelName, record.id, failure);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
return { result: undefined, written };
|
|
163
242
|
}
|
|
164
243
|
|
|
165
244
|
/**
|
package/src/mysql/connection.ts
CHANGED