1+ import type { MigrationInterface , QueryRunner } from 'typeorm'
2+
3+ export class AddTagsSchema2026020600000 implements MigrationInterface {
4+ name = 'AddTagsSchema2026020600000'
5+
6+ async up ( queryRunner : QueryRunner ) : Promise < void > {
7+ if ( ! ( await queryRunner . hasTable ( 'tags' ) ) ) {
8+ await queryRunner . query ( `
9+ CREATE TABLE "tags" (
10+ "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
11+ "name" text NOT NULL UNIQUE,
12+ "created_at" text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
13+ "updated_at" text NOT NULL DEFAULT (CURRENT_TIMESTAMP)
14+ )
15+ ` )
16+ }
17+
18+ if ( ! ( await queryRunner . hasTable ( 'student_tags' ) ) ) {
19+ await queryRunner . query ( `
20+ CREATE TABLE "student_tags" (
21+ "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
22+ "student_id" integer NOT NULL,
23+ "tag_id" integer NOT NULL,
24+ "created_at" text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
25+ FOREIGN KEY ("student_id") REFERENCES "students"("id") ON DELETE CASCADE,
26+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON DELETE CASCADE,
27+ UNIQUE("student_id", "tag_id")
28+ )
29+ ` )
30+ }
31+
32+ await queryRunner . query (
33+ `CREATE INDEX IF NOT EXISTS "IDX_student_tags_student_id" ON "student_tags" ("student_id")`
34+ )
35+ await queryRunner . query (
36+ `CREATE INDEX IF NOT EXISTS "IDX_student_tags_tag_id" ON "student_tags" ("tag_id")`
37+ )
38+
39+ await queryRunner . query ( `
40+ INSERT OR IGNORE INTO "tags" ("name") VALUES
41+ ('优秀生'),
42+ ('班干部'),
43+ ('勤奋'),
44+ ('活跃'),
45+ ('进步快')
46+ ` )
47+ }
48+
49+ async down ( queryRunner : QueryRunner ) : Promise < void > {
50+ await queryRunner . query ( `DROP TABLE IF EXISTS "student_tags"` )
51+ await queryRunner . query ( `DROP TABLE IF EXISTS "tags"` )
52+ }
53+ }
0 commit comments