-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathPostgresMetaTables.ts
257 lines (247 loc) · 7.26 KB
/
PostgresMetaTables.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { ident, literal } from 'pg-format'
import { DEFAULT_SYSTEM_SCHEMAS } from './constants.js'
import { coalesceRowsToArray, filterByList } from './helpers.js'
import columnsSql from './sql/columns.sql'
import tablesSql from './sql/tables.sql'
import {
PostgresMetaResult,
PostgresTable,
PostgresTableCreate,
PostgresTableUpdate,
} from './types.js'
export default class PostgresMetaTables {
query: (sql: string) => Promise<PostgresMetaResult<any>>
constructor(query: (sql: string) => Promise<PostgresMetaResult<any>>) {
this.query = query
}
async list(options: {
includeSystemSchemas?: boolean
includedSchemas?: string[]
excludedSchemas?: string[]
limit?: number
offset?: number
includeColumns: false
}): Promise<PostgresMetaResult<(PostgresTable & { columns: never })[]>>
async list(options?: {
includeSystemSchemas?: boolean
includedSchemas?: string[]
excludedSchemas?: string[]
limit?: number
offset?: number
includeColumns?: boolean
}): Promise<PostgresMetaResult<(PostgresTable & { columns: unknown[] })[]>>
async list({
includeSystemSchemas = false,
includedSchemas,
excludedSchemas,
limit,
offset,
includeColumns = true,
}: {
includeSystemSchemas?: boolean
includedSchemas?: string[]
excludedSchemas?: string[]
limit?: number
offset?: number
includeColumns?: boolean
} = {}): Promise<PostgresMetaResult<PostgresTable[]>> {
let sql = generateEnrichedTablesSql({ includeColumns })
const filter = filterByList(
includedSchemas,
excludedSchemas,
!includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
)
if (filter) {
sql += ` where schema ${filter}`
}
if (limit) {
sql += ` limit ${limit}`
}
if (offset) {
sql += ` offset ${offset}`
}
return await this.query(sql)
}
async retrieve({ id }: { id: number }): Promise<PostgresMetaResult<PostgresTable>>
async retrieve({
name,
schema,
}: {
name: string
schema: string
}): Promise<PostgresMetaResult<PostgresTable>>
async retrieve({
id,
name,
schema = 'public',
}: {
id?: number
name?: string
schema?: string
}): Promise<PostgresMetaResult<PostgresTable>> {
if (id) {
const sql = `${generateEnrichedTablesSql({
includeColumns: true,
})} where tables.id = ${literal(id)};`
const { data, error } = await this.query(sql)
if (error) {
return { data, error }
} else if (data.length === 0) {
return { data: null, error: { message: `Cannot find a table with ID ${id}` } }
} else {
return { data: data[0], error }
}
} else if (name) {
const sql = `${generateEnrichedTablesSql({
includeColumns: true,
})} where tables.name = ${literal(name)} and tables.schema = ${literal(schema)};`
const { data, error } = await this.query(sql)
if (error) {
return { data, error }
} else if (data.length === 0) {
return {
data: null,
error: { message: `Cannot find a table named ${name} in schema ${schema}` },
}
} else {
return { data: data[0], error }
}
} else {
return { data: null, error: { message: 'Invalid parameters on table retrieve' } }
}
}
async create({
name,
schema = 'public',
comment,
}: PostgresTableCreate): Promise<PostgresMetaResult<PostgresTable>> {
const tableSql = `CREATE TABLE ${ident(schema)}.${ident(name)} ();`
const commentSql =
comment === undefined
? ''
: `COMMENT ON TABLE ${ident(schema)}.${ident(name)} IS ${literal(comment)};`
const sql = `BEGIN; ${tableSql} ${commentSql} COMMIT;`
const { error } = await this.query(sql)
if (error) {
return { data: null, error }
}
return await this.retrieve({ name, schema })
}
async update(
id: number,
{
name,
schema,
rls_enabled,
rls_forced,
replica_identity,
replica_identity_index,
primary_keys,
comment,
}: PostgresTableUpdate
): Promise<PostgresMetaResult<PostgresTable>> {
const { data: old, error } = await this.retrieve({ id })
if (error) {
return { data: null, error }
}
const alter = `ALTER TABLE ${ident(old!.schema)}.${ident(old!.name)}`
const schemaSql = schema === undefined ? '' : `${alter} SET SCHEMA ${ident(schema)};`
let nameSql = ''
if (name !== undefined && name !== old!.name) {
const currentSchema = schema === undefined ? old!.schema : schema
nameSql = `ALTER TABLE ${ident(currentSchema)}.${ident(old!.name)} RENAME TO ${ident(name)};`
}
let enableRls = ''
if (rls_enabled !== undefined) {
const enable = `${alter} ENABLE ROW LEVEL SECURITY;`
const disable = `${alter} DISABLE ROW LEVEL SECURITY;`
enableRls = rls_enabled ? enable : disable
}
let forceRls = ''
if (rls_forced !== undefined) {
const enable = `${alter} FORCE ROW LEVEL SECURITY;`
const disable = `${alter} NO FORCE ROW LEVEL SECURITY;`
forceRls = rls_forced ? enable : disable
}
let replicaSql = ''
if (replica_identity === undefined) {
// skip
} else if (replica_identity === 'INDEX') {
replicaSql = `${alter} REPLICA IDENTITY USING INDEX ${replica_identity_index};`
} else {
replicaSql = `${alter} REPLICA IDENTITY ${replica_identity};`
}
let primaryKeysSql = ''
if (primary_keys === undefined) {
// skip
} else {
if (old!.primary_keys.length !== 0) {
primaryKeysSql += `
DO $$
DECLARE
r record;
BEGIN
SELECT conname
INTO r
FROM pg_constraint
WHERE contype = 'p' AND conrelid = ${literal(id)};
EXECUTE ${literal(`${alter} DROP CONSTRAINT `)} || quote_ident(r.conname);
END
$$;
`
}
if (primary_keys.length === 0) {
// skip
} else {
primaryKeysSql += `${alter} ADD PRIMARY KEY (${primary_keys
.map((x) => ident(x.name))
.join(',')});`
}
}
const commentSql =
comment === undefined
? ''
: `COMMENT ON TABLE ${ident(old!.schema)}.${ident(old!.name)} IS ${literal(comment)};`
// nameSql must be last, right below schemaSql
const sql = `
BEGIN;
${enableRls}
${forceRls}
${replicaSql}
${primaryKeysSql}
${commentSql}
${schemaSql}
${nameSql}
COMMIT;`
{
const { error } = await this.query(sql)
if (error) {
return { data: null, error }
}
}
return await this.retrieve({ id })
}
async remove(id: number, { cascade = false } = {}): Promise<PostgresMetaResult<PostgresTable>> {
const { data: table, error } = await this.retrieve({ id })
if (error) {
return { data: null, error }
}
const sql = `DROP TABLE ${ident(table!.schema)}.${ident(table!.name)} ${
cascade ? 'CASCADE' : 'RESTRICT'
};`
{
const { error } = await this.query(sql)
if (error) {
return { data: null, error }
}
}
return { data: table!, error: null }
}
}
const generateEnrichedTablesSql = ({ includeColumns }: { includeColumns: boolean }) => `
with tables as (${tablesSql})
${includeColumns ? `, columns as (${columnsSql})` : ''}
select
*
${includeColumns ? `, ${coalesceRowsToArray('columns', 'columns.table_id = tables.id')}` : ''}
from tables`