migrate from SQLite to PostgreSQL with Drizzle ORM

- Updated all packages to latest versions (React 19, Next.js 14.2.32)
- Replaced sqlite3 with pg and drizzle-orm dependencies
- Created complete PostgreSQL schema with relationships and indexes
- Migrated all API endpoints from SQLite to Drizzle queries
- Added database seeding with sample data
- Updated authentication to use bcrypt instead of pbkdf2
- Configured connection pooling for PostgreSQL
- Updated app version to 1.0.0
- All endpoints tested and working correctly
This commit is contained in:
2025-09-06 12:56:33 +02:00
parent 52bde64e7f
commit 860070a302
26 changed files with 2526 additions and 2403 deletions

View File

@@ -1,76 +1,74 @@
import type { NextApiRequest, NextApiResponse } from "next"
import sqlite3 from "sqlite3"
import path from "path"
import { db, schema } from '../../../lib/db/connection'
import { eq, and, desc, count } from 'drizzle-orm'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).json({ error: "Method not allowed" })
const { page = '1', limit = '50', action, resource_type, user_id } = req.query
const dbPath = path.join(process.cwd(), "database", "antihoax.db")
const db = new sqlite3.Database(dbPath)
try {
let whereConditions: string[] = []
let params: any[] = []
let whereConditions = []
if (action) {
whereConditions.push("a.action = ?")
params.push(action)
whereConditions.push(eq(schema.auditLogs.action, action as string))
}
if (resource_type) {
whereConditions.push("a.resource_type = ?")
params.push(resource_type)
whereConditions.push(eq(schema.auditLogs.resourceType, resource_type as string))
}
if (user_id) {
whereConditions.push("a.user_id = ?")
params.push(parseInt(user_id as string))
whereConditions.push(eq(schema.auditLogs.userId, parseInt(user_id as string)))
}
const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : ''
const offset = (parseInt(page as string) - 1) * parseInt(limit as string)
const limitInt = parseInt(limit as string)
const query = `
SELECT
a.*,
u.email as user_email,
COUNT(*) OVER() as total_count
FROM audit_logs a
LEFT JOIN users u ON a.user_id = u.id
${whereClause}
ORDER BY a.created_at DESC
LIMIT ? OFFSET ?
`
params.push(parseInt(limit as string), offset)
const logs = await new Promise<any[]>((resolve, reject) => {
db.all(query, params, (err, rows) => {
if (err) reject(err)
else resolve(rows)
// Get logs with user info
const logs = await db
.select({
id: schema.auditLogs.id,
userId: schema.auditLogs.userId,
userEmail: schema.users.email,
action: schema.auditLogs.action,
resourceType: schema.auditLogs.resourceType,
resourceId: schema.auditLogs.resourceId,
details: schema.auditLogs.details,
ipAddress: schema.auditLogs.ipAddress,
createdAt: schema.auditLogs.createdAt
})
})
.from(schema.auditLogs)
.leftJoin(schema.users, eq(schema.auditLogs.userId, schema.users.id))
.where(whereConditions.length > 0 ? and(...whereConditions) : undefined)
.orderBy(desc(schema.auditLogs.createdAt))
.limit(limitInt)
.offset(offset)
const total = logs.length > 0 ? logs[0].total_count : 0
const totalPages = Math.ceil(total / parseInt(limit as string))
// Get total count for pagination
const [totalResult] = await db
.select({ count: count() })
.from(schema.auditLogs)
.where(whereConditions.length > 0 ? and(...whereConditions) : undefined)
const total = totalResult.count
const totalPages = Math.ceil(total / limitInt)
res.json({
logs: logs.map(log => ({
id: log.id,
user_id: log.user_id,
user_email: log.user_email,
user_id: log.userId,
user_email: log.userEmail,
action: log.action,
resource_type: log.resource_type,
resource_id: log.resource_id,
resource_type: log.resourceType,
resource_id: log.resourceId,
details: log.details ? JSON.parse(log.details) : null,
ip_address: log.ip_address,
created_at: log.created_at
ip_address: log.ipAddress,
created_at: log.createdAt
})),
pagination: {
page: parseInt(page as string),
limit: parseInt(limit as string),
limit: limitInt,
total,
totalPages
}
@@ -79,7 +77,5 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
} catch (error) {
console.error('Audit logs error:', error)
res.status(500).json({ error: "Failed to fetch audit logs" })
} finally {
db.close()
}
}