|
1 | | -const knex = require("knex")({ |
2 | | - client: "mysql2", |
3 | | - connection: { |
4 | | - host: "tfb-database", |
5 | | - user: "benchmarkdbuser", |
6 | | - password: "benchmarkdbpass", |
7 | | - database: "hello_world" |
8 | | - } |
9 | | -}); |
| 1 | +const { createPool } = require("mariadb"); |
| 2 | + |
| 3 | +const clientOpts = { |
| 4 | + host: process.env.MYSQL_HOST, |
| 5 | + user: process.env.MYSQL_USER, |
| 6 | + password: process.env.MYSQL_PSWD, |
| 7 | + database: process.env.MYSQL_DBNAME, |
| 8 | +}; |
| 9 | + |
| 10 | +const pool = createPool({ ...clientOpts, connectionLimit: 1 }); |
| 11 | +const execute = (text, values) => pool.execute(text, values || undefined); |
10 | 12 |
|
11 | 13 | async function allFortunes() { |
12 | | - return knex("Fortune").select("*"); |
| 14 | + return execute("select id, message from fortune", []); |
13 | 15 | } |
14 | 16 |
|
15 | 17 | async function getWorld(id) { |
16 | | - return knex("World") |
17 | | - .first() |
18 | | - .where({ id }); |
| 18 | + return execute("select id, randomNumber from world where id = ?", [id]).then( |
| 19 | + (arr) => arr[0] |
| 20 | + ); |
19 | 21 | } |
20 | 22 |
|
21 | | -async function saveWorlds(worlds) { |
22 | | - const updates = []; |
23 | | - |
24 | | - worlds.forEach(world => { |
25 | | - const { id, randomNumber } = world; |
26 | | - |
27 | | - updates.push( |
28 | | - knex("World") |
29 | | - .update({ randomNumber }) |
30 | | - .where({ id }) |
31 | | - ); |
32 | | - }); |
33 | | - |
34 | | - return Promise.all(updates); |
| 23 | +async function bulkUpdate(worlds) { |
| 24 | + const sql = "update world set randomNumber = ? where id = ?"; |
| 25 | + const values = worlds |
| 26 | + .map((world) => [world.randomnumber, world.id]) |
| 27 | + .sort((a, b) => (a[0] < b[0] ? -1 : 1)); |
| 28 | + return pool.batch(sql, values); |
35 | 29 | } |
36 | 30 |
|
37 | 31 | module.exports = { |
38 | 32 | getWorld, |
39 | | - saveWorlds, |
40 | | - allFortunes |
| 33 | + bulkUpdate, |
| 34 | + allFortunes, |
41 | 35 | }; |
0 commit comments