import fs from 'fs' import path from 'path' import { fileURLToPath } from 'url' import { dirname } from 'path' import db, { initDatabase } from './database.js' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) async function seedDatabase() { console.log('데이터베이스 초기화 중...') initDatabase() // 기존 데이터 삭제 db.exec('DELETE FROM layers') // CSV 파일 읽기 const csvPath = path.join(__dirname, '../../../LayerList.csv') const csvContent = fs.readFileSync(csvPath, 'utf-8') // CSV 파싱 const lines = csvContent.split('\n') const headers = lines[0].split(',').map(h => h.replace(/"/g, '').trim()) const insert = db.prepare(` INSERT INTO layers (cmn_cd, up_cmn_cd, cmn_cd_full_nm, cmn_cd_nm, cmn_cd_level, clnm) VALUES (?, ?, ?, ?, ?, ?) `) const insertMany = db.transaction((rows: any[]) => { for (const row of rows) { insert.run(row) } }) const rows = [] for (let i = 1; i < lines.length; i++) { const line = lines[i].trim() if (!line) continue // CSV 파싱 (쉼표로 구분, 따옴표 처리) const values = [] let current = '' let inQuotes = false for (let j = 0; j < line.length; j++) { const char = line[j] if (char === '"') { inQuotes = !inQuotes } else if (char === ',' && !inQuotes) { values.push(current.trim()) current = '' } else { current += char } } values.push(current.trim()) // NULL 값 처리 const row = values.map(v => { if (v === 'NULL' || v === '') return null return v.replace(/"/g, '') }) if (row.length >= 6) { rows.push([ row[0], // cmn_cd row[1], // up_cmn_cd row[2], // cmn_cd_full_nm row[3], // cmn_cd_nm parseInt(row[4] || '0'), // cmn_cd_level row[5], // clnm ]) } } console.log(`${rows.length}개의 레이어 데이터 삽입 중...`) insertMany(rows) console.log('시드 완료!') // 결과 확인 const count = db.prepare('SELECT COUNT(*) as count FROM layers').get() as { count: number } console.log(`총 ${count.count}개의 레이어가 저장되었습니다.`) db.close() } seedDatabase().catch(console.error)