|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +try: |
| 4 | + from sqlalchemy import ( |
| 5 | + Column, |
| 6 | + ColumnElement, |
| 7 | + Integer, |
| 8 | + MetaData, |
| 9 | + String, |
| 10 | + Table, |
| 11 | + create_engine, |
| 12 | + delete, |
| 13 | + desc, |
| 14 | + func, |
| 15 | + select, |
| 16 | + ) |
| 17 | + from sqlalchemy.dialects.postgresql import JSONB |
| 18 | + from sqlalchemy.dialects.postgresql import insert as pg_insert |
| 19 | + from sqlalchemy.engine import Engine |
| 20 | +except ImportError: |
| 21 | + raise ImportError("Run `pip install postgres[binary]` to use Postgres backend.") |
| 22 | + |
| 23 | +from memstate.backends.base import StorageBackend |
| 24 | + |
| 25 | + |
| 26 | +class PostgresStorage(StorageBackend): |
| 27 | + def __init__(self, engine_or_url: str | Engine, table_prefix: str = "memstate") -> None: |
| 28 | + if isinstance(engine_or_url, str): |
| 29 | + self._engine = create_engine(engine_or_url, future=True) |
| 30 | + else: |
| 31 | + self._engine = engine_or_url |
| 32 | + |
| 33 | + self._metadata = MetaData() |
| 34 | + self._table_prefix = table_prefix |
| 35 | + |
| 36 | + # --- Define Tables --- |
| 37 | + self._facts_table = Table( |
| 38 | + f"{table_prefix}_facts", |
| 39 | + self._metadata, |
| 40 | + Column("id", String, primary_key=True), |
| 41 | + Column("doc", JSONB, nullable=False), # Используем JSONB для индексации |
| 42 | + ) |
| 43 | + |
| 44 | + self._log_table = Table( |
| 45 | + f"{table_prefix}_log", |
| 46 | + self._metadata, |
| 47 | + Column("seq", Integer, primary_key=True, autoincrement=True), |
| 48 | + Column("entry", JSONB, nullable=False), |
| 49 | + ) |
| 50 | + |
| 51 | + with self._engine.begin() as conn: |
| 52 | + self._metadata.create_all(conn) |
| 53 | + |
| 54 | + def load(self, id: str) -> dict[str, Any] | None: |
| 55 | + with self._engine.connect() as conn: |
| 56 | + stmt = select(self._facts_table.c.doc).where(self._facts_table.c.id == id) |
| 57 | + row = conn.execute(stmt).first() |
| 58 | + if row: |
| 59 | + return row[0] # SQLAlchemy deserializes JSONB automatically |
| 60 | + return None |
| 61 | + |
| 62 | + def save(self, fact_data: dict[str, Any]) -> None: |
| 63 | + # Postgres Native Upsert (INSERT ... ON CONFLICT DO UPDATE) |
| 64 | + stmt = pg_insert(self._facts_table).values(id=fact_data["id"], doc=fact_data) |
| 65 | + upsert_stmt = stmt.on_conflict_do_update( |
| 66 | + index_elements=["id"], set_={"doc": stmt.excluded.doc} # Conflict over PK |
| 67 | + ) |
| 68 | + |
| 69 | + with self._engine.begin() as conn: |
| 70 | + conn.execute(upsert_stmt) |
| 71 | + |
| 72 | + def delete(self, id: str) -> None: |
| 73 | + with self._engine.begin() as conn: |
| 74 | + conn.execute(delete(self._facts_table).where(self._facts_table.c.id == id)) |
| 75 | + |
| 76 | + def query(self, type_filter: str | None = None, json_filters: dict[str, Any] | None = None) -> list[dict[str, Any]]: |
| 77 | + |
| 78 | + stmt = select(self._facts_table.c.doc) |
| 79 | + |
| 80 | + # 1. Filter by type (fact) |
| 81 | + if type_filter: |
| 82 | + # Postgres JSONB access: doc->>'type' |
| 83 | + stmt = stmt.where(self._facts_table.c.doc["type"].astext == type_filter) |
| 84 | + |
| 85 | + # 2. JSON filters (the hardest part) |
| 86 | + # We expect keys of type "payload.user.id" |
| 87 | + if json_filters: |
| 88 | + for key, value in json_filters.items(): |
| 89 | + # Split the path: payload.role -> ['payload', 'role'] |
| 90 | + path_parts = key.split(".") |
| 91 | + |
| 92 | + # Building a JSONB access chain |
| 93 | + json_col: ColumnElement[Any] = self._facts_table.c.doc |
| 94 | + |
| 95 | + # Go deeper to the last key |
| 96 | + for part in path_parts[:-1]: |
| 97 | + json_col = json_col[part] |
| 98 | + |
| 99 | + # Compare the last key |
| 100 | + # Important: cast value to JSONB so that types (int/bool/str) work |
| 101 | + # Or use the @> (contains) operator for reliability |
| 102 | + |
| 103 | + # Simple option (SQLAlchemy automatically casts types when comparing JSONB) |
| 104 | + stmt = stmt.where(json_col[path_parts[-1]] == func.to_jsonb(value)) |
| 105 | + |
| 106 | + with self._engine.connect() as conn: |
| 107 | + rows = conn.execute(stmt).all() |
| 108 | + return [r[0] for r in rows] |
| 109 | + |
| 110 | + def append_tx(self, tx_data: dict[str, Any]) -> None: |
| 111 | + with self._engine.begin() as conn: |
| 112 | + conn.execute(self._log_table.insert().values(entry=tx_data)) |
| 113 | + |
| 114 | + def get_tx_log(self, limit: int = 100, offset: int = 0) -> list[dict[str, Any]]: |
| 115 | + stmt = select(self._log_table.c.entry).order_by(desc(self._log_table.c.seq)).limit(limit).offset(offset) |
| 116 | + with self._engine.connect() as conn: |
| 117 | + rows = conn.execute(stmt).all() |
| 118 | + return [r[0] for r in rows] |
| 119 | + |
| 120 | + def delete_session(self, session_id: str) -> list[str]: |
| 121 | + # 1. Find the ID to delete |
| 122 | + # WHERE doc->>'session_id' == session_id |
| 123 | + find_stmt = select(self._facts_table.c.id).where(self._facts_table.c.doc["session_id"].astext == session_id) |
| 124 | + |
| 125 | + with self._engine.connect() as conn: |
| 126 | + ids_to_delete = [r[0] for r in conn.execute(find_stmt).all()] |
| 127 | + |
| 128 | + if not ids_to_delete: |
| 129 | + return [] |
| 130 | + |
| 131 | + # 2. Delete |
| 132 | + del_stmt = delete(self._facts_table).where(self._facts_table.c.id.in_(ids_to_delete)) |
| 133 | + with self._engine.begin() as conn: |
| 134 | + conn.execute(del_stmt) |
| 135 | + |
| 136 | + return ids_to_delete |
0 commit comments