-
Notifications
You must be signed in to change notification settings - Fork 21
/
postgres-introspector.ts
147 lines (131 loc) · 4.07 KB
/
postgres-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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import {
DatabaseIntrospector,
DatabaseMetadata,
DatabaseMetadataOptions,
SchemaMetadata,
TableMetadata,
} from "kysely";
import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE } from "kysely";
import { Kysely } from "kysely";
import { sql } from "kysely";
export class PostgresIntrospector implements DatabaseIntrospector {
readonly #db: Kysely<any>;
constructor(db: Kysely<any>) {
this.#db = db;
}
async getSchemas(): Promise<SchemaMetadata[]> {
let rawSchemas = await this.#db
.selectFrom("pg_catalog.pg_namespace")
.select("nspname")
.$castTo<RawSchemaMetadata>()
.execute();
return rawSchemas.map((it) => ({ name: it.nspname }));
}
async getTables(
options: DatabaseMetadataOptions = { withInternalKyselyTables: false }
): Promise<TableMetadata[]> {
let query = this.#db
// column
.selectFrom("pg_catalog.pg_attribute as a")
// table
.innerJoin("pg_catalog.pg_class as c", "a.attrelid", "c.oid")
// table schema
.innerJoin("pg_catalog.pg_namespace as ns", "c.relnamespace", "ns.oid")
// column data type
.innerJoin("pg_catalog.pg_type as typ", "a.atttypid", "typ.oid")
// column data type schema
.innerJoin(
"pg_catalog.pg_namespace as dtns",
"typ.typnamespace",
"dtns.oid"
)
.select([
"a.attname as column",
"a.attnotnull as not_null",
"a.atthasdef as has_default",
"c.relname as table",
"c.relkind as table_type",
"ns.nspname as schema",
"typ.typname as type",
"dtns.nspname as type_schema",
// Detect if the column is auto incrementing by finding the sequence
// that is created for `serial` and `bigserial` columns.
this.#db
.selectFrom("pg_class")
.select(sql`true`.as("auto_incrementing"))
// Make sure the sequence is in the same schema as the table.
.whereRef("relnamespace", "=", "c.relnamespace")
.where("relkind", "=", "S")
.where("relname", "=", sql`c.relname || '_' || a.attname || '_seq'`)
.as("auto_incrementing"),
])
// r == normal table
.where((qb) =>
qb.where("c.relkind", "=", "r").orWhere("c.relkind", "=", "v")
)
.where("ns.nspname", "!~", "^pg_")
.where("ns.nspname", "!=", "information_schema")
// No system columns
.where("a.attnum", ">=", 0)
.where("a.attisdropped", "!=", true)
.orderBy("ns.nspname")
.orderBy("c.relname")
.orderBy("a.attnum")
.$castTo<RawColumnMetadata>();
if (!options.withInternalKyselyTables) {
query = query
.where("c.relname", "!=", DEFAULT_MIGRATION_TABLE)
.where("c.relname", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
}
const rawColumns = await query.execute();
return this.#parseTableMetadata(rawColumns);
}
async getMetadata(
options?: DatabaseMetadataOptions
): Promise<DatabaseMetadata> {
return {
tables: await this.getTables(options),
};
}
#parseTableMetadata(columns: RawColumnMetadata[]): TableMetadata[] {
return columns.reduce<TableMetadata[]>((tables, it) => {
let table = tables.find(
(tbl) => tbl.name === it.table && tbl.schema === it.schema
);
if (!table) {
table = Object.freeze({
name: it.table,
isView: it.table_type === "v",
schema: it.schema,
columns: [],
});
tables.push(table);
}
table.columns.push(
Object.freeze({
name: it.column,
dataType: it.type,
dataTypeSchema: it.type_schema,
isNullable: !it.not_null,
isAutoIncrementing: !!it.auto_incrementing,
hasDefaultValue: it.has_default,
})
);
return tables;
}, []);
}
}
interface RawSchemaMetadata {
nspname: string;
}
interface RawColumnMetadata {
column: string;
table: string;
table_type: string;
schema: string;
not_null: boolean;
has_default: boolean;
type: string;
type_schema: string;
auto_incrementing: boolean | null;
}