@stonyx/orm 0.2.1-alpha.2 → 0.2.1-alpha.21
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/.claude/code-style-rules.md +44 -0
- package/.claude/hooks.md +250 -0
- package/.claude/index.md +292 -0
- package/.claude/usage-patterns.md +300 -0
- package/.claude/views.md +292 -0
- package/.github/workflows/ci.yml +5 -25
- package/.github/workflows/publish.yml +24 -116
- package/README.md +461 -15
- package/config/environment.js +29 -6
- package/improvements.md +139 -0
- package/package.json +24 -8
- package/project-structure.md +343 -0
- package/scripts/setup-test-db.sh +21 -0
- package/src/aggregates.js +93 -0
- package/src/belongs-to.js +4 -1
- package/src/commands.js +170 -0
- package/src/db.js +132 -6
- package/src/has-many.js +4 -1
- package/src/hooks.js +124 -0
- package/src/index.js +12 -2
- package/src/main.js +77 -4
- package/src/manage-record.js +30 -4
- package/src/migrate.js +72 -0
- package/src/model-property.js +2 -2
- package/src/model.js +11 -0
- package/src/mysql/connection.js +28 -0
- package/src/mysql/migration-generator.js +286 -0
- package/src/mysql/migration-runner.js +110 -0
- package/src/mysql/mysql-db.js +473 -0
- package/src/mysql/query-builder.js +64 -0
- package/src/mysql/schema-introspector.js +325 -0
- package/src/mysql/type-map.js +37 -0
- package/src/orm-request.js +313 -53
- package/src/plural-registry.js +12 -0
- package/src/record.js +35 -8
- package/src/serializer.js +9 -2
- package/src/setup-rest-server.js +5 -2
- package/src/store.js +130 -1
- package/src/utils.js +1 -1
- package/src/view-resolver.js +183 -0
- package/src/view.js +21 -0
- package/test-events-setup.js +41 -0
- package/test-hooks-manual.js +54 -0
- package/test-hooks-with-logging.js +52 -0
- package/.claude/project-structure.md +0 -578
- package/stonyx-bootstrap.cjs +0 -30
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import Orm from '@stonyx/orm';
|
|
2
|
+
import { getMysqlType } from './type-map.js';
|
|
3
|
+
import { camelCaseToKebabCase } from '@stonyx/utils/string';
|
|
4
|
+
import { getPluralName } from '../plural-registry.js';
|
|
5
|
+
import { dbKey } from '../db.js';
|
|
6
|
+
import { AggregateProperty } from '../aggregates.js';
|
|
7
|
+
|
|
8
|
+
function getRelationshipInfo(property) {
|
|
9
|
+
if (typeof property !== 'function') return null;
|
|
10
|
+
const fnStr = property.toString();
|
|
11
|
+
const modelName = property.__relatedModelName || null;
|
|
12
|
+
|
|
13
|
+
if (fnStr.includes(`getRelationships('belongsTo',`)) return { type: 'belongsTo', modelName };
|
|
14
|
+
if (fnStr.includes(`getRelationships('hasMany',`)) return { type: 'hasMany', modelName };
|
|
15
|
+
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function sanitizeTableName(name) {
|
|
20
|
+
return name.replace(/[-/]/g, '_');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function introspectModels() {
|
|
24
|
+
const { models } = Orm.instance;
|
|
25
|
+
const schemas = {};
|
|
26
|
+
|
|
27
|
+
for (const [modelKey, modelClass] of Object.entries(models)) {
|
|
28
|
+
const name = camelCaseToKebabCase(modelKey.slice(0, -5));
|
|
29
|
+
|
|
30
|
+
if (name === dbKey) continue;
|
|
31
|
+
|
|
32
|
+
const model = new modelClass(modelKey);
|
|
33
|
+
const columns = {};
|
|
34
|
+
const foreignKeys = {};
|
|
35
|
+
const relationships = { belongsTo: {}, hasMany: {} };
|
|
36
|
+
let idType = 'number';
|
|
37
|
+
|
|
38
|
+
const transforms = Orm.instance.transforms;
|
|
39
|
+
|
|
40
|
+
for (const [key, property] of Object.entries(model)) {
|
|
41
|
+
if (key.startsWith('__')) continue;
|
|
42
|
+
|
|
43
|
+
const relInfo = getRelationshipInfo(property);
|
|
44
|
+
|
|
45
|
+
if (relInfo?.type === 'belongsTo') {
|
|
46
|
+
relationships.belongsTo[key] = relInfo.modelName;
|
|
47
|
+
} else if (relInfo?.type === 'hasMany') {
|
|
48
|
+
relationships.hasMany[key] = relInfo.modelName;
|
|
49
|
+
} else if (property?.constructor?.name === 'ModelProperty') {
|
|
50
|
+
if (key === 'id') {
|
|
51
|
+
idType = property.type;
|
|
52
|
+
} else {
|
|
53
|
+
columns[key] = getMysqlType(property.type, transforms[property.type]);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Build foreign keys from belongsTo relationships
|
|
59
|
+
for (const [relName, targetModelName] of Object.entries(relationships.belongsTo)) {
|
|
60
|
+
const fkColumn = `${relName}_id`;
|
|
61
|
+
foreignKeys[fkColumn] = {
|
|
62
|
+
references: sanitizeTableName(getPluralName(targetModelName)),
|
|
63
|
+
column: 'id',
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
schemas[name] = {
|
|
68
|
+
table: sanitizeTableName(getPluralName(name)),
|
|
69
|
+
idType,
|
|
70
|
+
columns,
|
|
71
|
+
foreignKeys,
|
|
72
|
+
relationships,
|
|
73
|
+
memory: modelClass.memory !== false, // default true for backward compat
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return schemas;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function buildTableDDL(name, schema, allSchemas = {}) {
|
|
81
|
+
const { idType, columns, foreignKeys } = schema;
|
|
82
|
+
const table = sanitizeTableName(schema.table);
|
|
83
|
+
const lines = [];
|
|
84
|
+
|
|
85
|
+
// Primary key
|
|
86
|
+
if (idType === 'string') {
|
|
87
|
+
lines.push(' `id` VARCHAR(255) PRIMARY KEY');
|
|
88
|
+
} else {
|
|
89
|
+
lines.push(' `id` INT AUTO_INCREMENT PRIMARY KEY');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Attribute columns
|
|
93
|
+
for (const [col, mysqlType] of Object.entries(columns)) {
|
|
94
|
+
lines.push(` \`${col}\` ${mysqlType}`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Foreign key columns
|
|
98
|
+
for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
|
|
99
|
+
const refIdType = getReferencedIdType(fkDef.references, allSchemas);
|
|
100
|
+
lines.push(` \`${fkCol}\` ${refIdType}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Timestamps
|
|
104
|
+
lines.push(' `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP');
|
|
105
|
+
lines.push(' `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
|
|
106
|
+
|
|
107
|
+
// Foreign key constraints
|
|
108
|
+
for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
|
|
109
|
+
const refTable = sanitizeTableName(fkDef.references);
|
|
110
|
+
lines.push(` FOREIGN KEY (\`${fkCol}\`) REFERENCES \`${refTable}\`(\`${fkDef.column}\`) ON DELETE SET NULL`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return `CREATE TABLE IF NOT EXISTS \`${table}\` (\n${lines.join(',\n')}\n)`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function getReferencedIdType(tableName, allSchemas) {
|
|
117
|
+
// Look up the referenced table's PK type from schemas
|
|
118
|
+
for (const schema of Object.values(allSchemas)) {
|
|
119
|
+
if (schema.table === tableName) {
|
|
120
|
+
return schema.idType === 'string' ? 'VARCHAR(255)' : 'INT';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Default to INT if referenced table not found in schemas
|
|
125
|
+
return 'INT';
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function getTopologicalOrder(schemas) {
|
|
129
|
+
const visited = new Set();
|
|
130
|
+
const order = [];
|
|
131
|
+
|
|
132
|
+
function visit(name) {
|
|
133
|
+
if (visited.has(name)) return;
|
|
134
|
+
visited.add(name);
|
|
135
|
+
|
|
136
|
+
const schema = schemas[name];
|
|
137
|
+
if (!schema) return;
|
|
138
|
+
|
|
139
|
+
// Visit dependencies (belongsTo targets) first
|
|
140
|
+
for (const targetModelName of Object.values(schema.relationships.belongsTo)) {
|
|
141
|
+
visit(targetModelName);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
order.push(name);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
for (const name of Object.keys(schemas)) {
|
|
148
|
+
visit(name);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return order;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function introspectViews() {
|
|
155
|
+
const orm = Orm.instance;
|
|
156
|
+
if (!orm.views) return {};
|
|
157
|
+
|
|
158
|
+
const schemas = {};
|
|
159
|
+
|
|
160
|
+
for (const [viewKey, viewClass] of Object.entries(orm.views)) {
|
|
161
|
+
const name = camelCaseToKebabCase(viewKey.slice(0, -4)); // Remove 'View' suffix
|
|
162
|
+
|
|
163
|
+
const source = viewClass.source;
|
|
164
|
+
if (!source) continue;
|
|
165
|
+
|
|
166
|
+
const model = new viewClass(name);
|
|
167
|
+
const columns = {};
|
|
168
|
+
const foreignKeys = {};
|
|
169
|
+
const aggregates = {};
|
|
170
|
+
const relationships = { belongsTo: {}, hasMany: {} };
|
|
171
|
+
|
|
172
|
+
for (const [key, property] of Object.entries(model)) {
|
|
173
|
+
if (key.startsWith('__')) continue;
|
|
174
|
+
if (key === 'id') continue;
|
|
175
|
+
|
|
176
|
+
if (property instanceof AggregateProperty) {
|
|
177
|
+
aggregates[key] = property;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const relInfo = getRelationshipInfo(property);
|
|
182
|
+
|
|
183
|
+
if (relInfo?.type === 'belongsTo') {
|
|
184
|
+
relationships.belongsTo[key] = relInfo.modelName;
|
|
185
|
+
const fkColumn = `${key}_id`;
|
|
186
|
+
foreignKeys[fkColumn] = {
|
|
187
|
+
references: sanitizeTableName(getPluralName(relInfo.modelName)),
|
|
188
|
+
column: 'id',
|
|
189
|
+
};
|
|
190
|
+
} else if (relInfo?.type === 'hasMany') {
|
|
191
|
+
relationships.hasMany[key] = relInfo.modelName;
|
|
192
|
+
} else if (property?.constructor?.name === 'ModelProperty') {
|
|
193
|
+
const transforms = Orm.instance.transforms;
|
|
194
|
+
columns[key] = getMysqlType(property.type, transforms[property.type]);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
schemas[name] = {
|
|
199
|
+
viewName: sanitizeTableName(getPluralName(name)),
|
|
200
|
+
source,
|
|
201
|
+
groupBy: viewClass.groupBy || undefined,
|
|
202
|
+
columns,
|
|
203
|
+
foreignKeys,
|
|
204
|
+
aggregates,
|
|
205
|
+
relationships,
|
|
206
|
+
isView: true,
|
|
207
|
+
memory: viewClass.memory !== false ? false : false, // Views default to memory:false
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return schemas;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function buildViewDDL(name, viewSchema, modelSchemas = {}) {
|
|
215
|
+
if (!viewSchema.source) {
|
|
216
|
+
throw new Error(`View '${name}' must define a source model`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const sourceModelName = viewSchema.source;
|
|
220
|
+
const sourceSchema = modelSchemas[sourceModelName];
|
|
221
|
+
const sourceTable = sanitizeTableName(sourceSchema
|
|
222
|
+
? sourceSchema.table
|
|
223
|
+
: getPluralName(sourceModelName));
|
|
224
|
+
|
|
225
|
+
const selectColumns = [];
|
|
226
|
+
const joins = [];
|
|
227
|
+
const hasAggregates = Object.keys(viewSchema.aggregates || {}).length > 0;
|
|
228
|
+
const groupByField = viewSchema.groupBy;
|
|
229
|
+
|
|
230
|
+
// ID column: groupBy field or source table PK
|
|
231
|
+
if (groupByField) {
|
|
232
|
+
selectColumns.push(`\`${sourceTable}\`.\`${groupByField}\` AS \`id\``);
|
|
233
|
+
} else {
|
|
234
|
+
selectColumns.push(`\`${sourceTable}\`.\`id\` AS \`id\``);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Aggregate columns
|
|
238
|
+
for (const [key, aggProp] of Object.entries(viewSchema.aggregates || {})) {
|
|
239
|
+
if (aggProp.relationship === undefined) {
|
|
240
|
+
// Field-level aggregate (groupBy views)
|
|
241
|
+
if (aggProp.aggregateType === 'count') {
|
|
242
|
+
selectColumns.push(`COUNT(*) AS \`${key}\``);
|
|
243
|
+
} else {
|
|
244
|
+
selectColumns.push(`${aggProp.mysqlFunction}(\`${sourceTable}\`.\`${aggProp.field}\`) AS \`${key}\``);
|
|
245
|
+
}
|
|
246
|
+
} else {
|
|
247
|
+
// Relationship aggregate
|
|
248
|
+
const relName = aggProp.relationship;
|
|
249
|
+
const relTable = sanitizeTableName(getPluralName(relName));
|
|
250
|
+
|
|
251
|
+
if (aggProp.aggregateType === 'count') {
|
|
252
|
+
selectColumns.push(`${aggProp.mysqlFunction}(\`${relTable}\`.\`id\`) AS \`${key}\``);
|
|
253
|
+
} else {
|
|
254
|
+
const field = aggProp.field;
|
|
255
|
+
selectColumns.push(`${aggProp.mysqlFunction}(\`${relTable}\`.\`${field}\`) AS \`${key}\``);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Add LEFT JOIN for the relationship if not already added
|
|
259
|
+
const joinKey = `${relTable}`;
|
|
260
|
+
if (!joins.find(j => j.table === joinKey)) {
|
|
261
|
+
const fkColumn = `${sourceModelName}_id`;
|
|
262
|
+
joins.push({
|
|
263
|
+
table: relTable,
|
|
264
|
+
condition: `\`${relTable}\`.\`${fkColumn}\` = \`${sourceTable}\`.\`id\``
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Regular columns (from resolve map string paths or direct attr fields)
|
|
271
|
+
for (const [key, mysqlType] of Object.entries(viewSchema.columns || {})) {
|
|
272
|
+
selectColumns.push(`\`${sourceTable}\`.\`${key}\` AS \`${key}\``);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Build JOIN clauses
|
|
276
|
+
const joinClauses = joins.map(j =>
|
|
277
|
+
`LEFT JOIN \`${j.table}\` ON ${j.condition}`
|
|
278
|
+
).join('\n ');
|
|
279
|
+
|
|
280
|
+
// Build GROUP BY
|
|
281
|
+
let groupBy = '';
|
|
282
|
+
if (groupByField) {
|
|
283
|
+
groupBy = `\nGROUP BY \`${sourceTable}\`.\`${groupByField}\``;
|
|
284
|
+
} else if (hasAggregates) {
|
|
285
|
+
groupBy = `\nGROUP BY \`${sourceTable}\`.\`id\``;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const viewName = sanitizeTableName(viewSchema.viewName);
|
|
289
|
+
const sql = `CREATE OR REPLACE VIEW \`${viewName}\` AS\nSELECT\n ${selectColumns.join(',\n ')}\nFROM \`${sourceTable}\`${joinClauses ? '\n ' + joinClauses : ''}${groupBy}`;
|
|
290
|
+
|
|
291
|
+
return sql;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function viewSchemasToSnapshot(viewSchemas) {
|
|
295
|
+
const snapshot = {};
|
|
296
|
+
|
|
297
|
+
for (const [name, schema] of Object.entries(viewSchemas)) {
|
|
298
|
+
snapshot[name] = {
|
|
299
|
+
viewName: schema.viewName,
|
|
300
|
+
source: schema.source,
|
|
301
|
+
...(schema.groupBy ? { groupBy: schema.groupBy } : {}),
|
|
302
|
+
columns: { ...schema.columns },
|
|
303
|
+
foreignKeys: { ...schema.foreignKeys },
|
|
304
|
+
isView: true,
|
|
305
|
+
viewQuery: buildViewDDL(name, schema),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
return snapshot;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export function schemasToSnapshot(schemas) {
|
|
313
|
+
const snapshot = {};
|
|
314
|
+
|
|
315
|
+
for (const [name, schema] of Object.entries(schemas)) {
|
|
316
|
+
snapshot[name] = {
|
|
317
|
+
table: schema.table,
|
|
318
|
+
idType: schema.idType,
|
|
319
|
+
columns: { ...schema.columns },
|
|
320
|
+
foreignKeys: { ...schema.foreignKeys },
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return snapshot;
|
|
325
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const typeMap = {
|
|
2
|
+
string: 'VARCHAR(255)',
|
|
3
|
+
number: 'INT',
|
|
4
|
+
float: 'FLOAT',
|
|
5
|
+
boolean: 'TINYINT(1)',
|
|
6
|
+
date: 'DATETIME',
|
|
7
|
+
timestamp: 'BIGINT',
|
|
8
|
+
passthrough: 'TEXT',
|
|
9
|
+
trim: 'VARCHAR(255)',
|
|
10
|
+
uppercase: 'VARCHAR(255)',
|
|
11
|
+
ceil: 'INT',
|
|
12
|
+
floor: 'INT',
|
|
13
|
+
round: 'INT',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Resolves a Stonyx ORM attribute type to a MySQL column type.
|
|
18
|
+
*
|
|
19
|
+
* For built-in types, returns the mapped MySQL type directly.
|
|
20
|
+
*
|
|
21
|
+
* For custom transforms (e.g. an `animal` transform that maps strings to ints):
|
|
22
|
+
* - If the transform function exports a `mysqlType` property, that value is used.
|
|
23
|
+
* Example: `const transform = (v) => codeMap[v]; transform.mysqlType = 'INT'; export default transform;`
|
|
24
|
+
* - Otherwise, defaults to JSON. Values are JSON-stringified on write and
|
|
25
|
+
* JSON-parsed on read. This handles primitives and plain objects correctly.
|
|
26
|
+
* Class instances will be reduced to plain objects — if a custom transform
|
|
27
|
+
* produces class instances, it must declare a `mysqlType` and handle
|
|
28
|
+
* serialization itself.
|
|
29
|
+
*/
|
|
30
|
+
export function getMysqlType(attrType, transformFn) {
|
|
31
|
+
if (typeMap[attrType]) return typeMap[attrType];
|
|
32
|
+
if (transformFn?.mysqlType) return transformFn.mysqlType;
|
|
33
|
+
|
|
34
|
+
return 'JSON';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export default typeMap;
|