-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.js
More file actions
235 lines (205 loc) · 6.73 KB
/
query.js
File metadata and controls
235 lines (205 loc) · 6.73 KB
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
235
const dbPool = require('./pool');
const { promisify } = require('util');
const logger = require('../logger');
class QueryExecutor {
constructor() {
this.pool = dbPool;
this.logger = logger.child({ module: 'database:query' });
}
/**
* Execute a read query (can be routed to read replicas)
* @param {string} text - SQL query string
* @param {Array} params - Query parameters
* @param {Object} [options] - Query options
* @param {boolean} [options.usePrimary=false] - Force using primary database
* @param {string} [options.queryName] - Name for logging and metrics
* @returns {Promise<Object>} Query result
*/
async query(text, params = [], options = {}) {
const { usePrimary = false, queryName } = options;
const startTime = Date.now();
const queryId = Math.random().toString(36).substring(2, 10);
const logContext = {
queryId,
query: queryName || this._getQueryName(text),
params: this._sanitizeParams(params),
usePrimary
};
try {
this.logger.debug(logContext, 'Executing database query');
// Use primary for writes or when explicitly requested
const result = usePrimary
? await this.pool.writeQuery(text, params)
: await this.pool.readQuery(text, params);
const duration = Date.now() - startTime;
this.logger.debug({
...logContext,
rowCount: result?.rowCount,
durationMs: duration
}, 'Query completed successfully');
return result;
} catch (error) {
const errorContext = {
...logContext,
error: error.message,
stack: error.stack,
code: error.code,
durationMs: Date.now() - startTime
};
this.logger.error(errorContext, 'Database query failed');
// Enhance error with context
error.queryId = queryId;
error.queryText = text;
error.queryParams = params;
throw error;
}
}
/**
* Execute a transaction
* @param {Function} callback - Async function that receives a client and performs queries
* @returns {Promise<*>} The result of the callback
*/
async transaction(callback) {
const client = await this.pool.connect();
const queryClient = {
query: (text, params) => client.query(text, params),
release: (err) => client.release(err)
};
try {
await client.query('BEGIN');
const result = await callback(queryClient);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
this.logger.error({ error: error.message, stack: error.stack }, 'Transaction failed');
throw error;
} finally {
client.release();
}
}
/**
* Execute multiple queries in a transaction
* @param {Array<{text: string, params: Array}>} queries - Array of query objects
* @returns {Promise<Array>} Array of query results
*/
async batch(queries) {
return this.transaction(async (client) => {
const results = [];
for (const query of queries) {
const result = await client.query(query.text, query.params || []);
results.push(result);
}
return results;
});
}
/**
* Get a single row from the database
* @param {string} text - SQL query
* @param {Array} params - Query parameters
* @returns {Promise<Object|null>} First row or null if no results
*/
async getOne(text, params = []) {
const result = await this.query(text, params);
return result.rows[0] || null;
}
/**
* Get all rows from a query
* @param {string} text - SQL query
* @param {Array} params - Query parameters
* @returns {Promise<Array>} Array of rows
*/
async getAll(text, params = []) {
const result = await this.query(text, params);
return result.rows;
}
/**
* Insert a row and return the inserted row
* @param {string} table - Table name
* @param {Object} data - Column-value pairs
* @param {string} [returning='*'] - Columns to return
* @returns {Promise<Object>} Inserted row
*/
async insert(table, data, returning = '*') {
const keys = Object.keys(data);
const values = Object.values(data);
const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
const columns = keys.map(k => `"${k}"`).join(', ');
const text = `
INSERT INTO "${table}" (${columns})
VALUES (${placeholders})
RETURNING ${returning}
`;
const result = await this.query(text, values, { usePrimary: true });
return result.rows[0];
}
/**
* Update rows and return the updated rows
* @param {string} table - Table name
* @param {Object} data - Column-value pairs to update
* @param {Object} where - Conditions for the WHERE clause
* @param {string} [returning='*'] - Columns to return
* @returns {Promise<Array>} Updated rows
*/
async update(table, data, where, returning = '*') {
const setClause = Object.keys(data)
.map((key, i) => `"${key}" = $${i + 1}`)
.join(', ');
const whereClause = Object.keys(where)
.map((key, i) => `"${key}" = $${i + Object.keys(data).length + 1}`)
.join(' AND ');
const values = [...Object.values(data), ...Object.values(where)];
const text = `
UPDATE "${table}"
SET ${setClause}
WHERE ${whereClause}
RETURNING ${returning}
`;
const result = await this.query(text, values, { usePrimary: true });
return result.rows;
}
/**
* Delete rows and return the deleted rows
* @param {string} table - Table name
* @param {Object} where - Conditions for the WHERE clause
* @param {string} [returning='*'] - Columns to return
* @returns {Promise<Array>} Deleted rows
*/
async delete(table, where, returning = '*') {
const whereClause = Object.keys(where)
.map((key, i) => `"${key}" = $${i + 1}`)
.join(' AND ');
const values = Object.values(where);
const text = `
DELETE FROM "${table}"
WHERE ${whereClause}
RETURNING ${returning}
`;
const result = await this.query(text, values, { usePrimary: true });
return result.rows;
}
/**
* Sanitize parameters for logging
* @private
*/
_sanitizeParams(params) {
if (!params || !Array.isArray(params)) return [];
return params.map(p => {
if (Buffer.isBuffer(p)) return '<Buffer>';
if (p instanceof Date) return p.toISOString();
if (typeof p === 'object') return JSON.stringify(p);
return p;
});
}
/**
* Extract a simple query name for logging
* @private
*/
_getQueryName(sql) {
if (!sql) return 'unknown';
const match = sql.trim().match(/^\s*(\w+)/);
return match ? match[1].toLowerCase() : 'unknown';
}
}
// Export a singleton instance
module.exports = new QueryExecutor();