Skip to content

Commit f236192

Browse files
authored
fix: resolve N+1 query in knowledge batch file add (open-webui#21006)
1 parent 9b1fd86 commit f236192

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

backend/open_webui/routers/knowledge.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -958,17 +958,19 @@ async def add_files_to_knowledge_batch(
958958
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
959959
)
960960

961-
# Get files content
961+
# Batch-fetch all files to avoid N+1 queries
962962
log.info(f"files/batch/add - {len(form_data)} files")
963-
files: List[FileModel] = []
964-
for form in form_data:
965-
file = Files.get_file_by_id(form.file_id, db=db)
966-
if not file:
967-
raise HTTPException(
968-
status_code=status.HTTP_400_BAD_REQUEST,
969-
detail=f"File {form.file_id} not found",
970-
)
971-
files.append(file)
963+
file_ids = [form.file_id for form in form_data]
964+
files = Files.get_files_by_ids(file_ids, db=db)
965+
966+
# Verify all requested files were found
967+
found_ids = {file.id for file in files}
968+
missing_ids = [fid for fid in file_ids if fid not in found_ids]
969+
if missing_ids:
970+
raise HTTPException(
971+
status_code=status.HTTP_400_BAD_REQUEST,
972+
detail=f"File {missing_ids[0]} not found",
973+
)
972974

973975
# Process files
974976
try:

0 commit comments

Comments
 (0)