Skip to content

Commit 4a092ae

Browse files
committed
feat: normalize mysql error codes to standard domain codes
Signed-off-by: Muhammad Aaqil <aaqilcs102@gmail.com>
1 parent 429ba5c commit 4a092ae

3 files changed

Lines changed: 254 additions & 8 deletions

File tree

‎lib/normalize-error.js‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
'use strict';
2+
3+
/**
4+
* Normalizes PostgreSQL-specific error codes (SQLSTATE) to standard, protocol-neutral domain codes.
5+
*/
6+
module.exports = function(err) {
7+
if (!err || !err.code) return err;
8+
9+
// PostgreSQL uses 5-character SQLSTATE error codes
10+
switch (err.code) {
11+
// 1. Data Integrity & Constraints
12+
case '23505': // unique_violation
13+
err.code = 'UNIQUE_CONSTRAINT_VIOLATION';
14+
break;
15+
case '23503': // foreign_key_violation
16+
case '23P01': // exclusion_violation
17+
err.code = 'FOREIGN_KEY_VIOLATION';
18+
break;
19+
case '23502': // not_null_violation
20+
err.code = 'NOT_NULL_VIOLATION';
21+
break;
22+
case '23514': // check_violation
23+
err.code = 'CHECK_CONSTRAINT_VIOLATION';
24+
break;
25+
26+
// 2. Schema & Object Definitions
27+
case '42P01': // undefined_table
28+
err.code = 'TABLE_NOT_FOUND';
29+
break;
30+
case '42703': // undefined_column
31+
err.code = 'COLUMN_NOT_FOUND';
32+
break;
33+
34+
// 3. Data Formatting & Types
35+
case '22001': // string_data_right_truncation
36+
case '22003': // numeric_value_out_of_range
37+
case '22P02': // invalid_text_representation
38+
err.code = 'DATA_TYPE_MISMATCH';
39+
break;
40+
41+
// 4. Concurrency & Execution
42+
case '40001': // serialization_failure
43+
case '40P01': // deadlock_detected
44+
case '55P03': // lock_not_available
45+
err.code = 'LOCK_CONFLICT';
46+
break;
47+
case '57014': // query_canceled
48+
err.code = 'QUERY_TIMEOUT';
49+
break;
50+
case '42601': // syntax_error
51+
err.code = 'SYNTAX_ERROR';
52+
break;
53+
54+
// 5. Infrastructure & Connection
55+
case '08000': // connection_exception
56+
case '08003': // connection_does_not_exist
57+
case '08006': // connection_failure
58+
case '57P01': // admin_shutdown
59+
case '57P02': // crash_shutdown
60+
case '57P03': // cannot_connect_now
61+
err.code = 'CONNECTION_FAILURE';
62+
break;
63+
}
64+
return err;
65+
};

‎lib/postgresql.js‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const debug = require('debug')('loopback:connector:postgresql');
1717
const debugData = require('debug')('loopback:connector:postgresql:data');
1818
const debugSort = require('debug')('loopback:connector:postgresql:order');
1919
const Promise = require('bluebird');
20+
const normalizePostgreSQLError = require('./normalize-error');
2021

2122
/**
2223
*
@@ -164,15 +165,23 @@ PostgreSQL.prototype.executeSQL = function(sql, params, options, callback) {
164165
debug('SQL: %s', sql);
165166
}
166167

168+
function handleResponse(releaseCb, err, result) {
169+
if (releaseCb) {
170+
releaseCb(err);
171+
}
172+
if (err) {
173+
debug('Raw driver error intercepted: %O', err);
174+
// Transform raw PostgreSQL driver error into standard LoopBack DB error
175+
err = normalizePostgreSQLError(err);
176+
}
177+
callback(err, result);
178+
}
179+
167180
function executeWithConnection(connection, releaseCb) {
168181
connection.query(sql, params, function(err, data) {
169182
// if(err) console.error(err);
170183
if (err) debug(err);
171184
if (data) debugData('%j', data);
172-
// Release the connection back to the pool.
173-
if (releaseCb) {
174-
releaseCb(err);
175-
}
176185
let result = null;
177186
if (data) {
178187
switch (data.command) {
@@ -188,28 +197,36 @@ PostgreSQL.prototype.executeSQL = function(sql, params, options, callback) {
188197
result = data.rows;
189198
}
190199
}
191-
callback(err ? err : null, result);
200+
handleResponse(releaseCb, err, result);
192201
});
193202
}
194203

195204
const transaction = options.transaction;
196205
if (transaction && transaction.connector === this) {
197206
if (!transaction.connection) {
198207
return process.nextTick(function() {
199-
callback(new Error(g.f('Connection does not exist')));
208+
const err = new Error(g.f('Transaction is not active'));
209+
err.code = 'TRANSACTION_NOT_ACTIVE';
210+
callback(err);
200211
});
201212
}
213+
202214
if (transaction.txId !== transaction.connection.txId) {
203215
return process.nextTick(function() {
204-
callback(new Error(g.f('Transaction is not active')));
216+
const err = new Error(g.f('Transaction is not active'));
217+
err.code = 'TRANSACTION_NOT_ACTIVE';
218+
callback(err);
205219
});
206220
}
207221
debug('Execute SQL within a transaction');
208222
// Do not release the connection
209223
executeWithConnection(transaction.connection, null);
210224
} else {
211225
self.pg.connect(function(err, connection, releaseCb) {
212-
if (err) return callback(err);
226+
if (err) {
227+
debug('Raw driver error intercepted: %O', err);
228+
return callback(normalizePostgreSQLError(err));
229+
}
213230
// pg-pool requires attaching an error handler to each item checked out off the pool,
214231
// which will handle connection-level errors.
215232
// See https://github.com/brianc/node-postgres/issues/1324

‎test/error-normalization.test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
'use strict';
2+
require('./init.js');
3+
const should = require('should');
4+
5+
let db, ErrorModel;
6+
const normalizePostgreSQLError = require('../lib/normalize-error.js');
7+
8+
describe('postgresql error normalization unit tests', function() {
9+
it('normalizes unique constraint violations (23505)', function() {
10+
const rawErr = new Error('duplicate key value violates unique constraint');
11+
rawErr.code = '23505';
12+
13+
const normalized = normalizePostgreSQLError(rawErr);
14+
normalized.should.have.property('code', 'UNIQUE_CONSTRAINT_VIOLATION');
15+
});
16+
17+
it('normalizes undefined table errors (42P01)', function() {
18+
const rawErr = new Error('relation "foo" does not exist');
19+
rawErr.code = '42P01';
20+
21+
const normalized = normalizePostgreSQLError(rawErr);
22+
normalized.should.have.property('code', 'TABLE_NOT_FOUND');
23+
});
24+
25+
it('normalizes undefined column errors (42703)', function() {
26+
const rawErr = new Error('column "non_existent" does not exist');
27+
rawErr.code = '42703';
28+
29+
const normalized = normalizePostgreSQLError(rawErr);
30+
normalized.should.have.property('code', 'COLUMN_NOT_FOUND');
31+
});
32+
33+
it('normalizes syntax errors (42601)', function() {
34+
const rawErr = new Error('syntax error at or near "SELCT"');
35+
rawErr.code = '42601';
36+
37+
const normalized = normalizePostgreSQLError(rawErr);
38+
normalized.should.have.property('code', 'SYNTAX_ERROR');
39+
});
40+
41+
it('normalizes query timeout errors (57014)', function() {
42+
const rawErr = new Error('canceling statement due to statement timeout');
43+
rawErr.code = '57014';
44+
45+
const normalized = normalizePostgreSQLError(rawErr);
46+
normalized.should.have.property('code', 'QUERY_TIMEOUT');
47+
});
48+
49+
it('normalizes lock conflict and deadlock errors (40P01, 40001, 55P03)', function() {
50+
['40P01', '40001', '55P03'].forEach(code => {
51+
const rawErr = new Error('lock conflict / deadlock');
52+
rawErr.code = code;
53+
const normalized = normalizePostgreSQLError(rawErr);
54+
normalized.should.have.property('code', 'LOCK_CONFLICT');
55+
});
56+
});
57+
58+
it('normalizes not-null violations (23502)', function() {
59+
const rawErr = new Error('null value in column violates not-null constraint');
60+
rawErr.code = '23502';
61+
62+
const normalized = normalizePostgreSQLError(rawErr);
63+
normalized.should.have.property('code', 'NOT_NULL_VIOLATION');
64+
});
65+
});
66+
67+
describe('postgresql error normalization', function() {
68+
before(function(done) {
69+
db = global.getDataSource(true);
70+
// Explicitly configure unique index so automigrate creates the constraint in Postgres
71+
ErrorModel = db.define('ErrorModel', {
72+
name: {type: String, index: {unique: true}, required: true},
73+
});
74+
db.automigrate('ErrorModel', done);
75+
});
76+
77+
beforeEach(function(done) {
78+
ErrorModel.destroyAll(done);
79+
});
80+
81+
it('normalizes unique constraint violations (23505 -> UNIQUE_CONSTRAINT_VIOLATION)', function(done) {
82+
ErrorModel.create({name: 'test-unique'}, function(err) {
83+
if (err) return done(err);
84+
// Attempt to insert duplicate record
85+
ErrorModel.create({name: 'test-unique'}, function(err) {
86+
should.exist(err);
87+
err.should.have.property('code', 'UNIQUE_CONSTRAINT_VIOLATION');
88+
done();
89+
});
90+
});
91+
});
92+
93+
it('normalizes table not found errors (42P01 -> TABLE_NOT_FOUND)', function(done) {
94+
db.connector.executeSQL(
95+
'SELECT * FROM "non_existent_table_xyz"',
96+
[],
97+
{},
98+
function(err, results) {
99+
should.exist(err);
100+
err.should.have.property('code', 'TABLE_NOT_FOUND');
101+
done();
102+
},
103+
);
104+
});
105+
106+
it('normalizes column not found errors (42703 -> COLUMN_NOT_FOUND)', function(done) {
107+
db.connector.executeSQL(
108+
'SELECT "non_existent_column" FROM "errormodel"',
109+
[],
110+
{},
111+
function(err) {
112+
should.exist(err);
113+
err.should.have.property('code', 'COLUMN_NOT_FOUND');
114+
done();
115+
},
116+
);
117+
});
118+
119+
it('normalizes syntax errors (42601 -> SYNTAX_ERROR)', function(done) {
120+
db.connector.executeSQL(
121+
'SELCT * FROM "errormodel"',
122+
[],
123+
{},
124+
function(err) {
125+
should.exist(err);
126+
err.should.have.property('code', 'SYNTAX_ERROR');
127+
done();
128+
},
129+
);
130+
});
131+
132+
it('normalizes not-null constraint violations (23502 -> NOT_NULL_VIOLATION)', function(done) {
133+
// Bypass model validation by executing raw SQL or using connector directly
134+
db.connector.executeSQL(
135+
'INSERT INTO "errormodel" ("name") VALUES ($1)',
136+
[null],
137+
{},
138+
function(err) {
139+
should.exist(err);
140+
err.should.have.property('code', 'NOT_NULL_VIOLATION');
141+
done();
142+
},
143+
);
144+
});
145+
146+
it('normalizes inactive transaction or connection errors at the connector level', function(done) {
147+
const Transaction = require('loopback-connector').Transaction;
148+
Transaction.begin(db.connector, function(err, tx) {
149+
if (err) return done(err);
150+
151+
// Force commit the transaction so its connection is cleared
152+
tx.commit(function(err) {
153+
if (err) return done(err);
154+
155+
// Call executeSQL directly to exercise the connector's internal check
156+
db.connector.executeSQL('SELECT 1', [], {transaction: tx}, function(err) {
157+
should.exist(err);
158+
err.should.have.property('code', 'TRANSACTION_NOT_ACTIVE');
159+
done();
160+
});
161+
});
162+
});
163+
});
164+
});

0 commit comments

Comments
 (0)