75 lines
2.5 KiB
TypeScript
75 lines
2.5 KiB
TypeScript
import type { Sequelize } from "sequelize";
|
|
import { DataTypes, QueryTypes } from "sequelize";
|
|
|
|
import { ticketColumns } from "./support-record-relational";
|
|
import { initializeSupportChildren } from "./support-record-schema";
|
|
|
|
export async function migrateTickets(database: Sequelize) {
|
|
const query = database.getQueryInterface();
|
|
const tables = await database.query<{ name: string }>(
|
|
"SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()",
|
|
{ type: QueryTypes.SELECT }
|
|
);
|
|
|
|
const fk = (model: string, nullable = false) => ({
|
|
type: DataTypes.UUID,
|
|
allowNull: nullable,
|
|
references: { model, key: "id" },
|
|
onDelete: "RESTRICT",
|
|
});
|
|
|
|
const definitions = [
|
|
[
|
|
"ticket_counter",
|
|
{
|
|
id: { type: DataTypes.INTEGER, primaryKey: true },
|
|
nextNumber: { type: DataTypes.INTEGER, allowNull: false },
|
|
},
|
|
],
|
|
[
|
|
"tickets",
|
|
{
|
|
id: { type: DataTypes.UUID, primaryKey: true },
|
|
companyId: fk("companies"),
|
|
reference: { type: DataTypes.STRING(40), allowNull: false, unique: true },
|
|
requestKey: { type: DataTypes.UUID, allowNull: false, unique: true },
|
|
requesterId: fk("company_contacts", true),
|
|
assigneeId: fk("users", true),
|
|
...ticketColumns,
|
|
},
|
|
],
|
|
[
|
|
"ticket_revisions",
|
|
{
|
|
id: { type: DataTypes.UUID, primaryKey: true },
|
|
ticketId: fk("tickets"),
|
|
actorId: fk("users"),
|
|
requesterId: fk("company_contacts", true),
|
|
assigneeId: fk("users", true),
|
|
...ticketColumns,
|
|
recordedAt: { type: DataTypes.STRING(30), allowNull: false },
|
|
position: { type: DataTypes.INTEGER, allowNull: false },
|
|
},
|
|
],
|
|
] as const;
|
|
|
|
for (const [table, columns] of definitions) {
|
|
if (!tables.some((item) => item.name === table)) {
|
|
await query.createTable(table, columns);
|
|
}
|
|
}
|
|
await database.query("INSERT IGNORE INTO ticket_counter (id,nextNumber) VALUES (1,1)");
|
|
const indexes = await database.query<{ name: string }>(
|
|
"SELECT DISTINCT INDEX_NAME AS name FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='ticket_revisions'",
|
|
{ type: QueryTypes.SELECT }
|
|
);
|
|
|
|
if (!indexes.some((item) => item.name === "ticket_revision_position")) {
|
|
await query.addIndex("ticket_revisions", ["ticketId", "position"], {
|
|
name: "ticket_revision_position",
|
|
unique: true,
|
|
});
|
|
}
|
|
await initializeSupportChildren(database, "tickets", "ticket_revisions");
|
|
}
|