Skip to content

Commit

Permalink
support postgres create enums statements (#13)
Browse files Browse the repository at this point in the history
* ts: support postgres create enums statments

* js:  support postgres create enums statments
  • Loading branch information
ronenlu authored Dec 20, 2023
1 parent 8ea70d1 commit d06935e
Show file tree
Hide file tree
Showing 19 changed files with 92 additions and 20 deletions.
14 changes: 14 additions & 0 deletions js/src/sequelize_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ const loadSequelizeModels = (dialect, ...models) => {
const attr = sequelize
.getQueryInterface()
.queryGenerator.attributesToSQL(def.getAttributes(), { ...def.options });
// create enum types for postgres
if (dialect === "postgres") {
for (const key in attr) {
if (!attr[key].startsWith("ENUM")) {
continue;
}
const enumValues = attr[key].substring(
attr[key].indexOf("("),
attr[key].lastIndexOf(")") + 1,
);
const enumName = `enum_${def.tableName}_${key}`;
sql += `CREATE TYPE "${enumName}" AS ENUM${enumValues};\n`;
}
}
sql +=
sequelize
.getQueryInterface()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CREATE TABLE `Recipes` (
`title` varchar(255) NOT NULL,
`description` text NOT NULL,
`instructions` text NOT NULL,
`meal` enum('breakfast','lunch','dinner','dessert') NULL DEFAULT "lunch",
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
`deletedAt` datetime NULL,
Expand Down
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:iiEZ5BKOIIrn/v6gnOMLybPtmdE+CF9zgQGkBUNTSak=
20231217121351.sql h1:OloC5SnSg1SNwiBwdJ8/0JzGE+z1IJxrC7PZzCE52pM=
h1:cI6IUVRHfJbkk65AWg0ge7Xeb1RGs9oMJkszrVexwss=
20231218113756.sql h1:UGw8bFPavN0GrLFrN0nAl+P7VFaOX/a2yKZXq4P29fA=
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
-- Create enum type "enum_Recipes_meal"
CREATE TYPE "public"."enum_Recipes_meal" AS ENUM ('breakfast', 'lunch', 'dinner', 'dessert');
-- Create "Ingredients" table
CREATE TABLE "public"."Ingredients" (
"id" serial NOT NULL,
Expand All @@ -13,6 +15,7 @@ CREATE TABLE "public"."Recipes" (
"title" character varying(255) NOT NULL,
"description" text NOT NULL,
"instructions" text NOT NULL,
"meal" "public"."enum_Recipes_meal" NULL DEFAULT 'lunch',
"createdAt" timestamptz NOT NULL,
"updatedAt" timestamptz NOT NULL,
"deletedAt" timestamptz NULL,
Expand Down
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:uJ7wU+6p3ohypex+0pRKcsw86vEtzStoE6JJLatVoAo=
20231217121326.sql h1:d2jBf2rcjqt+l7WZhoeosIndYjndY0eAkBtcm4e8PcE=
h1:JCDQK9pnfdBoi3LjhfZWKQ0vmrl01yT+z/iI9z2xcO0=
20231218113750.sql h1:G5dZYzfZamTnaCw/gsxOz0ZtT2QuxwC+OwmeOaaKKbQ=
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ CREATE TABLE `Recipes` (
`title` varchar NOT NULL,
`description` text NOT NULL,
`instructions` text NOT NULL,
`meal` text NULL DEFAULT 'lunch',
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
`deletedAt` datetime NULL
Expand Down
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:BYAmffj+Yu0UriXgwsQxyg2oirRqrQYz2VS/GUE2oL4=
20231217121207.sql h1:fMjw2OFFzGMAzehqpEZjFdbgbHjyCBEwSiSG/rhNDek=
h1:XZPNKrbW25KYA84JijT+3mt1j7v061dL4noOCiKC1Ws=
20231218113759.sql h1:Xoq/BkJqpRZ05eyN12Ub/8SOTm/zHVyxelGCmBAtAl4=
5 changes: 5 additions & 0 deletions js/testdata/models/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ module.exports = function (sequelize, DataTypes) {
type: DataTypes.TEXT,
allowNull: false,
},
meal: {
type: DataTypes.ENUM,
values: ["breakfast", "lunch", "dinner", "dessert"],
defaultValue: "lunch",
},
},
{
paranoid: true,
Expand Down
2 changes: 1 addition & 1 deletion ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ y.command(
dialect: argv.dialect,
models: [absolutePath + "/*.ts"],
} as SequelizeOptions);
console.log(loadSQL(sequelize));
console.log(loadSQL(sequelize, argv.dialect));
} catch (e) {
if (e instanceof Error) {
console.error(e.message);
Expand Down
2 changes: 1 addition & 1 deletion ts/src/sequelize_schema.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +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;
export declare const loadSQL: (sequelize: Sequelize, dialect: string) => string;
20 changes: 17 additions & 3 deletions ts/src/sequelize_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,41 @@ var loadModels = function (dialect, models) {
dialect: dialect,
models: models
});
return (0, exports.loadSQL)(sequelize);
return (0, exports.loadSQL)(sequelize, dialect);
};
exports.loadModels = loadModels;
var loadSQL = function (sequelize) {
var loadSQL = function (sequelize, dialect) {
var _a, _b, _c;
if (!validDialects.includes(dialect)) {
throw new Error("Invalid dialect ".concat(dialect));
}
var orderedModels = (_a = sequelize.modelManager
.getModelsTopoSortedByForeignKey()) === null || _a === void 0 ? void 0 : _a.reverse();
if (!orderedModels) {
throw new Error("no models found");
}
var sql = "";
var queryGenerator = sequelize.getQueryInterface().queryGenerator;
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 = queryGenerator.attributesToSQL(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
def.getAttributes(), Object.assign({}, def.options));
// create enum types for postgres
if (dialect === "postgres") {
for (var key in attr) {
if (!attr[key].startsWith("ENUM")) {
continue;
}
var enumValues = attr[key].substring(attr[key].indexOf("("), attr[key].lastIndexOf(")") + 1);
var enumName = "enum_".concat(def.tableName, "_").concat(key);
sql += "CREATE TYPE \"".concat(enumName, "\" AS ENUM").concat(enumValues, ";\n");
}
}
sql +=
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down
23 changes: 20 additions & 3 deletions ts/src/sequelize_schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,23 @@ export const loadModels = (dialect: string, models: ModelCtor[]) => {
dialect: dialect,
models: models,
} as SequelizeOptions);
return loadSQL(sequelize);
return loadSQL(sequelize, dialect);
};

export const loadSQL = (sequelize: Sequelize) => {
export const loadSQL = (sequelize: Sequelize, dialect: string) => {
if (!validDialects.includes(dialect)) {
throw new Error(`Invalid dialect ${dialect}`);
}
const orderedModels = sequelize.modelManager
.getModelsTopoSortedByForeignKey()
?.reverse();
if (!orderedModels) {
throw new Error("no models found");
}
let sql = "";
const queryGenerator = sequelize.getQueryInterface().queryGenerator;
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 = queryGenerator.attributesToSQL(
Expand All @@ -34,6 +37,20 @@ export const loadSQL = (sequelize: Sequelize) => {
def.getAttributes(),
Object.assign({}, def.options),
);
// create enum types for postgres
if (dialect === "postgres") {
for (const key in attr) {
if (!attr[key].startsWith("ENUM")) {
continue;
}
const enumValues = attr[key].substring(
attr[key].indexOf("("),
attr[key].lastIndexOf(")") + 1,
);
const enumName = `enum_${def.tableName}_${key}`;
sql += `CREATE TYPE "${enumName}" AS ENUM${enumValues};\n`;
}
}
sql +=
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ CREATE TABLE `contact` (
CREATE TABLE `email` (
`id` int NOT NULL AUTO_INCREMENT,
`email` varchar(60) NOT NULL,
`subscription` enum('free','basic','premium') NULL DEFAULT "free",
`contact_id` int NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
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:rRnJAJPIaK0/o4jqGM/wJvJYwl86hJWkAFKaqZ8vE+8=
20231217124500.sql h1:f+vFf2MPBTjigPYuT2pzyuntsgcUhXasXK10k13zWtw=
h1:FgLFaCDhD0U47MWzfkZpP75HuvunyRLwvOXnkTl8PBM=
20231218100006.sql h1:AN6HBOp/myVOSUmGq4VCwdJjoQxWEj0f5k8Y9JRKVuI=
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
-- Create enum type "enum_email_subscription"
CREATE TYPE "public"."enum_email_subscription" AS ENUM ('free', 'basic', 'premium');
-- Create "contact" table
CREATE TABLE "public"."contact" (
"id" serial NOT NULL,
Expand All @@ -13,6 +15,7 @@ CREATE UNIQUE INDEX "name-alias" ON "public"."contact" ("name", "alias");
CREATE TABLE "public"."email" (
"id" serial NOT NULL,
"email" character varying(60) NOT NULL,
"subscription" "public"."enum_email_subscription" NULL DEFAULT 'free',
"contact_id" integer NOT NULL,
"created_at" timestamptz NOT NULL,
"updated_at" timestamptz 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:XIYtaHM79msFK/eAOwe/Wv6kzA3aMwoh3/D1ztZ1e6c=
20231217124605.sql h1:QriWPdvwTcmZ3/M3ngm9/oJS1waROy1BJA/JNd8C0Bs=
h1:/nXukveAulETUVN5Z0bzgsElJANsXeiSFkyGquPVJZI=
20231218095939.sql h1:RMBy+CArZu+YaCd5OuDlyq5J78/OY/4I2CuKaTfaD+I=
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ CREATE TABLE `phone` (
CREATE TABLE `email` (
`id` integer NULL PRIMARY KEY AUTOINCREMENT,
`email` varchar NOT NULL,
`subscription` text NULL DEFAULT 'free',
`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:CKVzjBvTtLsH1BjT76EdtN91cCSsF9hPIyXW9dtij7A=
20231217124556.sql h1:3Ogc8234OVj3wzDeTf6MlbkyTHOSbmNSKNr9kKR5dRs=
h1:ZWfD8ALiOT7OQQFHUD3qRcl9QS/pCY73wQh/k3wcp7Y=
20231218100055.sql h1:HH5klns2KwrPC9Oe8FiIwxaI8DZul08igCINkcHqYdk=
12 changes: 12 additions & 0 deletions ts/testdata/models/Email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ const EMAIL_VALIDATION = {
addressMaxLength: 190,
};

enum Subscription {
FREE = "free",
BASIC = "basic",
PREMIUM = "premium",
}

@DefaultScope(() => ({
attributes: {
exclude: ["contact_id", "created_at", "updated_at"],
Expand All @@ -49,6 +55,12 @@ class Email extends Model {
@Column(DataType.STRING(60))
email!: string;

@Column({
type: DataType.ENUM(...Object.values(Subscription)),
defaultValue: Subscription.FREE,
})
subscription!: Subscription;

@AllowNull(false)
@ForeignKey(() => Contact)
@Column(DataType.INTEGER)
Expand Down

0 comments on commit d06935e

Please sign in to comment.