| 8 | } |
| 9 | |
| 10 | export class PostgresVectorStore implements VectorStore { |
| 11 | private table: string; |
| 12 | |
| 13 | constructor(private db: DbOps, tableName: string = "vectors") { |
| 14 | this.table = tableName; |
| 15 | } |
| 16 | |
| 17 | async storeVector(id: string, sector: string, vector: number[], dim: number, user_id?: string): Promise<void> { |
| 18 | const v = vectorToBuffer(vector); |
| 19 | const sql = `insert into ${this.table}(id,sector,user_id,v,dim) values($1,$2,$3,$4,$5) on conflict(id,sector) do update set user_id=excluded.user_id,v=excluded.v,dim=excluded.dim`; |
| 20 | await this.db.run_async(sql, [id, sector, user_id || "anonymous", v, dim]); |
| 21 | } |
| 22 | |
| 23 | async deleteVector(id: string, sector: string): Promise<void> { |
| 24 | await this.db.run_async(`delete from ${this.table} where id=$1 and sector=$2`, [id, sector]); |
| 25 | } |
| 26 | |
| 27 | async deleteVectors(id: string): Promise<void> { |
| 28 | await this.db.run_async(`delete from ${this.table} where id=$1`, [id]); |
| 29 | } |
| 30 | |
| 31 | async searchSimilar(sector: string, queryVec: number[], topK: number): Promise<Array<{ id: string; score: number }>> { |
| 32 | // Postgres implementation (in-memory cosine sim for now, as per original) |
| 33 | const rows = await this.db.all_async(`select id,v,dim from ${this.table} where sector=$1`, [sector]); |
| 34 | const sims: Array<{ id: string; score: number }> = []; |
| 35 | for (const row of rows) { |
| 36 | const vec = bufferToVector(row.v); |
| 37 | const sim = cosineSimilarity(queryVec, vec); |
| 38 | sims.push({ id: row.id, score: sim }); |
| 39 | } |
| 40 | sims.sort((a, b) => b.score - a.score); |
| 41 | return sims.slice(0, topK); |
| 42 | } |
| 43 | |
| 44 | async getVector(id: string, sector: string): Promise<{ vector: number[]; dim: number } | null> { |
| 45 | const row = await this.db.get_async(`select v,dim from ${this.table} where id=$1 and sector=$2`, [id, sector]); |
| 46 | if (!row) return null; |
| 47 | return { vector: bufferToVector(row.v), dim: row.dim }; |
| 48 | } |
| 49 | |
| 50 | async getVectorsById(id: string): Promise<Array<{ sector: string; vector: number[]; dim: number }>> { |
| 51 | const rows = await this.db.all_async(`select sector,v,dim from ${this.table} where id=$1`, [id]); |
| 52 | return rows.map(row => ({ sector: row.sector, vector: bufferToVector(row.v), dim: row.dim })); |
| 53 | } |
| 54 | |
| 55 | async getVectorsBySector(sector: string): Promise<Array<{ id: string; vector: number[]; dim: number }>> { |
| 56 | const rows = await this.db.all_async(`select id,v,dim from ${this.table} where sector=$1`, [sector]); |
| 57 | return rows.map(row => ({ id: row.id, vector: bufferToVector(row.v), dim: row.dim })); |
| 58 | } |
| 59 | } |
nothing calls this directly
no outgoing calls
no test coverage detected