From 9c290e9db8a105729ea7d0eaa2dcccbd736094ae Mon Sep 17 00:00:00 2001 From: Jason Jacobs Date: Thu, 14 Mar 2024 13:24:12 -0700 Subject: [PATCH] Refactor DB (#960) * Refactor table creation and SQLite connection initialization. Previously, attempts to create the 'docs' table were made on every interaction with it. Now, table creation is attempted only upon the first interaction. Additionally, the SQLite connection is now initialized just once, enhancing performance. * no longer need createDocsTable * library no longer used --- core/indexing/docs/db.ts | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts index a59c1c934..73651452e 100644 --- a/core/indexing/docs/db.ts +++ b/core/indexing/docs/db.ts @@ -2,7 +2,6 @@ import { Database, open } from "sqlite"; import sqlite3 from "sqlite3"; import { Chunk } from "../.."; import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths"; -import { SqliteDb } from "../refreshIndex"; import { downloadPreIndexedDocs } from "./preIndexed"; import { default as configs } from "./preIndexedDocs"; @@ -21,12 +20,23 @@ interface LanceDbDocsRow { [key: string]: any; } -async function createDocsTable(db: Database) { - db.exec(`CREATE TABLE IF NOT EXISTS docs ( +let dbDocs:Database; + +async function getDBDocs() { + if (!dbDocs) { + dbDocs = await open({ + filename: getDocsSqlitePath(), + driver: sqlite3.Database, + }); + + dbDocs.exec(`CREATE TABLE IF NOT EXISTS docs ( id INTEGER PRIMARY KEY AUTOINCREMENT, title STRING NOT NULL, baseUrl STRING NOT NULL UNIQUE )`); + } + + return dbDocs; } export async function retrieveDocs( @@ -37,8 +47,7 @@ export async function retrieveDocs( nested: boolean = false, ): Promise { const lancedb = await import("vectordb"); - const db = await SqliteDb.get(); - await createDocsTable(db); + const db = await getDBDocs(); const lance = await lancedb.connect(getLanceDbPath()); const downloadDocs = async () => { @@ -116,11 +125,7 @@ export async function addDocs( } // Only after add it to SQLite - const db = await open({ - filename: getDocsSqlitePath(), - driver: sqlite3.Database, - }); - await createDocsTable(db); + const db = await getDBDocs(); await db.run( `INSERT INTO docs (title, baseUrl) VALUES (?, ?)`, title, @@ -131,11 +136,7 @@ export async function addDocs( export async function listDocs(): Promise< { title: string; baseUrl: string }[] > { - const db = await open({ - filename: getDocsSqlitePath(), - driver: sqlite3.Database, - }); - await createDocsTable(db); - const docs = await db.all(`SELECT title, baseUrl FROM docs`); + const db = await getDBDocs(); + const docs = db.all(`SELECT title, baseUrl FROM docs`); return docs; }