Merge pull request #34 from shumaiOne/refactor-search-query-builder

refactor(search): unify search and delegate condition building to SqlQueryBuilder
This commit is contained in:
Yiling-J
2026-05-29 12:17:27 +08:00
committed by GitHub
4 changed files with 537 additions and 682 deletions
+82 -27
View File
@@ -1,8 +1,8 @@
import { describe, expect, it, beforeEach, vi } from 'vitest' import { describe, expect, it, beforeEach } from 'vitest'
import { prisma } from '@/db' import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks' import { setupTestDbHooks } from '@/db-test-hooks'
import { SearchService } from './search' import { SearchService } from './search'
import { AssetType, Prisma } from '@/generated/prisma/client.ts' import { AssetType } from '@/generated/prisma/client.ts'
describe('N-gram Search Integration', () => { describe('N-gram Search Integration', () => {
setupTestDbHooks() setupTestDbHooks()
@@ -184,48 +184,103 @@ describe('N-gram Search Integration', () => {
}) })
it('should use GIN index when probe count is less than 10001', async () => { it('should use GIN index when probe count is less than 10001', async () => {
// Mock count to return a rare count const queries: string[] = []
const countSpy = vi.spyOn(prisma.asset, 'count').mockResolvedValue(5) const mockPrisma = new Proxy(prisma, {
const findManySpy = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([]) get(target, prop) {
if (prop === '$queryRaw') {
return (prismaSql: unknown) => {
const sqlStr = (prismaSql as { text?: string })?.text || ''
if (sqlStr) {
queries.push(sqlStr)
}
let result: { id: string }[] = []
if (!sqlStr.includes('as "assetId"')) {
// Probe query: return 5 matches
result = Array(5).fill({ id: '1' })
}
const promise = Promise.resolve(result)
Object.defineProperty(promise, Symbol.toStringTag, {
value: 'PrismaPromise',
configurable: true,
writable: true,
})
return promise as unknown as ReturnType<typeof prisma.$queryRaw>
}
}
const val = Reflect.get(target, prop)
if (typeof val === 'function') {
return val.bind(target)
}
return val
},
})
await searchService.search(rootId, { const localSearchService = new SearchService(mockPrisma)
await localSearchService.search(rootId, {
operator: 'AND', operator: 'AND',
recursively: true, recursively: true,
isSemantic: false, isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'rareterm' }], conditions: [{ field: 'name', operator: 'contains', value: 'rareterm' }],
}) })
// Check that findMany was called with nameNgram condition // Verify probe and main query were executed
const findManyArgs = findManySpy.mock.calls[0][0] as Prisma.AssetFindManyArgs expect(queries).toHaveLength(2)
const where = findManyArgs.where as Prisma.AssetWhereInput // Check that main query used GIN index
expect(where).toHaveProperty('nameNgram') const mainQuery = queries.find((q) => q.includes('as "assetId"'))
expect(where.nameNgram).toHaveProperty('hasEvery') expect(mainQuery).toBeDefined()
expect(mainQuery).toContain('name_ngram @>')
countSpy.mockRestore() expect(mainQuery).toContain('name ILIKE')
findManySpy.mockRestore()
}) })
it('should fallback to simple ILIKE when probe count is 10001 or more', async () => { it('should fallback to simple ILIKE when probe count is 10001 or more', async () => {
// Mock count to return a common count for the probe, and again for the full count const queries: string[] = []
const countSpy = vi.spyOn(prisma.asset, 'count').mockResolvedValue(10001) const mockPrisma = new Proxy(prisma, {
const findManySpy = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([]) get(target, prop) {
if (prop === '$queryRaw') {
return (prismaSql: unknown) => {
const sqlStr = (prismaSql as { text?: string })?.text || ''
if (sqlStr) {
queries.push(sqlStr)
}
let result: { id: string }[] = []
if (!sqlStr.includes('as "assetId"')) {
// Probe query: return 10001 matches
result = Array(10001).fill({ id: '1' })
}
const promise = Promise.resolve(result)
Object.defineProperty(promise, Symbol.toStringTag, {
value: 'PrismaPromise',
configurable: true,
writable: true,
})
return promise as unknown as ReturnType<typeof prisma.$queryRaw>
}
}
const val = Reflect.get(target, prop)
if (typeof val === 'function') {
return val.bind(target)
}
return val
},
})
await searchService.search(rootId, { const localSearchService = new SearchService(mockPrisma)
await localSearchService.search(rootId, {
operator: 'AND', operator: 'AND',
recursively: true, recursively: true,
isSemantic: false, isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'commonterm' }], conditions: [{ field: 'name', operator: 'contains', value: 'commonterm' }],
}) })
// Check that findMany was called WITHOUT nameNgram condition, and WITH name contains // Verify probe and main query were executed
const findManyArgs = findManySpy.mock.calls[0][0] as Prisma.AssetFindManyArgs expect(queries).toHaveLength(2)
const where = findManyArgs.where as Prisma.AssetWhereInput // Check that main query did NOT use GIN index but used ILIKE
expect(where).not.toHaveProperty('nameNgram') const mainQuery = queries.find((q) => q.includes('as "assetId"'))
expect(where).toHaveProperty('name') expect(mainQuery).toBeDefined()
expect(where.name).toHaveProperty('contains', 'commonterm') expect(mainQuery).not.toContain('name_ngram @>')
expect(mainQuery).toContain('name ILIKE')
countSpy.mockRestore()
findManySpy.mockRestore()
}) })
}) })
}) })
+154 -654
View File
@@ -3,13 +3,7 @@ import { Prisma, AssetType, WorkflowTaskType } from '@/generated/prisma/client.t
import { AssetService, assetService } from '@/services/asset/asset' import { AssetService, assetService } from '@/services/asset/asset'
import { AssetInfo } from '@/dtos/asset' import { AssetInfo } from '@/dtos/asset'
import { SearchRequest } from '@/dtos/search' import { SearchRequest } from '@/dtos/search'
import { import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@/services/pagination'
paginateQuery,
PaginatedData,
decodeCursor,
encodeCursor,
PageInfo,
} from '@/services/pagination'
import { generateSearchNgrams } from '@/utils/ngram' import { generateSearchNgrams } from '@/utils/ngram'
import { workflowService } from '@/workflow/workflow' import { workflowService } from '@/workflow/workflow'
import { HTTPException } from 'hono/http-exception' import { HTTPException } from 'hono/http-exception'
@@ -30,41 +24,8 @@ export class SearchService {
targetFolderIds = await this.assetSvc.getDescendantFolderIds(folderId) targetFolderIds = await this.assetSvc.getDescendantFolderIds(folderId)
} }
const where: Prisma.AssetWhereInput = {
isDeleted: false,
}
if (targetFolderIds.length > 0) {
where.parentId = { in: targetFolderIds }
}
const targetTypes = const targetTypes =
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack] req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
const typeCondition: Prisma.AssetWhereInput = req.showSymlink
? {
OR: [
{ type: { in: targetTypes } },
{
type: AssetType.symlink,
target: { type: { in: targetTypes } },
},
],
}
: { type: { in: targetTypes } }
if (req.conditions && req.conditions.length > 0) {
const conditionPredicates: Prisma.AssetWhereInput[] = req.conditions.map((cond) => {
return this.buildConditionPredicate(cond.field, cond.operator as string, cond.value)
})
if (req.operator === 'OR') {
where.AND = [typeCondition, { OR: conditionPredicates }]
} else {
where.AND = [typeCondition, ...conditionPredicates]
}
} else {
Object.assign(where, typeCondition)
}
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// AI Semantic search // AI Semantic search
@@ -132,18 +93,7 @@ export class SearchService {
} }
if (req.conditions && req.conditions.length > 0) { if (req.conditions && req.conditions.length > 0) {
const condSqls: Prisma.Sql[] = [] builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
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') const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
@@ -227,18 +177,7 @@ export class SearchService {
} }
if (req.conditions && req.conditions.length > 0) { if (req.conditions && req.conditions.length > 0) {
const condSqls: Prisma.Sql[] = [] countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
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) { if (nameCond) {
@@ -265,629 +204,190 @@ export class SearchService {
return { data, pageInfo } return { data, pageInfo }
} }
const orderBy: Prisma.AssetOrderByWithRelationInput = {} // ----------------------------------------------------------------------
if (req.sort) { // Non-semantic search (using SqlQueryBuilder)
const direction = req.sort.order === 'desc' ? 'desc' : 'asc' // ----------------------------------------------------------------------
if (req.sort.field === 'custom') { const builder = new SqlQueryBuilder()
orderBy.sortIndex = 'asc' .select(Prisma.sql`a.id as "assetId"`)
} else if (req.sort.field === 'name') { .from(Prisma.sql`assets a`)
orderBy.name = direction .addWhere(Prisma.sql`a.is_deleted = false`)
} else if (req.sort.field === 'created_at' || req.sort.field === 'createdAt') {
orderBy.createdAt = direction if (targetFolderIds.length > 0) {
} else if (req.sort.field === 'size_byte' || req.sort.field === 'sizeByte') { builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
orderBy.sizeByte = direction
} else {
orderBy.id = 'desc'
}
} else {
orderBy.sortIndex = 'asc'
} }
// ---------------------------------------------------------------------- if (req.showSymlink) {
// Switching Search Implementation 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"[]))))
let finalWhere = where `)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
// name contains n-grams / Switching Search Optimization
let countOverride: number | undefined let countOverride: number | undefined
let useNgram = false
let valStr = ''
let ngrams: string[] = []
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains') const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) { if (nameCond) {
const valStr = String(nameCond.value) valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr) ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) { if (ngrams.length > 0) {
const PROBE_LIMIT = 10001 const PROBE_LIMIT = 10001
// We need to build the probe WHERE clause manually since it's a mix of existing conditions and n-grams
// For the probe, we use both GIN and ILIKE to ensure correctness // Build SQL probe query to limit and fetch selective IDs
const probeWhere = { const probeBuilder = new SqlQueryBuilder()
...where, .select(Prisma.sql`a.id`)
nameNgram: { hasEvery: ngrams }, .from(Prisma.sql`assets a`)
name: { contains: valStr, mode: 'insensitive' as const }, .addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
probeBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
} }
const probeCount = await this.prismaClient.asset.count({ if (req.showSymlink) {
where: probeWhere, probeBuilder.addWhere(Prisma.sql`
take: PROBE_LIMIT, (a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
}) `)
} else {
probeBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
probeBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
probeBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
probeBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
probeBuilder.limit(PROBE_LIMIT)
const probeMatches = await this.prismaClient.$queryRaw<{ id: string }[]>(
probeBuilder.build(),
)
const probeCount = probeMatches.length
if (probeCount < PROBE_LIMIT) { if (probeCount < PROBE_LIMIT) {
// SELECTIVE CASE: The term is rare. Use GIN index for high performance. useNgram = true
finalWhere = {
...where,
nameNgram: { hasEvery: ngrams },
name: { contains: valStr, mode: 'insensitive' },
}
countOverride = probeCount countOverride = probeCount
} else { } else {
// NON-SELECTIVE CASE: The term is common.
// Revert to simple ILIKE to allow B-tree short-circuiting during pagination.
// We set countOverride to PROBE_LIMIT to avoid a full table scan for the count.
finalWhere = {
...where,
name: { contains: valStr, mode: 'insensitive' },
}
countOverride = PROBE_LIMIT countOverride = PROBE_LIMIT
} }
}
}
if (nameCond) {
if (useNgram && ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else { } else {
// Fallback for queries that yield no n-grams builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
finalWhere = {
...where,
name: { contains: valStr, mode: 'insensitive' },
}
} }
} }
const { data: assets, pageInfo } = await paginateQuery( // Sorting
(skip, take) => let orderSql = Prisma.sql`a.sort_index ASC`
this.prismaClient.asset.findMany({ if (req.sort) {
where: finalWhere, const direction = req.sort.order === 'desc' ? Prisma.raw('DESC') : Prisma.raw('ASC')
orderBy, if (req.sort.field === 'custom') {
skip, orderSql = Prisma.sql`a.sort_index ASC`
take, } else if (req.sort.field === 'name') {
}), orderSql = Prisma.sql`a.name ${direction}`
countOverride !== undefined } else if (req.sort.field === 'created_at' || req.sort.field === 'createdAt') {
? async () => countOverride! orderSql = Prisma.sql`a.created_at ${direction}`
: () => this.prismaClient.asset.count({ where: finalWhere }), } else if (req.sort.field === 'size_byte' || req.sort.field === 'sizeByte') {
req, orderSql = Prisma.sql`a.size_byte ${direction}`
) } else {
orderSql = Prisma.sql`a.id DESC`
}
}
builder.orderBy(orderSql)
const assetInfos = await this.assetSvc.listAssetsByIds(assets.map((a) => a.id)) // Paginate in SQL using limit/offset
let limit = req.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
return { data: assetInfos, pageInfo } let offset = 0
} if (req.after) {
offset = decodeCursor(req.after)
}
private buildConditionPredicate( builder.limit(limit + 1).offset(offset)
field: string,
operator: string, // Execute raw SQL query
// eslint-disable-next-line @typescript-eslint/no-explicit-any const query = builder.build()
value: any, const matches = await this.prismaClient.$queryRaw<{ assetId: string }[]>(query)
): Prisma.AssetWhereInput {
if (field === 'name') { const hasNextPage = matches.length > limit
const valStr = String(value) const finalMatches = hasNextPage ? matches.slice(0, limit) : matches
switch (operator) {
case 'eq': // Map back to full rich metadata
return { name: { equals: valStr } } const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
case 'neq': const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds)
return { name: { not: valStr } } const assetInfosMap = new Map<string, AssetInfo>()
case 'contains': for (const info of fetchedInfos) {
// We handle 'contains' specially in the main search loop for Switching Search. assetInfosMap.set(info.id, info)
// Here we just return the simple condition as a fallback. }
return { name: { contains: valStr, mode: 'insensitive' } }
case 'notContains': const data: AssetInfo[] = []
return { NOT: { name: { contains: valStr, mode: 'insensitive' } } } for (const match of finalMatches) {
case 'isEmpty': const baseInfo = assetInfosMap.get(match.assetId)
return { name: { equals: '' } } if (baseInfo) {
case 'isNotEmpty': data.push(baseInfo)
return { name: { not: '' } }
default:
throw new Error(`Unsupported operator for name field: ${operator}`)
} }
} }
if (field === 'sizeByte' || field === 'size_byte') { const pageInfo: PageInfo = {}
const valNum = Number(value) if (req.includeCount) {
switch (operator) { if (countOverride !== undefined) {
case 'eq': pageInfo.total = countOverride
return { sizeByte: { equals: valNum } } } else {
case 'neq': const countBuilder = new SqlQueryBuilder()
return { sizeByte: { not: valNum } } .select(Prisma.sql`COUNT(*)`)
case 'gt': .from(Prisma.sql`assets a`)
return { sizeByte: { gt: valNum } } .addWhere(Prisma.sql`a.is_deleted = false`)
case 'gte':
return { sizeByte: { gte: valNum } } if (targetFolderIds.length > 0) {
case 'lt': countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
return { sizeByte: { lt: valNum } } }
case 'lte':
return { sizeByte: { lte: valNum } } if (req.showSymlink) {
default: countBuilder.addWhere(Prisma.sql`
throw new Error(`Unsupported operator for sizeByte field: ${operator}`) (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) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
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 ( if (hasNextPage) {
field === 'createdAt' || pageInfo.cursor = encodeCursor(offset + limit)
field === 'updatedAt' ||
field === 'created_at' ||
field === 'updated_at'
) {
const col = field === 'createdAt' || field === 'created_at' ? 'createdAt' : 'updatedAt'
const valDate = this.toDate(value)
switch (operator) {
case 'eq':
return { [col]: { equals: valDate } }
case 'neq':
return { [col]: { not: valDate } }
case 'gt':
return { [col]: { gt: this.toDateBound(value, 'end') } }
case 'gte':
return { [col]: { gte: this.toDateBound(value, 'start') } }
case 'lt':
return { [col]: { lt: this.toDateBound(value, 'start') } }
case 'lte':
return { [col]: { lte: this.toDateBound(value, 'end') } }
case 'isWithin': {
const range = this.parseDateRange(value)
return {
[col]: {
gte: range.start,
lte: range.end,
},
}
}
default:
throw new Error(`Unsupported operator for ${field} field: ${operator}`)
}
} }
// EAV queries on metadataValues return { data, pageInfo }
const baseFilter = { fieldKey: field }
// Handle Empty/NotEmpty globally for EAV
if (operator === 'isEmpty') {
return { metadataValues: { none: { fieldKey: field } } }
}
if (operator === 'isNotEmpty') {
return { metadataValues: { some: { fieldKey: field } } }
}
const valuePredicate = (): Prisma.AssetMetadataValueWhereInput => {
const or: Prisma.AssetMetadataValueWhereInput[] = []
if (typeof value === 'string' && !this.isDate(value)) {
or.push({ stringValue: value })
}
if (typeof value === 'number') {
or.push({ numberValue: value })
}
if (typeof value === 'boolean') {
or.push({ booleanValue: value })
}
if (this.isDate(value)) {
const d = this.parseRelativeDate(value)
if (d instanceof Date) {
or.push({ dateValue: d })
} else if (d && 'gte' in d) {
return {
dateValue: {
gte: d.gte,
lte: d.lte,
},
}
}
}
if (
Array.isArray(value) ||
(typeof value === 'object' && value !== null && !(value instanceof Date))
) {
or.push({ jsonValue: { equals: value } })
}
if (or.length === 1) return or[0]
return { OR: or }
}
switch (operator) {
case 'eq':
return {
metadataValues: {
some: {
...baseFilter,
...valuePredicate(),
},
},
}
case 'neq':
return {
// "is not" in EAV context: either the field doesn't exist,
// OR it exists but has a different value.
OR: [
{ metadataValues: { none: { fieldKey: field } } },
{
metadataValues: {
some: {
fieldKey: field,
NOT: valuePredicate(),
},
},
},
],
}
case 'gt':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { gt: Number(value) } },
{ dateValue: { gt: this.toDateBound(value, 'end') } },
],
},
},
}
case 'gte':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { gte: Number(value) } },
{ dateValue: { gte: this.toDateBound(value, 'start') } },
],
},
},
}
case 'lt':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { lt: Number(value) } },
{ dateValue: { lt: this.toDateBound(value, 'start') } },
],
},
},
}
case 'lte':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { lte: Number(value) } },
{ dateValue: { lte: this.toDateBound(value, 'end') } },
],
},
},
}
case 'contains':
return {
metadataValues: {
some: {
...baseFilter,
stringValue: { contains: String(value), mode: 'insensitive' },
},
},
}
case 'notContains':
return {
metadataValues: {
none: {
...baseFilter,
stringValue: { contains: String(value), mode: 'insensitive' },
},
},
}
case 'in': // "is any of"
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ stringValue: { in: Array.isArray(value) ? value : [value] } },
{
numberValue: { in: Array.isArray(value) ? (value as number[]) : [Number(value)] },
},
],
},
},
}
case 'notIn': // "is none of"
return {
metadataValues: {
none: {
...baseFilter,
OR: [
{ stringValue: { in: Array.isArray(value) ? value : [value] } },
{
numberValue: { in: Array.isArray(value) ? (value as number[]) : [Number(value)] },
},
],
},
},
}
case 'hasAny':
return {
metadataValues: {
some: {
...baseFilter,
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: value },
},
},
}
case 'hasAll':
return {
metadataValues: {
some: {
...baseFilter,
AND: Array.isArray(value)
? value.map((v) => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: v },
}))
: [
{
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: value },
},
],
},
},
}
case 'hasNone':
return {
metadataValues: {
none: {
...baseFilter,
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: value },
},
},
}
case 'isWithin': {
const range = this.parseDateRange(value)
return {
metadataValues: {
some: {
...baseFilter,
dateValue: {
gte: range.start,
lte: range.end,
},
},
},
}
}
default:
throw new Error(`Unsupported operator for metadata field: ${operator}`)
}
}
private isDate(value: unknown): boolean {
if (value instanceof Date) return true
if (typeof value !== 'string') return false
const valStr = value.toLowerCase()
const relativeKeywords = [
'today',
'yesterday',
'tomorrow',
'one week ago',
'one week from now',
'one month ago',
'one month from now',
]
if (relativeKeywords.includes(valStr) || valStr.match(/\d+\s+days?\s+(ago|from\s+now)/)) {
return true
}
const d = new Date(value)
return !isNaN(d.getTime()) && value.includes('-')
}
private toDate(value: unknown): Date {
return this.toDateBound(value, 'start')
}
private toDateBound(value: unknown, bound: 'start' | 'end'): Date {
const d = this.parseRelativeDate(value)
if (d instanceof Date) return d
if (d && 'gte' in d && 'lte' in d) {
return bound === 'start' ? d.gte! : d.lte!
}
return new Date(value as string)
}
private parseDateRange(value: unknown): { start: Date; end: Date } {
const d = this.parseRelativeDate(value)
if (d && 'gte' in d && 'lte' in d) {
return { start: d.gte!, end: d.lte! }
}
const date = d instanceof Date ? d : new Date(value as string)
const start = new Date(date)
start.setHours(0, 0, 0, 0)
const end = new Date(date)
end.setHours(23, 59, 59, 999)
return { start, end }
}
private parseRelativeDate(value: unknown): { gte?: Date; lte?: Date } | Date | null {
if (value instanceof Date) return value
const valStr = String(value).toLowerCase()
const now = new Date()
const startOf = (d: Date) => {
const res = new Date(d)
res.setHours(0, 0, 0, 0)
return res
}
const endOf = (d: Date) => {
const res = new Date(d)
res.setHours(23, 59, 59, 999)
return res
}
if (valStr === 'today') {
return { gte: startOf(now), lte: endOf(now) }
}
if (valStr === 'yesterday') {
const d = new Date(now)
d.setDate(d.getDate() - 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'tomorrow') {
const d = new Date(now)
d.setDate(d.getDate() + 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'one week ago') {
const d = new Date(now)
d.setDate(d.getDate() - 7)
return d
}
if (valStr === 'one week from now') {
const d = new Date(now)
d.setDate(d.getDate() + 7)
return d
}
if (valStr === 'one month ago') {
const d = new Date(now)
d.setMonth(d.getMonth() - 1)
return d
}
if (valStr === 'one month from now') {
const d = new Date(now)
d.setMonth(d.getMonth() + 1)
return d
}
const daysAgoMatch = valStr.match(/(\d+)\s+days?\s+ago/)
if (daysAgoMatch) {
const d = new Date(now)
d.setDate(d.getDate() - parseInt(daysAgoMatch[1]))
return d
}
const daysFromNowMatch = valStr.match(/(\d+)\s+days?\s+from\s+now/)
if (daysFromNowMatch) {
const d = new Date(now)
d.setDate(d.getDate() + parseInt(daysFromNowMatch[1]))
return d
}
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
} }
} }
+298
View File
@@ -1,4 +1,5 @@
import { Prisma } from '@/generated/prisma/client.ts' import { Prisma } from '@/generated/prisma/client.ts'
import { SearchCondition } from '@/dtos/search'
export class SqlQueryBuilder { export class SqlQueryBuilder {
private selectSql: Prisma.Sql = Prisma.sql`*` private selectSql: Prisma.Sql = Prisma.sql`*`
@@ -38,6 +39,32 @@ export class SqlQueryBuilder {
return this return this
} }
addSearchConditions(
operator: 'AND' | 'OR',
conditions: SearchCondition[],
options?: { skipNameContains?: boolean },
): this {
if (!conditions || conditions.length === 0) return this
const condSqls: Prisma.Sql[] = []
for (const cond of conditions) {
if (options?.skipNameContains && 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 = operator === 'OR' ? ' OR ' : ' AND '
this.addWhere(Prisma.sql`(${Prisma.join(condSqls, separator)})`)
}
return this
}
build(): Prisma.Sql { build(): Prisma.Sql {
if (!this.fromSql) { if (!this.fromSql) {
throw new Error('FROM clause is required in SqlQueryBuilder') throw new Error('FROM clause is required in SqlQueryBuilder')
@@ -70,4 +97,275 @@ export class SqlQueryBuilder {
return Prisma.join(queryParts, ' ') return Prisma.join(queryParts, ' ')
} }
private isDate(value: unknown): boolean {
if (value instanceof Date) return true
if (typeof value !== 'string') return false
const valStr = value.toLowerCase()
const relativeKeywords = [
'today',
'yesterday',
'tomorrow',
'one week ago',
'one week from now',
'one month ago',
'one month from now',
]
if (relativeKeywords.includes(valStr) || valStr.match(/\d+\s+days?\s+(ago|from\s+now)/)) {
return true
}
const d = new Date(value)
return !isNaN(d.getTime()) && value.includes('-')
}
private toDate(value: unknown): Date {
return this.toDateBound(value, 'start')
}
private toDateBound(value: unknown, bound: 'start' | 'end'): Date {
const d = this.parseRelativeDate(value)
if (d instanceof Date) return d
if (d && 'gte' in d && 'lte' in d) {
return bound === 'start' ? d.gte! : d.lte!
}
return new Date(value as string)
}
private parseDateRange(value: unknown): { start: Date; end: Date } {
const d = this.parseRelativeDate(value)
if (d && 'gte' in d && 'lte' in d) {
return { start: d.gte!, end: d.lte! }
}
const date = d instanceof Date ? d : new Date(value as string)
const start = new Date(date)
start.setHours(0, 0, 0, 0)
const end = new Date(date)
end.setHours(23, 59, 59, 999)
return { start, end }
}
private parseRelativeDate(value: unknown): { gte?: Date; lte?: Date } | Date | null {
if (value instanceof Date) return value
const valStr = String(value).toLowerCase()
const now = new Date()
const startOf = (d: Date) => {
const res = new Date(d)
res.setHours(0, 0, 0, 0)
return res
}
const endOf = (d: Date) => {
const res = new Date(d)
res.setHours(23, 59, 59, 999)
return res
}
if (valStr === 'today') {
return { gte: startOf(now), lte: endOf(now) }
}
if (valStr === 'yesterday') {
const d = new Date(now)
d.setDate(d.getDate() - 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'tomorrow') {
const d = new Date(now)
d.setDate(d.getDate() + 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'one week ago') {
const d = new Date(now)
d.setDate(d.getDate() - 7)
return d
}
if (valStr === 'one week from now') {
const d = new Date(now)
d.setDate(d.getDate() + 7)
return d
}
if (valStr === 'one month ago') {
const d = new Date(now)
d.setMonth(d.getMonth() - 1)
return d
}
if (valStr === 'one month from now') {
const d = new Date(now)
d.setMonth(d.getMonth() + 1)
return d
}
const daysAgoMatch = valStr.match(/(\d+)\s+days?\s+ago/)
if (daysAgoMatch) {
const d = new Date(now)
d.setDate(d.getDate() - parseInt(daysAgoMatch[1]))
return d
}
const daysFromNowMatch = valStr.match(/(\d+)\s+days?\s+from\s+now/)
if (daysFromNowMatch) {
const d = new Date(now)
d.setDate(d.getDate() + parseInt(daysFromNowMatch[1]))
return d
}
const parsed = new Date(value as string)
return isNaN(parsed.getTime()) ? null : parsed
}
private buildEavValueMatch(value: unknown): Prisma.Sql {
if (typeof value === 'string') {
const valStr = String(value)
if (this.isDate(valStr)) {
const d = this.parseRelativeDate(valStr)
if (d instanceof Date) {
return Prisma.sql`date_value = ${d}`
} else if (d && 'gte' in d) {
return Prisma.sql`date_value >= ${d.gte} AND date_value <= ${d.lte}`
}
}
return Prisma.sql`string_value = ${valStr}`
}
if (typeof value === 'number') {
return Prisma.sql`number_value = ${Number(value)}`
}
if (typeof value === 'boolean') {
return Prisma.sql`boolean_value = ${Boolean(value)}`
}
if (value instanceof Date) {
return Prisma.sql`date_value = ${value}`
}
if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
return Prisma.sql`json_value = ${JSON.stringify(value)}::jsonb`
}
return Prisma.sql`string_value = ${String(value)}`
}
private buildSqlCondition(field: string, operator: string, value: unknown): 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
switch (operator) {
case 'isEmpty':
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
case 'isNotEmpty':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
case 'eq': {
const matchSql = this.buildEavValueMatch(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND ${matchSql})`
}
case 'neq': {
const matchSql = this.buildEavValueMatch(value)
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field}) OR a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND NOT (${matchSql}))`
}
case 'gt':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value > ${Number(value)} OR date_value > ${this.toDateBound(value, 'end')}))`
case 'gte':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value >= ${Number(value)} OR date_value >= ${this.toDateBound(value, 'start')}))`
case 'lt':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value < ${Number(value)} OR date_value < ${this.toDateBound(value, 'start')}))`
case 'lte':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value <= ${Number(value)} OR date_value <= ${this.toDateBound(value, 'end')}))`
case 'contains':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value ILIKE ${'%' + String(value) + '%'})`
case 'notContains':
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value ILIKE ${'%' + String(value) + '%'})`
case 'in': {
const valArr = Array.isArray(value) ? value : [value]
const valNumArr = valArr.map((v) => Number(v)).filter((v) => !isNaN(v))
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (string_value = ANY(${valArr}) OR number_value = ANY(${valNumArr}::double precision[])))`
}
case 'notIn': {
const valArr = Array.isArray(value) ? value : [value]
const valNumArr = valArr.map((v) => Number(v)).filter((v) => !isNaN(v))
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (string_value = ANY(${valArr}) OR number_value = ANY(${valNumArr}::double precision[])))`
}
case 'hasAny':
case 'hasAll':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)`
case 'hasNone':
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)`
case 'isWithin': {
const range = this.parseDateRange(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value >= ${range.start} AND date_value <= ${range.end})`
}
default:
throw new Error(`Unsupported operator for metadata field: ${operator}`)
}
}
} }
@@ -369,7 +369,9 @@ export function SearchFilterDialog({
</p> </p>
{isSemantic && ( {isSemantic && (
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3"> <p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
Semantic search results will be ordered by their relevance to the search query text, but won't be strictly filtered. If you need accurate filtering, please add filter conditions to control that. Semantic search results will be ordered by their relevance to the search query
text, but won't be strictly filtered. If you need accurate filtering, please add
filter conditions to control that.
</p> </p>
)} )}
</div> </div>