Files
weeklyreport/backend/utils/db.ts
2026-01-04 17:24:47 +09:00

72 lines
1.6 KiB
TypeScript

import pg from 'pg'
const { Pool } = pg
let pool: pg.Pool | null = null
/**
* PostgreSQL 연결 풀 가져오기
*/
export function getPool(): pg.Pool {
if (!pool) {
const config = useRuntimeConfig()
const poolConfig = {
host: config.dbHost,
port: parseInt(config.dbPort as string),
database: config.dbName,
user: config.dbUser,
password: config.dbPassword,
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
}
console.log(`[DB] Connecting to ${poolConfig.host}:${poolConfig.port}/${poolConfig.database}`)
pool = new Pool(poolConfig)
pool.on('error', (err) => {
console.error('[DB] Unexpected pool error:', err)
})
console.log('[DB] PostgreSQL pool created')
}
return pool
}
/**
* 쿼리 실행
*/
export async function query<T = any>(sql: string, params?: any[]): Promise<T[]> {
const pool = getPool()
const result = await pool.query(sql, params)
return result.rows as T[]
}
/**
* 단일 행 조회
*/
export async function queryOne<T = any>(sql: string, params?: any[]): Promise<T | null> {
const rows = await query<T>(sql, params)
return rows[0] || null
}
/**
* INSERT/UPDATE/DELETE 실행
*/
export async function execute(sql: string, params?: any[]): Promise<number> {
const pool = getPool()
const result = await pool.query(sql, params)
return result.rowCount || 0
}
/**
* INSERT 후 반환
*/
export async function insertReturning<T = any>(sql: string, params?: any[]): Promise<T | null> {
const pool = getPool()
const result = await pool.query(sql, params)
return result.rows[0] || null
}