From 6104b9aedeb1668f24f704470c892b48108a869f Mon Sep 17 00:00:00 2001 From: Shigma <1700011071@pku.edu.cn> Date: Fri, 23 Apr 2021 03:41:53 +0800 Subject: [PATCH] feat(mysql): support orm foreign key, fix #243 --- packages/koishi-core/src/database.ts | 7 +++++-- packages/plugin-mysql/src/database.ts | 6 +++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/koishi-core/src/database.ts b/packages/koishi-core/src/database.ts index 55bf3490fa..c2cffa0d3c 100644 --- a/packages/koishi-core/src/database.ts +++ b/packages/koishi-core/src/database.ts @@ -17,15 +17,18 @@ export namespace Tables { export type Field = string & keyof Tables[T] interface Meta { + type?: 'incremental' primary?: keyof O unique?: (keyof O)[] - type?: 'incremental' + foreign?: { + [K in keyof O]: [TableType, string] + } } export const config: { [T in TableType]?: Meta } = {} export function extend(name: T, meta?: Meta) { - config[name] = { primary: 'id', unique: [], type: 'incremental', ...meta } as any + config[name] = { primary: 'id', unique: [], type: 'incremental', foreign: {}, ...meta } as any } extend('user') diff --git a/packages/plugin-mysql/src/database.ts b/packages/plugin-mysql/src/database.ts index 8bb9149167..e888debe16 100644 --- a/packages/plugin-mysql/src/database.ts +++ b/packages/plugin-mysql/src/database.ts @@ -82,7 +82,7 @@ class MysqlDatabase { const cols = Object.keys(table) .filter((key) => typeof table[key] !== 'function') .map((key) => `${escapeId(key)} ${MysqlDatabase.Domain.definition(table[key])}`) - const { primary, unique } = KoishiTables.config[name as TableType] + const { primary, unique, foreign } = KoishiTables.config[name as TableType] cols.push(`primary key (${escapeId(primary)})`) for (const key of unique) { cols.push(`unique index (${escapeId(key)})`) @@ -92,6 +92,10 @@ class MysqlDatabase { cols.push(`unique index (${escapeId(key)})`) } } + for (const key in foreign) { + const [table, key2] = foreign[key] + cols.push(`foreign key (${escapeId(key)}) references ${escapeId(table)} (${escapeId(key2)})`) + } logger.info('auto creating table %c', name) await this.query(`CREATE TABLE ?? (${cols.join(',')}) COLLATE = ?`, [name, this.config.charset]) } else {