@stonyx/orm 0.2.1-beta.2 → 0.2.1-beta.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/src/model.js CHANGED
@@ -1,6 +1,17 @@
1
1
  import { attr } from '@stonyx/orm';
2
2
 
3
3
  export default class Model {
4
+ /**
5
+ * Controls whether records of this model are loaded into memory on startup.
6
+ *
7
+ * - true → loaded on boot, kept in store (default for backward compatibility)
8
+ * - false → never cached; find() always queries MySQL
9
+ *
10
+ * Override in subclass: static memory = false;
11
+ */
12
+ static memory = true;
13
+ static pluralName = undefined;
14
+
4
15
  id = attr('number');
5
16
 
6
17
  constructor(name) {
@@ -0,0 +1,28 @@
1
+ let pool = null;
2
+
3
+ export async function getPool(mysqlConfig) {
4
+ if (pool) return pool;
5
+
6
+ const mysql = await import('mysql2/promise');
7
+
8
+ pool = mysql.createPool({
9
+ host: mysqlConfig.host,
10
+ port: mysqlConfig.port,
11
+ user: mysqlConfig.user,
12
+ password: mysqlConfig.password,
13
+ database: mysqlConfig.database,
14
+ connectionLimit: mysqlConfig.connectionLimit,
15
+ waitForConnections: true,
16
+ enableKeepAlive: true,
17
+ keepAliveInitialDelay: 10000,
18
+ });
19
+
20
+ return pool;
21
+ }
22
+
23
+ export async function closePool() {
24
+ if (!pool) return;
25
+
26
+ await pool.end();
27
+ pool = null;
28
+ }
@@ -0,0 +1,188 @@
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
+ }
@@ -0,0 +1,110 @@
1
+ import { readFile, fileExists } from '@stonyx/utils/file';
2
+ import path from 'path';
3
+ import fs from 'fs/promises';
4
+
5
+ export async function ensureMigrationsTable(pool, tableName = '__migrations') {
6
+ await pool.execute(`
7
+ CREATE TABLE IF NOT EXISTS \`${tableName}\` (
8
+ id INT AUTO_INCREMENT PRIMARY KEY,
9
+ filename VARCHAR(255) NOT NULL UNIQUE,
10
+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
11
+ )
12
+ `);
13
+ }
14
+
15
+ export async function getAppliedMigrations(pool, tableName = '__migrations') {
16
+ const [rows] = await pool.execute(
17
+ `SELECT filename FROM \`${tableName}\` ORDER BY id ASC`
18
+ );
19
+
20
+ return rows.map(row => row.filename);
21
+ }
22
+
23
+ export async function getMigrationFiles(migrationsDir) {
24
+ const exists = await fileExists(migrationsDir);
25
+ if (!exists) return [];
26
+
27
+ const entries = await fs.readdir(migrationsDir);
28
+
29
+ return entries
30
+ .filter(f => f.endsWith('.sql'))
31
+ .sort();
32
+ }
33
+
34
+ export function parseMigrationFile(content) {
35
+ const upMarker = '-- UP';
36
+ const downMarker = '-- DOWN';
37
+ const upIndex = content.indexOf(upMarker);
38
+ const downIndex = content.indexOf(downMarker);
39
+
40
+ if (upIndex === -1) {
41
+ return { up: content.trim(), down: '' };
42
+ }
43
+
44
+ const upStart = upIndex + upMarker.length;
45
+ const upEnd = downIndex !== -1 ? downIndex : content.length;
46
+ const up = content.slice(upStart, upEnd).trim();
47
+ const down = downIndex !== -1 ? content.slice(downIndex + downMarker.length).trim() : '';
48
+
49
+ return { up, down };
50
+ }
51
+
52
+ export async function applyMigration(pool, filename, upSql, tableName = '__migrations') {
53
+ const connection = await pool.getConnection();
54
+
55
+ try {
56
+ await connection.beginTransaction();
57
+
58
+ // Execute each statement separately (split on semicolons)
59
+ const statements = splitStatements(upSql);
60
+
61
+ for (const stmt of statements) {
62
+ await connection.execute(stmt);
63
+ }
64
+
65
+ await connection.execute(
66
+ `INSERT INTO \`${tableName}\` (filename) VALUES (?)`,
67
+ [filename]
68
+ );
69
+
70
+ await connection.commit();
71
+ } catch (error) {
72
+ await connection.rollback();
73
+ throw error;
74
+ } finally {
75
+ connection.release();
76
+ }
77
+ }
78
+
79
+ export async function rollbackMigration(pool, filename, downSql, tableName = '__migrations') {
80
+ const connection = await pool.getConnection();
81
+
82
+ try {
83
+ await connection.beginTransaction();
84
+
85
+ const statements = splitStatements(downSql);
86
+
87
+ for (const stmt of statements) {
88
+ await connection.execute(stmt);
89
+ }
90
+
91
+ await connection.execute(
92
+ `DELETE FROM \`${tableName}\` WHERE filename = ?`,
93
+ [filename]
94
+ );
95
+
96
+ await connection.commit();
97
+ } catch (error) {
98
+ await connection.rollback();
99
+ throw error;
100
+ } finally {
101
+ connection.release();
102
+ }
103
+ }
104
+
105
+ function splitStatements(sql) {
106
+ return sql
107
+ .split(';')
108
+ .map(s => s.trim())
109
+ .filter(s => s.length > 0 && !s.startsWith('--'));
110
+ }