{"record":{"id":"866a226decb3527f","repo":"infiniflow/ragflow","slug":"database-error-document","errorCode":null,"errorMessage":"Database error (Document)!","messagePattern":"Database error \\(Document\\)!","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"critical","filePath":"api/db/services/document_service.py","lineNumber":456,"sourceCode":"        docs = cls.model.select(*fields).join(Knowledgebase, on=(Knowledgebase.id == cls.model.kb_id)).where(cls.model.created_by == creator_id)\n        docs.order_by(cls.model.create_time.asc())\n        # maybe cause slow query by deep paginate, optimize later\n        offset, limit = 0, 100\n        res = []\n        while True:\n            doc_batch = docs.offset(offset).limit(limit)\n            _temp = list(doc_batch.dicts())\n            if not _temp:\n                break\n            res.extend(_temp)\n            offset += limit\n        return res\n\n    @classmethod\n    @DB.connection_context()\n    def insert(cls, doc):\n        if not cls.save(**doc):\n            raise RuntimeError(\"Database error (Document)!\")\n        if not KnowledgebaseService.atomic_increase_doc_num_by_id(doc[\"kb_id\"]):\n            raise RuntimeError(\"Database error (Knowledgebase)!\")\n        return Document(**doc)\n\n    @classmethod\n    @DB.connection_context()\n    def remove_document(cls, doc, tenant_id):\n        from api.db.services.task_service import TaskService, cancel_all_task_of\n\n        if not cls.delete_document_and_update_kb_counts(doc.id):\n            return True\n\n        chunk_index_name = search.index_name(tenant_id)\n        chunk_index_exists = settings.docStoreConn.index_exist(chunk_index_name, doc.kb_id)\n\n        # Cancel all running tasks first using preset function in task_service.py --- set cancel flag in Redis\n        try:\n            cancel_all_task_of(doc.id)","sourceCodeStart":438,"sourceCodeEnd":474,"githubUrl":"https://github.com/infiniflow/ragflow/blob/554fb1133ac3861732235ad9c377eb5e0a770665/api/db/services/document_service.py#L438-L474","documentation":"RuntimeError from DocumentService.insert when cls.save(**doc) returns falsy — Peewee failed to persist the new Document row (constraint violation, invalid field, or DB error swallowed into a False result). It marks the transaction for rollback inside the connection_context decorator.","triggerScenarios":"Creating a document with a dict that violates the Document schema: unknown/missing required fields, duplicate id, or a DB-level constraint; the save() helper returns 0 rows affected and the guard fires.","commonSituations":"Passing fields not on the model; NULL in a non-nullable column (e.g. kb_id); DB connection issues or schema drift after a migration; oversized values for varchar columns.","solutions":["Inspect the doc dict: only model fields, all required columns set, valid types.","Enable SQL logging (Peewee debug / service logs) to see the underlying INSERT error.","Verify DB schema matches the model (run migrations) and the connection is healthy."],"exampleFix":"# before\ndoc = {\"id\": uid, \"kb_id\": kb_id, \"name\": name}  # missing other required columns\n# after: build the full field set the model expects\nfrom api.db.services.document_service import DocumentService\ndoc = {\"id\": get_uuid(), \"kb_id\": kb_id, \"name\": name, \"parser_id\": parser_id, \"type\": filetype, \"created_by\": tenant_id, \"size\": size, \"status\": \"1\"}","handlingStrategy":"try-catch","validationCode":"fields = DocumentService.get_cls_model_fields()\nextra = set(doc) - set(fields)\nrequired_missing = {'kb_id', 'name'} - set(doc)\nif extra or required_missing:\n    raise ValueError(f'bad document fields: extra={extra}, missing={required_missing}')","typeGuard":null,"tryCatchPattern":"try:\n    DocumentService.insert(doc)\nexcept RuntimeError as e:\n    if 'Database error (Document)' in str(e):\n        log_with_payload('document insert failed', doc)  # inspect Peewee logs, fix fields, do NOT blind-retry\n    raise","preventionTips":["Log the full doc dict when this fires — the cause is almost always a field mismatch.","Build documents through one factory that mirrors the model's columns."],"tags":["database","insert","document","persistence"],"backgroundTag":null,"analyzedSha":"554fb1133ac3861732235ad9c377eb5e0a770665","analyzedAt":"2026-08-15T09:20:16.380Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}