-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathrepl
executable file
·103 lines (90 loc) · 2.83 KB
/
repl
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
#!/usr/bin/env node
const { DBSQLClient } = require('..');
const repl = require('node:repl');
const { Console } = require('node:console');
const { Transform } = require('node:stream');
const { program } = require('commander');
const ts = new Transform({ transform(chunk, enc, cb) { cb(null, chunk) } })
const logger = new Console({ stdout: ts })
async function initClient({ host, endpointId, token }) {
const client = new DBSQLClient();
return client.connect({
host,
path: `/sql/2.0/warehouses/${endpointId}`,
token,
userAgentEntry: 'REPL',
});
}
async function runQuery(session, query) {
const queryOperation = await session.executeStatement(query);
const result = await queryOperation.fetchAll();
await queryOperation.close();
return result;
}
const format = {
reset: '\x1b[0m',
bold: '\x1b[1m',
fg: {
black: '\x1b[30m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
},
bg: {
black: '\x1b[40m',
red: '\x1b[41m',
green: '\x1b[42m',
yellow: '\x1b[43m',
blue: '\x1b[44m',
magenta: '\x1b[45m',
cyan: '\x1b[46m',
white: '\x1b[47m',
},
};
async function main(args) {
const client = await initClient(args);
const session = await client.openSession();
repl.start({
prompt: `${format.bold}dbsql > ${format.reset}`,
useColors: true,
eval: async (input, context, filename, callback) => {
try {
const result = await runQuery(session, input);
callback(null, result);
} catch (e) {
callback(null, e);
}
},
writer: (output) => {
if (output instanceof Error) {
const message = output?.response?.errorMessage || output.message;
return `${format.fg.red}Error: ${message}${format.reset}`;
} else {
if (!output?.length) {
return `${format.fg.cyan}Query executed successfully, but returned no results${format.reset}`;
}
logger.table(output)
return (ts.read() || '').toString();
}
},
}).on('exit', async () => {
await session.close();
await client.close();
process.exit();
});
}
program
.requiredOption('-h, --host <host>', 'Host (required)')
.requiredOption('-e, --endpoint <endpointId>', 'SQL endpoint ID (required)')
.requiredOption('-t, --token <token>', 'Personal access token (required)')
.showHelpAfterError();
program.parse(process.argv);
main({
host: program.opts().host,
endpointId: program.opts().endpoint,
token: program.opts().token,
});