-
-
Notifications
You must be signed in to change notification settings - Fork 290
/
index.ts
146 lines (124 loc) · 4.39 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
import {
ConnectionDialect,
} from '@sqltools/core/interface';
import * as Utils from '@sqltools/core/utils';
import SQLiteLib from 'sqlite3';
import GenericDialect from '../generic';
import queries from './queries';
import { DatabaseInterface } from '@sqltools/core/plugin-api';
import makeDir from 'make-dir';
import { dirname } from 'path';
const SQLite3Version = '4.0.8';
export default class SQLite extends GenericDialect<SQLiteLib.Database> implements ConnectionDialect {
public static deps: typeof GenericDialect['deps'] = [{
type: 'package',
name: 'sqlite3',
version: SQLite3Version,
}];
queries = queries;
private get lib() {
return __non_webpack_require__('sqlite3') as SQLiteLib.sqlite3;
}
createFileIfNotExists = () => {
if (this.credentials.database.toLowerCase() === ':memory:') return;
const baseDir = dirname(this.credentials.database);
makeDir.sync(baseDir);
}
public async open() {
if (this.connection) {
return this.connection;
}
this.needToInstallDependencies();
this.createFileIfNotExists();
const db = await new Promise<SQLiteLib.Database>((resolve, reject) => {
const instance = new (this.lib).Database(this.credentials.database, (err) => {
if (err) return reject(err);
return resolve(instance);
});
});
this.connection = Promise.resolve(db);
return this.connection;
}
public async close() {
if (!this.connection) return Promise.resolve();
const db = await this.connection
await new Promise((resolve, reject) => {
db.close(err => err ? reject(err) : resolve());
});
this.connection = null;
}
private runSingleQuery(db: SQLiteLib.Database, query: string) {
return new Promise<any[]>((resolve, reject) => {
db.all(query,(err, rows) => {
if (err) return reject(err);
return resolve(rows);
})
});
}
public async query(query: string): Promise<DatabaseInterface.QueryResults[]> {
const db = await this.open();
const queries = Utils.query.parse(query).filter(Boolean);
const results: DatabaseInterface.QueryResults[] = [];
for(let i = 0; i < queries.length; i++) {
const res: any[][] = (await this.runSingleQuery(db, queries[i])) || [];
const messages = [];
if (res.length === 0 && queries[i].toLowerCase() !== 'select') {
messages.push(`${res.length} rows were affected.`);
}
results.push({
connId: this.getId(),
cols: res && res.length ? Object.keys(res[0]) : [],
messages,
query: queries[i],
results: res,
});
}
return results;
}
public async getTables(): Promise<DatabaseInterface.Table[]> {
const [ queryRes ] = await this.query(this.queries.fetchTables);
return queryRes.results
.reduce((prev, curr) => prev.concat(curr), [])
.map((obj) => {
return {
name: obj.tableName,
isView: obj.type === 'view',
tableDatabase: this.credentials.database,
tree: obj.tree,
} as DatabaseInterface.Table;
});
}
public async getColumns(): Promise<DatabaseInterface.TableColumn[]> {
const allTables = await this.getTables();
const columns: DatabaseInterface.TableColumn[] = [];
await Promise.all(allTables.map(async t => {
const [[{ results: tableColumns }], [{ results: fks }]] = await Promise.all([
this.query(Utils.replacer(this.queries.fetchColumns, { table: t.name })),
this.query(Utils.replacer(this.queries.listFks, { table: t.name })),
]);
const fksMap = fks.reduce((agg, fk) => ({ ...agg, [fk.from]: true }), {});
tableColumns.forEach(obj => columns.push({
columnName: obj.name,
defaultValue: obj.dftl_value || undefined,
isNullable: obj.notnull ? obj.notnull.toString() === '1' : null,
tableCatalog: obj.tablecatalog,
tableDatabase: this.credentials.database,
tableName: t.name,
type: obj.type,
size: null,
isPk: Boolean(obj.pk),
isFk: !!fksMap[obj.name],
tree: obj.tree,
}));
return Promise.resolve();
}));
return columns;
}
public getFunctions() {
// this doesn exists for SQLite. It's just to avoid watning messages
return Promise.resolve([]);
}
public describeTable(prefixedTable: string) {
return super.describeTable(prefixedTable.replace(/^("(.+)")$/g, '$2'));
}
}