Skip to content

Commit a74e015

Browse files
committed
Fix performance regression + add async stack to end of error stack
1 parent 9e165f0 commit a74e015

File tree

3 files changed

+26
-7
lines changed

3 files changed

+26
-7
lines changed

lib/connection.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ function Connection(options = {}) {
114114
query.result.count = null
115115
timeout && clearTimeout(timer)
116116

117-
options.debug && options.debug(id, str, args)
117+
typeof options.debug === 'function' && options.debug(id, str, args)
118118
const buffer = query.simple
119119
? simple(str, query)
120120
: sig in statements
@@ -162,7 +162,7 @@ function Connection(options = {}) {
162162
function onready(err) {
163163
if (err) {
164164
if (backend.query) {
165-
err.origin = backend.query.origin
165+
err.stack += backend.query.origin.replace(/.*\n/, '\n')
166166
Object.defineProperty(err, 'query', {
167167
value: backend.query.str,
168168
enumerable: false

lib/index.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ Object.assign(Postgres, {
3535
toKebab
3636
})
3737

38+
const originCache = new Map()
39+
3840
module.exports = Postgres
3941

4042
function Postgres(a, b) {
@@ -159,7 +161,7 @@ function Postgres(a, b) {
159161
}
160162

161163
function query(query, connection, xs, args) {
162-
query.origin = new Error('Query failed')
164+
query.origin = options.debug ? new Error().stack : cachedError(xs)
163165
if (!query.raw && (!Array.isArray(xs) || !Array.isArray(xs.raw)))
164166
return nested(xs, args)
165167

@@ -178,6 +180,17 @@ function Postgres(a, b) {
178180
return promise
179181
}
180182

183+
function cachedError(xs) {
184+
if (originCache.has(xs))
185+
return originCache.get(xs)
186+
187+
const x = Error.stackTraceLimit
188+
Error.stackTraceLimit = 4
189+
originCache.set(xs, new Error().stack)
190+
Error.stackTraceLimit = x
191+
return originCache.get(xs)
192+
}
193+
181194
function nested(first, rest) {
182195
const o = Object.create(notPromise)
183196
o.first = first

tests/index.js

+10-4
Original file line numberDiff line numberDiff line change
@@ -875,10 +875,16 @@ t('numeric is returned as string', async() => [
875875
typeof (await sql`select 1.2 as x`)[0].x
876876
])
877877

878-
t('Error contains origin', async() => [
879-
true,
880-
(await sql`selec 1`.catch(err => 'origin' in err))
881-
])
878+
function get() {
879+
return sql`selec 1`
880+
}
881+
882+
t('Async stack trace', async() => {
883+
return [
884+
parseInt(new Error().stack.split('\n')[1].split(':')[1]) + 1,
885+
parseInt(await sql.begin(sql => sql`select.sql`).catch(x => x.stack.split('\n').pop().split(':')[1]))
886+
]
887+
})
882888

883889
t('Error contains query string', async() => [
884890
'selec 1',

0 commit comments

Comments
 (0)