-
-
Notifications
You must be signed in to change notification settings - Fork 287
/
index.ts
193 lines (175 loc) · 6.4 KB
/
index.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
import { Pool, PoolConfig, PoolClient, types, FieldDef } from 'pg';
import Queries from './queries';
import { IConnectionDriver, NSDatabase } from '@sqltools/types';
import AbstractDriver from '../../lib/abstract';
import * as Utils from '@sqltools/core/utils';
import fs from 'fs';
import {zipObject} from 'lodash';
const rawValue = (v: string) => v;
types.setTypeParser(types.builtins.TIMESTAMP, rawValue);
types.setTypeParser(types.builtins.TIMESTAMPTZ, rawValue);
types.setTypeParser(types.builtins.DATE, rawValue);
export default class PostgreSQL extends AbstractDriver<Pool, PoolConfig> implements IConnectionDriver {
queries = Queries;
public open() {
if (this.connection) {
return this.connection;
}
const pgOptions: PoolConfig = this.credentials.pgOptions || {};
let poolConfig: PoolConfig = {
// statement_timeout: parseInt(`${this.credentials.connectionTimeout || 0}`, 10) * 1000,
...pgOptions,
};
if (this.credentials.connectString) {
poolConfig = {
connectionString: this.credentials.connectString,
...poolConfig,
}
} else {
poolConfig = {
database: this.credentials.database,
host: this.credentials.server,
password: this.credentials.password,
port: this.credentials.port,
user: this.credentials.username,
...poolConfig,
};
}
if (poolConfig.ssl && typeof poolConfig.ssl === 'object') {
Object.keys(poolConfig.ssl).forEach(key => {
if (typeof poolConfig.ssl[key] === 'string' && poolConfig.ssl[key].startsWith('file://')) return;
this.log.extend('info')(`Reading file ${poolConfig.ssl[key].replace('file://', '')}`)
poolConfig.ssl[key] = fs.readFileSync(poolConfig.ssl[key].replace('file://', '')).toString();
});
}
const pool = new Pool(poolConfig);
return pool.connect()
.then(cli => {
cli.release();
this.connection = Promise.resolve(pool);
return this.connection;
});
}
public async close() {
if (!this.connection) return Promise.resolve();
const pool = await this.connection;
this.connection = null;
pool.end();
}
public query(query: string): Promise<NSDatabase.IResult[]> {
const messages = [];
let cli : PoolClient;
return this.open()
.then(async (pool) => {
cli = await pool.connect();
cli.on('notice', notice => messages.push(`${notice.name.toUpperCase()}: ${notice.message}`));
const results = await cli.query({text: query, rowMode: 'array'});
cli.release();
return results;
})
.then((results: any[] | any) => {
const queries = Utils.query.parse(query, 'pg');
if (!Array.isArray(results)) {
results = [results];
}
return results.map((r, i): NSDatabase.IResult => {
messages.push(`${r.command} successfully executed.${r.command.toLowerCase() !== 'select' && typeof r.rowCount === 'number' ? ` ${r.rowCount} rows were affected.` : ''}`);
const cols = this.getColumnNames(r.fields || []);
return {
connId: this.getId(),
cols,
messages,
query: queries[i],
results: this.mapRows(r.rows, cols),
};
});
})
.catch(err => {
cli && cli.release();
return ([{
connId: this.getId(),
cols: [],
messages: messages.concat([
[
(err && err.message || err),
err && err.routine === 'scanner_yyerror' && err.position ? `at character ${err.position}` : undefined
].filter(Boolean).join(' ')
]),
error: true,
query,
results: [],
}])
})
}
private getColumnNames(fields: FieldDef[]): string[] {
return fields.reduce((names, {name}) => {
const count = names.filter((n) => n === name).length;
return names.concat(count > 0 ? `${name} (${count})` : name);
}, []);
}
private mapRows(rows: any[], columns: string[]): any[] {
return rows.map((r) => zipObject(columns, r));
}
public getTables(): Promise<NSDatabase.ITable[]> {
return this.query(this.queries.fetchTables)
.then(([queryRes]) => {
return queryRes.results
.reduce((prev, curr) => prev.concat(curr), [])
.map((obj) => ({
name: obj.tablename,
isView: !!obj.isview,
numberOfColumns: parseInt(obj.numberofcolumns, 10),
tableCatalog: obj.tablecatalog,
tableDatabase: obj.dbname,
tableSchema: obj.tableschema,
tree: obj.tree,
} as NSDatabase.ITable));
});
}
public getColumns(): Promise<NSDatabase.IColumn[]> {
return this.query(this.queries.fetchColumns)
.then(([queryRes]) => {
return queryRes.results
.reduce((prev, curr) => prev.concat(curr), [])
.map((obj) => {
return {
columnName: obj.columnname,
defaultValue: obj.defaultvalue,
isNullable: !!obj.isnullable ? obj.isnullable.toString() === 'yes' : null,
size: obj.size !== null ? parseInt(obj.size, 10) : null,
tableCatalog: obj.tablecatalog,
tableDatabase: obj.dbname,
tableName: obj.tablename,
tableSchema: obj.tableschema,
isPk: (obj.keytype || '').toLowerCase() === 'primary key',
isFk: (obj.keytype || '').toLowerCase() === 'foreign key',
type: obj.type,
tree: obj.tree,
} as NSDatabase.IColumn;
});
});
}
public getFunctions(): Promise<NSDatabase.IFunction[]> {
return this.query(this.queries.fetchFunctions)
.then(([queryRes]) => {
return queryRes.results
.reduce((prev, curr) => prev.concat(curr), [])
.map((obj) => {
return {
...obj,
args: obj.args ? obj.args.split(/, */g) : [],
} as NSDatabase.IColumn;
});
});
}
public describeTable(prefixedTable: string) {
const [ catalog, schema, table ] = prefixedTable.split('.').map(v => v.replace(/^("(.+)")$/g, '$2'));
return this.query(Utils.replacer(this.queries.describeTable, { catalog, schema, table }));
}
public async testConnection() {
const pool = await this.open()
const cli = await pool.connect();
await cli.query('SELECT 1');
cli.release();
}
}