New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@nyffels/mynodeorm

Package Overview
Dependencies
Maintainers
1
Versions
66
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nyffels/mynodeorm - npm Package Compare versions

Comparing version 1.0.0-alpha100 to 1.0.0-alpha101

471

dist/logic/migration.logic.js
import path from "node:path";
import fs from "node:fs";
import { mkdirSync } from "fs";
import { uniq } from "lodash-es";
import { getTable, getAllProperties, getAutoIncrement, getColumn, getDefaultSql, getNullable, getPrimary, getSqlType, getType, getUnique, getUnsigned, getForeignKey, ForeignKeyOption } from "../decorators/index.js";
import { MigrationFileBuilder } from "../models/index.js";
export function createMigration(name, migrationLocationPath, classes) {
var _a, _b, _c;
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
if (!name) {

@@ -64,6 +65,4 @@ console.error("❌ Name is required for a migration. Use '--name={{name}}' to declare a name of this migration.");

let migrationFileContent = MigrationFileBuilder.GetFileTemplate();
const upQueries = [];
const downQueries = [];
const queryLines = [];
for (const table of Object.keys(schema)) {
downQueries.push(`DROP TABLE ${table}`);
const tableSchema = (_c = schema[table]) === null || _c === void 0 ? void 0 : _c.columns;

@@ -140,6 +139,5 @@ if (tableSchema === undefined) {

const sql = `CREATE TABLE ${table}(${columnSql.join(', ')});`;
upQueries.push(sql);
queryLines.push(sql);
}
migrationFileContent = migrationFileContent.replace("{{{{TEMPLATE-DATA-UP}}}}", upQueries.map(q => ` this._builder.addQuery('${q.replaceAll("'", "\\'")}');`).join("\n"));
migrationFileContent = migrationFileContent.replace("{{{{TEMPLATE-DATA-DOWN}}}}", downQueries.map(q => ` this._builder.addQuery('${q.replaceAll("'", "\\'")}');`).join("\n"));
migrationFileContent = migrationFileContent.replace("{{{{TEMPLATE-DATA}}}}", queryLines.map(q => ` this._builder.addQuery('${q.replaceAll("'", "\\'")}');`).join("\n"));
migrationFileContent = migrationFileContent.replace("{{{{VERSION}}}}", version.toString());

@@ -153,156 +151,307 @@ mkdirSync(path.join(migrationLocation, migrationName), { recursive: true });

let migrationFileContent = MigrationFileBuilder.GetFileTemplate();
const scriptLines = [];
// const newSchema = Object.keys(schema);
// const oldSchema = Object.keys(oldSchema);
// A schema exists!
//
// let migrationFileContent = MigrationFileBuilder.GetFileTemplate();
//
// let downlogic = ''; // TODO Create up logic
// let uplogic = ''; // TODO Create up logic
//
// if (isEqual(oldSchema, schema)) {
// const oldSchemaTables = Object.keys(oldSchema);
// const schemaTables = Object.keys(schema);
//
// const addedTables = schemaTables.filter(t => oldSchemaTables.indexOf(t) < 0);
// const removedTables = oldSchemaTables.filter(t => schemaTables.indexOf(t) < 0);
// const existingTables = schemaTables.filter(t => !addedTables.concat(removedTables)
// .includes(t));
//
// let isFirstEntry = true;
// let tIndex = 0;
//
// (addedTables ?? []).forEach((table) => {
// if (!isFirstEntry) {
// uplogic += `\n\n `;
// downlogic += `\n\n `;
// } else {
// isFirstEntry = false;
// }
//
// uplogic += `const table_${tIndex} = this._builder.addTable('${table}');\n`;
//
// // @ts-ignore
// Object.keys(schema[table].columns)
// .forEach((column, cIndex) => {
// if (cIndex !== 0) {
// uplogic += `\n`
// }
// // @ts-ignore
// const sColumn = schema[table].columns[column];
// // @ts-ignore
// uplogic += ` table_${tIndex}.addColumn('${column}', '${sColumn.type}')`;
//
// // @ts-ignore
// if (sColumn.primary) {
// uplogic += `.primary()`;
// }
// // @ts-ignore
// if (sColumn.nullable) {
// uplogic += `.nullable()`;
// }
// // @ts-ignore
// if (sColumn.unique) {
// uplogic += `.unique()`;
// }
// // @ts-ignore
// if (sColumn.unsigned) {
// uplogic += `.unsigned()`;
// }
// // @ts-ignore
// if (sColumn.autoIncrement) {
// uplogic += `.autoIncrement()`;
// }
// // @ts-ignore
// if ((sColumn.defaultSql ?? "").trim().length > 0) {
// // @ts-ignore
// uplogic += `.defaultSql('${sColumn.defaultSql.replaceAll('\'', '\\\'')}')`;
// }
// if (sColumn?.foreignKey !== null) {
// // @ts-ignore
// uplogic += `.foreignKey('${sColumn.foreignKey.table}', '${sColumn.foreignKey.column}', ${sColumn.foreignKey.onDelete}, ${sColumn.foreignKey.onUpdate})`;
// }
// uplogic += `;`;
// });
//
// downlogic += `this._builder.dropTable('${table}')`;
//
// tIndex += 1;
// });
//
// (removedTables ?? []).forEach((table) => {
// if (!isFirstEntry) {
// uplogic += `\n\n `;
// downlogic += `\n\n `;
// } else {
// isFirstEntry = false;
// }
//
// downlogic += `const table_${tIndex} = this._builder.addTable('${table}');\n`;
//
// // @ts-ignore
// Object.keys(oldSchema[table].columns)
// .forEach((column, cIndex) => {
// if (cIndex !== 0) {
// downlogic += `\n`
// }
// // @ts-ignore
// const sColumn = oldSchema[table].columns[column];
// // @ts-ignore
// downlogic += ` table_${tIndex}.addColumn('${column}', '${sColumn.type}')`;
//
// // @ts-ignore
// if (sColumn.primary) {
// downlogic += `.primary()`;
// }
// // @ts-ignore
// if (sColumn.nullable) {
// downlogic += `.nullable()`;
// }
// // @ts-ignore
// if (sColumn.unique) {
// downlogic += `.unique()`;
// }
// // @ts-ignore
// if (sColumn.unsigned) {
// downlogic += `.unsigned()`;
// }
// // @ts-ignore
// if (sColumn.autoIncrement) {
// downlogic += `.autoIncrement()`;
// }
// // @ts-ignore
// if ((sColumn.defaultSql ?? "").trim().length > 0) {
// // @ts-ignore
// downlogic += `.defaultSql('${sColumn.defaultSql.replaceAll('\'', '\\\'')}')`;
// }
// if (sColumn?.foreignKey !== null) {
// // @ts-ignore
// uplogic += `.foreignKey('${sColumn.foreignKey.table}', '${sColumn.foreignKey.column}', ${sColumn.foreignKey.onDelete}, ${sColumn.foreignKey.onUpdate})`;
// }
// downlogic += `;`;
// });
//
// uplogic += `this._builder.dropTable('${table}')`;
//
// tIndex += 1;
// });
//
// if (uplogic.trim().length > 0) {
// uplogic += `\n\n this._builder.execute();`;
// }
// if (downlogic.trim().length > 0) {
// downlogic += `\n\n this._builder.execute();`;
// }
// } else {
// console.log("⚠ Schema has no differences. Creating empty migration file...");
// }
//
// migrationFileContent = migrationFileContent.replace("{{{{TEMPLATE-DATA-DOWN}}}}", downlogic);
// migrationFileContent = migrationFileContent.replace("{{{{TEMPLATE-DATA-UP}}}}", uplogic);
//
// mkdirSync(path.join(migrationLocation, migrationName), {recursive: true});
// fs.writeFileSync(path.join(migrationLocation, migrationName, "migration-plan.ts"), migrationFileContent);
// console.log("• Migration file created.");
const queryLines = [];
const newTables = Object.keys(schema);
const oldTables = Object.keys(oldSchema);
const droptables = oldTables.filter(e => !newTables.includes(e));
const addtables = newTables.filter(e => !oldTables.includes(e));
const updateTables = oldTables.filter(e => newTables.includes(e));
for (const table of droptables) {
queryLines.push(`DROP TABLE ${table};`);
}
for (const table of addtables) {
const tableSchema = (_d = schema[table]) === null || _d === void 0 ? void 0 : _d.columns;
if (tableSchema === undefined) {
continue;
}
const columnSql = [];
const primaryColumns = [];
const uniqueColumns = [];
const foreignKeys = [];
for (const column of Object.keys(tableSchema)) {
const data = tableSchema[column];
if (data == null) {
continue;
}
let sql = "";
sql += `${column} ${data.type}`;
if (data.unsigned) {
sql += ` UNSIGNED`;
}
sql += ` ${data.nullable ? 'NULL' : 'NOT NULL'}`;
if (data.defaultSql) {
sql += ` DEFAULT ${data.defaultSql}`;
}
if (data.autoIncrement) {
sql += ` AUTO_INCREMENT`;
}
columnSql.push(sql);
if (data.primary) {
primaryColumns.push(column);
}
if (data.unique) {
uniqueColumns.push(column);
}
if (data.foreignKey) {
foreignKeys.push({ column: data.foreignKey.column, table: data.foreignKey.table, sourceColumn: column, onDelete: data.foreignKey.onDelete, onUpdate: data.foreignKey.onUpdate });
}
}
if (primaryColumns.length > 0) {
columnSql.push(`PRIMARY KEY (${primaryColumns.join(', ')})`);
}
for (const uniqueColumn of uniqueColumns) {
columnSql.push(`UNIQUE INDEX ${uniqueColumn}_UNIQUE (${uniqueColumn} ASC) VISIBLE`);
}
for (const key of foreignKeys) {
let onDeleteAction = "CASCADE";
let onUpdateAction = "CASCADE";
switch (key.onDelete) {
case ForeignKeyOption.SetNull:
onDeleteAction = "SET NULL";
break;
case ForeignKeyOption.Restrict:
onDeleteAction = "RESTRICT";
break;
case ForeignKeyOption.Cascade:
onDeleteAction = "CASCADE";
break;
}
switch (key.onUpdate) {
case ForeignKeyOption.SetNull:
onUpdateAction = "SET NULL";
break;
case ForeignKeyOption.Restrict:
onUpdateAction = "RESTRICT";
break;
case ForeignKeyOption.Cascade:
onUpdateAction = "CASCADE";
break;
}
columnSql.push(`INDEX \`fk_${key.table}_${key.column}_idx\` (\`${key.sourceColumn}\` ASC) VISIBLE`);
columnSql.push(`CONSTRAINT \`fk_${key.table}_${key.column}\` FOREIGN KEY (\`${key.sourceColumn}\`) REFERENCES \`${key.table}\` (\`${key.column}\`) ON DELETE ${onDeleteAction} ON UPDATE ${onUpdateAction}`);
}
const sql = `CREATE TABLE ${table}(${columnSql.join(', ')});`;
queryLines.push(sql);
}
for (const table of updateTables) {
const dbTableSchema = (_e = schema[table]) === null || _e === void 0 ? void 0 : _e.columns;
const oldTableSchema = (_f = oldSchema[table]) === null || _f === void 0 ? void 0 : _f.columns;
const addColumnScript = [];
let dropColumnScript = [];
const modifyColumnScript = [];
const addedUniqColumns = [];
const deletedUniqColumns = [];
let redoPrimary = false;
const dropkeys = [];
const addedKeys = [];
if (dbTableSchema === undefined || oldTableSchema === undefined) {
continue;
}
const columnsToAdd = Object.keys(oldTableSchema)
.filter(e => !Object.keys(dbTableSchema)
.includes(e));
const columnsToDelete = Object.keys(dbTableSchema)
.filter(e => !Object.keys(oldTableSchema)
.includes(e));
const columnsToCheck = Object.keys(oldTableSchema)
.filter(e => Object.keys(dbTableSchema)
.includes(e));
if (columnsToAdd.length > 0) {
for (const column of columnsToAdd) {
const data = oldTableSchema[column];
if (data === undefined) {
continue;
}
let sql = "";
sql += `${column} ${data.type}`;
if (data.unsigned) {
sql += ` UNSIGNED`;
}
sql += ` ${data.nullable ? 'NULL' : 'NOT NULL'}`;
if (data.defaultSql) {
sql += ` DEFAULT ${data.defaultSql}`;
}
if (data.autoIncrement) {
sql += ` AUTO_INCREMENT`;
}
addColumnScript.push(`ADD COLUMN ${sql}`);
if (data.primary) {
redoPrimary = true;
}
if (data.unique) {
addedUniqColumns.push(column);
}
if (data.foreignKey) {
addedKeys.push({
column: data.foreignKey.column,
table: data.foreignKey.table,
sourceColumn: column,
onDelete: data.foreignKey.onDelete,
onUpdate: data.foreignKey.onUpdate
});
}
}
}
if (columnsToDelete.length > 0) {
for (const column of columnsToDelete) {
dropColumnScript.push(`DROP COLUMN ${column}`);
const dbData = dbTableSchema[column];
if (dbData === undefined) {
continue;
}
if (dbData.primary) {
redoPrimary = true;
}
if (dbData.unique) {
deletedUniqColumns.push(column);
}
}
}
if (columnsToCheck.length > 0) {
for (const column of columnsToCheck) {
let hasDifferences = false;
const dbColumn = dbTableSchema[column];
const migrationColumn = oldTableSchema[column];
if (dbColumn === undefined || migrationColumn === undefined) {
continue;
}
if (dbColumn.type.toLowerCase()
.replaceAll(" ", "") != migrationColumn.type.toLowerCase()
.replaceAll(" ", "")) {
hasDifferences = true;
}
if (dbColumn.autoIncrement != migrationColumn.autoIncrement) {
hasDifferences = true;
}
if (dbColumn.nullable != migrationColumn.nullable) {
hasDifferences = true;
}
if ((dbColumn.defaultSql ? ((_g = dbColumn.defaultSql) !== null && _g !== void 0 ? _g : "").replace(/^\'/, "")
.replace(/\'$/, "") : dbColumn.defaultSql) != (migrationColumn.defaultSql ? ((_h = migrationColumn.defaultSql) !== null && _h !== void 0 ? _h : "").replace(/^\'/, "")
.replace(/\'$/, "") : migrationColumn.defaultSql)) {
hasDifferences = true;
}
if (dbColumn.unsigned != migrationColumn.unsigned) {
hasDifferences = true;
}
if (dbColumn.primary != migrationColumn.primary) {
redoPrimary = true;
}
if (dbColumn.unique != migrationColumn.unique) {
if (migrationColumn.unique && !dbColumn.unique) {
addedUniqColumns.push(column);
}
else if (!migrationColumn.unique && dbColumn.unique) {
deletedUniqColumns.push(column);
}
}
if (dbColumn.foreignKey && (!migrationColumn.foreignKey || dbColumn.foreignKey.column != ((_j = migrationColumn.foreignKey) === null || _j === void 0 ? void 0 : _j.column) || dbColumn.foreignKey.table != ((_k = migrationColumn.foreignKey) === null || _k === void 0 ? void 0 : _k.table) || dbColumn.foreignKey.onUpdate != ((_l = migrationColumn.foreignKey) === null || _l === void 0 ? void 0 : _l.onUpdate) || dbColumn.foreignKey.onDelete != ((_m = migrationColumn.foreignKey) === null || _m === void 0 ? void 0 : _m.onDelete))) {
dropkeys.push(dbColumn.foreignKey['name']);
}
if (migrationColumn.foreignKey !== null && (!dbColumn.foreignKey || dbColumn.foreignKey.column != ((_o = migrationColumn.foreignKey) === null || _o === void 0 ? void 0 : _o.column) || dbColumn.foreignKey.table != ((_p = migrationColumn.foreignKey) === null || _p === void 0 ? void 0 : _p.table) || dbColumn.foreignKey.onUpdate != ((_q = migrationColumn.foreignKey) === null || _q === void 0 ? void 0 : _q.onUpdate) || dbColumn.foreignKey.onDelete != ((_r = migrationColumn.foreignKey) === null || _r === void 0 ? void 0 : _r.onDelete))) {
addedKeys.push({
column: migrationColumn.foreignKey.column,
table: migrationColumn.foreignKey.table,
sourceColumn: column,
onDelete: migrationColumn.foreignKey.onDelete,
onUpdate: migrationColumn.foreignKey.onUpdate,
});
}
if (hasDifferences) {
let sql = "";
sql += `${column} ${migrationColumn.type}`;
if (migrationColumn.unsigned) {
sql += ` UNSIGNED`;
}
sql += ` ${migrationColumn.nullable ? 'NULL' : 'NOT NULL'}`;
if (migrationColumn.defaultSql) {
sql += ` DEFAULT ${migrationColumn.defaultSql}`;
}
if (migrationColumn.autoIncrement) {
sql += ` AUTO_INCREMENT`;
}
modifyColumnScript.push(`MODIFY COLUMN ${sql}`);
}
}
}
let lines = [];
if (addColumnScript.length > 0) {
lines = lines.concat(addColumnScript);
}
if (dropColumnScript) {
lines.concat(dropColumnScript);
}
if (modifyColumnScript.length > 0) {
lines = lines.concat(modifyColumnScript);
}
if (redoPrimary) {
let indexExists = false;
// @ts-ignore
for (const column of Object.keys(oldSchema[table].columns)) {
// @ts-ignore
if (oldSchema[table].columns[column].primary) {
indexExists = true;
break;
}
}
if (indexExists) {
lines.push("DROP PRIMARY KEY");
}
const primaryKeys = Object.keys(oldTableSchema)
.filter(column => { var _a; return (_a = oldTableSchema[column]) === null || _a === void 0 ? void 0 : _a.primary; });
if (primaryKeys.length > 0) {
lines.push(`ADD PRIMARY KEY (${primaryKeys.join(", ")})`);
}
}
if (deletedUniqColumns.length > 0) {
for (const column of uniq(deletedUniqColumns)) {
lines.push(`DROP INDEX ${column}_UNIQUE`);
}
}
if (addedUniqColumns.length > 0) {
for (const column of uniq(addedUniqColumns)) {
lines.push(`ADD UNIQUE INDEX ${column}_UNIQUE (${column} ASC) VISIBLE`);
}
}
if (dropkeys.length > 0) {
queryLines.push(`ALTER TABLE \`${table}\` ${dropkeys.map(k => `DROP FOREIGN KEY \`${k}\``).join(", ")}, ${dropkeys.map(k => `DROP INDEX \`${k}_idx\``)}`);
}
if (addedKeys.length > 0) {
for (const key of addedKeys) {
let onDeleteAction = "CASCADE";
let onUpdateAction = "CASCADE";
switch (key.onDelete) {
case ForeignKeyOption.SetNull:
onDeleteAction = "SET NULL";
break;
case ForeignKeyOption.Restrict:
onDeleteAction = "RESTRICT";
break;
case ForeignKeyOption.Cascade:
onDeleteAction = "CASCADE";
break;
}
switch (key.onUpdate) {
case ForeignKeyOption.SetNull:
onUpdateAction = "SET NULL";
break;
case ForeignKeyOption.Restrict:
onUpdateAction = "RESTRICT";
break;
case ForeignKeyOption.Cascade:
onUpdateAction = "CASCADE";
break;
}
lines.push(`ADD INDEX \`fk_${key.table}_${key.column}_idx\` (\`${key.sourceColumn}\` ASC) VISIBLE`);
lines.push(`ADD CONSTRAINT \`fk_${key.table}_${key.column}\` FOREIGN KEY (\`${key.sourceColumn}\`) REFERENCES \`${key.table}\` (\`${key.column}\`) ON DELETE ${onDeleteAction} ON UPDATE ${onUpdateAction}`);
}
}
if (lines.length > 0) {
queryLines.push(`ALTER TABLE ${table} ${lines.join(', ')};`);
}
}
migrationFileContent = migrationFileContent.replace("{{{{TEMPLATE-DATA}}}}", queryLines.map(q => ` this._builder.addQuery('${q.replaceAll("'", "\\'")}');`).join("\n"));
migrationFileContent = migrationFileContent.replace("{{{{VERSION}}}}", version.toString());
mkdirSync(path.join(migrationLocation, migrationName), { recursive: true });
fs.writeFileSync(path.join(migrationLocation, migrationName, "migration-plan.ts"), migrationFileContent);
console.log("• Migration file created.");
}

@@ -309,0 +458,0 @@ console.log("✅ Migration completed.");

@@ -7,3 +7,3 @@ export declare abstract class MigrationFileBuilder {

addQuery(query: string): void;
execute(): void;
execute(version: string): void;
}

@@ -9,3 +9,3 @@ export class MigrationFileBuilder {

public async up() {
public async migrate() {
/*

@@ -15,3 +15,3 @@ You can add custom data here to be run before the migration plan.

{{{{TEMPLATE-DATA-UP}}}}
{{{{TEMPLATE-DATA}}}}

@@ -22,18 +22,4 @@ /*

this._builder.execute();
this._builder.execute(_version);
}
public async down(this._version) {
/*
You can add custom data here to be run before the migration plan.
*/
{{{{TEMPLATE-DATA-DOWN}}}}
/*
You can add custom data here to be run after the migration plan.
*/
this._builder.execute(this._version - 1);
}
}`;

@@ -49,6 +35,12 @@ }

}
execute() {
execute(version) {
// TODO
// if version === 0:
// scriptLines.push(`DROP TABLE IF EXISTS __myNodeORM;`)
// scriptLines.push(`CREATE TABLE __myNodeORM (version INT NOT NULL, DATE DATETIME NOT NULL DEFAULT NOW());`);
// scriptLines.push(`INSERT INTO __myNodeORM (version) VALUES (${(latestMigrationVersion ?? "").split(".").find(x => x)});`);
// else
// scriptLines.push(`INSERT INTO __myNodeORM (version) VALUES (${(latestMigrationVersion ?? "").split(".").find(x => x)});`);
}
}
//# sourceMappingURL=migration.models.js.map
{
"name": "@nyffels/mynodeorm",
"version": "1.0.0-alpha100",
"version": "1.0.0-alpha101",
"description": "A full-fledged ORM framework for NodeJS and MySQL with develop friendly code aimed to handle database migrations, MySQL Query builder / helper and property mapping.",

@@ -5,0 +5,0 @@ "private": false,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc