import Database from 'better-sqlite3' import fs from 'fs' import path from 'path' let db = null let isInitialized = false export function getDb() { if (db) return db const dataDir = path.join(process.cwd(), 'data') if (!fs.existsSync(dataDir)) { fs.mkdirSync(dataDir, { recursive: true }) } const dbPath = path.join(dataDir, 'knowledge.db') db = new Database(dbPath) db.pragma('journal_mode = WAL') db.pragma('cache_size = -64000') db.pragma('temp_store = memory') setupTables(db) return db } function setupTables(db) { db.exec(` CREATE VIRTUAL TABLE IF NOT EXISTS documents USING fts5( title, content, tags, metadata ); `) db.exec(` CREATE TABLE IF NOT EXISTS documents_raw ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, content TEXT NOT NULL, tags TEXT, metadata TEXT, date TEXT, source_url TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); `) db.exec(` CREATE INDEX IF NOT EXISTS idx_date ON documents_raw(date DESC); `) db.exec(` CREATE TRIGGER IF NOT EXISTS documents_ai AFTER INSERT ON documents_raw BEGIN INSERT INTO documents(rowid, title, content, tags, metadata) VALUES (new.id, new.title, new.content, new.tags, new.metadata); END; `) db.exec(` CREATE TRIGGER IF NOT EXISTS documents_ad AFTER DELETE ON documents_raw BEGIN INSERT INTO documents(documents, rowid, title, content, tags, metadata) VALUES('delete', old.id, old.title, old.content, old.tags, old.metadata); END; `) db.exec(` CREATE TRIGGER IF NOT EXISTS documents_au AFTER UPDATE ON documents_raw BEGIN INSERT INTO documents(documents, rowid, title, content, tags, metadata) VALUES('delete', old.id, old.title, old.content, old.tags, old.metadata); INSERT INTO documents(rowid, title, content, tags, metadata) VALUES (new.id, new.title, new.content, new.tags, new.metadata); END; `) } export function initializeDatabase() { if (isInitialized) return const db = getDb() const count = db.prepare('SELECT count(*) as count FROM documents_raw').get() if (count.count === 0) { console.log('Seeding database with sample data...') seedDatabase(db) } isInitialized = true } function seedDatabase(db) { const seedData = [ { title: "Introduction to Next.js 14", content: "Next.js 14 introduces the App Router as stable. It allows for better server component usage, layout nesting, and improved performance. Key features include Server Actions, partial prerendering, and turbopack.", tags: "react,nextjs,webdev", metadata: '{"duration": "15:30"}', date: "2024-01-15", source_url: "https://youtube.com/watch?v=example1" }, { title: "Docker Best Practices 2024", content: "When building Docker images for production, always use multi-stage builds to reduce image size. Use alpine base images when possible. Don't run as root user. Leverage layer caching by copying package.json before source code.", tags: "docker,devops,deployment", metadata: '{"duration": "22:10"}', date: "2024-02-10", source_url: "https://youtube.com/watch?v=example2" }, { title: "SQLite for Local Apps", content: "SQLite is perfect for local-first applications. It requires no server setup, stores data in a single file, and supports full-text search via FTS5 extension. It's ACID compliant and extremely fast for read-heavy workloads.", tags: "database,sqlite,architecture", metadata: '{"duration": "18:45"}', date: "2024-03-05", source_url: "https://youtube.com/watch?v=example3" }, { title: "React Performance Optimization", content: "Key React performance techniques include memoization with useMemo and useCallback, code splitting with React.lazy, virtualization for long lists, and proper key usage. Avoid unnecessary re-renders by using React.memo.", tags: "react,performance,optimization", metadata: '{"duration": "25:00"}', date: "2024-03-20", source_url: "https://youtube.com/watch?v=example4" }, { title: "TypeScript Best Practices", content: "Use strict mode, avoid any types, leverage utility types, create proper interfaces, and use generics wisely. TypeScript improves code quality and catches errors at compile time.", tags: "typescript,webdev,bestpractices", metadata: '{"duration": "20:15"}', date: "2024-04-01", source_url: "https://youtube.com/watch?v=example5" } ] const stmt = db.prepare(` INSERT INTO documents_raw (title, content, tags, metadata, date, source_url) VALUES (@title, @content, @tags, @metadata, @date, @source_url) `) const insertMany = db.transaction((docs) => { for (const doc of docs) { stmt.run(doc) } }) insertMany(seedData) } export function closeDatabase() { if (db) { db.close() db = null isInitialized = false } }