feat(search): implement multi-chunk semantic search with segment timestamps

This commit is contained in:
yiling
2026-05-29 11:00:23 +08:00
parent 1855ca1405
commit 4f9c4db9ce
10 changed files with 690 additions and 117 deletions
+2 -2
View File
@@ -59,7 +59,7 @@ describe('AuthzService', () => {
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, searchMode: 'name' },
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
@@ -263,7 +263,7 @@ describe('AuthzService', () => {
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, searchMode: 'name' },
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
+4 -4
View File
@@ -48,7 +48,7 @@ describe('CollectionService', () => {
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'test' }],
recursively: true,
searchMode: 'name',
isSemantic: false,
},
},
})
@@ -69,7 +69,7 @@ describe('CollectionService', () => {
operator: 'AND',
conditions: [{ field: 'rating', operator: 'eq', value: 5 }],
recursively: true,
searchMode: 'name',
isSemantic: false,
},
},
})
@@ -92,7 +92,7 @@ describe('CollectionService', () => {
name: `Collection ${i}`,
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, searchMode: 'name' },
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
}
@@ -130,7 +130,7 @@ describe('CollectionService', () => {
name: 'To be deleted',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, searchMode: 'name' },
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
+5 -5
View File
@@ -60,7 +60,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [
{
field: 'name',
@@ -88,7 +88,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [
{
field: 'name',
@@ -158,7 +158,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [
{
field: 'name',
@@ -191,7 +191,7 @@ describe('N-gram Search Integration', () => {
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'rareterm' }],
})
@@ -213,7 +213,7 @@ describe('N-gram Search Integration', () => {
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'commonterm' }],
})
+207 -12
View File
@@ -1,9 +1,10 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { describe, expect, it, beforeEach, vi } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { SearchService } from './search'
import { SearchConditionOperator } from '@/dtos/search'
import { metadataService } from '@/services/metadata/metadata'
import { workflowService } from '@/workflow/workflow'
import { AssetType } from '@/generated/prisma/client.ts'
@@ -376,7 +377,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
const names = result.data.map((a) => a.name).sort()
expect(names).toEqual(expected.sort())
@@ -391,7 +392,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
expect(result.data).toHaveLength(1)
@@ -406,7 +407,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
expect(result.data).toHaveLength(2)
@@ -423,7 +424,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
expect(result.data).toHaveLength(1)
@@ -438,7 +439,7 @@ describe('SearchService', () => {
recursively: false,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
// Should only find file1, as file2 is in subfolder
@@ -459,7 +460,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultAsc.data[0].name).toBe('file1')
expect(resultAsc.data[1].name).toBe('file2')
@@ -470,7 +471,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultDesc.data[0].name).toBe('file2')
expect(resultDesc.data[1].name).toBe('file1')
@@ -486,7 +487,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultAsc.data[0].sizeByte).toBe(100)
expect(resultAsc.data[1].sizeByte).toBe(200)
@@ -497,7 +498,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultDesc.data[0].sizeByte).toBe(200)
expect(resultDesc.data[1].sizeByte).toBe(100)
@@ -524,7 +525,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultNormal.data.find((a) => a.id === symlink.id)).toBeUndefined()
@@ -535,8 +536,202 @@ describe('SearchService', () => {
operator: 'AND',
conditions: [],
showSymlink: true,
searchMode: 'name',
isSemantic: false,
})
expect(resultWithSymlink.data.find((a) => a.id === symlink.id)).toBeDefined()
})
describe('Semantic Search with multiple chunks and distance ordering', () => {
it('returns multiple matching segments from the same asset and orders by distance', async () => {
const user = await prisma.user.create({
data: { name: 'semantic-user', email: 'semantic-user@example.com', type: 'human' },
})
const team = await prisma.team.create({
data: { name: 'semantic-team' },
})
const project = await prisma.project.create({
data: { name: 'semantic-project', teamId: team.id },
})
// We need an embedding agent that is enabled for semantic search to be allowed
const botUser = await prisma.user.create({
data: { name: 'Embedding Bot', email: 'emb@example.com', type: 'agent' },
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: { api: 'google', apiKey: 'key' } as unknown as PrismaJson.ProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: {
reasoning: false,
input: ['text'],
contextWindow: 1000,
maxTokens: 1000,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
} as unknown as PrismaJson.ModelConfig,
},
})
await prisma.agent.create({
data: {
id: botUser.id,
teamId: team.id,
type: 'embedding',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini' },
},
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const videoAssetA = await prisma.asset.create({
data: {
name: 'videoA.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
status: 'uploaded',
},
})
const videoAssetB = await prisma.asset.create({
data: {
name: 'videoB.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
status: 'uploaded',
},
})
// Insert embedding chunks:
// We will insert 2 chunks for videoAssetA and 1 chunk for videoAssetB.
// Vector size is 1536. We use unit vectors to ensure distinct cosine distances:
// Chunk A1: startTime = 0.0, endTime = 10.0, embedding = [1, 0, 0...] (cosine similarity = 1.0, distance = 0.0)
// Chunk B1: startTime = 5.0, endTime = 15.0, embedding = [1, 1, 0...] (cosine similarity = 0.707, distance = 0.293)
// Chunk A2: startTime = 10.0, endTime = 20.0, embedding = [0, 1, 0...] (cosine similarity = 0.0, distance = 1.0)
const arrA1 = Array(1536).fill(0)
arrA1[0] = 1.0
const vectorA1 = JSON.stringify(arrA1)
const arrB1 = Array(1536).fill(0)
arrB1[0] = 1.0
arrB1[1] = 1.0
const vectorB1 = JSON.stringify(arrB1)
const arrA2 = Array(1536).fill(0)
arrA2[1] = 1.0
const vectorA2 = JSON.stringify(arrA2)
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-a1',
${videoAssetA.id},
${vectorA1}::vector,
0.0,
10.0,
NOW(),
NOW()
)
`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-a2',
${videoAssetA.id},
${vectorA2}::vector,
10.0,
20.0,
NOW(),
NOW()
)
`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-b1',
${videoAssetB.id},
${vectorB1}::vector,
5.0,
15.0,
NOW(),
NOW()
)
`
// Mock the embedding generation workflow task.
// Our query vector points along the first dimension [1, 0, 0...]
const queryVector = Array(1536).fill(0)
queryVector[0] = 1.0
const mockExecuteWait = vi
.spyOn(workflowService, 'executeWait')
.mockImplementation(async (task) => {
return {
...task,
status: 'completed',
output: {
embedding: queryVector,
},
} as unknown as typeof task
})
// Search using semantic mode
const result = await searchService.search(rootFolder.id, {
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
query: 'find some cute cat video segments',
isSemantic: true,
})
// We expect 3 distinct results because videoAssetA matches twice and videoAssetB matches once:
// Sorting should be based on vector distance:
// Distance from query (0.2) to:
// - Chunk A1 (0.1): |0.2 - 0.1| = 0.1 -> closest (1st)
// - Chunk B1 (0.5): |0.2 - 0.5| = 0.3 -> medium (2nd)
// - Chunk A2 (0.9): |0.2 - 0.9| = 0.7 -> farthest (3rd)
expect(result.data).toHaveLength(3)
// 1st: Chunk A1
expect(result.data[0].id).toBe(videoAssetA.id)
expect(result.data[0].startTime).toBe(0)
expect(result.data[0].endTime).toBe(10)
// 2nd: Chunk B1
expect(result.data[1].id).toBe(videoAssetB.id)
expect(result.data[1].startTime).toBe(5)
expect(result.data[1].endTime).toBe(15)
// 3rd: Chunk A2
expect(result.data[2].id).toBe(videoAssetA.id)
expect(result.data[2].startTime).toBe(10)
expect(result.data[2].endTime).toBe(20)
mockExecuteWait.mockRestore()
})
})
})
+276 -27
View File
@@ -3,10 +3,17 @@ import { Prisma, AssetType, WorkflowTaskType } from '@/generated/prisma/client.t
import { AssetService, assetService } from '@/services/asset/asset'
import { AssetInfo } from '@/dtos/asset'
import { SearchRequest } from '@/dtos/search'
import { paginateQuery, PaginatedData } from '@/services/pagination'
import {
paginateQuery,
PaginatedData,
decodeCursor,
encodeCursor,
PageInfo,
} from '@/services/pagination'
import { generateSearchNgrams } from '@/utils/ngram'
import { workflowService } from '@/workflow/workflow'
import { HTTPException } from 'hono/http-exception'
import { SqlQueryBuilder } from './sql-query-builder'
export class SearchService {
constructor(
@@ -62,8 +69,7 @@ export class SearchService {
// ----------------------------------------------------------------------
// AI Semantic search
// ----------------------------------------------------------------------
let semanticIds: string[] = []
if (req.query && (req.searchMode === 'content' || req.searchMode === 'all')) {
if (req.query && req.isSemantic) {
// 1. Check if embedding agent exists and is enabled
const team = await this.prismaClient.asset.findUnique({
where: { id: folderId },
@@ -87,9 +93,9 @@ export class SearchService {
data: {
type: WorkflowTaskType.query_embedding_for_search,
teamId,
assetId: folderId, // Just using folderId as a placeholder
assetId: folderId,
payload: {
projectId: '', // Not used for this task type
projectId: '',
queryEmbeddingForSearch: { text: req.query },
} as PrismaJson.WorkflowTaskPayload,
status: 'pending',
@@ -104,31 +110,159 @@ export class SearchService {
throw new Error('Failed to generate query embedding')
}
// 3. Fetch top 1000 unique asset IDs from asset_embeddings via pgvector
// 3. Construct raw SQL using SqlQueryBuilder
const vectorJson = JSON.stringify(queryVector)
const semanticMatches = await this.prismaClient.$queryRaw<{ assetId: string }[]>`
SELECT DISTINCT ON (asset_id) asset_id as "assetId" FROM (
SELECT asset_id, embedding <=> ${vectorJson}::vector as dist
FROM asset_embeddings
ORDER BY embedding <=> ${vectorJson}::vector
LIMIT 2000
) as sub
ORDER BY asset_id, dist
LIMIT 1000
`
semanticIds = semanticMatches.map((m) => m.assetId)
const builder = new SqlQueryBuilder()
.select(
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", (ae.embedding <=> ${vectorJson}::vector) as "distance"`,
)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (req.searchMode === 'content') {
where.id = { in: semanticIds }
} else if (req.searchMode === 'all') {
const keywordCondition: Prisma.AssetWhereInput = {
name: { contains: req.query, mode: 'insensitive' },
}
const semanticCondition: Prisma.AssetWhereInput = {
id: { in: semanticIds },
}
where.OR = [keywordCondition, semanticCondition]
if (targetFolderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
const condSqls: Prisma.Sql[] = []
for (const cond of req.conditions) {
if (cond.field === 'name' && cond.operator === 'contains') continue
const sqlCond = this.buildSqlCondition(cond.field, cond.operator, cond.value)
if (sqlCond) {
condSqls.push(sqlCond)
}
}
if (condSqls.length > 0) {
const separator = req.operator === 'OR' ? ' OR ' : ' AND '
builder.addWhere(Prisma.sql`(${Prisma.join(condSqls, separator)})`)
}
}
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
builder.orderBy(Prisma.sql`distance ASC`)
// 4. Paginate in SQL using limit/offset
let limit = req.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
let offset = 0
if (req.after) {
offset = decodeCursor(req.after)
}
builder.limit(limit + 1).offset(offset)
// 5. Execute raw SQL query
const query = builder.build()
const semanticMatches = await this.prismaClient.$queryRaw<
{
assetId: string
startTime: number | null
endTime: number | null
distance: number
}[]
>(query)
const hasNextPage = semanticMatches.length > limit
const finalMatches = hasNextPage ? semanticMatches.slice(0, limit) : semanticMatches
// 6. Map back to full rich metadata and return time-based duplicate segments
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds)
const assetInfosMap = new Map<string, AssetInfo>()
for (const info of fetchedInfos) {
assetInfosMap.set(info.id, info)
}
const data: AssetInfo[] = []
for (const match of finalMatches) {
const baseInfo = assetInfosMap.get(match.assetId)
if (baseInfo) {
data.push({
...baseInfo,
startTime: match.startTime,
endTime: match.endTime,
})
}
}
const pageInfo: PageInfo = {}
if (req.includeCount) {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
const condSqls: Prisma.Sql[] = []
for (const cond of req.conditions) {
if (cond.field === 'name' && cond.operator === 'contains') continue
const sqlCond = this.buildSqlCondition(cond.field, cond.operator, cond.value)
if (sqlCond) {
condSqls.push(sqlCond)
}
}
if (condSqls.length > 0) {
const separator = req.operator === 'OR' ? ' OR ' : ' AND '
countBuilder.addWhere(Prisma.sql`(${Prisma.join(condSqls, separator)})`)
}
}
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(
countBuilder.build(),
)
pageInfo.total = Number(countRes[0]?.count || 0)
}
if (hasNextPage) {
pageInfo.cursor = encodeCursor(offset + limit)
}
return { data, pageInfo }
}
const orderBy: Prisma.AssetOrderByWithRelationInput = {}
@@ -640,6 +774,121 @@ export class SearchService {
const parsed = new Date(value as string)
return isNaN(parsed.getTime()) ? null : parsed
}
private buildSqlCondition(
field: string,
operator: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any,
): Prisma.Sql | null {
const colName =
field === 'sizeByte' || field === 'size_byte'
? 'size_byte'
: field === 'createdAt' || field === 'created_at'
? 'created_at'
: field === 'updatedAt' || field === 'updated_at'
? 'updated_at'
: field
const dbCol = Prisma.raw(`a."${colName}"`)
if (field === 'name') {
const valStr = String(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valStr}`
case 'neq':
return Prisma.sql`${dbCol} != ${valStr}`
case 'contains':
return Prisma.sql`${dbCol} ILIKE ${'%' + valStr + '%'}`
case 'notContains':
return Prisma.sql`${dbCol} NOT ILIKE ${'%' + valStr + '%'}`
case 'isEmpty':
return Prisma.sql`${dbCol} = ''`
case 'isNotEmpty':
return Prisma.sql`${dbCol} != ''`
default:
throw new Error(`Unsupported operator for name field: ${operator}`)
}
}
if (field === 'sizeByte' || field === 'size_byte') {
const valNum = Number(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valNum}`
case 'neq':
return Prisma.sql`${dbCol} != ${valNum}`
case 'gt':
return Prisma.sql`${dbCol} > ${valNum}`
case 'gte':
return Prisma.sql`${dbCol} >= ${valNum}`
case 'lt':
return Prisma.sql`${dbCol} < ${valNum}`
case 'lte':
return Prisma.sql`${dbCol} <= ${valNum}`
default:
throw new Error(`Unsupported operator for sizeByte field: ${operator}`)
}
}
if (
field === 'createdAt' ||
field === 'updatedAt' ||
field === 'created_at' ||
field === 'updated_at'
) {
const valDate = this.toDate(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valDate}`
case 'neq':
return Prisma.sql`${dbCol} != ${valDate}`
case 'gt':
return Prisma.sql`${dbCol} > ${this.toDateBound(value, 'end')}`
case 'gte':
return Prisma.sql`${dbCol} >= ${this.toDateBound(value, 'start')}`
case 'lt':
return Prisma.sql`${dbCol} < ${this.toDateBound(value, 'start')}`
case 'lte':
return Prisma.sql`${dbCol} <= ${this.toDateBound(value, 'end')}`
case 'isWithin': {
const range = this.parseDateRange(value)
return Prisma.sql`${dbCol} >= ${range.start} AND ${dbCol} <= ${range.end}`
}
default:
throw new Error(`Unsupported operator for date field: ${operator}`)
}
}
// Custom EAV metadata field query on asset_metadata_values
if (operator === 'isEmpty') {
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
}
if (operator === 'isNotEmpty') {
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
}
// Standard EAV value matching based on type of value
if (typeof value === 'string') {
const valStr = String(value)
if (this.isDate(valStr)) {
const valDate = this.toDate(valStr)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value = ${valDate})`
}
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value = ${valStr})`
}
if (typeof value === 'number') {
const valNum = Number(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND number_value = ${valNum})`
}
if (typeof value === 'boolean') {
const valBool = Boolean(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND boolean_value = ${valBool})`
}
return null
}
}
export const searchService = new SearchService()
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { SqlQueryBuilder } from './sql-query-builder'
import { Prisma } from '@/generated/prisma/client.ts'
describe('SqlQueryBuilder', () => {
it('correctly constructs a basic SQL query', () => {
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id, a.name`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
const query = builder.build()
expect(query.text).toContain('SELECT a.id, a.name FROM assets a WHERE a.is_deleted = false')
})
it('correctly constructs query with where clauses, order, limit, and offset', () => {
const vectorJson = '[0.1, 0.2, 0.3]'
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id, ae.start_time as "startTime"`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
.addWhere(Prisma.sql`a.project_id = ${'project-123'}`)
.orderBy(Prisma.sql`ae.embedding <=> ${vectorJson}::vector ASC`)
.limit(10)
.offset(20)
const query = builder.build()
expect(query.text).toContain(
'SELECT a.id, ae.start_time as "startTime" FROM assets a JOIN asset_embeddings ae ON a.id = ae.asset_id WHERE a.is_deleted = false AND a.project_id = $1 ORDER BY ae.embedding <=> $2::vector ASC LIMIT $3 OFFSET $4',
)
expect(query.values).toEqual(['project-123', vectorJson, 10, 20])
})
it('throws an error if FROM clause is missing', () => {
const builder = new SqlQueryBuilder().select(Prisma.sql`id`)
expect(() => builder.build()).toThrow('FROM clause is required')
})
})
+73
View File
@@ -0,0 +1,73 @@
import { Prisma } from '@/generated/prisma/client.ts'
export class SqlQueryBuilder {
private selectSql: Prisma.Sql = Prisma.sql`*`
private fromSql: Prisma.Sql | null = null
private wheres: Prisma.Sql[] = []
private orderSql: Prisma.Sql | null = null
private limitCount: number | null = null
private offsetCount: number | null = null
select(fields: Prisma.Sql): this {
this.selectSql = fields
return this
}
from(relation: Prisma.Sql): this {
this.fromSql = relation
return this
}
addWhere(condition: Prisma.Sql): this {
this.wheres.push(condition)
return this
}
orderBy(order: Prisma.Sql): this {
this.orderSql = order
return this
}
limit(n: number): this {
this.limitCount = n
return this
}
offset(n: number): this {
this.offsetCount = n
return this
}
build(): Prisma.Sql {
if (!this.fromSql) {
throw new Error('FROM clause is required in SqlQueryBuilder')
}
const queryParts: Prisma.Sql[] = [
Prisma.sql`SELECT`,
this.selectSql,
Prisma.sql`FROM`,
this.fromSql,
]
if (this.wheres.length > 0) {
queryParts.push(Prisma.sql`WHERE`)
queryParts.push(Prisma.join(this.wheres, ' AND '))
}
if (this.orderSql) {
queryParts.push(Prisma.sql`ORDER BY`)
queryParts.push(this.orderSql)
}
if (this.limitCount !== null) {
queryParts.push(Prisma.sql`LIMIT ${this.limitCount}`)
}
if (this.offsetCount !== null) {
queryParts.push(Prisma.sql`OFFSET ${this.offsetCount}`)
}
return Prisma.join(queryParts, ' ')
}
}