{"record":{"id":"11a11252fa00b4e6","repo":"lfnovo/open-notebook","slug":"failed-to-create-record","errorCode":null,"errorMessage":"Failed to create record","messagePattern":"Failed to create record","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"open_notebook/database/repository.py","lineNumber":139,"sourceCode":"async def repo_create(table: str, data: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"Create a new record in the specified table\"\"\"\n    # Remove 'id' attribute if it exists in data\n    data.pop(\"id\", None)\n    data[\"created\"] = datetime.now(timezone.utc)\n    data[\"updated\"] = datetime.now(timezone.utc)\n    try:\n        async with db_connection() as connection:\n            result = parse_record_ids(await connection.insert(table, data))\n            # SurrealDB may return a string error message instead of the expected record\n            if isinstance(result, str):\n                raise RuntimeError(result)\n            return result\n    except RuntimeError as e:\n        logger.error(str(e))\n        raise\n    except Exception as e:\n        logger.exception(e)\n        raise RuntimeError(\"Failed to create record\")\n\n\nasync def repo_relate(\n    source: Union[str, RecordID],\n    relationship: str,\n    target: Union[str, RecordID],\n    data: Optional[Dict[str, Any]] = None,\n) -> List[Dict[str, Any]]:\n    \"\"\"Create a relationship between two records with optional data\"\"\"\n    if data is None:\n        data = {}\n    # relationship is an edge-table name, not a record value, so it can't be\n    # bound as a query parameter; validate it against an identifier allowlist\n    # instead of trusting the caller. source/target are always bound.\n    _ensure_safe_identifier(relationship, \"relationship\")\n    query = f\"RELATE $source->{relationship}->$target CONTENT $data;\"\n    # logger.debug(f\"Relate query: {query}\")\n","sourceCodeStart":121,"sourceCodeEnd":157,"githubUrl":"https://github.com/lfnovo/open-notebook/blob/a7de90d38aaf18ee85fd661854d35c11e44613e2/open_notebook/database/repository.py#L121-L157","documentation":"repo_create() wraps record creation; RuntimeError escapes with its original message (logged), while any other exception is masked as a generic RuntimeError('Failed to create record') with the real cause only in logs. The underlying failure is almost always a SurrealQL/schema issue: missing table, schema validation, duplicate unique key, or serialization of an unsupported field type.","triggerScenarios":"Creating a record for a table that doesn't exist yet (migrations not run); inserting a field value SurrealDB can't store (e.g. datetime without isoformat, custom objects); violating a unique index; record data containing RecordID strings in a field defined with a different type in schema.","commonSituations":"API started against a fresh database before migrations; schema drift after model changes (new required field not in DB schema); passing enums or Python objects instead of primitives; namespace/database mismatch so the table lives elsewhere.","solutions":["Check the API/worker logs — logger.exception printed the real underlying exception just before this re-raise","Confirm schema migrations ran (restart make api and read startup logs)","Verify the target table exists in the expected namespace/database and the payload uses JSON-primitive values (isoformat dates, str ids)","If a unique index exists, check for a duplicate record before create"],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"rows = await repo_query(f\"SELECT id FROM {table} LIMIT 1\")\nif not rows:\n    logger.warning('table %s may not exist yet', table)","typeGuard":null,"tryCatchPattern":"try:\n    rec = await repo_create(table, data)\nexcept RuntimeError as e:\n    logger.exception('create failed for %s', table)\n    raise HTTPException(500, 'Failed to create record') from e","preventionTips":["Always inspect server logs — the true cause is logged before the generic re-raise","Keep model field types aligned with DB schema via migrations","Serialize dates/enums to JSON primitives before create"],"tags":["database","surrealdb","create","schema"],"backgroundTag":"database-insert-failed","analyzedSha":"a7de90d38aaf18ee85fd661854d35c11e44613e2","analyzedAt":"2026-08-27T02:39:58.166Z","schemaVersion":2},"datasetVersion":"2026-08-27T03:17:27.898Z"}