ff-admin-server/src/migrations/ormHelper.ts

106 lines
2.8 KiB
TypeScript
Raw Normal View History

export type ORMType = "int" | "bigint" | "boolean" | "date" | "datetime" | "time" | "text" | "varchar" | "uuid";
export type ORMDefault = "currentTimestamp" | "string" | "boolean" | "number" | "null";
export type ColumnConfig = {
type: string;
length?: string;
precision?: number;
isNullable: boolean;
};
export type Primary = {
isPrimary: boolean;
isGenerated: boolean;
generationStrategy: "increment" | "uuid" | "rowid" | "identity";
};
2025-01-30 15:58:34 +01:00
export function getTypeByORM(type: ORMType, nullable: boolean = false, length: number = 255): ColumnConfig {
2025-01-30 15:58:34 +01:00
const dbType = process.env.DB_TYPE;
const typeMap: Record<string, Record<ORMType, string>> = {
mysql: {
int: "int",
bigint: "bigint",
boolean: "tinyint",
date: "date",
datetime: "datetime",
time: "time",
text: "text",
varchar: "varchar",
uuid: "varchar",
2025-01-30 15:58:34 +01:00
},
postgres: {
int: "integer",
bigint: "bigint",
boolean: "boolean",
date: "date",
datetime: "timestamp",
time: "time",
text: "text",
varchar: "character varying",
uuid: "uuid",
2025-01-30 15:58:34 +01:00
},
sqlite: {
int: "integer",
bigint: "integer",
boolean: "integer",
date: "date",
datetime: "datetime",
2025-01-30 15:58:34 +01:00
time: "text",
text: "text",
varchar: "varchar",
uuid: "varchar",
},
};
let obj: ColumnConfig = {
type: typeMap[dbType]?.[type] || type,
isNullable: nullable,
};
if (type == "datetime") obj.precision = length;
else if (dbType != "sqlite" && (obj.type == "varchar" || type == "varchar")) obj.length = `${length}`;
else if (dbType != "postgres" && type == "uuid") obj.length = "36";
return obj;
}
export function getDefaultByORM<T = string | null>(type: ORMDefault, data?: string | number | boolean): T {
const dbType = process.env.DB_TYPE;
const typeMap: Record<string, Record<ORMDefault, string | null>> = {
mysql: {
currentTimestamp: `CURRENT_TIMESTAMP(${data ?? 6})`,
string: `'${data ?? ""}'`,
boolean: Boolean(data).toString(),
number: Number(data).toString(),
null: null,
},
postgres: {
currentTimestamp: `now()`,
string: `'${data ?? ""}'`,
boolean: Boolean(data) == true ? "true" : "false",
number: Number(data).toString(),
null: null,
},
sqlite: {
currentTimestamp: `datetime('now')`,
string: `'${data ?? ""}'`,
boolean: Boolean(data) == true ? "1" : "0",
number: Number(data).toString(),
null: null,
2025-01-30 15:58:34 +01:00
},
};
return (typeMap[dbType]?.[type] || type) as T;
2025-01-30 15:58:34 +01:00
}
export const isIncrementPrimary: Primary = {
isPrimary: true,
isGenerated: true,
generationStrategy: "increment",
};
export const isUUIDPrimary: Primary = {
isPrimary: true,
isGenerated: true,
generationStrategy: "uuid",
};