@stonyx/orm 0.2.1-beta.9 → 0.2.1-beta.91
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 +64 -6
- package/config/environment.js +37 -1
- package/dist/aggregates.d.ts +21 -0
- package/dist/aggregates.js +93 -0
- package/dist/attr.d.ts +2 -0
- package/dist/attr.js +22 -0
- package/dist/belongs-to.d.ts +11 -0
- package/dist/belongs-to.js +59 -0
- package/dist/cli.d.ts +22 -0
- package/dist/cli.js +148 -0
- package/dist/commands.d.ts +7 -0
- package/dist/commands.js +146 -0
- package/dist/db.d.ts +21 -0
- package/dist/db.js +180 -0
- package/dist/exports/db.d.ts +7 -0
- package/{src → dist}/exports/db.js +2 -4
- package/dist/has-many.d.ts +11 -0
- package/dist/has-many.js +58 -0
- package/dist/hooks.d.ts +75 -0
- package/dist/hooks.js +110 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +34 -0
- package/dist/main.d.ts +46 -0
- package/dist/main.js +181 -0
- package/dist/manage-record.d.ts +13 -0
- package/dist/manage-record.js +123 -0
- package/dist/meta-request.d.ts +6 -0
- package/dist/meta-request.js +52 -0
- package/dist/migrate.d.ts +2 -0
- package/dist/migrate.js +57 -0
- package/dist/model-property.d.ts +9 -0
- package/dist/model-property.js +29 -0
- package/dist/model.d.ts +15 -0
- package/dist/model.js +18 -0
- package/dist/mysql/connection.d.ts +14 -0
- package/dist/mysql/connection.js +24 -0
- package/dist/mysql/migration-generator.d.ts +45 -0
- package/dist/mysql/migration-generator.js +254 -0
- package/dist/mysql/migration-runner.d.ts +12 -0
- package/dist/mysql/migration-runner.js +88 -0
- package/dist/mysql/mysql-db.d.ts +100 -0
- package/dist/mysql/mysql-db.js +425 -0
- package/dist/mysql/query-builder.d.ts +10 -0
- package/dist/mysql/query-builder.js +44 -0
- package/dist/mysql/schema-introspector.d.ts +19 -0
- package/dist/mysql/schema-introspector.js +257 -0
- package/dist/mysql/type-map.d.ts +21 -0
- package/dist/mysql/type-map.js +36 -0
- package/dist/orm-request.d.ts +38 -0
- package/dist/orm-request.js +475 -0
- package/dist/plural-registry.d.ts +4 -0
- package/dist/plural-registry.js +9 -0
- package/dist/postgres/connection.d.ts +15 -0
- package/dist/postgres/connection.js +32 -0
- package/dist/postgres/migration-generator.d.ts +45 -0
- package/dist/postgres/migration-generator.js +261 -0
- package/dist/postgres/migration-runner.d.ts +10 -0
- package/dist/postgres/migration-runner.js +87 -0
- package/dist/postgres/postgres-db.d.ts +119 -0
- package/dist/postgres/postgres-db.js +477 -0
- package/dist/postgres/query-builder.d.ts +27 -0
- package/dist/postgres/query-builder.js +98 -0
- package/dist/postgres/schema-introspector.d.ts +28 -0
- package/dist/postgres/schema-introspector.js +280 -0
- package/dist/postgres/type-map.d.ts +23 -0
- package/dist/postgres/type-map.js +56 -0
- package/dist/record.d.ts +75 -0
- package/dist/record.js +129 -0
- package/dist/relationships.d.ts +10 -0
- package/dist/relationships.js +41 -0
- package/dist/schema-helpers.d.ts +20 -0
- package/dist/schema-helpers.js +48 -0
- package/dist/serializer.d.ts +17 -0
- package/dist/serializer.js +136 -0
- package/dist/setup-rest-server.d.ts +1 -0
- package/dist/setup-rest-server.js +52 -0
- package/dist/standalone-db.d.ts +58 -0
- package/dist/standalone-db.js +142 -0
- package/dist/store.d.ts +62 -0
- package/dist/store.js +286 -0
- package/dist/timescale/query-builder.d.ts +43 -0
- package/dist/timescale/query-builder.js +115 -0
- package/dist/timescale/timescale-db.d.ts +45 -0
- package/dist/timescale/timescale-db.js +84 -0
- package/dist/transforms.d.ts +2 -0
- package/dist/transforms.js +17 -0
- package/dist/types/orm-types.d.ts +142 -0
- package/dist/types/orm-types.js +1 -0
- package/dist/utils.d.ts +7 -0
- package/dist/utils.js +17 -0
- package/dist/view-resolver.d.ts +8 -0
- package/dist/view-resolver.js +171 -0
- package/dist/view.d.ts +11 -0
- package/dist/view.js +18 -0
- package/package.json +57 -15
- package/src/aggregates.ts +109 -0
- package/src/{attr.js → attr.ts} +2 -2
- package/src/belongs-to.ts +90 -0
- package/src/cli.ts +183 -0
- package/src/{commands.js → commands.ts} +179 -170
- package/src/{db.js → db.ts} +55 -29
- package/src/exports/db.ts +7 -0
- package/src/has-many.ts +92 -0
- package/src/hooks.ts +151 -0
- package/src/{index.js → index.ts} +11 -2
- package/src/main.ts +229 -0
- package/src/manage-record.ts +161 -0
- package/src/{meta-request.js → meta-request.ts} +17 -14
- package/src/{migrate.js → migrate.ts} +9 -9
- package/src/model-property.ts +35 -0
- package/src/model.ts +21 -0
- package/src/mysql/{connection.js → connection.ts} +43 -28
- package/src/mysql/migration-generator.ts +337 -0
- package/src/mysql/{migration-runner.js → migration-runner.ts} +121 -110
- package/src/mysql/mysql-db.ts +543 -0
- package/src/mysql/{query-builder.js → query-builder.ts} +69 -64
- package/src/mysql/schema-introspector.ts +310 -0
- package/src/mysql/{type-map.js → type-map.ts} +42 -37
- package/src/{orm-request.js → orm-request.ts} +187 -108
- package/src/plural-registry.ts +12 -0
- package/src/postgres/connection.ts +48 -0
- package/src/postgres/migration-generator.ts +348 -0
- package/src/postgres/migration-runner.ts +115 -0
- package/src/postgres/postgres-db.ts +616 -0
- package/src/postgres/query-builder.ts +148 -0
- package/src/postgres/schema-introspector.ts +343 -0
- package/src/postgres/type-map.ts +61 -0
- package/src/record.ts +186 -0
- package/src/relationships.ts +54 -0
- package/src/schema-helpers.ts +59 -0
- package/src/serializer.ts +161 -0
- package/src/{setup-rest-server.js → setup-rest-server.ts} +18 -16
- package/src/standalone-db.ts +185 -0
- package/src/store.ts +373 -0
- package/src/timescale/query-builder.ts +174 -0
- package/src/timescale/timescale-db.ts +119 -0
- package/src/transforms.ts +20 -0
- package/src/types/mysql2.d.ts +49 -0
- package/src/types/orm-types.ts +146 -0
- package/src/types/pg.d.ts +32 -0
- package/src/types/stonyx-cron.d.ts +5 -0
- package/src/types/stonyx-events.d.ts +4 -0
- package/src/types/stonyx-rest-server.d.ts +16 -0
- package/src/types/stonyx-utils.d.ts +33 -0
- package/src/types/stonyx.d.ts +21 -0
- package/src/utils.ts +22 -0
- package/src/view-resolver.ts +211 -0
- package/src/view.ts +22 -0
- package/.claude/code-style-rules.md +0 -44
- package/.claude/hooks.md +0 -250
- package/.claude/index.md +0 -279
- package/.claude/usage-patterns.md +0 -217
- package/.github/workflows/ci.yml +0 -16
- package/.github/workflows/publish.yml +0 -51
- package/improvements.md +0 -139
- package/project-structure.md +0 -343
- package/src/belongs-to.js +0 -63
- package/src/has-many.js +0 -61
- package/src/hooks.js +0 -124
- package/src/main.js +0 -148
- package/src/manage-record.js +0 -118
- package/src/model-property.js +0 -29
- package/src/model.js +0 -9
- package/src/mysql/migration-generator.js +0 -188
- package/src/mysql/mysql-db.js +0 -320
- package/src/mysql/schema-introspector.js +0 -158
- package/src/record.js +0 -127
- package/src/relationships.js +0 -43
- package/src/serializer.js +0 -138
- package/src/store.js +0 -211
- package/src/transforms.js +0 -20
- package/src/utils.js +0 -12
- package/test-events-setup.js +0 -41
- package/test-hooks-manual.js +0 -54
- package/test-hooks-with-logging.js +0 -52
package/src/hooks.js
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Copyright 2025 Stone Costa
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the 'License');
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Middleware-based hooks registry for ORM operations.
|
|
19
|
-
* Unlike event-based hooks, middleware hooks run sequentially and can halt operations.
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
// Map of "operation:model" -> handler[]
|
|
23
|
-
const beforeHooks = new Map();
|
|
24
|
-
const afterHooks = new Map();
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Register a before hook middleware that runs before the operation executes.
|
|
28
|
-
*
|
|
29
|
-
* @param {string} operation - Operation name: 'create', 'update', 'delete', 'get', or 'list'
|
|
30
|
-
* @param {string} model - Model name (e.g., 'user', 'animal')
|
|
31
|
-
* @param {Function} handler - Middleware function (context) => any
|
|
32
|
-
* - Return undefined to continue to next hook/handler
|
|
33
|
-
* - Return any value to halt operation (integer = HTTP status, object = response body)
|
|
34
|
-
* @returns {Function} Unsubscribe function
|
|
35
|
-
*/
|
|
36
|
-
export function beforeHook(operation, model, handler) {
|
|
37
|
-
const key = `${operation}:${model}`;
|
|
38
|
-
if (!beforeHooks.has(key)) {
|
|
39
|
-
beforeHooks.set(key, []);
|
|
40
|
-
}
|
|
41
|
-
beforeHooks.get(key).push(handler);
|
|
42
|
-
|
|
43
|
-
// Return unsubscribe function
|
|
44
|
-
return () => {
|
|
45
|
-
const hooks = beforeHooks.get(key);
|
|
46
|
-
if (hooks) {
|
|
47
|
-
const index = hooks.indexOf(handler);
|
|
48
|
-
if (index > -1) hooks.splice(index, 1);
|
|
49
|
-
}
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Register an after hook middleware that runs after the operation completes.
|
|
55
|
-
* After hooks cannot halt operations (they run after completion).
|
|
56
|
-
*
|
|
57
|
-
* @param {string} operation - Operation name
|
|
58
|
-
* @param {string} model - Model name
|
|
59
|
-
* @param {Function} handler - Middleware function (context) => void
|
|
60
|
-
* @returns {Function} Unsubscribe function
|
|
61
|
-
*/
|
|
62
|
-
export function afterHook(operation, model, handler) {
|
|
63
|
-
const key = `${operation}:${model}`;
|
|
64
|
-
if (!afterHooks.has(key)) {
|
|
65
|
-
afterHooks.set(key, []);
|
|
66
|
-
}
|
|
67
|
-
afterHooks.get(key).push(handler);
|
|
68
|
-
|
|
69
|
-
// Return unsubscribe function
|
|
70
|
-
return () => {
|
|
71
|
-
const hooks = afterHooks.get(key);
|
|
72
|
-
if (hooks) {
|
|
73
|
-
const index = hooks.indexOf(handler);
|
|
74
|
-
if (index > -1) hooks.splice(index, 1);
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Get all before hooks for an operation:model combination.
|
|
81
|
-
* @param {string} operation
|
|
82
|
-
* @param {string} model
|
|
83
|
-
* @returns {Function[]}
|
|
84
|
-
*/
|
|
85
|
-
export function getBeforeHooks(operation, model) {
|
|
86
|
-
const key = `${operation}:${model}`;
|
|
87
|
-
return beforeHooks.get(key) || [];
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Get all after hooks for an operation:model combination.
|
|
92
|
-
* @param {string} operation
|
|
93
|
-
* @param {string} model
|
|
94
|
-
* @returns {Function[]}
|
|
95
|
-
*/
|
|
96
|
-
export function getAfterHooks(operation, model) {
|
|
97
|
-
const key = `${operation}:${model}`;
|
|
98
|
-
return afterHooks.get(key) || [];
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Clear registered hooks for a specific operation:model.
|
|
103
|
-
*
|
|
104
|
-
* @param {string} operation - Operation name
|
|
105
|
-
* @param {string} model - Model name
|
|
106
|
-
* @param {string} [type] - 'before' or 'after' (if omitted, clears both)
|
|
107
|
-
*/
|
|
108
|
-
export function clearHook(operation, model, type) {
|
|
109
|
-
const key = `${operation}:${model}`;
|
|
110
|
-
if (!type || type === 'before') {
|
|
111
|
-
beforeHooks.set(key, []);
|
|
112
|
-
}
|
|
113
|
-
if (!type || type === 'after') {
|
|
114
|
-
afterHooks.set(key, []);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Clear all hooks (useful for testing).
|
|
120
|
-
*/
|
|
121
|
-
export function clearAllHooks() {
|
|
122
|
-
beforeHooks.clear();
|
|
123
|
-
afterHooks.clear();
|
|
124
|
-
}
|
package/src/main.js
DELETED
|
@@ -1,148 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Copyright 2025 Stone Costa
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
import DB from './db.js';
|
|
18
|
-
import config from 'stonyx/config';
|
|
19
|
-
import log from 'stonyx/log';
|
|
20
|
-
import { forEachFileImport } from '@stonyx/utils/file';
|
|
21
|
-
import { kebabCaseToPascalCase, pluralize } from '@stonyx/utils/string';
|
|
22
|
-
import setupRestServer from './setup-rest-server.js';
|
|
23
|
-
import baseTransforms from './transforms.js';
|
|
24
|
-
import Store from './store.js';
|
|
25
|
-
import Serializer from './serializer.js';
|
|
26
|
-
import { setup } from '@stonyx/events';
|
|
27
|
-
|
|
28
|
-
const defaultOptions = {
|
|
29
|
-
dbType: 'json'
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export default class Orm {
|
|
33
|
-
static initialized = false;
|
|
34
|
-
static relationships = new Map();
|
|
35
|
-
static store = new Store();
|
|
36
|
-
|
|
37
|
-
models = {};
|
|
38
|
-
serializers = {};
|
|
39
|
-
transforms = { ...baseTransforms };
|
|
40
|
-
warnings = new Set();
|
|
41
|
-
|
|
42
|
-
constructor(options={}) {
|
|
43
|
-
if (Orm.instance) return Orm.instance;
|
|
44
|
-
|
|
45
|
-
const { relationships } = Orm;
|
|
46
|
-
|
|
47
|
-
// Declare relationship maps
|
|
48
|
-
for (const key of ['hasMany', 'belongsTo', 'global', 'pending', 'pendingBelongsTo']) {
|
|
49
|
-
relationships.set(key, new Map());
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
this.options = { ...defaultOptions, ...options };
|
|
53
|
-
|
|
54
|
-
Orm.instance = this;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async init() {
|
|
58
|
-
const { paths, restServer } = config.orm;
|
|
59
|
-
const promises = ['Model', 'Serializer', 'Transform'].map(type => {
|
|
60
|
-
const lowerCaseType = type.toLowerCase();
|
|
61
|
-
const path = paths[lowerCaseType];
|
|
62
|
-
|
|
63
|
-
if (!path) throw new Error(`Configuration Error: ORM path for "${type}" must be defined.`);
|
|
64
|
-
|
|
65
|
-
return forEachFileImport(path, (exported, { name }) => {
|
|
66
|
-
// Transforms keep their original name, everything else gets converted to PascalCase with the type suffix
|
|
67
|
-
const alias = type === 'Transform' ? name : `${kebabCaseToPascalCase(name)}${type}`;
|
|
68
|
-
|
|
69
|
-
if (type === 'Model') Orm.store.set(name, new Map());
|
|
70
|
-
|
|
71
|
-
return this[pluralize(lowerCaseType)][alias] = exported;
|
|
72
|
-
}, { ignoreAccessFailure: true, rawName: true, recursive: true, recursiveNaming: true });
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
// Wait for imports before db & rest server setup
|
|
76
|
-
await Promise.all(promises);
|
|
77
|
-
|
|
78
|
-
// Setup event names for hooks after models are loaded
|
|
79
|
-
const eventNames = [];
|
|
80
|
-
const operations = ['list', 'get', 'create', 'update', 'delete'];
|
|
81
|
-
const timings = ['before', 'after'];
|
|
82
|
-
|
|
83
|
-
for (const modelName of Orm.store.data.keys()) {
|
|
84
|
-
for (const timing of timings) {
|
|
85
|
-
for (const operation of operations) {
|
|
86
|
-
eventNames.push(`${timing}:${operation}:${modelName}`);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
setup(eventNames);
|
|
92
|
-
|
|
93
|
-
if (config.orm.mysql) {
|
|
94
|
-
const { default: MysqlDB } = await import('./mysql/mysql-db.js');
|
|
95
|
-
this.mysqlDb = new MysqlDB();
|
|
96
|
-
this.db = this.mysqlDb;
|
|
97
|
-
promises.push(this.mysqlDb.init());
|
|
98
|
-
} else if (this.options.dbType !== 'none') {
|
|
99
|
-
const db = new DB();
|
|
100
|
-
this.db = db;
|
|
101
|
-
|
|
102
|
-
promises.push(db.init());
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
if (restServer.enabled === 'true') {
|
|
106
|
-
promises.push(setupRestServer(restServer.route, paths.access, restServer.metaRoute));
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
Orm.ready = await Promise.all(promises);
|
|
110
|
-
Orm.initialized = true;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
async startup() {
|
|
114
|
-
if (this.mysqlDb) await this.mysqlDb.startup();
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
async shutdown() {
|
|
118
|
-
if (this.mysqlDb) await this.mysqlDb.shutdown();
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
static get db() {
|
|
122
|
-
if (!Orm.initialized) throw new Error('ORM has not been initialized yet');
|
|
123
|
-
|
|
124
|
-
return Orm.instance.db;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
getRecordClasses(modelName) {
|
|
128
|
-
const modelClassPrefix = kebabCaseToPascalCase(modelName);
|
|
129
|
-
|
|
130
|
-
return {
|
|
131
|
-
modelClass: this.models[`${modelClassPrefix}Model`],
|
|
132
|
-
serializerClass: this.serializers[`${modelClassPrefix}Serializer`] || Serializer
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// Queue warnings to avoid the same error from being logged in the same iteration
|
|
137
|
-
warn(message) {
|
|
138
|
-
this.warnings.add(message);
|
|
139
|
-
|
|
140
|
-
setTimeout(() => {
|
|
141
|
-
this.warnings.forEach(warning => log.warn(warning));
|
|
142
|
-
this.warnings.clear();
|
|
143
|
-
}, 0);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export const store = Orm.store;
|
|
148
|
-
export const relationships = Orm.relationships;
|
package/src/manage-record.js
DELETED
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
import Orm, { store, relationships } from '@stonyx/orm';
|
|
2
|
-
import Record from './record.js';
|
|
3
|
-
|
|
4
|
-
const defaultOptions = {
|
|
5
|
-
isDbRecord: false,
|
|
6
|
-
serialize: true,
|
|
7
|
-
transform: true
|
|
8
|
-
};
|
|
9
|
-
|
|
10
|
-
export function createRecord(modelName, rawData={}, userOptions={}) {
|
|
11
|
-
const orm = Orm.instance;
|
|
12
|
-
const { initialized } = Orm;
|
|
13
|
-
const options = { ...defaultOptions, ...userOptions };
|
|
14
|
-
|
|
15
|
-
if (!initialized && !options.isDbRecord) throw new Error('ORM is not ready');
|
|
16
|
-
|
|
17
|
-
const modelStore = store.get(modelName);
|
|
18
|
-
const globalRelationships = relationships.get('global');
|
|
19
|
-
const pendingRelationships = relationships.get('pending');
|
|
20
|
-
|
|
21
|
-
assignRecordId(modelName, rawData);
|
|
22
|
-
if (modelStore.has(rawData.id)) return modelStore.get(rawData.id);
|
|
23
|
-
|
|
24
|
-
const { modelClass, serializerClass } = orm.getRecordClasses(modelName);
|
|
25
|
-
|
|
26
|
-
if (!modelClass) throw new Error(`A model named '${modelName}' does not exist`);
|
|
27
|
-
|
|
28
|
-
const model = new modelClass(modelName);
|
|
29
|
-
const serializer = new serializerClass(model);
|
|
30
|
-
const record = new Record(model, serializer);
|
|
31
|
-
|
|
32
|
-
record.serialize(rawData, options);
|
|
33
|
-
modelStore.set(record.id, record);
|
|
34
|
-
|
|
35
|
-
// populate global hasMany relationships
|
|
36
|
-
const globalHasMany = globalRelationships.get(modelName);
|
|
37
|
-
if (globalHasMany) for (const relationship of globalHasMany) relationship.push(record);
|
|
38
|
-
|
|
39
|
-
// populate pending hasMany relationships and clear the queue
|
|
40
|
-
const pendingHasMany = pendingRelationships.get(modelName)?.get(record.id);
|
|
41
|
-
if (pendingHasMany) {
|
|
42
|
-
for (const relationship of pendingHasMany) relationship.push(record);
|
|
43
|
-
pendingHasMany.splice(0);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Fulfill pending belongsTo relationships
|
|
47
|
-
const pendingBelongsToQueue = relationships.get('pendingBelongsTo');
|
|
48
|
-
const pendingBelongsTo = pendingBelongsToQueue.get(modelName)?.get(record.id);
|
|
49
|
-
|
|
50
|
-
if (pendingBelongsTo) {
|
|
51
|
-
const belongsToReg = relationships.get('belongsTo');
|
|
52
|
-
const hasManyReg = relationships.get('hasMany');
|
|
53
|
-
|
|
54
|
-
for (const { sourceRecord, sourceModelName, relationshipKey, relationshipId } of pendingBelongsTo) {
|
|
55
|
-
// Update the belongsTo relationship on the source record
|
|
56
|
-
sourceRecord.__relationships[relationshipKey] = record;
|
|
57
|
-
sourceRecord[relationshipKey] = record; // Also update the direct property
|
|
58
|
-
|
|
59
|
-
// Update the belongsTo relationship registry
|
|
60
|
-
const sourceModelReg = belongsToReg.get(sourceModelName);
|
|
61
|
-
if (sourceModelReg) {
|
|
62
|
-
const targetModelReg = sourceModelReg.get(modelName);
|
|
63
|
-
if (targetModelReg) {
|
|
64
|
-
targetModelReg.set(relationshipId, record);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// Wire inverse hasMany if it exists
|
|
69
|
-
const inverseHasMany = hasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
|
|
70
|
-
|
|
71
|
-
if (inverseHasMany && !inverseHasMany.includes(sourceRecord)) {
|
|
72
|
-
inverseHasMany.push(sourceRecord);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// Clear the pending queue
|
|
77
|
-
pendingBelongsTo.length = 0;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
return record;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function updateRecord(record, rawData, userOptions={}) {
|
|
84
|
-
if (!rawData) throw new Error('rawData must be passed in to updateRecord call');
|
|
85
|
-
|
|
86
|
-
const options = { ...defaultOptions, ...userOptions, update:true };
|
|
87
|
-
|
|
88
|
-
record.serialize(rawData, options);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* gets the next available id based on last record entry.
|
|
93
|
-
*
|
|
94
|
-
* In MySQL mode with numeric IDs, assigns a temporary pending ID.
|
|
95
|
-
* MySQL's AUTO_INCREMENT provides the real ID after INSERT.
|
|
96
|
-
*/
|
|
97
|
-
function assignRecordId(modelName, rawData) {
|
|
98
|
-
if (rawData.id) return;
|
|
99
|
-
|
|
100
|
-
// In MySQL mode with numeric IDs, defer to MySQL auto-increment
|
|
101
|
-
if (Orm.instance?.mysqlDb && !isStringIdModel(modelName)) {
|
|
102
|
-
rawData.id = `__pending_${Date.now()}_${Math.random()}`;
|
|
103
|
-
rawData.__pendingMysqlId = true;
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const modelStore = Array.from(store.get(modelName).values());
|
|
108
|
-
rawData.id = modelStore.length ? modelStore.at(-1).id + 1 : 1;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function isStringIdModel(modelName) {
|
|
112
|
-
const { modelClass } = Orm.instance.getRecordClasses(modelName);
|
|
113
|
-
if (!modelClass) return false;
|
|
114
|
-
|
|
115
|
-
const model = new modelClass(modelName);
|
|
116
|
-
|
|
117
|
-
return model.id?.type === 'string';
|
|
118
|
-
}
|
package/src/model-property.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import Orm from '@stonyx/orm';
|
|
2
|
-
|
|
3
|
-
function validType(type) {
|
|
4
|
-
return Object.keys(Orm.instance.transforms).includes(type);
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export default class ModelProperty {
|
|
8
|
-
constructor(type='passthrough', defaultValue) {
|
|
9
|
-
if (!validType(type)) throw new Error(`Invalid model property type: ${type}`);
|
|
10
|
-
|
|
11
|
-
this.type = type;
|
|
12
|
-
this.value = defaultValue;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
get value() {
|
|
16
|
-
return this._value;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
set value(newValue) {
|
|
20
|
-
if (this.ignoreFirstTransform) {
|
|
21
|
-
delete this.ignoreFirstTransform;
|
|
22
|
-
return this._value = newValue;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
if (newValue === undefined || newValue === null) return;
|
|
26
|
-
|
|
27
|
-
this._value = Orm.instance.transforms[this.type](newValue);
|
|
28
|
-
}
|
|
29
|
-
}
|
package/src/model.js
DELETED
|
@@ -1,188 +0,0 @@
|
|
|
1
|
-
import { introspectModels, buildTableDDL, schemasToSnapshot, getTopologicalOrder } from './schema-introspector.js';
|
|
2
|
-
import { readFile, createFile, createDirectory, fileExists } from '@stonyx/utils/file';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import config from 'stonyx/config';
|
|
5
|
-
import log from 'stonyx/log';
|
|
6
|
-
|
|
7
|
-
export async function generateMigration(description = 'migration') {
|
|
8
|
-
const { migrationsDir } = config.orm.mysql;
|
|
9
|
-
const rootPath = config.rootPath;
|
|
10
|
-
const migrationsPath = path.resolve(rootPath, migrationsDir);
|
|
11
|
-
|
|
12
|
-
await createDirectory(migrationsPath);
|
|
13
|
-
|
|
14
|
-
const schemas = introspectModels();
|
|
15
|
-
const currentSnapshot = schemasToSnapshot(schemas);
|
|
16
|
-
const previousSnapshot = await loadLatestSnapshot(migrationsPath);
|
|
17
|
-
const diff = diffSnapshots(previousSnapshot, currentSnapshot);
|
|
18
|
-
|
|
19
|
-
if (!diff.hasChanges) {
|
|
20
|
-
log.db('No schema changes detected.');
|
|
21
|
-
return null;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const upStatements = [];
|
|
25
|
-
const downStatements = [];
|
|
26
|
-
|
|
27
|
-
// New tables — in topological order (parents before children)
|
|
28
|
-
const allOrder = getTopologicalOrder(schemas);
|
|
29
|
-
const addedOrdered = allOrder.filter(name => diff.addedModels.includes(name));
|
|
30
|
-
|
|
31
|
-
for (const name of addedOrdered) {
|
|
32
|
-
upStatements.push(buildTableDDL(name, schemas[name], schemas) + ';');
|
|
33
|
-
downStatements.unshift(`DROP TABLE IF EXISTS \`${schemas[name].table}\`;`);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// Removed tables (warn only, commented out)
|
|
37
|
-
for (const name of diff.removedModels) {
|
|
38
|
-
upStatements.push(`-- WARNING: Model '${name}' was removed. Uncomment to drop table:`);
|
|
39
|
-
upStatements.push(`-- DROP TABLE IF EXISTS \`${previousSnapshot[name].table}\`;`);
|
|
40
|
-
downStatements.push(`-- Recreate table for removed model '${name}' manually if needed`);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// Added columns
|
|
44
|
-
for (const { model, column, type } of diff.addedColumns) {
|
|
45
|
-
const table = currentSnapshot[model].table;
|
|
46
|
-
upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
|
|
47
|
-
downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Removed columns
|
|
51
|
-
for (const { model, column, type } of diff.removedColumns) {
|
|
52
|
-
const table = previousSnapshot[model].table;
|
|
53
|
-
upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
54
|
-
downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Changed column types
|
|
58
|
-
for (const { model, column, from, to } of diff.changedColumns) {
|
|
59
|
-
const table = currentSnapshot[model].table;
|
|
60
|
-
upStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${to};`);
|
|
61
|
-
downStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${from};`);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// Added foreign keys
|
|
65
|
-
for (const { model, column, references } of diff.addedForeignKeys) {
|
|
66
|
-
const table = currentSnapshot[model].table;
|
|
67
|
-
// Resolve FK column type from the referenced table's PK type
|
|
68
|
-
const refModel = Object.entries(currentSnapshot).find(([, s]) => s.table === references.references);
|
|
69
|
-
const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
|
|
70
|
-
upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
|
|
71
|
-
upStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
|
|
72
|
-
downStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
|
|
73
|
-
downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// Removed foreign keys
|
|
77
|
-
for (const { model, column, references } of diff.removedForeignKeys) {
|
|
78
|
-
const table = previousSnapshot[model].table;
|
|
79
|
-
// Resolve FK column type from the referenced table's PK type in previous snapshot
|
|
80
|
-
const refModel = Object.entries(previousSnapshot).find(([, s]) => s.table === references.references);
|
|
81
|
-
const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
|
|
82
|
-
upStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
|
|
83
|
-
upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
84
|
-
downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
|
|
85
|
-
downStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const sanitizedDescription = description.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
|
|
89
|
-
const timestamp = Math.floor(Date.now() / 1000);
|
|
90
|
-
const filename = `${timestamp}_${sanitizedDescription}.sql`;
|
|
91
|
-
const content = `-- UP\n${upStatements.join('\n')}\n\n-- DOWN\n${downStatements.join('\n')}\n`;
|
|
92
|
-
|
|
93
|
-
await createFile(path.join(migrationsPath, filename), content);
|
|
94
|
-
await createFile(path.join(migrationsPath, '.snapshot.json'), JSON.stringify(currentSnapshot, null, 2));
|
|
95
|
-
|
|
96
|
-
log.db(`Migration generated: ${filename}`);
|
|
97
|
-
|
|
98
|
-
return { filename, content, snapshot: currentSnapshot };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export async function loadLatestSnapshot(migrationsPath) {
|
|
102
|
-
const snapshotPath = path.join(migrationsPath, '.snapshot.json');
|
|
103
|
-
const exists = await fileExists(snapshotPath);
|
|
104
|
-
|
|
105
|
-
if (!exists) return {};
|
|
106
|
-
|
|
107
|
-
return readFile(snapshotPath, { json: true });
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
export function diffSnapshots(previous, current) {
|
|
111
|
-
const addedModels = [];
|
|
112
|
-
const removedModels = [];
|
|
113
|
-
const addedColumns = [];
|
|
114
|
-
const removedColumns = [];
|
|
115
|
-
const changedColumns = [];
|
|
116
|
-
const addedForeignKeys = [];
|
|
117
|
-
const removedForeignKeys = [];
|
|
118
|
-
|
|
119
|
-
// Find added models
|
|
120
|
-
for (const name of Object.keys(current)) {
|
|
121
|
-
if (!previous[name]) addedModels.push(name);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// Find removed models
|
|
125
|
-
for (const name of Object.keys(previous)) {
|
|
126
|
-
if (!current[name]) removedModels.push(name);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
// Find column changes in existing models
|
|
130
|
-
for (const name of Object.keys(current)) {
|
|
131
|
-
if (!previous[name]) continue;
|
|
132
|
-
|
|
133
|
-
const { columns: prevCols = {} } = previous[name];
|
|
134
|
-
const { columns: currCols = {} } = current[name];
|
|
135
|
-
|
|
136
|
-
// Added columns
|
|
137
|
-
for (const [col, type] of Object.entries(currCols)) {
|
|
138
|
-
if (!prevCols[col]) {
|
|
139
|
-
addedColumns.push({ model: name, column: col, type });
|
|
140
|
-
} else if (prevCols[col] !== type) {
|
|
141
|
-
changedColumns.push({ model: name, column: col, from: prevCols[col], to: type });
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// Removed columns
|
|
146
|
-
for (const [col, type] of Object.entries(prevCols)) {
|
|
147
|
-
if (!currCols[col]) {
|
|
148
|
-
removedColumns.push({ model: name, column: col, type });
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// Foreign key changes
|
|
153
|
-
const prevFKs = previous[name].foreignKeys || {};
|
|
154
|
-
const currFKs = current[name].foreignKeys || {};
|
|
155
|
-
|
|
156
|
-
for (const [col, refs] of Object.entries(currFKs)) {
|
|
157
|
-
if (!prevFKs[col]) {
|
|
158
|
-
addedForeignKeys.push({ model: name, column: col, references: refs });
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
for (const [col, refs] of Object.entries(prevFKs)) {
|
|
163
|
-
if (!currFKs[col]) {
|
|
164
|
-
removedForeignKeys.push({ model: name, column: col, references: refs });
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const hasChanges = addedModels.length > 0 || removedModels.length > 0 ||
|
|
170
|
-
addedColumns.length > 0 || removedColumns.length > 0 ||
|
|
171
|
-
changedColumns.length > 0 || addedForeignKeys.length > 0 || removedForeignKeys.length > 0;
|
|
172
|
-
|
|
173
|
-
return {
|
|
174
|
-
hasChanges,
|
|
175
|
-
addedModels,
|
|
176
|
-
removedModels,
|
|
177
|
-
addedColumns,
|
|
178
|
-
removedColumns,
|
|
179
|
-
changedColumns,
|
|
180
|
-
addedForeignKeys,
|
|
181
|
-
removedForeignKeys,
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
export function detectSchemaDrift(schemas, snapshot) {
|
|
186
|
-
const current = schemasToSnapshot(schemas);
|
|
187
|
-
return diffSnapshots(snapshot, current);
|
|
188
|
-
}
|