Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 27 additions & 15 deletions lib/tedious/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,31 @@ class Request extends BaseRequest {
}
}

/*
Add the error that tedious gives the callback of a request to `errors`, and emit it in stream
mode. `errors` already has each error from the server, because the connection emits each one
while the request runs. So only an error that tedious makes, such as a timeout, is new. When
the server sends two or more errors, tedious 15+ gives one AggregateError that holds them all.
They are the last errors in `errors`, so each one is compared with the error in its position.
*/

_addCallbackError (err, errors) {
if (!err) return

const reported = Array.isArray(err.errors) ? err.errors : [err]
// the position in `errors` of the first reported error; below 0 if fewer were collected
const start = errors.length - reported.length

reported.forEach((e, i) => {
const collected = errors[start + i]
if (collected && collected.message === e.message) return

e = new RequestError(e, 'EREQUEST')
if (this.stream) this.emit('error', e)
errors.push(e)
})
}

/*
Execute specified sql batch.
*/
Expand Down Expand Up @@ -560,15 +585,7 @@ class Request extends BaseRequest {
debug('request(%d): query', IDS.get(this), command)

const req = new tds.Request(command, err => {
// tedious v15 has started using AggregateErrors to wrap multiple errors into single error objects
(err?.errors ? err.errors : [err]).forEach((e, i, { length }) => {
// to make sure we handle no-sql errors as well
if (e && (!errors.length || (errors.length && errors.length >= length && e.message !== errors[errors.length - length + i].message))) {
e = new RequestError(e, 'EREQUEST')
if (this.stream) this.emit('error', e)
errors.push(e)
}
})
this._addCallbackError(err, errors)

// process batch outputs
if (batchHasOutput) {
Expand Down Expand Up @@ -969,12 +986,7 @@ class Request extends BaseRequest {
}

const req = new tds.Request(procedureName, err => {
// to make sure we handle no-sql errors as well
if (err && (!errors.length || (errors.length && err.message !== errors[errors.length - 1].message))) {
err = new RequestError(err, 'EREQUEST')
if (this.stream) this.emit('error', err)
errors.push(err)
}
this._addCallbackError(err, errors)

delete this._cancel

Expand Down
42 changes: 42 additions & 0 deletions test/common/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,48 @@ module.exports = (sql, driver) => {
})
},

// `mode` is 'execute', 'stream' or 'prepared statement'
'execute with multiple errors' (mode, done) {
// a procedure call that gets two errors from the server, which tedious 15+ calls the
// request back with as one AggregateError
const statement = 'raiserror(N\'first\', 16, 1); raiserror(N\'second\', 16, 1)'
const execute = request => request.input('stmt', sql.NVarChar(sql.MAX), statement).execute('sp_executesql')
const isLastOfTwo = err => {
assert.ok(err instanceof sql.RequestError, `the request should fail with a RequestError, got ${err}`)
assert.strictEqual(err.message, 'second', 'the error should be the last one from the server')
assert.strictEqual(err.number, 50000, 'the error should be the one from the server')
assert.deepStrictEqual(err.precedingErrors.map(e => e.message), ['first'], 'the error before it should precede it, once')
return true
}

let run
if (mode === 'stream') {
run = new Promise((resolve, reject) => {
const req = new sql.Request()
req.stream = true
const errors = []
req.on('error', err => errors.push(err.message))
req.on('done', () => {
try {
assert.deepStrictEqual(errors, ['first', 'second'], 'the stream should emit each error from the server once and in order')
resolve()
} catch (e) {
reject(e)
}
})
execute(req)
})
} else if (mode === 'prepared statement') {
const ps = new sql.PreparedStatement()
run = ps.prepare(statement)
.then(() => assert.rejects(ps.execute({}), isLastOfTwo))
.finally(() => ps.unprepare())
} else {
run = assert.rejects(execute(new sql.Request()), isLastOfTwo)
}
run.then(() => done(), done)
},

'query with an error that does not end the batch' (done) {
const req = new TestRequest()
req.query('raiserror(N\'Something went wrong\', 16, 1); select 1 as a', err => {
Expand Down
89 changes: 89 additions & 0 deletions test/common/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -2251,6 +2251,95 @@ describe('error codes', () => {
})
})

describe('errors from the server (tedious)', () => {
const { EventEmitter } = require('node:events')
const tds = require('tedious')
const Request = require('../../lib/tedious/request')

before(() => { sql.Promise = Promise })

// what the connection emits for an error from the server
const serverError = message => ({ message, number: 50000, state: 1, class: 16, lineNumber: 1 })

// what tedious 15+ calls a request back with when the server sent errors with `messages`
const reported = messages => {
const errors = messages.map(message => Object.assign(new tds.RequestError(message, 'EREQUEST'), { number: 50000 }))
return errors.length > 1 ? new AggregateError(errors) : errors[0]
}

// stands in for a tedious connection that answers each request with an error from the server
// for each of `messages`, and then calls the request back with `err`
const connect = (messages, err = reported(messages)) => {
const connection = Object.assign(new EventEmitter(), { cancel () {} })
connection.execSql = connection.execSqlBatch = connection.callProcedure = request => setImmediate(() => {
for (const message of messages) connection.emit('errorMessage', serverError(message))
request.callback(err, 0)
})
return connection
}

// a pool that lends `connection`
const lend = connection => {
const pool = new BasePool({})
pool._connected = true
pool._acquire = () => Promise.resolve(connection)
pool.release = () => pool
return pool
}

// a request on a connection that answers as `connect` says
const requestTo = (...answer) => new Request(lend(connect(...answer)))

// runs `method` on `request`
const run = (method, request) => request[method](method === 'execute' ? 'sp_test' : 'select 1')

// the error should be the last error from the server, after the ones before it, each once
const isLastOf = messages => err => {
assert.ok(err instanceof sql.RequestError, `the error should be a RequestError, got ${err.name}`)
assert.strictEqual(err.message, messages.at(-1), 'the error should be the last one from the server')
assert.strictEqual(err.number, 50000, 'the error should be the one that the connection emitted')
assert.deepStrictEqual(err.precedingErrors.map(e => e.message), messages.slice(0, -1), 'the errors before it should precede it, each once and in order')
return true
}

for (const method of ['query', 'execute']) {
it(`should reject with the last of two errors from the server (${method})`, async () => {
await assert.rejects(run(method, requestTo(['first', 'second'])), isLastOf(['first', 'second']))
})

it(`should keep each of two errors that have the same message (${method})`, async () => {
await assert.rejects(run(method, requestTo(['same', 'same'])), isLastOf(['same', 'same']))
})

it(`should reject with the one error from the server (${method})`, async () => {
await assert.rejects(run(method, requestTo(['only'])), isLastOf(['only']))
})

it(`should add an error that tedious makes after the errors from the server (${method})`, async () => {
const timeout = new tds.RequestError('Timeout: Request failed to complete in 15000ms', 'ETIMEOUT')

await assert.rejects(run(method, requestTo(['first', 'second'], timeout)), err => {
assert.strictEqual(err.code, 'ETIMEOUT', 'the error should be the one that tedious made')
assert.strictEqual(err.originalError, timeout, 'the error should be the one that tedious made')
assert.deepStrictEqual(err.precedingErrors.map(e => e.message), ['first', 'second'], 'the errors from the server should precede it')
return true
})
})

it(`should emit each of two errors from the server once from a stream, then done (${method})`, async () => {
const request = requestTo(['first', 'second'])
request.stream = true
const emitted = []
request.on('error', err => emitted.push(err.message))
const done = new Promise(resolve => request.once('done', resolve))

run(method, request)
await within(done, 'the stream should emit done')
assert.deepStrictEqual(emitted, ['first', 'second'], 'the stream should emit each error from the server once and in order')
})
}
})

describe('operations with no connection', () => {
// no global pool exists in this suite, so these objects have no parent at all
const cases = [
Expand Down
3 changes: 3 additions & 0 deletions test/tedious/tedious.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ describe('tedious', () => {
it('query with an error that does not end the batch', done => TESTS['query with an error that does not end the batch'](done))
it('query with a constraint violation', done => TESTS['query with a constraint violation'](true, done))
it('query with multiple errors', done => TESTS['query with multiple errors'](done))
it('execute with multiple errors', done => TESTS['execute with multiple errors']('execute', done))
it('execute with multiple errors (stream)', done => TESTS['execute with multiple errors']('stream', done))
it('execute with multiple errors (prepared statement)', done => TESTS['execute with multiple errors']('prepared statement', done))
it('query with raiseerror', done => TESTS['query with raiseerror'](done))
it('query with toReadableStream', done => TESTS['query with toReadableStream'](done))
it('query with pipe', done => TESTS['query with pipe'](done))
Expand Down