-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
630 lines (575 loc) · 20.3 KB
/
cli.js
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
#!/usr/bin/env node
const path = require("path");
const yargs = require('yargs')
.scriptName("sqlcli")
.showHelpOnFail(true)
.command("$0", "Create an SQL CLI that is disconnected to begin with", (y) => {
y.options({
"username": {
alias: ["user", "u"],
string: true,
},
"password": {
alias: ["pass", "p"],
string: true,
},
"host": {
alias: ["h"],
string: true,
},
"port": {
number: true,
},
"database": {
alias: ["b"],
string: true,
},
"driver": {
alias: ["d"],
string: true,
},
"variable": {
alias: ["v"],
string: true,
describe: "The environment variable holding the URI to connect to\n[default: SQL_URL]",
},
"dotenv": {
alias: ["e"],
string: true,
describe: "The path to a DotEnv file\n[default: ./.env]",
}
});
})
.command("<uri>", "Connect to a DB using a URI", (y) => {
y.positional("uri", {
desc: "URI to a DB server to connect to",
type: "string",
conflicts: ["username", "password", "host", "port", "database"]
});
});
const requireg = require("requireg");
const rl = require("readline");
const vm = require("vm");
const fs = require("fs");
const $ = [];
const $$ = [];
const vmContext = vm.createContext();
Object.defineProperties(vmContext, {
$: {
get: () => Array.from($)
},
$0: {
get: () => Object.values(Object.assign({}, Array.from($)[0]))
},
$$: {
get: () => Array.from($$)
},
$$0: {
get: () => Object.values(Object.assign({}, Array.from($$)[0]))
},
});
const chalk = require("chalk");
const url = require("url");
const rawModes = {
"all": 0b11,
"schema": 0b10,
"values": 0b01,
};
let db = null;
let repl = null;
let config = {
host: null,
port: null,
user: null,
password: null,
database: null,
driver: null,
};
let driverPackage;
let settings = {
prompt: "sql",
raw: {
active: false,
mode: rawModes.values,
getMode: (v) => Object.keys(rawModes).find(e => rawModes[e] == (v || settings.raw.mode))
},
nestTables: null,
saveCount: 20
};
let lastRetCode = 0;
function log(obj) {
process.stdout.write(typeof obj === "string" ? obj : JSON.stringify(obj, null, 2));
}
function logn(obj) {
log(obj);
log("\n");
}
function logerr(err) {
if(err instanceof Error) {
err = {
name: err.name,
code: err.code || -1,
message: err.message,
stack: err.stack || "no stack"
};
}
// TODO: Pretty print the errors
process.stderr.write(typeof err === "string" ? err : JSON.stringify(err, null, 2).replace(/\\n/g, "\n").replace(/\\\\/g, "\\"));
process.stderr.write("\n");
}
async function processArgs() {
let args = yargs.argv;
config.uri = args._[0] || null;
config.host = args.host || config.host;
config.port = args.port || config.port;
config.user = args.username || config.user;
config.password = args.password || config.password;
config.database = args.database || config.database;
config.driver = args.driver || config.driver;
if(args.variable) {
args.variable = typeof args.variable === "string" ? args.variable : "SQL_URI";
let env = Object.assign({}, process.env);
if(args.dotenv) {
args.dotenv = typeof args.dotenv === "string" ? args.dotenv : "./.env";
let de = require("dotenv").parse(fs.readFileSync(path.resolve(args.dotenv)));
env = Object.assign(env, de);
}
console.log(!!args.variable);
config.uri = env[args.variable];
}
try {
// if(config.uri) {
// let obj = new URL(config.uri);
// config.host = obj.hostname;
// config.port = obj.port;
// config.user = obj.username;
// config.password = obj.password;
// config.database = obj.pathname.substring(1);
// }
await (connectToDB(config.uri || config));
} catch(err) {
logerr(err);
db = null;
}
}
async function connectToDB(opts) {
try {
if(typeof opts === "string") {
let obj = new URL(opts);
opts = {};
opts.host = obj.hostname;
opts.port = obj.port;
opts.user = obj.username;
opts.password = obj.password;
opts.database = obj.pathname.substring(1);
opts.driver = obj.protocol.substring(0, obj.protocol.length - 1);
}
Object.assign(config, opts);
switch(opts.driver) {
case "mysql":
driverPackage = requireg("sqlclid-mysql");
break;
case "sqlite":
driverPackage = requireg("sqlclid-sqlite");
break;
default:
driverPackage = requireg("sqlclid-" + opts.driver);
// throw {
// message: `Bad driver parsed: '${opts.driver}'.`,
// name: "BADURI",
// code: 11
// };
break;
}
return (db = await driverPackage.createConnection(opts));
} catch(err) {
logerr(err);
db = null;
}
}
async function handleCommand(data) {
data = data.trim();
if(data.startsWith(">")) {
// do it in a different repl
return await handleJsInstruction(data.substring(1));
} else if(data.startsWith("/")) {
// set it with a setting
return await handleAppCommand(data.substring(1));
} else {
// execute on the server
if(db === null) throw {
message: "DB not connected.",
name: "DBDISCON",
code: 12
};
let suppress = data.endsWith("sh");
if(suppress) data = data.substring(0, data.length - 2);
let r = await db.query(data, settings);
$.splice(0, 0, r[0]);
$.splice(settings.saveCount, $.length - settings.saveCount);
$$.splice(0, 0, r[1]);
$$.splice(settings.saveCount, $$.length - settings.saveCount);
if(settings.raw.active && !suppress) return settings.raw.mode == rawModes.all ? r : settings.raw.mode == rawModes.schema ? r[1] : r[0];
else if(!suppress) return r[1] != null ? handleSQLResponse(r[0]) : handleSQLModify(r[0], data.split(" ")[0]);
else return null;
}
}
function handleJsInstruction(inst) {
try {
let ret = vm.runInContext(inst, vmContext, {
displayErrors: true,
breakOnSigint: true,
});
if(ret === undefined && inst.trim().startsWith("let")) {
ret = vm.runInNewContext(inst.trim().split(/ +/)[1], vmContext);
if(ret === undefined) ret = chalk.italic.grey("undefined...");
}
return ret;
} catch(err) {
logerr(err);
}
}
const appCommands = {
"_": {
"commands": [
"Prints out all available commands."
],
"connect": [
"[driver] [user] [pass] [host] [?port]",
"Connects to the host using the specified username and password. Disconnects from the currently connected database if not done already.",
"Port is optional, and defaults to whatever the driver defaults to."
],
"connectu": [
"[uri]",
"Connects to the database at the specified URI. Determines the driver automatically. Disconnects from the currently connected database if not done already.",
],
"connecte": [
"[variable] [?dotenvFile]",
"Connects to the database using the URI found in the environment variable, optionally found in the DotEnv file specified."
],
"disconnect": [
"Disconnects from the currently connected database."
],
"prompt": [
"[?prompt]",
"Prompt can be any string, and can include $config values or be $reset to reset."
],
"set": [
"[?setting] [?values...]",
"Gets or sets the setting. Settings:",
"raw active -- Gets the raw active setting.",
"raw active [on/off] -- Sets the raw active setting to on or off.",
"raw mode -- Gets the raw mode setting. Returns the value name.",
"raw mode [value] -- Sets the raw mode setting. Value must be a string.",
" values - Values Only (default)",
" schema - Schema Only",
" all - Values and Schema",
"nesttables -- Gets the nest tables prefix.",
"nesttables [prefix] -- Sets the nest tables prefix. Useful for removing colliding column names.",
" Use $reset to reset to null.",
],
"dump": [
"[?tables...]",
"Creates an exact copy of the tables in SQL format. If no tables are specified, this will dump all tables in the database."
],
"clear": [
"Clears the screen."
],
"help": [
"[?command]",
"Prints this help message, or the command's specific help message."
],
"exit": [
"Exits the program. (Calls SIGINT)"
]
},
async dump(...tables) {
let comment = driverPackage.COMMENT_MARKER ?? "--";
let dump = [
comment + " Dump created by SQLCLI by TheBrenny // https://github.com/thebrenny/sql-cli-repl " + comment,
"",
...await db.dump(...tables),
"",
comment + " Dump created by SQLCLI by TheBrenny // https://github.com/thebrenny/sql-cli-repl " + comment,
];
return dump.join("\n");
},
async connect(driver, user, password, host) {
let opts = {
driver,
user,
password,
host,
};
await connectToDB(opts);
setDefaultPrompt();
return null;
},
async connectu(uri) {
await connectToDB(uri);
setDefaultPrompt();
return null;
},
async connecte(variable, dotenvFile) {
let env = Object.assign({}, process.env);
if(!!dotenvFile) {
let de = require("dotenv").parse(fs.readFileSync(dotenvFile));
env = Object.assign(env, de);
}
let uri = env[variable];
await connectToDB(uri);
setDefaultPrompt();
return null;
},
disconnect() {
db.end();
db = null;
setDefaultPrompt();
return null;
},
prompt(...p) {
if(p.length == 0 || p.join("").trim() == "") return `Current Prompt: ${settings.prompt}`;
if(p[0].toLowerCase() == "$reset") setDefaultPrompt();
else {
for(let c in config) p = p.map(v => v.replace(new RegExp("\\$" + c, "gi"), config[c])); //jshint ignore:line
setPrompt(p.join(" "));
}
return "Prompt updated!";
},
set(...v) {
let key = v[0];
let values = v.slice(1);
switch(key) {
case "raw":
if(values.length == 0) return [`Raw active: ${settings.raw.active ? "on" : "off"}`, `Raw mode: ${settings.raw.getMode()}`];
switch(values[0]) {
case "active":
if(values.length == 1) return `Raw active: ${settings.raw.active ? "on" : "off"}`;
settings.raw.active = ["true", "on"].includes(values[1].trim().toLowerCase());
return `Raw active ${settings.raw.active ? "on" : "off"}`;
case "mode":
if(values.length == 1) return `Raw mode: ${settings.raw.getMode()}`;
settings.raw.mode = rawModes[values[1].trim().toLowerCase()] || rawModes.values;
return `Raw mode ${settings.raw.getMode()}`;
default:
ret = {
message: "Unknown raw setting: " + values[0],
name: "NULLAPPSET",
code: 110
};
return ret;
}
break;
case "nesttables":
if(values.length == 0) return `Nest tables: ${settings.nestTables ? "on" : "off"}`;
if(values == "$reset") settings.nestTables = null;
else settings.nestTables = values[0];
return `Nest tables ${settings.nestTables || "off"}`;
default:
ret = {
message: "Unknown app setting: " + key,
name: "NULLAPPSET",
code: 110
};
return ret;
}
},
clear() {
process.stdout.cursorTo(0, 0);
process.stdout.clearScreenDown();
return null;
},
commands() {
return Object.keys(appCommands).filter(c => c !== "_");
},
help: printHelp,
exit() {
process.emit("SIGINT");
},
};
async function badCommand(cmd) {
return chalk.italic.red("Unknown command: \"" + cmd + "\"");
}
async function handleAppCommand(cmd) {
let ret = null;
cmd = cmd.split(" ");
if(cmd[0] !== "_" && !!appCommands[cmd[0]]) ret = await appCommands[cmd[0]](...cmd.slice(1));
else return (await badCommand(cmd));
if(ret !== null && ret.code !== undefined) throw ret;
if(!Array.isArray(ret) && ret !== null) ret = [ret];
return (ret === null ? null : ret.map(r => chalk.italic.green(" " + r)).join("\n"));
}
function handleSQLResponse(records) {
if(records.length == 0) return "Returned " + chalk.yellow("0") + " rows.";
let keys = Object.keys(records[0]);
let data = new Array(keys.length).fill(new Array(1 + records.length));
let lengths = new Array(keys.length);
const clampString = (clampLength, maxLength, str) => {
clampLength = Math.min(clampLength, maxLength);
str = str.padStart(clampLength, " ");
if(str.length > clampLength) str = str.substring(0, clampLength - 4) + " ...";
else str = str.substring(0, clampLength);
return str;
};
const buildRecordRow = (r, a, c) => a.concat(c[r]);
for(let k = 0; k < keys.length; k++) {
data[k][0] = keys[k];
lengths[k] = [];
lengths[k].push(keys[k].length);
for(let r = 0; r < records.length; r++) {
let rec = records[r][keys[k]];
if(rec === null || rec === undefined) rec = "null";
if(rec instanceof Date) rec = rec.toJSON();
if(typeof rec === "object") {
rec = JSON.parse(JSON.stringify(rec));
rec = (rec.type || "???????").substring(0, 3) + JSON.stringify(rec.data);
}
rec = rec.toString();
data[k][r + 1] = rec;
lengths[k].push(rec.length);
}
data[k] = data[k].map(clampString.bind(this, 40, Math.max(...lengths[k])));
}
let lines = [];
for(let r = 0; r < records.length + 1; r++) {
let line = "| " + data.reduce(buildRecordRow.bind(null, r), []).join(" | ") + " |";
lines.push(line);
}
lines.splice(1, 0, lines[0].replace(/[^|]/g, "-"));
lines.splice(0, 0, lines[0].replace(/[^|]/g, "-"));
lines.push(lines[0]);
return lines.join("\n");
}
const actionMap = {
"DELETE": "Deleted",
"INSERT": "Inserted",
"UPDATE": "Updated",
"ALTER": "Altered",
"CREATE": "Created",
"DROP": "Dropped",
"TRUNCATE": "Truncated",
"RENAME": "Renamed",
"REPLACE": "Replaced",
"LOAD": "Loaded",
};
function handleSQLModify(record, action) {
action = action.toUpperCase();
action = actionMap[action] || action;
action = action.substring(0, 1).toUpperCase() + action.substring(1).toLowerCase();
let id = record.insertId;
let rows = record.affectedRows;
let changed = record.changedRows ?? record.affectedRows;
let response = `${action} ${chalk.yellow(changed)} record${changed == 1 ? "" : "s"} (${rows} accessed).`;
if(id > 0) response += `\nAffected ID: ${chalk.yellow(id)}`;
return response;
}
function isValidCommand(c) {
return c.endsWith(";") || c.endsWith(";sh") || // SQL command
c.startsWith("/") || // internal command
c.startsWith(">"); // js command
}
async function setDefaultPrompt() {
setPrompt(db === null ? chalk.bold.red(`disconnected`) : `${chalk.bold.green(config.user)}@${config.host}`);
}
function setPrompt(p) {
settings.prompt = p;
repl.setPrompt(`${p}> `);
}
function enterRepl() {
repl = rl.createInterface({
input: process.stdin,
output: process.stdout,
prompt: settings.prompt + "> "
});
setDefaultPrompt();
let d = "";
let p = null;
repl.prompt();
repl.on("line", (data) => {
data = data.trim();
d += data;
if(isValidCommand(d)) {
Promise.resolve(d)
.then((ret) => {
if(p !== null) setPrompt(p);
p = null;
repl.pause();
return ret;
})
.then((ret) => handleCommand(ret))
.then((ret) => {
if(ret !== null) logn(ret);
return 0;
})
.catch((err) => {
logerr(err);
return err.code;
})
.finally((retcode) => {
lastRetCode = retcode;
repl.prompt();
repl.resume();
});
d = "";
} else if(d != "") {
d += " ";
if(p === null) p = settings.prompt;
repl.setPrompt("... ");
repl.prompt();
} else {
repl.prompt();
}
}).on("SIGINT", () => process.emit("SIGINT"));
process.on("SIGINT", () => {
if(d === "") {
logn("\nBye!");
process.exit(lastRetCode);
} else {
d = "";
if(p !== null) setPrompt(p);
p = null;
log("\n");
repl.emit("line", "");
}
});
}
function printHelp(cmd) {
let h = [""];
for(let c in appCommands) {
if(c === "_") continue;
if(!!cmd && c !== cmd) continue;
h.push("/" + c);
h = h.concat(appCommands._[c].map(v => " " + v));
h.push("");
}
return h.map(v => " " + v).join("\n");
}
if(require.main === module) {
if(yargs.argv.help) yargs.showHelp();
else processArgs().then(() => new Promise((resolve, reject) => {
if(process.stdin.isTTY) return enterRepl();
else {
let data = "";
let stdin = process.stdin;
stdin.on('data', (chunk) => data += chunk);
stdin.on('end', function () {
return Promise.resolve(data)
.then((ret) => handleCommand(ret))
.then((ret) => {
if(ret !== null) logn(ret);
return 0;
})
.catch((err) => {
logerr(err);
return err.code;
}).finally((retcode) => {
lastRetCode = retcode;
resolve(retcode);
});
});
stdin.on('error', reject);
}
}))
.catch((err) => (logerr(err), err.code))
.finally((code) => process.exit(code || lastRetCode || 0));
} else module.exports = {};