diff --git a/js/src/sequelize_schema.js b/js/src/sequelize_schema.js index 57aa1e7..772468d 100644 --- a/js/src/sequelize_schema.js +++ b/js/src/sequelize_schema.js @@ -40,6 +40,13 @@ const loadSequelizeModels = (dialect, ...models) => { .queryGenerator.createTableQuery(def.tableName, attr, { ...def.options, }) + "\n"; + + for (const index of def.options.indexes) { + sql += + sequelize + .getQueryInterface() + .queryGenerator.addIndexQuery(def.tableName, index) + ";\n"; + } } return sql; }; diff --git a/js/testdata/migrations/mysql/20230912115222.sql b/js/testdata/migrations/mysql/20231217121351.sql similarity index 91% rename from js/testdata/migrations/mysql/20230912115222.sql rename to js/testdata/migrations/mysql/20231217121351.sql index 9739d2d..e2ced69 100644 --- a/js/testdata/migrations/mysql/20230912115222.sql +++ b/js/testdata/migrations/mysql/20231217121351.sql @@ -29,6 +29,7 @@ CREATE TABLE `RecipeIngredients` ( `deletedAt` datetime NULL, PRIMARY KEY (`recipeId`, `ingredientId`), INDEX `ingredientId` (`ingredientId`), + UNIQUE INDEX `recipe_ingredients_meassurement_type_meassurement_amount` (`meassurementType`, `meassurementAmount`), CONSTRAINT `RecipeIngredients_ibfk_1` FOREIGN KEY (`recipeId`) REFERENCES `Recipes` (`id`) ON UPDATE CASCADE ON DELETE CASCADE, CONSTRAINT `RecipeIngredients_ibfk_2` FOREIGN KEY (`ingredientId`) REFERENCES `Ingredients` (`id`) ON UPDATE CASCADE ON DELETE CASCADE ) CHARSET utf8mb4 COLLATE utf8mb4_0900_ai_ci; diff --git a/js/testdata/migrations/mysql/atlas.sum b/js/testdata/migrations/mysql/atlas.sum index fb6b97a..b652c73 100644 --- a/js/testdata/migrations/mysql/atlas.sum +++ b/js/testdata/migrations/mysql/atlas.sum @@ -1,2 +1,2 @@ -h1:CJf+okXgMJNuJC0zHAZBLEvxsU6Puk5Pm4OuLPyy6sQ= -20230912115222.sql h1:6nMV/9/tt7G/l8iUqmnQlicQC1xZpu1FGLKTe4B//uM= +h1:iiEZ5BKOIIrn/v6gnOMLybPtmdE+CF9zgQGkBUNTSak= +20231217121351.sql h1:OloC5SnSg1SNwiBwdJ8/0JzGE+z1IJxrC7PZzCE52pM= diff --git a/js/testdata/migrations/postgres/20230912115319.sql b/js/testdata/migrations/postgres/20231217121326.sql similarity index 83% rename from js/testdata/migrations/postgres/20230912115319.sql rename to js/testdata/migrations/postgres/20231217121326.sql index 046134e..44da286 100644 --- a/js/testdata/migrations/postgres/20230912115319.sql +++ b/js/testdata/migrations/postgres/20231217121326.sql @@ -31,3 +31,5 @@ CREATE TABLE "public"."RecipeIngredients" ( CONSTRAINT "RecipeIngredients_ingredientId_fkey" FOREIGN KEY ("ingredientId") REFERENCES "public"."Ingredients" ("id") ON UPDATE CASCADE ON DELETE CASCADE, CONSTRAINT "RecipeIngredients_recipeId_fkey" FOREIGN KEY ("recipeId") REFERENCES "public"."Recipes" ("id") ON UPDATE CASCADE ON DELETE CASCADE ); +-- Create index "recipe_ingredients_meassurement_type_meassurement_amount" to table: "RecipeIngredients" +CREATE UNIQUE INDEX "recipe_ingredients_meassurement_type_meassurement_amount" ON "public"."RecipeIngredients" ("meassurementType", "meassurementAmount"); diff --git a/js/testdata/migrations/postgres/atlas.sum b/js/testdata/migrations/postgres/atlas.sum index f641d4c..3672e4e 100644 --- a/js/testdata/migrations/postgres/atlas.sum +++ b/js/testdata/migrations/postgres/atlas.sum @@ -1,2 +1,2 @@ -h1:5uiGpKZdqZnoC6BgEYwOIt8rx1se3mFBe+QuzLjBAAc= -20230912115319.sql h1:Cm4ToPSY1c1qkiYrDRsXYgl7InrXXCyM42KzaDjGzfI= +h1:uJ7wU+6p3ohypex+0pRKcsw86vEtzStoE6JJLatVoAo= +20231217121326.sql h1:d2jBf2rcjqt+l7WZhoeosIndYjndY0eAkBtcm4e8PcE= diff --git a/js/testdata/migrations/sqlite/20230912115344.sql b/js/testdata/migrations/sqlite/20231217121207.sql similarity index 81% rename from js/testdata/migrations/sqlite/20230912115344.sql rename to js/testdata/migrations/sqlite/20231217121207.sql index 98dc95a..f58b483 100644 --- a/js/testdata/migrations/sqlite/20230912115344.sql +++ b/js/testdata/migrations/sqlite/20231217121207.sql @@ -29,3 +29,5 @@ CREATE TABLE `RecipeIngredients` ( CONSTRAINT `0` FOREIGN KEY (`ingredientId`) REFERENCES `Ingredients` (`id`) ON UPDATE CASCADE ON DELETE CASCADE, CONSTRAINT `1` FOREIGN KEY (`recipeId`) REFERENCES `Recipes` (`id`) ON UPDATE CASCADE ON DELETE CASCADE ); +-- Create index "recipe_ingredients_meassurement_type_meassurement_amount" to table: "RecipeIngredients" +CREATE UNIQUE INDEX `recipe_ingredients_meassurement_type_meassurement_amount` ON `RecipeIngredients` (`meassurementType`, `meassurementAmount`); diff --git a/js/testdata/migrations/sqlite/atlas.sum b/js/testdata/migrations/sqlite/atlas.sum index 9f83ac9..938b7f3 100644 --- a/js/testdata/migrations/sqlite/atlas.sum +++ b/js/testdata/migrations/sqlite/atlas.sum @@ -1,2 +1,2 @@ -h1:lH+RIjBcnGS9napEBLAJ0fsQdzxOEz/MWUR3gIEAPPk= -20230912115344.sql h1:C/VGRJ4f8pncM8xlf/6U8kufS5AO+kt8TjWt3SY1TGk= +h1:BYAmffj+Yu0UriXgwsQxyg2oirRqrQYz2VS/GUE2oL4= +20231217121207.sql h1:fMjw2OFFzGMAzehqpEZjFdbgbHjyCBEwSiSG/rhNDek= diff --git a/js/testdata/models/recipe-ingredient.js b/js/testdata/models/recipe-ingredient.js index bdfa4ed..71f5d21 100644 --- a/js/testdata/models/recipe-ingredient.js +++ b/js/testdata/models/recipe-ingredient.js @@ -22,6 +22,12 @@ module.exports = (sequelize, DataTypes) => { }, { paranoid: true, + indexes: [ + { + unique: true, + fields: ["meassurementType", "meassurementAmount"], + }, + ], }, ); diff --git a/ts/src/index.ts b/ts/src/index.ts index 62f72f7..c1e4df2 100755 --- a/ts/src/index.ts +++ b/ts/src/index.ts @@ -5,51 +5,7 @@ import { hideBin } from "yargs/helpers"; import fs from "fs"; import { Sequelize, SequelizeOptions } from "sequelize-typescript"; import path from "path"; - -// get sql state of sequelize models -const loadSQL = async ( - relativePath: string, - driver: string, -): Promise => { - if (!fs.existsSync(relativePath)) { - throw new Error("path does not exist"); - } - const absolutePath = path.resolve(relativePath); - const sequelize = new Sequelize({ - dialect: driver, - models: [absolutePath + "/*.ts"], - } as SequelizeOptions); - - const models = sequelize.modelManager - .getModelsTopoSortedByForeignKey() - ?.reverse(); - if (!models) { - throw new Error("no models found"); - } - let sql = ""; - for (const model of models) { - const def = sequelize.modelManager.getModel(model.name); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const attr = sequelize.getQueryInterface().queryGenerator.attributesToSQL( - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - def.getAttributes(), - Object.assign({}, def.options), - ); - sql += - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - sequelize - .getQueryInterface() - .queryGenerator.createTableQuery( - def.tableName, - attr, - Object.assign({}, def.options), - ) + "\n"; - } - return sql; -}; +import { loadSQL } from "./sequelize_schema"; const y = yargs(hideBin(process.argv)) .usage( @@ -74,9 +30,16 @@ y.command( }, async function (argv) { try { - loadSQL(argv.path, argv.dialect).then((sql) => { - console.log(sql); - }); + if (!fs.existsSync(argv.path)) { + console.error(`path ${argv.path} does not exist`); + return; + } + const absolutePath = path.resolve(argv.path); + const sequelize = new Sequelize({ + dialect: argv.dialect, + models: [absolutePath + "/*.ts"], + } as SequelizeOptions); + console.log(loadSQL(sequelize)); } catch (e) { if (e instanceof Error) { console.error(e.message); diff --git a/ts/src/sequelize_schema.d.ts b/ts/src/sequelize_schema.d.ts index 0e842aa..48f33ba 100644 --- a/ts/src/sequelize_schema.d.ts +++ b/ts/src/sequelize_schema.d.ts @@ -1,2 +1,4 @@ import { ModelCtor } from "sequelize-typescript/dist/model/model/model"; +import { Sequelize } from "sequelize-typescript"; export declare const loadModels: (dialect: string, models: ModelCtor[]) => string; +export declare const loadSQL: (sequelize: Sequelize) => string; diff --git a/ts/src/sequelize_schema.js b/ts/src/sequelize_schema.js index dbbc76e..219cad1 100644 --- a/ts/src/sequelize_schema.js +++ b/ts/src/sequelize_schema.js @@ -1,11 +1,10 @@ "use strict"; exports.__esModule = true; -exports.loadModels = void 0; +exports.loadSQL = exports.loadModels = void 0; var sequelize_typescript_1 = require("sequelize-typescript"); var validDialects = ["mysql", "postgres", "sqlite", "mariadb", "mssql"]; // load sql state of sequelize models var loadModels = function (dialect, models) { - var _a; if (!validDialects.includes(dialect)) { throw new Error("Invalid dialect ".concat(dialect)); } @@ -13,6 +12,11 @@ var loadModels = function (dialect, models) { dialect: dialect, models: models }); + return (0, exports.loadSQL)(sequelize); +}; +exports.loadModels = loadModels; +var loadSQL = function (sequelize) { + var _a, _b, _c; var orderedModels = (_a = sequelize.modelManager .getModelsTopoSortedByForeignKey()) === null || _a === void 0 ? void 0 : _a.reverse(); if (!orderedModels) { @@ -22,21 +26,25 @@ var loadModels = function (dialect, models) { for (var _i = 0, orderedModels_1 = orderedModels; _i < orderedModels_1.length; _i++) { var model = orderedModels_1[_i]; var def = sequelize.modelManager.getModel(model.name); + var queryGenerator = sequelize.getQueryInterface().queryGenerator; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - var attr = sequelize.getQueryInterface().queryGenerator.attributesToSQL( + var attr = queryGenerator.attributesToSQL( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore def.getAttributes(), Object.assign({}, def.options)); sql += // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - sequelize - .getQueryInterface() + queryGenerator.createTableQuery(def.tableName, attr, Object.assign({}, def.options)) + "\n"; + for (var _d = 0, _e = (_c = (_b = def.options) === null || _b === void 0 ? void 0 : _b.indexes) !== null && _c !== void 0 ? _c : []; _d < _e.length; _d++) { + var index = _e[_d]; + sql += // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - .queryGenerator.createTableQuery(def.tableName, attr, Object.assign({}, def.options)) + "\n"; + queryGenerator.addIndexQuery(def.tableName, index, Object.assign({}, def.options)) + ";\n"; + } } return sql; }; -exports.loadModels = loadModels; +exports.loadSQL = loadSQL; diff --git a/ts/src/sequelize_schema.ts b/ts/src/sequelize_schema.ts index 2ceaf8c..b9a1705 100644 --- a/ts/src/sequelize_schema.ts +++ b/ts/src/sequelize_schema.ts @@ -12,6 +12,10 @@ export const loadModels = (dialect: string, models: ModelCtor[]) => { dialect: dialect, models: models, } as SequelizeOptions); + return loadSQL(sequelize); +}; + +export const loadSQL = (sequelize: Sequelize) => { const orderedModels = sequelize.modelManager .getModelsTopoSortedByForeignKey() ?.reverse(); @@ -21,9 +25,10 @@ export const loadModels = (dialect: string, models: ModelCtor[]) => { let sql = ""; for (const model of orderedModels) { const def = sequelize.modelManager.getModel(model.name); + const queryGenerator = sequelize.getQueryInterface().queryGenerator; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - const attr = sequelize.getQueryInterface().queryGenerator.attributesToSQL( + const attr = queryGenerator.attributesToSQL( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore def.getAttributes(), @@ -32,15 +37,21 @@ export const loadModels = (dialect: string, models: ModelCtor[]) => { sql += // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - sequelize - .getQueryInterface() + queryGenerator.createTableQuery( + def.tableName, + attr, + Object.assign({}, def.options), + ) + "\n"; + for (const index of def.options?.indexes ?? []) { + sql += // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - .queryGenerator.createTableQuery( + queryGenerator.addIndexQuery( def.tableName, - attr, + index, Object.assign({}, def.options), - ) + "\n"; + ) + ";\n"; + } } return sql; }; diff --git a/ts/testdata/migrations/mysql/20230912121933.sql b/ts/testdata/migrations/mysql/20231217124500.sql similarity index 94% rename from ts/testdata/migrations/mysql/20230912121933.sql rename to ts/testdata/migrations/mysql/20231217124500.sql index 16fbd8c..4be74d9 100644 --- a/ts/testdata/migrations/mysql/20230912121933.sql +++ b/ts/testdata/migrations/mysql/20231217124500.sql @@ -5,7 +5,8 @@ CREATE TABLE `contact` ( `alias` varchar(45) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, - PRIMARY KEY (`id`) + PRIMARY KEY (`id`), + UNIQUE INDEX `name-alias` (`name`, `alias`) ) CHARSET utf8mb4 COLLATE utf8mb4_0900_ai_ci; -- Create "email" table CREATE TABLE `email` ( diff --git a/ts/testdata/migrations/mysql/atlas.sum b/ts/testdata/migrations/mysql/atlas.sum index 015141e..3538266 100644 --- a/ts/testdata/migrations/mysql/atlas.sum +++ b/ts/testdata/migrations/mysql/atlas.sum @@ -1,2 +1,2 @@ -h1:WICudLNwmqoF0SH5PLFjXluCQhGwaIZmV0rvOHJX/6s= -20230912121933.sql h1:jcH5UOkumyUFeyv2EXiTsmW2uYfgAMUcmmJXdKTA1RE= +h1:rRnJAJPIaK0/o4jqGM/wJvJYwl86hJWkAFKaqZ8vE+8= +20231217124500.sql h1:f+vFf2MPBTjigPYuT2pzyuntsgcUhXasXK10k13zWtw= diff --git a/ts/testdata/migrations/postgres/20230912121955.sql b/ts/testdata/migrations/postgres/20231217124605.sql similarity index 89% rename from ts/testdata/migrations/postgres/20230912121955.sql rename to ts/testdata/migrations/postgres/20231217124605.sql index 5738fb4..7c7e8dc 100644 --- a/ts/testdata/migrations/postgres/20230912121955.sql +++ b/ts/testdata/migrations/postgres/20231217124605.sql @@ -7,6 +7,8 @@ CREATE TABLE "public"."contact" ( "updated_at" timestamptz NOT NULL, PRIMARY KEY ("id") ); +-- Create index "name-alias" to table: "contact" +CREATE UNIQUE INDEX "name-alias" ON "public"."contact" ("name", "alias"); -- Create "email" table CREATE TABLE "public"."email" ( "id" serial NOT NULL, diff --git a/ts/testdata/migrations/postgres/atlas.sum b/ts/testdata/migrations/postgres/atlas.sum index 6c4484e..fb50999 100644 --- a/ts/testdata/migrations/postgres/atlas.sum +++ b/ts/testdata/migrations/postgres/atlas.sum @@ -1,2 +1,2 @@ -h1:gwRo5ytz/gX8ZG87ZdJxincXdKsO89R8e6bh7a/QQTs= -20230912121955.sql h1:2TpK15SLhtNwn8WagIwoHIXxQtfCqc1mRK+yxr1dmW4= +h1:XIYtaHM79msFK/eAOwe/Wv6kzA3aMwoh3/D1ztZ1e6c= +20231217124605.sql h1:QriWPdvwTcmZ3/M3ngm9/oJS1waROy1BJA/JNd8C0Bs= diff --git a/ts/testdata/migrations/sqlite/20230912122006.sql b/ts/testdata/migrations/sqlite/20231217124556.sql similarity index 88% rename from ts/testdata/migrations/sqlite/20230912122006.sql rename to ts/testdata/migrations/sqlite/20231217124556.sql index 39bf02b..7dbe779 100644 --- a/ts/testdata/migrations/sqlite/20230912122006.sql +++ b/ts/testdata/migrations/sqlite/20231217124556.sql @@ -6,19 +6,21 @@ CREATE TABLE `contact` ( `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL ); --- Create "email" table -CREATE TABLE `email` ( +-- Create index "name-alias" to table: "contact" +CREATE UNIQUE INDEX `name-alias` ON `contact` (`name`, `alias`); +-- Create "phone" table +CREATE TABLE `phone` ( `id` integer NULL PRIMARY KEY AUTOINCREMENT, - `email` varchar NOT NULL, + `phone` varchar NOT NULL, `contact_id` integer NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, CONSTRAINT `0` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`id`) ON UPDATE CASCADE ON DELETE CASCADE ); --- Create "phone" table -CREATE TABLE `phone` ( +-- Create "email" table +CREATE TABLE `email` ( `id` integer NULL PRIMARY KEY AUTOINCREMENT, - `phone` varchar NOT NULL, + `email` varchar NOT NULL, `contact_id` integer NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, diff --git a/ts/testdata/migrations/sqlite/atlas.sum b/ts/testdata/migrations/sqlite/atlas.sum index 6a8fb7e..afa4b57 100644 --- a/ts/testdata/migrations/sqlite/atlas.sum +++ b/ts/testdata/migrations/sqlite/atlas.sum @@ -1,2 +1,2 @@ -h1:WSjXuQ0BOC/96TS1P0WjPYzRtGqaijFhjqTfeRrLc5U= -20230912122006.sql h1:dJMMwJ2SuHQcBulNO7Ns2taqfHlbplU8MTw0A8ieUsY= +h1:CKVzjBvTtLsH1BjT76EdtN91cCSsF9hPIyXW9dtij7A= +20231217124556.sql h1:3Ogc8234OVj3wzDeTf6MlbkyTHOSbmNSKNr9kKR5dRs= diff --git a/ts/testdata/models/Contact.ts b/ts/testdata/models/Contact.ts index 5cdb10b..6dc7baf 100644 --- a/ts/testdata/models/Contact.ts +++ b/ts/testdata/models/Contact.ts @@ -12,6 +12,7 @@ import { AfterCreate, HasMany, Length, + Index, } from "sequelize-typescript"; import Phone from "./Phone"; import Email from "./Email"; @@ -41,11 +42,13 @@ class Contact extends Model { @AllowNull(false) @Length({ min: 3, max: 45 }) @Column(DataType.STRING(45)) + @Index({ name: "name-alias", unique: true }) name!: string; @AllowNull(false) @Length({ min: 3, max: 45 }) @Column(DataType.STRING(45)) + @Index({ name: "name-alias", unique: true }) alias!: string; @HasMany(() => Phone, { onDelete: "CASCADE" })