* Initialize a new database at the given path
(dbPath: string)
| 94 | * Initialize a new database at the given path |
| 95 | */ |
| 96 | static initialize(dbPath: string): DatabaseConnection { |
| 97 | // Ensure parent directory exists |
| 98 | const dir = path.dirname(dbPath); |
| 99 | if (!fs.existsSync(dir)) { |
| 100 | fs.mkdirSync(dir, { recursive: true }); |
| 101 | } |
| 102 | |
| 103 | // Create and configure database |
| 104 | const { db, backend } = createDatabase(dbPath); |
| 105 | |
| 106 | configureConnection(db); |
| 107 | |
| 108 | // Run schema initialization |
| 109 | const schemaPath = path.join(__dirname, 'schema.sql'); |
| 110 | const schema = fs.readFileSync(schemaPath, 'utf-8'); |
| 111 | db.exec(schema); |
| 112 | |
| 113 | // Record current schema version so migrations aren't re-applied on open |
| 114 | const currentVersion = getCurrentVersion(db); |
| 115 | if (currentVersion < CURRENT_SCHEMA_VERSION) { |
| 116 | db.prepare( |
| 117 | 'INSERT OR IGNORE INTO schema_versions (version, applied_at, description) VALUES (?, ?, ?)' |
| 118 | ).run(CURRENT_SCHEMA_VERSION, Date.now(), 'Initial schema includes all migrations'); |
| 119 | } |
| 120 | |
| 121 | return new DatabaseConnection(db, dbPath, backend); |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Open an existing database |