-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsqlcommand.js
More file actions
102 lines (97 loc) · 2.82 KB
/
sqlcommand.js
File metadata and controls
102 lines (97 loc) · 2.82 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
const readline = require("readline");
const { Client } = require("pg");
const Cursor = require("pg-cursor");
require("dotenv").config();
let client = null;
let cursor = null;
let transactionOpen = false;
async function sqlCommand() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
historySize: 100,
});
rl.setPrompt("sql>");
let sqlLine = "";
rl.prompt();
rl.on("line", async (line) => {
sqlLine += line;
if (!sqlLine.includes(";")) {
rl.setPrompt("");
rl.prompt();
} else {
try {
const actionString = sqlLine.trim();
if (actionString == "BEGIN;") {
transactionOpen = true;
} else if (actionString == "COMMIT;" || actionString == "ROLLBACK;") {
transactionOpen = false;
}
if (!client) {
client = new Client({ connectionString: process.env.DB_URL });
await client.connect();
client.on("error", () => {
console.log(
"\nA connection failure or timeout occurred. Any transactions in process have been rolled back.\nsql>",
);
if (cursor) {
cursor.close();
cursor = null;
}
if (client) {
client.end();
client = null;
}
transactionOpen = false;
});
}
cursor = client.query(new Cursor(sqlLine, [], { rowMode: "array" }));
let firstRow = true;
let rows;
while (true) {
rows = await cursor.read(100);
if (firstRow) {
const columnNames = cursor._result.fields.map(
(field) => field.name,
);
console.log(columnNames.join("\t"));
firstRow = false;
}
if (rows && rows.length) {
rows.forEach((row) => {
const rowStrings = row.map((column) => {
if (column === null) {
return "null"
} else {
return column.toString();
}
})
console.log(rowStrings.join("\t"));
});
} else {
break;
}
}
} catch (error) {
// This is a mystery error, assumed to be not recoverable
console.log("96");
console.log(
`An error occurred: ${error.name} ${error.message} ${error.stack}`,
);
}
cursor.close();
cursor = null;
if (!transactionOpen) {
client.end();
client = null;
}
rl.setPrompt("sql>");
sqlLine = "";
rl.prompt();
}
});
}
console.log(
"The tables in this database are customers, employees, products, orders, and line_items. Enter SQL statements below. Each statement must end in a semicolon.",
);
sqlCommand();