def save(self, doc: Document) -> None:
"""Save document to the unified documents table."""
# 1. Base mapping (Common to all types)
row: dict[str, Any] = {
"id": doc.document_id, # Use stable ID property
"content": doc.content
if isinstance(doc.content, str)
else doc.content.decode("utf-8", errors="ignore"),
"created_at": doc.created_at,
"source_checksum": doc.internal_metadata.get("checksum"),
"doc_type": doc.type.value,
"status": doc.metadata.get("status", "published"), # Default status if not provided
"extensions": None,
}
# 2. Type-specific mapping
if doc.type == DocumentType.POST:
row.update(
{
"title": doc.metadata.get("title"),
"slug": doc.slug, # Use property that handles fallback
"date": doc.internal_metadata.get("date"),
"summary": doc.metadata.get("summary"),
"authors": doc.metadata.get("authors", []),
"tags": doc.metadata.get("tags", []),
"status": doc.metadata.get("status"),
}
)
elif doc.type == DocumentType.PROFILE:
row.update(
{
"subject_uuid": doc.internal_metadata.get("subject_uuid")
or doc.document_id, # Fallback to ID if needed
"title": doc.metadata.get("title") or doc.metadata.get("name"),
"alias": doc.internal_metadata.get("alias"),
"summary": doc.metadata.get("summary") or doc.metadata.get("bio"),
"avatar_url": doc.metadata.get("avatar_url"),
"interests": doc.metadata.get("interests", []),
}
)
elif doc.type == DocumentType.MEDIA:
row.update(
{
"filename": doc.internal_metadata.get("filename"),
"mime_type": doc.internal_metadata.get("mime_type"), # Was mime_type in schema
"media_type": doc.internal_metadata.get("media_type"),
"phash": doc.internal_metadata.get("phash"),
}
)
elif doc.type == DocumentType.JOURNAL:
row.update(
{
"title": doc.metadata.get("title") or doc.metadata.get("window_label"),
"window_start": doc.internal_metadata.get("window_start"),
"window_end": doc.internal_metadata.get("window_end"),
}
)
elif doc.type == DocumentType.ANNOTATION:
pass
try:
self.db.replace_rows("documents", [row], by_keys={"id": row["id"]})
except Exception as e:
msg = f"Failed to save document {row['id']}: {e}"
raise DatabaseOperationError(msg) from e