-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
234 lines (195 loc) · 5.53 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
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
const pgDotTemplate = require('@conjurelabs/pg-dot-template')
const path = require('path')
const fs = require('fs')
const { Pool } = require('pg')
const chalk = require('chalk')
const debugQuery = require('debug')('pg-dir:query')
const debugExecuted = require('debug')('pg-dir:executed')
let poolConfig
const privateDirPath = Symbol('privateDirPath')
const privateSession = Symbol('privateSession')
let existingPool
function getPool() {
if (existingPool) {
return existingPool
}
existingPool = new Pool(poolConfig)
return existingPool
}
function snakeToCamelCase(name, expr = /_+[a-z]/g) {
// expecting lower_snake_cased names form postgres
return name.replace(expr, match => {
return match.substr(-1).toUpperCase()
})
}
// mutates an object
// changing keys to camelCase
function objWithCamelCaseKeys(obj) {
for (let key in obj) {
let camelCased = snakeToCamelCase(key)
if (camelCased === key) {
continue
}
obj[camelCased] = obj[key]
delete obj[key]
}
return obj
}
function performFullResponse({ dirPath, filename, session }, placeholders = {}, ...args) {
return new Promise(async (resolve, reject) => {
const template = pgDotTemplate(path.resolve(dirPath, filename))
let queryString, result
const queryArgs = [placeholders, ...args]
queryArgs.push(session)
try {
queryString = await template(...queryArgs)
} catch(err) {
return reject(err)
}
debugQuery(chalk.blue(queryString.sanitized))
try {
result = await queryString.query()
} catch(err) {
return reject(err)
}
result.rows = result.rows.map(row => objWithCamelCaseKeys(row))
resolve(result)
})
return template.query(...args)
}
function performQuery(options, ...args) {
return new Promise((resolve, reject) => {
performFullResponse(options, ...args)
.then(response => {
resolve(response.rows)
})
.catch(reject)
})
}
function performOne(options, ...args) {
return new Promise((resolve, reject) => {
performQuery(options, ...args)
.then(rows => {
resolve(rows[0])
})
.catch(reject)
})
}
function performQueryToHash(options, key, ...args) {
return new Promise((resolve, reject) => {
performFullResponse(options, ...args)
.then(response => {
const hash = response.rows.reduce((hash, row) => {
hash[ row[key] ] = row
return hash
}, {})
resolve(hash)
})
.catch(reject)
})
}
function queryPassthrough(options) {
function query(...args) {
return performQuery(options, ...args)
}
query.one = function one(...args) {
return performOne(options, ...args)
}
query.fullResponse = function fullResponse(...args) {
return performFullResponse(options, ...args)
}
query.hash = function(key) {
return function(...args) {
return performQueryToHash(options, key, ...args)
}
}
return query
}
module.exports = class PgDir {
// !!! reads dirs synchronously
// so, this will block, while doing so
// this is intentional, since `constructor`
// does not yet support await
constructor(dirPath, withinTransaction = false) {
this[privateDirPath] = dirPath
this[privateSession] = { client: null, keepAlive: withinTransaction }
const directoryDirents = fs.readdirSync(dirPath, { withFileTypes: true })
if (withinTransaction) {
this.begin = () => {
debugQuery(chalk.blue('begin'))
return handleQuery('begin', null, this[privateSession])
}
this.commit = () => {
this[privateSession].keepAlive = false
debugQuery(chalk.blue('commit'))
return handleQuery('commit', null, this[privateSession])
}
this.savepoint = name => {
const command = `savepoint ${name}`
debugQuery(chalk.blue(command))
return handleQuery(command, null, this[privateSession])
}
this.rollback = name => {
if (!name) {
this[privateSession].keepAlive = false
}
const command = name ? `rollback to ${name}` : 'rollback'
debugQuery(chalk.blue(command))
return handleQuery(command, null, this[privateSession])
}
}
for (let dirent of directoryDirents) {
if (!dirent.isFile()) {
continue
}
const nameParts = path.parse(dirent.name)
if (nameParts.ext !== '.sql') {
continue
}
const nameKey = snakeToCamelCase(nameParts.name, /[_-]+[a-z]/g)
this[nameKey] = queryPassthrough({
dirPath,
filename: dirent.name,
session: this[privateSession]
})
}
}
get transaction() {
return new PgDir(this[privateDirPath], true)
}
}
module.exports.usingPoolConfig = config => {
poolConfig = config
existingPool = null
}
// if `client` is passed, then .handleQuery assumes
// that .release() will be handled manually
function handleQuery(queryString, queryArgs, session) {
return new Promise(async (resolve, reject) => {
const pool = getPool()
let result, err
if (!session.client) {
try {
session.client = await pool.connect()
} catch(connErr) {
return reject(connErr)
}
}
debugExecuted(queryString, queryArgs)
try {
result = await session.client.query(queryString, queryArgs)
} catch(tryErr) {
err = tryErr
} finally {
if (!session.keepAlive && session.client) {
session.client.release()
session.client = null
}
}
if (err) {
return reject(err)
}
resolve(result)
})
}
pgDotTemplate.handleQuery = handleQuery