-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathpostgres.ts
More file actions
551 lines (505 loc) · 15.2 KB
/
postgres.ts
File metadata and controls
551 lines (505 loc) · 15.2 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import fs from "fs"
import {
Integration,
DatasourceFieldType,
QueryType,
SqlQuery,
Table,
DatasourcePlus,
DatasourceFeature,
ConnectionInfo,
SourceName,
Schema,
TableSourceType,
DatasourcePlusQueryResponse,
SqlClient,
EnrichedQueryJson,
SqlQueryBinding,
} from "@budibase/types"
import {
getSqlQuery,
buildExternalTableId,
generateColumnDefinition,
finaliseExternalTables,
checkExternalTables,
HOST_ADDRESS,
} from "./utils"
import { PostgresColumn } from "./base/types"
import { escapeDangerousCharacters } from "../utilities"
import { Client, ClientConfig, types } from "pg"
import { getReadableErrorMessage } from "./base/errorMapping"
import { exec } from "child_process"
import { storeTempFile } from "../utilities/fileSystem"
import { env, sql } from "@budibase/backend-core"
// Return "date" and "timestamp" types as plain strings.
// This lets us reference the original stored timezone.
// types is undefined when running in a test env for some reason.
if (types) {
types.setTypeParser(1114, (val: unknown) => val) // timestamp
types.setTypeParser(1082, (val: unknown) => val) // date
types.setTypeParser(1184, (val: unknown) => val) // timestampz
}
const JSON_REGEX = /'{\s*.*?\s*}'::json/gs
const Sql = sql.Sql
interface PostgresConfig {
host: string
port: number
database: string
user: string
password: string
schema: string
ssl?: boolean
ca?: string
clientKey?: string
clientCert?: string
rejectUnauthorized?: boolean
}
const SCHEMA: Integration = {
docs: "https://node-postgres.com",
plus: true,
friendlyName: "PostgreSQL",
type: "Relational",
description:
"PostgreSQL, also known as Postgres, is a free and open-source relational database management system emphasizing extensibility and SQL compliance.",
features: {
[DatasourceFeature.CONNECTION_CHECKING]: true,
[DatasourceFeature.FETCH_TABLE_NAMES]: true,
[DatasourceFeature.EXPORT_SCHEMA]: true,
},
datasource: {
host: {
type: DatasourceFieldType.STRING,
default: HOST_ADDRESS,
required: true,
},
port: {
type: DatasourceFieldType.NUMBER,
required: true,
default: 5432,
},
database: {
type: DatasourceFieldType.STRING,
default: "postgres",
required: true,
},
user: {
type: DatasourceFieldType.STRING,
default: "root",
required: true,
},
password: {
type: DatasourceFieldType.PASSWORD,
default: "root",
required: true,
},
schema: {
type: DatasourceFieldType.STRING,
default: "public",
required: true,
},
ssl: {
type: DatasourceFieldType.BOOLEAN,
default: false,
required: false,
},
rejectUnauthorized: {
type: DatasourceFieldType.BOOLEAN,
default: false,
required: false,
},
ca: {
display: "Server CA",
type: DatasourceFieldType.LONGFORM,
default: false,
required: false,
},
clientKey: {
display: "Client key",
type: DatasourceFieldType.LONGFORM,
default: false,
required: false,
},
clientCert: {
display: "Client cert",
type: DatasourceFieldType.LONGFORM,
default: false,
required: false,
},
},
query: {
create: {
type: QueryType.SQL,
},
read: {
type: QueryType.SQL,
},
update: {
type: QueryType.SQL,
},
delete: {
type: QueryType.SQL,
},
},
}
function processBindings(bindings: SqlQueryBinding): SqlQueryBinding {
return bindings.map(binding => {
if (binding instanceof Date) {
return binding.toISOString()
}
return binding
})
}
class PostgresIntegration extends Sql implements DatasourcePlus {
private readonly client: Client
private readonly config: PostgresConfig
private index = 1
private open: boolean
PRIMARY_KEYS_SQL = () => `
SELECT pg_namespace.nspname table_schema
, pg_class.relname table_name
, pg_attribute.attname primary_key
FROM pg_class
JOIN pg_index ON pg_class.oid = pg_index.indrelid AND pg_index.indisprimary
JOIN pg_attribute ON pg_attribute.attrelid = pg_class.oid AND pg_attribute.attnum = ANY(pg_index.indkey)
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
WHERE pg_namespace.nspname = ANY(current_schemas(false))
AND pg_table_is_visible(pg_class.oid)
AND pg_class.relkind = 'r';
`
ENUM_VALUES = () => `
SELECT t.typname,
e.enumlabel
FROM pg_type t
JOIN pg_enum e on t.oid = e.enumtypid
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace;
`
VIEWS_SQL = () => `
SELECT DISTINCT pg_class.relname as view_name,
pg_namespace.nspname as table_schema,
pg_get_viewdef(pg_class.oid) as definition
FROM pg_class
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
WHERE pg_namespace.nspname = ANY(current_schemas(false))
AND pg_table_is_visible(pg_class.oid)
AND pg_class.relkind = 'v';
`
COLUMNS_SQL = () => `
SELECT columns.*
FROM information_schema.columns columns
JOIN pg_class pg_class ON pg_class.relname = columns.table_name
JOIN pg_namespace name_space ON name_space.oid = pg_class.relnamespace
WHERE columns.table_schema = ANY(current_schemas(false))
AND columns.table_schema = name_space.nspname
AND pg_table_is_visible(pg_class.oid)
AND pg_class.relkind = 'r';
`
constructor(config: PostgresConfig) {
super(SqlClient.POSTGRES)
this.config = config
let newConfig: ClientConfig = {
...this.config,
ssl: this.config.ssl
? {
rejectUnauthorized: this.config.rejectUnauthorized,
ca: this.config.ca,
key: this.config.clientKey,
cert: this.config.clientCert,
}
: undefined,
}
this.client = new Client(newConfig)
this.open = false
}
async testConnection() {
const response: ConnectionInfo = {
connected: false,
}
try {
await this.openConnection()
response.connected = true
} catch (e: any) {
if (typeof e.message === "string" && e.message !== "") {
response.error = e.message as string
} else if (typeof e.code === "string" && e.code !== "") {
response.error = e.code
} else {
response.error = "Unknown error"
}
} finally {
await this.closeConnection()
}
return response
}
getBindingIdentifier(): string {
return `$${this.index++}`
}
getStringConcat(parts: string[]): string {
return parts.join(" || ")
}
async openConnection() {
if (this.open) {
return
}
try {
await this.client.connect()
} catch (error) {
if ((error as Error).message.includes("already been connected")) {
// Already connected, continue
} else {
throw error
}
}
if (!this.config.schema) {
this.config.schema = "public"
}
const search_path = this.config.schema
.split(",")
.map(item => `"${item.trim()}"`)
await this.client.query(`SET search_path TO ${search_path.join(",")};`)
await this.client.query(`SET TIME ZONE 'UTC';`)
this.open = true
}
closeConnection() {
const pg = this
return new Promise<void>((resolve, reject) => {
this.client.end((err: any) => {
pg.open = false
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
async internalQuery(query: SqlQuery, close = true) {
if (!this.open) {
await this.openConnection()
}
const client = this.client
this.index = 1
// need to handle a specific issue with json data types in postgres,
// new lines inside the JSON data will break it
if (query && query.sql) {
const matches = query.sql.match(JSON_REGEX)
if (matches && matches.length > 0) {
for (let match of matches) {
const escaped = escapeDangerousCharacters(match)
query.sql = query.sql.replace(match, escaped)
}
}
}
try {
const bindings = processBindings(query.bindings || [])
this.log(query.sql, bindings)
return await client.query(query.sql, bindings)
} catch (err: any) {
await this.closeConnection()
let readableMessage = getReadableErrorMessage(
SourceName.POSTGRES,
err.code
)
if (readableMessage) {
throw new Error(readableMessage)
} else {
throw new Error(err.message as string)
}
} finally {
if (close) {
await this.closeConnection()
}
}
}
/**
* Fetches the tables from the postgres table and assigns them to the datasource.
* @param datasourceId - datasourceId to fetch
* @param entities - the tables that are to be built
*/
async buildSchema(
datasourceId: string,
entities: Record<string, Table>
): Promise<Schema> {
let tableKeys: { [key: string]: string[] } = {}
await this.openConnection()
try {
const primaryKeysResponse = await this.client.query(
this.PRIMARY_KEYS_SQL()
)
for (let table of primaryKeysResponse.rows) {
const tableName = table.table_name
if (!tableKeys[tableName]) {
tableKeys[tableName] = []
}
const key = table.column_name || table.primary_key
// only add the unique keys
if (key && tableKeys[tableName].indexOf(key) === -1) {
tableKeys[tableName].push(key)
}
}
} catch (err) {
tableKeys = {}
}
try {
const columnsResponse: { rows: PostgresColumn[] } =
await this.client.query(this.COLUMNS_SQL())
const tables: { [key: string]: Table } = {}
// Fetch enum values
const enumsResponse = await this.client.query(this.ENUM_VALUES())
// output array, allows for more than 1 single-select to be used at a time
const enumValues = enumsResponse.rows?.reduce((acc, row) => {
return {
...acc,
[row.typname]: [...(acc[row.typname] || []), row.enumlabel],
}
}, {})
for (let column of columnsResponse.rows) {
const tableName: string = column.table_name
const columnName: string = column.column_name
// table key doesn't exist yet
if (!tables[tableName] || !tables[tableName].schema) {
tables[tableName] = {
type: "table",
_id: buildExternalTableId(datasourceId, tableName),
primary: tableKeys[tableName] || [],
name: tableName,
schema: {},
sourceId: datasourceId,
sourceType: TableSourceType.EXTERNAL,
}
}
const identity = !!(
column.identity_generation ||
column.identity_start ||
column.identity_increment
)
const hasDefault = column.column_default != null
const hasNextVal =
typeof column.column_default === "string" &&
column.column_default.startsWith("nextval")
const isGenerated =
column.is_generated && column.is_generated !== "NEVER"
const isAuto: boolean = hasNextVal || identity || isGenerated
const required = column.is_nullable === "NO"
tables[tableName].schema[columnName] = generateColumnDefinition({
autocolumn: isAuto,
name: columnName,
presence: required && !hasDefault && !isGenerated,
externalType: column.data_type,
options: enumValues?.[column.udt_name],
userDefinedType: column.udt_name,
})
}
const finalizedTables = finaliseExternalTables(tables, entities)
const errors = checkExternalTables(finalizedTables)
return { tables: finalizedTables, errors }
} catch (err) {
// @ts-ignore
throw new Error(err)
} finally {
await this.closeConnection()
}
}
async getTableNames() {
try {
await this.openConnection()
const columnsResponse: { rows: PostgresColumn[] } =
await this.client.query(this.COLUMNS_SQL())
const names = columnsResponse.rows.map(row => row.table_name)
return [...new Set(names)]
} finally {
await this.closeConnection()
}
}
async getViewNames() {
try {
await this.openConnection()
const viewsResponse = await this.client.query(this.VIEWS_SQL())
const views: string[] = viewsResponse.rows.map(row => row.view_name)
return views
} finally {
await this.closeConnection()
}
}
async create(query: SqlQuery | string) {
const response = await this.internalQuery(getSqlQuery(query))
return response.rows.length ? response.rows : [{ created: true }]
}
async read(query: SqlQuery | string) {
const response = await this.internalQuery(getSqlQuery(query))
return response.rows
}
async update(query: SqlQuery | string) {
const response = await this.internalQuery(getSqlQuery(query))
return response.rows.length ? response.rows : [{ updated: true }]
}
async delete(query: SqlQuery | string) {
const response = await this.internalQuery(getSqlQuery(query))
return response.rows.length ? response.rows : [{ deleted: true }]
}
async query(json: EnrichedQueryJson): Promise<DatasourcePlusQueryResponse> {
const operation = this._operation(json).toLowerCase()
const input = this._query(json) as SqlQuery
if (Array.isArray(input)) {
const responses = []
for (let query of input) {
responses.push(await this.internalQuery(query, false))
}
await this.closeConnection()
return responses
} else {
const response = await this.internalQuery(input)
return response.rows.length ? response.rows : [{ [operation]: true }]
}
}
async getExternalSchema() {
if (!env.SELF_HOSTED) {
// This is because it relies on shelling out to pg_dump and we don't want
// to enable shell injection attacks.
throw new Error(
"schema export for Postgres is not supported in Budibase Cloud"
)
}
const dumpCommandParts = [
`user=${this.config.user}`,
`host=${this.config.host}`,
`port=${this.config.port}`,
`dbname=${this.config.database}`,
]
if (this.config.ssl) {
dumpCommandParts.push("sslmode=verify-ca")
if (this.config.ca) {
const caFilePath = storeTempFile(this.config.ca)
fs.chmodSync(caFilePath, "0600")
dumpCommandParts.push(`sslrootcert=${caFilePath}`)
}
if (this.config.clientCert) {
const clientCertFilePath = storeTempFile(this.config.clientCert)
fs.chmodSync(clientCertFilePath, "0600")
dumpCommandParts.push(`sslcert=${clientCertFilePath}`)
}
if (this.config.clientKey) {
const clientKeyFilePath = storeTempFile(this.config.clientKey)
fs.chmodSync(clientKeyFilePath, "0600")
dumpCommandParts.push(`sslkey=${clientKeyFilePath}`)
}
}
const dumpCommand = `PGPASSWORD="${
this.config.password
}" pg_dump --schema-only "${dumpCommandParts.join(" ")}"`
return new Promise<string>((resolve, reject) => {
exec(dumpCommand, (error, stdout, stderr) => {
if (error || stderr) {
console.error(stderr)
reject(new Error(stderr))
return
}
resolve(stdout)
console.log("SQL dump generated successfully!")
})
})
}
}
export default {
schema: SCHEMA,
integration: PostgresIntegration,
}