deckhearth/lib/database.js

47 lines
1.4 KiB
JavaScript
Raw Normal View History

import { neon } from '@neondatabase/serverless';
// Get the database URL from environment variables
const sql = neon(process.env.POSTGRES_URL);
// Database adapter that works with Neon
class DatabaseAdapter {
async query(sqlString, params = []) {
try {
// For Neon, we need to use tagged template literals
// This is a simplified approach - in production you'd want more robust parameter handling
let result;
if (params.length === 0) {
// No parameters
result = await sql`${sql.unsafe(sqlString)}`;
} else {
// With parameters - this is a simplified approach
// In production, you'd want proper parameter escaping
const escapedParams = params.map(param =>
typeof param === 'string' ? `'${param.replace(/'/g, "''")}'` : param
);
let query = sqlString;
for (let i = 0; i < escapedParams.length; i++) {
query = query.replace(`$${i + 1}`, escapedParams[i]);
}
result = await sql`${sql.unsafe(query)}`;
}
return {
rows: Array.isArray(result) ? result : [result],
rowCount: Array.isArray(result) ? result.length : 1
};
} catch (error) {
console.error('Database query error:', error);
throw error;
}
}
async raw(sqlString, params = []) {
return await this.query(sqlString, params);
}
}
export const db = new DatabaseAdapter();