-
Notifications
You must be signed in to change notification settings - Fork 279
/
mysql-introspector.ts
75 lines (63 loc) · 1.83 KB
/
mysql-introspector.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {
DatabaseIntrospector,
DatabaseMetadata,
DatabaseMetadataOptions,
TableMetadata,
} from '../../introspection/database-introspector.js'
import {
MIGRATION_LOCK_TABLE,
MIGRATION_TABLE,
} from '../../migration/migration.js'
import { Kysely } from '../../kysely.js'
import { ColumnDataType } from '../../operation-node/data-type-node.js'
import { freeze } from '../../util/object-utils.js'
export class MysqlIntrospector implements DatabaseIntrospector {
readonly #db: Kysely<any>
constructor(db: Kysely<any>) {
this.#db = db
}
async getMetadata(
options: DatabaseMetadataOptions = { withInternalKyselyTables: false }
): Promise<DatabaseMetadata> {
let query = this.#db
.selectFrom('information_schema.columns')
.selectAll()
.where('table_schema', '=', this.#db.raw('database()'))
.castTo<RawColumnMetadata>()
if (!options.withInternalKyselyTables) {
query = query
.where('table_name', '!=', MIGRATION_TABLE)
.where('table_name', '!=', MIGRATION_LOCK_TABLE)
}
const rawColumns = await query.execute()
return {
tables: this.#parseTableMetadata(rawColumns),
}
}
#parseTableMetadata(columns: RawColumnMetadata[]): TableMetadata[] {
return columns.reduce<TableMetadata[]>((tables, it) => {
let table = tables.find((tbl) => tbl.name === it.TABLE_NAME)
if (!table) {
table = freeze({
name: it.TABLE_NAME,
columns: [],
})
tables.push(table)
}
table.columns.push(
freeze({
name: it.COLUMN_NAME,
dataType: it.DATA_TYPE,
isNullable: it.IS_NULLABLE === 'YES',
})
)
return tables
}, [])
}
}
interface RawColumnMetadata {
COLUMN_NAME: string
TABLE_NAME: string
IS_NULLABLE: 'YES' | 'NO'
DATA_TYPE: ColumnDataType
}