107 lines
2.8 KiB
TypeScript
107 lines
2.8 KiB
TypeScript
import { DB_TYPE } from "../env.defaults";
|
|
|
|
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";
|
|
};
|
|
|
|
export function getTypeByORM(type: ORMType, nullable: boolean = false, length: number = 255): ColumnConfig {
|
|
const dbType = 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",
|
|
},
|
|
postgres: {
|
|
int: "integer",
|
|
bigint: "bigint",
|
|
boolean: "boolean",
|
|
date: "date",
|
|
datetime: "timestamp",
|
|
time: "time",
|
|
text: "text",
|
|
varchar: "character varying",
|
|
uuid: "uuid",
|
|
},
|
|
sqlite: {
|
|
int: "integer",
|
|
bigint: "integer",
|
|
boolean: "integer",
|
|
date: "date",
|
|
datetime: "datetime",
|
|
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 = 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,
|
|
},
|
|
};
|
|
|
|
return (typeMap[dbType]?.[type] || type) as T;
|
|
}
|
|
|
|
export const isIncrementPrimary: Primary = {
|
|
isPrimary: true,
|
|
isGenerated: true,
|
|
generationStrategy: "increment",
|
|
};
|
|
|
|
export const isUUIDPrimary: Primary = {
|
|
isPrimary: true,
|
|
isGenerated: true,
|
|
generationStrategy: "uuid",
|
|
};
|