This repository was archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
78 lines (68 loc) · 1.82 KB
/
db.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
const { Client } = require('pg')
const client = new Client({
user: 'thor_user',
host: 'localhost',
database: 'thor',
password: 'thor_password',
port: 9432,
})
let initial = true
module.exports = {
/**
* Deletes the provided row IDs from the table.
*
* @param {String} tableName
* @param {Array<Number>} rowIds
* @returns {Number}
*/
deleteRows: async (tableName, rowIds) => {
return await client.query(`DELETE FROM ${tableName} WHERE id IN (${rowIds.join(',')})`)
},
/**
* Returns the column names for the supplied table.
*
* @param {String} tableName
* @returns {Array<String>}
*/
getTableColumns: async tableName => {
const res = await client.query('SELECT * FROM information_schema.columns WHERE table_schema = \'public\' AND table_name = \'' + tableName + '\'')
return res.rows.map(({ column_name }) => column_name)
},
/**
* Fetches and returns all the (user defined) table names for the current DB.
*
* @returns {Array<String>}
*/
getTableNames: async () => {
if (initial) {
initial = false
await client.connect()
}
const res = await client.query('SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\' ORDER BY table_name')
return res.rows.map(({ table_name }) => table_name)
},
/**
* Returns data rows for the supplied table.
*
* @param {String} tableName
* @returns {Array<Object>}
*/
getTableRows: async tableName => {
const res = await client.query('SELECT * FROM ' + tableName)
return res.rows
},
/**
* Runs a generic SQL query and returns the resulting rows.
*
* @param {String} sql
* @returns {Array<Object>}
*/
query: async sql => {
try {
const res = await client.query(sql)
return res.rows
} catch (err) {
throw err
}
},
}