102 lines
2.8 KiB
TypeScript
102 lines
2.8 KiB
TypeScript
|
import { PrismaClient, Prisma } from '../generated/prisma';
|
||
|
|
||
|
// Global variable to store the Prisma client instance
|
||
|
const globalForPrisma = globalThis as unknown as {
|
||
|
prisma: PrismaClient | undefined;
|
||
|
};
|
||
|
|
||
|
// Create Prisma client with logging
|
||
|
export const prisma = globalForPrisma.prisma ?? new PrismaClient({
|
||
|
log: process.env.NODE_ENV === 'development'
|
||
|
? ['query', 'error', 'warn']
|
||
|
: ['error'],
|
||
|
});
|
||
|
|
||
|
// Prevent multiple instances in development
|
||
|
if (process.env.NODE_ENV !== 'production') {
|
||
|
globalForPrisma.prisma = prisma;
|
||
|
}
|
||
|
|
||
|
// Database initialization function
|
||
|
export async function initializeDatabase() {
|
||
|
try {
|
||
|
console.log('[DB] Initializing database connection...');
|
||
|
|
||
|
// Test connection
|
||
|
await prisma.$connect();
|
||
|
console.log('[DB] Database connection established');
|
||
|
|
||
|
// Ensure core properties exist (name, description)
|
||
|
await prisma.property.upsert({
|
||
|
where: { name: 'name' },
|
||
|
update: {},
|
||
|
create: { name: 'name', globalUsageCount: 0 }
|
||
|
});
|
||
|
|
||
|
await prisma.property.upsert({
|
||
|
where: { name: 'description' },
|
||
|
update: {},
|
||
|
create: { name: 'description', globalUsageCount: 0 }
|
||
|
});
|
||
|
|
||
|
console.log('[DB] Core properties initialized');
|
||
|
return true;
|
||
|
} catch (error) {
|
||
|
console.error('[DB] Failed to initialize database:', error);
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Graceful shutdown
|
||
|
export async function disconnectDatabase() {
|
||
|
try {
|
||
|
await prisma.$disconnect();
|
||
|
console.log('[DB] Database connection closed');
|
||
|
} catch (error) {
|
||
|
console.error('[DB] Error closing database connection:', error);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Helper function for transactions
|
||
|
export async function withTransaction<T>(
|
||
|
callback: (tx: Prisma.TransactionClient) => Promise<T>
|
||
|
): Promise<T> {
|
||
|
return await prisma.$transaction(async (tx) => {
|
||
|
console.log('[DB] Transaction started');
|
||
|
try {
|
||
|
const result = await callback(tx);
|
||
|
console.log('[DB] Transaction completed successfully');
|
||
|
return result;
|
||
|
} catch (error) {
|
||
|
console.log('[DB] Transaction failed:', error);
|
||
|
throw error;
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// Debug function
|
||
|
export async function debugDump() {
|
||
|
if (process.env.NODE_ENV !== 'development') return;
|
||
|
|
||
|
console.log('[DATABASE DEBUG] URLs:');
|
||
|
const urls = await prisma.url.findMany();
|
||
|
urls.forEach(url => {
|
||
|
console.log(`[DATABASE DEBUG] ID: ${url.id}, URL: ${url.url}`);
|
||
|
});
|
||
|
|
||
|
console.log('[DATABASE DEBUG] Items:');
|
||
|
const items = await prisma.item.findMany({
|
||
|
include: {
|
||
|
itemProperties: {
|
||
|
include: { property: true }
|
||
|
}
|
||
|
}
|
||
|
});
|
||
|
|
||
|
items.forEach(item => {
|
||
|
const nameProperty = item.itemProperties.find(ip => ip.property.name === 'name');
|
||
|
console.log(`[DATABASE DEBUG] ID: ${item.id}, Name: '${nameProperty?.value || 'Unknown'}'`);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
export default prisma;
|