SQLITE 3
This commit is contained in:
63
server/utils/database.ts
Normal file
63
server/utils/database.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import Database from 'better-sqlite3'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
let db: Database.Database | null = null
|
||||
|
||||
export function getDatabase(): Database.Database {
|
||||
if (db) return db
|
||||
|
||||
const dbDir = path.join(process.cwd(), 'server/database')
|
||||
const dbPath = path.join(dbDir, 'evilspins.db')
|
||||
|
||||
// Créer le dossier si nécessaire
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true })
|
||||
}
|
||||
|
||||
// Connexion à la base
|
||||
db = new Database(dbPath, {
|
||||
verbose: process.env.NODE_ENV === 'development' ? console.log : undefined
|
||||
})
|
||||
|
||||
// Activer les clés étrangères
|
||||
db.pragma('foreign_keys = ON')
|
||||
|
||||
// Initialiser le schéma si la DB est vide
|
||||
initializeSchema(db)
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
function initializeSchema(database: Database.Database) {
|
||||
const schemaPath = path.join(process.cwd(), 'server/database/schema.sql')
|
||||
|
||||
// Vérifier si les tables existent déjà
|
||||
const tableCheck = database
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='tracks'")
|
||||
.get()
|
||||
|
||||
if (!tableCheck) {
|
||||
console.log('🔧 Initialisation du schéma de la base de données...')
|
||||
const schema = fs.readFileSync(schemaPath, 'utf-8')
|
||||
|
||||
// Exécuter chaque statement SQL
|
||||
const statements = schema
|
||||
.split(';')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
|
||||
for (const statement of statements) {
|
||||
database.exec(statement)
|
||||
}
|
||||
|
||||
console.log('✅ Schéma initialisé avec succès')
|
||||
}
|
||||
}
|
||||
|
||||
export function closeDatabase() {
|
||||
if (db) {
|
||||
db.close()
|
||||
db = null
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user