airprompter-datastore-postgres 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,120 @@
1
+ """``airprompter-datastore-postgres`` — the release datastore's ``KvStore`` over one PostgreSQL table (T40,
2
+ ``protocol/datastore-format.md``). The same table as ``@airprompter/datastore-postgres``, so a Python puller and a
3
+ TypeScript runtime share it. No driver is bundled: hand in a DB-API connection (``psycopg`` 3 or ``psycopg2``) or a
4
+ ``psycopg_pool.ConnectionPool``, and the adapter keeps the contract in plain SQL — ``INSERT … ON CONFLICT DO
5
+ NOTHING`` for ``if_absent``, ``UPDATE … WHERE version = %s`` for ``if_version`` (a counter bumped on every write), an
6
+ escaped ``LIKE`` over a ``text_pattern_ops`` index for ``list``. Postgres 11 or later.
7
+
8
+ Example::
9
+
10
+ import psycopg
11
+ from airprompter_agent import kv_release_datastore
12
+ from airprompter_datastore_postgres import postgres_kv_store
13
+
14
+ kv = postgres_kv_store(connection=psycopg.connect(os.environ["DATABASE_URL"], autocommit=True))
15
+ kv.ensure_schema() # or run postgres_kv_schema() in your own migrations
16
+ releases = kv_release_datastore(kv)
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ import threading
23
+ from contextlib import contextmanager
24
+ from typing import Any, Iterator, Optional, Sequence
25
+
26
+ from airprompter_agent_sync.store.kv_store import KvEntry, check_condition
27
+
28
+ __all__ = ["PostgresKvStore", "postgres_kv_schema", "postgres_kv_store"]
29
+
30
+ _IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")
31
+
32
+
33
+ def _quoted(table: str) -> tuple[str, str]:
34
+ parts = table.split(".")
35
+ if len(parts) > 2 or not all(_IDENTIFIER.match(part) for part in parts):
36
+ raise ValueError(f"not a table name: {table!r} (letters, digits and _; optionally schema.name)")
37
+ return ".".join(f'"{part}"' for part in parts), f'"{parts[-1]}_key_prefix"'
38
+
39
+
40
+ def postgres_kv_schema(table: str = "airprompter_kv") -> list[str]:
41
+ """The DDL the adapter needs, for teams that run migrations themselves (the same as the TypeScript adapter's)."""
42
+ quoted, index = _quoted(table)
43
+ return [
44
+ f"CREATE TABLE IF NOT EXISTS {quoted} (key text PRIMARY KEY, value text NOT NULL, version bigint NOT NULL DEFAULT 1, updated_at timestamptz NOT NULL DEFAULT now())",
45
+ f"CREATE INDEX IF NOT EXISTS {index} ON {quoted} (key text_pattern_ops)",
46
+ ]
47
+
48
+
49
+ def _like_prefix(prefix: str) -> str:
50
+ return re.sub(r"([\\%_])", r"\\\1", prefix) + "%"
51
+
52
+
53
+ class PostgresKvStore:
54
+ def __init__(self, *, connection: Any = None, pool: Any = None, table: str = "airprompter_kv") -> None:
55
+ if (connection is None) == (pool is None):
56
+ raise ValueError("pass exactly one of connection= (a DB-API connection) or pool= (a psycopg_pool.ConnectionPool)")
57
+ self.table = table
58
+ self._quoted, _ = _quoted(table)
59
+ self._connection = connection
60
+ self._pool = pool
61
+ # One connection is one transaction at a time: operations from several threads take turns.
62
+ self._lock = threading.Lock()
63
+
64
+ @contextmanager
65
+ def _conn(self) -> Iterator[Any]:
66
+ if self._pool is not None:
67
+ with self._pool.connection() as conn:
68
+ yield conn
69
+ else:
70
+ with self._lock:
71
+ yield self._connection
72
+
73
+ def _run(self, sql: str, params: Sequence[Any] = ()) -> tuple[list[Sequence[Any]], int]:
74
+ with self._conn() as conn:
75
+ try:
76
+ cur = conn.cursor()
77
+ try:
78
+ cur.execute(sql, tuple(params))
79
+ rows = list(cur.fetchall()) if cur.description is not None else []
80
+ count = cur.rowcount
81
+ finally:
82
+ cur.close()
83
+ if not getattr(conn, "autocommit", False):
84
+ conn.commit()
85
+ return rows, count
86
+ except Exception:
87
+ if not getattr(conn, "autocommit", False):
88
+ conn.rollback()
89
+ raise
90
+
91
+ def ensure_schema(self) -> None:
92
+ """Create the table and its prefix index when they are missing (idempotent)."""
93
+ for statement in postgres_kv_schema(self.table):
94
+ self._run(statement)
95
+
96
+ def get(self, key: str) -> Optional[KvEntry]:
97
+ rows, _ = self._run(f"SELECT value, version::text FROM {self._quoted} WHERE key = %s", (key,))
98
+ return KvEntry(str(rows[0][0]), str(rows[0][1])) if rows else None
99
+
100
+ def put(self, key: str, value: str, *, if_absent: bool = False, if_version: Optional[str] = None) -> bool:
101
+ check_condition(if_absent, if_version)
102
+ if if_absent:
103
+ _, count = self._run(f"INSERT INTO {self._quoted} (key, value, version) VALUES (%s, %s, 1) ON CONFLICT (key) DO NOTHING", (key, value))
104
+ return count == 1
105
+ # A version this adapter never issued cannot match; never let it reach the cast.
106
+ if not re.fullmatch(r"\d{1,19}", if_version or ""):
107
+ return False
108
+ _, count = self._run(f"UPDATE {self._quoted} SET value = %s, version = version + 1, updated_at = now() WHERE key = %s AND version = %s::bigint", (value, key, if_version))
109
+ return count == 1
110
+
111
+ def list(self, prefix: str) -> list[str]:
112
+ rows, _ = self._run(f"SELECT key FROM {self._quoted} WHERE key LIKE %s ESCAPE '\\'", (_like_prefix(prefix),))
113
+ return [str(row[0]) for row in rows if str(row[0]).startswith(prefix)]
114
+
115
+ def delete(self, key: str) -> None:
116
+ self._run(f"DELETE FROM {self._quoted} WHERE key = %s", (key,))
117
+
118
+
119
+ def postgres_kv_store(*, connection: Any = None, pool: Any = None, table: str = "airprompter_kv") -> PostgresKvStore:
120
+ return PostgresKvStore(connection=connection, pool=pool, table=table)
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.5
2
+ Name: airprompter-datastore-postgres
3
+ Version: 0.3.0
4
+ Summary: The AirPrompter release datastore over one PostgreSQL table: a KvStore with INSERT … ON CONFLICT and versioned UPDATEs, for kv_release_datastore. Bring your own driver (psycopg 3, psycopg2, a psycopg_pool).
5
+ Project-URL: Homepage, https://github.com/airprompter/airprompter-agent-sdk
6
+ Project-URL: Source, https://github.com/airprompter/airprompter-agent-sdk/tree/main/sdk-python/packages/datastore-postgres
7
+ Project-URL: Protocol, https://github.com/airprompter/airprompter-agent-sdk/blob/main/protocol/datastore-format.md
8
+ Project-URL: Changelog, https://github.com/airprompter/airprompter-agent-sdk/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/airprompter/airprompter-agent-sdk/issues
10
+ Author: AirPrompter
11
+ License-Expression: BSD-3-Clause
12
+ License-File: LICENSE
13
+ Keywords: agent,airprompter,datastore,llm,postgres,postgresql,prompts
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: airprompter-agent-sync==0.3.0
25
+ Provides-Extra: psycopg
26
+ Requires-Dist: psycopg>=3.1; extra == 'psycopg'
27
+ Provides-Extra: psycopg2
28
+ Requires-Dist: psycopg2-binary>=2.9; extra == 'psycopg2'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # airprompter-datastore-postgres
32
+
33
+ The AirPrompter release datastore over one PostgreSQL table: a `KvStore` for
34
+ `kv_release_datastore` (`airprompter-agent-sync`). The puller writes sealed
35
+ releases through it; every runtime hydrates from it
36
+ ([docs/datastore.md](https://github.com/airprompter/airprompter-agent-sdk/blob/main/docs/datastore.md)).
37
+ The table is the one `@airprompter/datastore-postgres` uses, so Python and
38
+ TypeScript share it.
39
+
40
+ ```python
41
+ import psycopg
42
+ from airprompter_agent import kv_release_datastore
43
+ from airprompter_datastore_postgres import postgres_kv_store
44
+
45
+ kv = postgres_kv_store(connection=psycopg.connect(os.environ["DATABASE_URL"], autocommit=True))
46
+ kv.ensure_schema() # or postgres_kv_schema() in your migrations
47
+ releases = kv_release_datastore(kv)
48
+ ```
49
+
50
+ - `connection=` a DB-API connection (psycopg 3 or psycopg2; operations take
51
+ turns on it) or `pool=` a `psycopg_pool.ConnectionPool`.
52
+ - `INSERT … ON CONFLICT DO NOTHING` and `UPDATE … WHERE version = %s`: no
53
+ transaction or lock is ever held across calls. Postgres 11+.
54
+ - Prove it against your database: `check_kv_store(kv)` → `KvStoreReport(ok, passed, failures)`.
@@ -0,0 +1,5 @@
1
+ airprompter_datastore_postgres/__init__.py,sha256=klvY-zbNvbXss2VSWQEjgEEj4SLk0be_cPIe6R03JdQ,5629
2
+ airprompter_datastore_postgres-0.3.0.dist-info/METADATA,sha256=jbkYVVwjBrkYBT02rly9BpC70zPOMQD3cmnmb8yYuLk,2794
3
+ airprompter_datastore_postgres-0.3.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
4
+ airprompter_datastore_postgres-0.3.0.dist-info/licenses/LICENSE,sha256=9Y6aLKFYYF8tI1_e-0pRxb52ANU6HFSNkX4tVkY6jLU,1498
5
+ airprompter_datastore_postgres-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, AirPrompter
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.