Skip to content

Commit

Permalink
feat(mysql): support orm foreign key, fix #243
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Apr 22, 2021
1 parent 9139e7a commit 6104b9a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
7 changes: 5 additions & 2 deletions packages/koishi-core/src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ export namespace Tables {
export type Field<T extends TableType> = string & keyof Tables[T]

interface Meta<O> {
type?: 'incremental'
primary?: keyof O
unique?: (keyof O)[]
type?: 'incremental'
foreign?: {
[K in keyof O]: [TableType, string]
}
}

export const config: { [T in TableType]?: Meta<Tables[T]> } = {}

export function extend<T extends TableType>(name: T, meta?: Meta<Tables[T]>) {
config[name] = { primary: 'id', unique: [], type: 'incremental', ...meta } as any
config[name] = { primary: 'id', unique: [], type: 'incremental', foreign: {}, ...meta } as any
}

extend('user')
Expand Down
6 changes: 5 additions & 1 deletion packages/plugin-mysql/src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)})`)
Expand All @@ -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 {
Expand Down

0 comments on commit 6104b9a

Please sign in to comment.