Skip to content

Commit

Permalink
support indexes (#12)
Browse files Browse the repository at this point in the history
* js/src: add index support for js

* update the tests

* update typescript library
  • Loading branch information
ronenlu authored Dec 17, 2023
1 parent 09ca982 commit 8ea70d1
Show file tree
Hide file tree
Showing 19 changed files with 90 additions and 80 deletions.
7 changes: 7 additions & 0 deletions js/src/sequelize_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
4 changes: 2 additions & 2 deletions js/testdata/migrations/mysql/atlas.sum
Original file line number Diff line number Diff line change
@@ -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=
Original file line number Diff line number Diff line change
Expand Up @@ -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");
4 changes: 2 additions & 2 deletions js/testdata/migrations/postgres/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
h1:5uiGpKZdqZnoC6BgEYwOIt8rx1se3mFBe+QuzLjBAAc=
20230912115319.sql h1:Cm4ToPSY1c1qkiYrDRsXYgl7InrXXCyM42KzaDjGzfI=
h1:uJ7wU+6p3ohypex+0pRKcsw86vEtzStoE6JJLatVoAo=
20231217121326.sql h1:d2jBf2rcjqt+l7WZhoeosIndYjndY0eAkBtcm4e8PcE=
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
4 changes: 2 additions & 2 deletions js/testdata/migrations/sqlite/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
h1:lH+RIjBcnGS9napEBLAJ0fsQdzxOEz/MWUR3gIEAPPk=
20230912115344.sql h1:C/VGRJ4f8pncM8xlf/6U8kufS5AO+kt8TjWt3SY1TGk=
h1:BYAmffj+Yu0UriXgwsQxyg2oirRqrQYz2VS/GUE2oL4=
20231217121207.sql h1:fMjw2OFFzGMAzehqpEZjFdbgbHjyCBEwSiSG/rhNDek=
6 changes: 6 additions & 0 deletions js/testdata/models/recipe-ingredient.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ module.exports = (sequelize, DataTypes) => {
},
{
paranoid: true,
indexes: [
{
unique: true,
fields: ["meassurementType", "meassurementAmount"],
},
],
},
);

Expand Down
59 changes: 11 additions & 48 deletions ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> => {
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(
Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions ts/src/sequelize_schema.d.ts
Original file line number Diff line number Diff line change
@@ -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;
22 changes: 15 additions & 7 deletions ts/src/sequelize_schema.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
"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));
}
var sequelize = new sequelize_typescript_1.Sequelize({
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) {
Expand All @@ -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;
23 changes: 17 additions & 6 deletions ts/src/sequelize_schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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(),
Expand All @@ -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;
};
Original file line number Diff line number Diff line change
Expand Up @@ -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` (
Expand Down
4 changes: 2 additions & 2 deletions ts/testdata/migrations/mysql/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
h1:WICudLNwmqoF0SH5PLFjXluCQhGwaIZmV0rvOHJX/6s=
20230912121933.sql h1:jcH5UOkumyUFeyv2EXiTsmW2uYfgAMUcmmJXdKTA1RE=
h1:rRnJAJPIaK0/o4jqGM/wJvJYwl86hJWkAFKaqZ8vE+8=
20231217124500.sql h1:f+vFf2MPBTjigPYuT2pzyuntsgcUhXasXK10k13zWtw=
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions ts/testdata/migrations/postgres/atlas.sum
Original file line number Diff line number Diff line change
@@ -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=
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions ts/testdata/migrations/sqlite/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
h1:WSjXuQ0BOC/96TS1P0WjPYzRtGqaijFhjqTfeRrLc5U=
20230912122006.sql h1:dJMMwJ2SuHQcBulNO7Ns2taqfHlbplU8MTw0A8ieUsY=
h1:CKVzjBvTtLsH1BjT76EdtN91cCSsF9hPIyXW9dtij7A=
20231217124556.sql h1:3Ogc8234OVj3wzDeTf6MlbkyTHOSbmNSKNr9kKR5dRs=
3 changes: 3 additions & 0 deletions ts/testdata/models/Contact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
AfterCreate,
HasMany,
Length,
Index,
} from "sequelize-typescript";
import Phone from "./Phone";
import Email from "./Email";
Expand Down Expand Up @@ -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" })
Expand Down

0 comments on commit 8ea70d1

Please sign in to comment.