Spaces:
Running

File size: 5,048 Bytes
f5c246b
 
 
 
 
7058290
f5c246b
 
 
 
 
 
 
 
 
 
 
 
7058290
 
 
 
 
 
f5c246b
7058290
f5c246b
 
 
 
 
7058290
f5c246b
 
 
 
 
7058290
 
 
f5c246b
 
 
7058290
 
f5c246b
 
 
7058290
 
 
 
f5c246b
 
7058290
f5c246b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7058290
f5c246b
 
 
 
 
7058290
 
f5c246b
7058290
f5c246b
 
 
 
7058290
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5c246b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
  }
}