Improved knex error reporting.

This commit is contained in:
DebaucheryLibrarian
2026-03-10 04:41:30 +01:00
parent d7c1c0ae5c
commit c7111329dc
3 changed files with 37 additions and 2 deletions

View File

@@ -27,7 +27,7 @@
"require-await": "off",
"no-param-reassign": ["error", {
"props": true,
"ignorePropertyModificationsFor": ["state", "acc", "req"]
"ignorePropertyModificationsFor": ["state", "acc", "req", "error"]
}]
},
"globals": {

View File

@@ -3,7 +3,7 @@
const config = require('config');
const knex = require('knex');
module.exports = knex({
const knexInstance = knex({
client: 'pg',
connection: config.database.owner,
pool: config.database.pool,
@@ -11,3 +11,23 @@ module.exports = knex({
asyncStackTraces: process.env.NODE_ENV === 'development',
// debug: process.env.NODE_ENV === 'development',
});
knexInstance.on('query', function onQuery(query) {
const bindingCount = query.bindings?.length ?? 0;
if (bindingCount > 10000) {
const error = new Error(`[knex] Dangerous query: ${bindingCount} bindings detected: ${query.sql?.slice(0, 200)}${query.sql?.length > 200 ? '...' : ''}`);
Error.captureStackTrace(error, onQuery);
// console.error(error);
throw error; // optionally hard-fail so you get a real stack trace
}
});
knexInstance.on('query-error', (error, query) => {
error.knexSql = `${query.sql?.slice(0, 200)}${query.sql?.length > 200 ? '...' : ''}`;
error.knexBindingCount = query.bindings?.length;
});
module.exports = knexInstance;

15
src/tools/huge-query.js Normal file
View File

@@ -0,0 +1,15 @@
'use strict';
const knex = require('../knex');
async function init() {
const data = Array.from({ length: 100_000 }, (value, index) => ({
id: `test_affiliate_${index}`,
}));
await knex('affiliates').insert(data);
console.log('Done!');
}
init();