-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (87 loc) · 2.38 KB
/
index.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
// if commandline arg is "cockroachdb", use cockroachdb
// else use sqlite3
const { default: knex } = require("knex");
const knex_sqlite = require("knex")({
client: "sqlite3",
connection: {
filename: "./mydb.sqlite",
},
useNullAsDefault: true,
debug: false,
});
const knex_cockroach = require("knex")({
client: "cockroachdb",
connection: {
host: "127.0.0.1",
port: 26257,
user: "root",
password: "",
database: "knex",
},
debug: false,
});
(async () => {
try {
await createTable(knex_cockroach);
await createTable(knex_sqlite);
let arr = [];
for (let i = 0; i < 100; i++) {
arr.push(i.toString());
}
await Promise.all(arr.map((i) => addRows(i, knex_cockroach)));
await Promise.all(arr.map((i) => addRows(i, knex_sqlite)));
await new Promise((resolve) => setTimeout(resolve, 1000));
// console.log("sqlite");
// await printRows(knex_sqlite);
console.log("cockroach");
await printRows(knex_cockroach);
knex_cockroach.destroy();
knex_sqlite.destroy();
// Finally, add a catch statement
} catch (e) {
console.error(e);
}
})();
async function addRows(blog_id, knex) {
try {
const trx = await knex.transaction();
const maxResults = await knex
.select("comment_id")
.max("blog_order", { as: "max" })
.whereIn("comment_id", [1])
.where({})
.groupBy("comment_id")
.from("knex_test")
.transacting(trx);
const max = maxResults.length === 0 ? 0 : parseInt(maxResults[0].max) + 1;
// copy the above insert query and run it using knex
await knex("knex_test")
.insert({
blog_id: blog_id,
blog_order: max,
comment_id: 1,
comment_order: 1,
})
.returning("id")
.transacting(trx);
await trx.commit();
} catch (e) {
console.log(e);
}
}
async function createTable(knex) {
const tableExists = await knex.schema.hasTable("knex_test");
tableExists ? await knex.schema.dropTable("knex_test") : null;
await knex.schema.createTable("knex_test", (table) => {
table.increments("id").notNullable();
table.integer("blog_id");
table.integer("comment_id");
table.integer("blog_order");
table.integer("comment_order");
});
}
async function printRows(knex) {
const rows = await knex.select("*").from("knex_test");
// print the rows in a nice formatted table
console.table(rows);
}