|
| 1 | +import { PoolClient, QueryResult, QueryResultRow } from 'pg'; |
| 2 | + |
| 3 | +export class DatabaseService { |
| 4 | + constructor(private _client: PoolClient) {} |
| 5 | + |
| 6 | + /** |
| 7 | + * Runs a query with parameters and returns the result. |
| 8 | + */ |
| 9 | + async query<T extends QueryResultRow>(sql: string, params: any[] = []): Promise<QueryResult<T>> { |
| 10 | + try { |
| 11 | + return await this._client.query<T>(sql, params); |
| 12 | + } catch (error) { |
| 13 | + console.error('Database query error:', error); |
| 14 | + throw error; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Inserts a new record and returns the inserted row. |
| 20 | + */ |
| 21 | + async insert<T extends QueryResultRow>(tableName: string, data: Record<string, any>, returning: string[] = ['*']): Promise<T> { |
| 22 | + const columns = Object.keys(data).join(', '); |
| 23 | + const values = Object.values(data); |
| 24 | + const placeholders = values.map((_, i) => `$${i + 1}`).join(', '); |
| 25 | + const sql = `INSERT INTO "${tableName}" (${columns}) VALUES (${placeholders}) RETURNING ${returning.join(', ')};`; |
| 26 | + |
| 27 | + const result = await this.query<T>(sql, values); |
| 28 | + return result.rows[0]; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Updates a record and returns the updated row. |
| 33 | + */ |
| 34 | + async update<T extends QueryResultRow>(tableName: string, data: Record<string, any>, condition: Record<string, any>, returning: string[] = ['*']): Promise<T> { |
| 35 | + const setClauses = Object.keys(data) |
| 36 | + .map((key, i) => `"${key}" = $${i + 1}`) |
| 37 | + .join(', '); |
| 38 | + const whereClauses = Object.keys(condition) |
| 39 | + .map((key, i) => `"${key}" = $${i + Object.keys(data).length + 1}`) |
| 40 | + .join(' AND '); |
| 41 | + |
| 42 | + const values = [...Object.values(data), ...Object.values(condition)]; |
| 43 | + const sql = `UPDATE "${tableName}" SET ${setClauses} WHERE ${whereClauses} RETURNING ${returning.join(', ')};`; |
| 44 | + const result = await this.query<T>(sql, values); |
| 45 | + return result.rows[0]; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Deletes records and optionally returns the deleted rows. |
| 50 | + */ |
| 51 | + async delete<T extends QueryResultRow>(tableName: string, condition: Record<string, any>, returning: string[] = ['*']): Promise<T[]> { |
| 52 | + const whereClauses = Object.keys(condition) |
| 53 | + .map((key, i) => `"${key}" = $${i + 1}`) |
| 54 | + .join(' AND '); |
| 55 | + const values = Object.values(condition); |
| 56 | + const sql = `DELETE FROM "${tableName}" WHERE ${whereClauses} RETURNING ${returning.join(', ')};`; |
| 57 | + const result = await this.query<T>(sql, values); |
| 58 | + return result.rows; |
| 59 | + } |
| 60 | +} |
0 commit comments