File size: 2,968 Bytes
dc891c8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | """Bookmark Manager — Snapshot repository."""
from __future__ import annotations
import logging
import uuid
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
class BookmarkProcessor:
"""Thin repository wrapper for Snapshot persistence in Bookmark Manager."""
TABLE = "snapshots"
def __init__(self, db: Any) -> None:
self._db = db
logger.debug("BookmarkProcessor bound to %s", db)
def insert(self, title: Any, saved_at: Any, **kwargs: Any) -> str:
"""Persist a new Snapshot row and return its generated ID."""
rec_id = str(uuid.uuid4())
row: Dict[str, Any] = {
"id": rec_id,
"title": title,
"saved_at": saved_at,
"created_at": datetime.now(timezone.utc).isoformat(),
**kwargs,
}
self._db.insert(self.TABLE, row)
return rec_id
def fetch(self, rec_id: str) -> Optional[Dict[str, Any]]:
"""Return the Snapshot row for *rec_id*, or None."""
return self._db.fetch(self.TABLE, rec_id)
def update(self, rec_id: str, **fields: Any) -> bool:
"""Patch *fields* on an existing Snapshot row."""
if not self._db.exists(self.TABLE, rec_id):
return False
fields["updated_at"] = datetime.now(timezone.utc).isoformat()
self._db.update(self.TABLE, rec_id, fields)
return True
def delete(self, rec_id: str) -> bool:
"""Hard-delete a Snapshot row; returns False if not found."""
if not self._db.exists(self.TABLE, rec_id):
return False
self._db.delete(self.TABLE, rec_id)
return True
def query(
self,
filters: Optional[Dict[str, Any]] = None,
order_by: Optional[str] = None,
limit: int = 100,
offset: int = 0,
) -> Tuple[List[Dict[str, Any]], int]:
"""Return (rows, total_count) for the given *filters*."""
rows = self._db.select(self.TABLE, filters or {}, limit, offset)
total = self._db.count(self.TABLE, filters or {})
logger.debug("query snapshots: %d/%d", len(rows), total)
return rows, total
def export_by_url(
self, value: Any, limit: int = 50
) -> List[Dict[str, Any]]:
"""Fetch snapshots filtered by *url*."""
rows, _ = self.query({"url": value}, limit=limit)
return rows
def bulk_insert(
self, records: List[Dict[str, Any]]
) -> List[str]:
"""Insert *records* in bulk and return their generated IDs."""
ids: List[str] = []
for rec in records:
rec_id = self.insert(
rec["title"], rec.get("saved_at"),
**{k: v for k, v in rec.items() if k not in ("title", "saved_at")}
)
ids.append(rec_id)
logger.info("bulk_insert snapshots: %d rows", len(ids))
return ids
|