psycache 26.2.0__tar.gz → 26.3.0__tar.gz

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.
Files changed (67) hide show
  1. {psycache-26.2.0 → psycache-26.3.0}/CHANGELOG.md +12 -0
  2. {psycache-26.2.0 → psycache-26.3.0}/PKG-INFO +7 -3
  3. {psycache-26.2.0 → psycache-26.3.0}/README.md +6 -2
  4. {psycache-26.2.0 → psycache-26.3.0}/docs/getting-started.md +39 -0
  5. {psycache-26.2.0 → psycache-26.3.0}/docs/index.md +1 -1
  6. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/__main__.py +22 -6
  7. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/_async.py +16 -6
  8. psycache-26.3.0/src/psycache/_sql.py +87 -0
  9. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/_sync.py +23 -6
  10. psycache-26.3.0/src/psycache/_tables.py +26 -0
  11. psycache-26.3.0/tests/test_cli.py +118 -0
  12. {psycache-26.2.0 → psycache-26.3.0}/tests/test_raw.py +42 -1
  13. {psycache-26.2.0 → psycache-26.3.0}/tests/test_raw_async.py +28 -0
  14. {psycache-26.2.0 → psycache-26.3.0}/tox.ini +1 -0
  15. psycache-26.2.0/src/psycache/_sql.py +0 -33
  16. psycache-26.2.0/src/psycache/_tables.py +0 -30
  17. psycache-26.2.0/tests/test_cli.py +0 -45
  18. {psycache-26.2.0 → psycache-26.3.0}/.git_archival.txt +0 -0
  19. {psycache-26.2.0 → psycache-26.3.0}/.gitattributes +0 -0
  20. {psycache-26.2.0 → psycache-26.3.0}/.github/AI_POLICY.md +0 -0
  21. {psycache-26.2.0 → psycache-26.3.0}/.github/CODE_OF_CONDUCT.md +0 -0
  22. {psycache-26.2.0 → psycache-26.3.0}/.github/CONTRIBUTING.md +0 -0
  23. {psycache-26.2.0 → psycache-26.3.0}/.github/FUNDING.yml +0 -0
  24. {psycache-26.2.0 → psycache-26.3.0}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  25. {psycache-26.2.0 → psycache-26.3.0}/.github/dependabot.yml +0 -0
  26. {psycache-26.2.0 → psycache-26.3.0}/.github/workflows/ci.yml +0 -0
  27. {psycache-26.2.0 → psycache-26.3.0}/.github/workflows/codeql-analysis.yml +0 -0
  28. {psycache-26.2.0 → psycache-26.3.0}/.github/workflows/pypi-package.yml +0 -0
  29. {psycache-26.2.0 → psycache-26.3.0}/.github/workflows/zizmor.yml +0 -0
  30. {psycache-26.2.0 → psycache-26.3.0}/.gitignore +0 -0
  31. {psycache-26.2.0 → psycache-26.3.0}/.pre-commit-config.yaml +0 -0
  32. {psycache-26.2.0 → psycache-26.3.0}/.python-version +0 -0
  33. {psycache-26.2.0 → psycache-26.3.0}/.readthedocs.yaml +0 -0
  34. {psycache-26.2.0 → psycache-26.3.0}/LICENSE +0 -0
  35. {psycache-26.2.0 → psycache-26.3.0}/conftest.py +0 -0
  36. {psycache-26.2.0 → psycache-26.3.0}/docs/api-types.md +0 -0
  37. {psycache-26.2.0 → psycache-26.3.0}/docs/api.md +0 -0
  38. {psycache-26.2.0 → psycache-26.3.0}/docs/assets/javascript/readthedocs.js +0 -0
  39. {psycache-26.2.0 → psycache-26.3.0}/docs/async.md +0 -0
  40. {psycache-26.2.0 → psycache-26.3.0}/docs/cleanup.md +0 -0
  41. {psycache-26.2.0 → psycache-26.3.0}/docs/instrumentation/custom.md +0 -0
  42. {psycache-26.2.0 → psycache-26.3.0}/docs/instrumentation/index.md +0 -0
  43. {psycache-26.2.0 → psycache-26.3.0}/docs/instrumentation/prometheus.md +0 -0
  44. {psycache-26.2.0 → psycache-26.3.0}/docs/instrumentation/sentry.md +0 -0
  45. {psycache-26.2.0 → psycache-26.3.0}/docs/pool-adapters.md +0 -0
  46. {psycache-26.2.0 → psycache-26.3.0}/docs/quality-of-life.md +0 -0
  47. {psycache-26.2.0 → psycache-26.3.0}/docs/raw-queries.md +0 -0
  48. {psycache-26.2.0 → psycache-26.3.0}/pyproject.toml +0 -0
  49. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/__init__.py +0 -0
  50. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/_durations.py +0 -0
  51. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/instrumentation/__init__.py +0 -0
  52. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/instrumentation/_spans.py +0 -0
  53. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/instrumentation/prometheus.py +0 -0
  54. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/instrumentation/sentry.py +0 -0
  55. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/psycopg_pool.py +0 -0
  56. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/py.typed +0 -0
  57. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/sqlalchemy.py +0 -0
  58. {psycache-26.2.0 → psycache-26.3.0}/src/psycache/typing.py +0 -0
  59. {psycache-26.2.0 → psycache-26.3.0}/tests/__init__.py +0 -0
  60. {psycache-26.2.0 → psycache-26.3.0}/tests/test_maintenance.py +0 -0
  61. {psycache-26.2.0 → psycache-26.3.0}/tests/test_psycopg_pool.py +0 -0
  62. {psycache-26.2.0 → psycache-26.3.0}/tests/test_sqlalchemy.py +0 -0
  63. {psycache-26.2.0 → psycache-26.3.0}/tests/typing/README.md +0 -0
  64. {psycache-26.2.0 → psycache-26.3.0}/tests/typing/core.py +0 -0
  65. {psycache-26.2.0 → psycache-26.3.0}/tests/typing/psycopg_pool.py +0 -0
  66. {psycache-26.2.0 → psycache-26.3.0}/tests/typing/sqlalchemy.py +0 -0
  67. {psycache-26.2.0 → psycache-26.3.0}/zensical.toml +0 -0
@@ -14,6 +14,18 @@ The **third number** is for emergencies when we need to start branches for older
14
14
 
15
15
  <!-- changelog follows -->
16
16
 
17
+
18
+ ## [26.3.0](https://github.com/hynek/psycache/compare/26.2.0...26.3.0) - 2026-06-26
19
+
20
+ ### Added
21
+
22
+ - Support for PostgreSQL schemas for keeping multiple cache tables in one database.
23
+ [#5](https://github.com/hynek/psycache/pull/5)
24
+
25
+ - `python -Im psycache init-db` now prints the initialization SQL to stdout if no DSN is passed.
26
+ [#6](https://github.com/hynek/psycache/pull/6)
27
+
28
+
17
29
  ## [26.2.0](https://github.com/hynek/psycache/compare/26.1.0...26.2.0) - 2026-06-25
18
30
 
19
31
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: psycache
3
- Version: 26.2.0
3
+ Version: 26.3.0
4
4
  Summary: A psycopg-Backed PostgreSQL Cache
5
5
  Project-URL: Documentation, https://psycache.hynek.me/
6
6
  Project-URL: Changelog, https://github.com/hynek/psycache/blob/main/CHANGELOG.md
@@ -43,7 +43,7 @@ Description-Content-Type: text/markdown
43
43
  [![No AI slop inside.](https://img.shields.io/badge/no-slop-purple)](https://github.com/hynek/psycache/blob/main/.github/AI_POLICY.md)
44
44
 
45
45
 
46
- A simple key-value cache that stores JSON in PostgreSQL through [*psycopg*](https://www.psycopg.org/) 3, with TTL-based expiration and pluggable instrumentation.
46
+ A key-value cache that stores JSON in PostgreSQL through [*psycopg*](https://www.psycopg.org/) 3, with TTL-based expiration and pluggable instrumentation.
47
47
 
48
48
  - Sync and async ✔︎
49
49
  - Type-safe ✔︎
@@ -67,7 +67,11 @@ First, install *psycache* from PyPI with the `sqlalchemy` extra:
67
67
  $ uv pip install "psycache[sqlalchemy]"
68
68
  ```
69
69
 
70
- Initialize the cache table once (`python -Im psycache init-db <dsn>` does the same from the shell), then store and retrieve JSON with a TTL:
70
+ Initialize the cache table once[^cli] then store and retrieve JSON with a TTL:
71
+
72
+ [^cli]: `python -Im psycache init-db <dsn>` does the same from the shell.
73
+ Add `--schema <schema>` to use a non-default PostgreSQL schema.
74
+ Omit `<dsn>` to print the SQL.
71
75
 
72
76
  ```python
73
77
  import psycopg
@@ -6,7 +6,7 @@
6
6
  [![No AI slop inside.](https://img.shields.io/badge/no-slop-purple)](https://github.com/hynek/psycache/blob/main/.github/AI_POLICY.md)
7
7
 
8
8
 
9
- A simple key-value cache that stores JSON in PostgreSQL through [*psycopg*](https://www.psycopg.org/) 3, with TTL-based expiration and pluggable instrumentation.
9
+ A key-value cache that stores JSON in PostgreSQL through [*psycopg*](https://www.psycopg.org/) 3, with TTL-based expiration and pluggable instrumentation.
10
10
 
11
11
  - Sync and async ✔︎
12
12
  - Type-safe ✔︎
@@ -30,7 +30,11 @@ First, install *psycache* from PyPI with the `sqlalchemy` extra:
30
30
  $ uv pip install "psycache[sqlalchemy]"
31
31
  ```
32
32
 
33
- Initialize the cache table once (`python -Im psycache init-db <dsn>` does the same from the shell), then store and retrieve JSON with a TTL:
33
+ Initialize the cache table once[^cli] then store and retrieve JSON with a TTL:
34
+
35
+ [^cli]: `python -Im psycache init-db <dsn>` does the same from the shell.
36
+ Add `--schema <schema>` to use a non-default PostgreSQL schema.
37
+ Omit `<dsn>` to print the SQL.
34
38
 
35
39
  ```python
36
40
  import psycopg
@@ -54,10 +54,49 @@ with psycopg.connect(
54
54
  $ python -Im psycache init-db postgresql://psycache@127.0.0.1/psycache
55
55
  ```
56
56
 
57
+ Omit the DSN to print the SQL instead:
58
+
59
+ ```console
60
+ $ python -Im psycache init-db
61
+ CREATE UNLOGGED TABLE IF NOT EXISTS "psycache" (
62
+ ...
63
+ ```
64
+
57
65
  This creates the `psycache` unlogged table and an index on `expires_at`.
58
66
  [`init_db()`][psycache.init_db] is idempotent, so running it again leaves existing data untouched.
59
67
 
60
68
 
69
+ ### Schemas
70
+
71
+ By default, *psycache* uses the connection's current default schema.
72
+ To keep multiple cache tables in one database, create them in separate PostgreSQL schemas and pass the same schema to initialization and the cache object:
73
+
74
+ ```python
75
+ from sqlalchemy import create_engine
76
+
77
+ from psycache import PostgresCache
78
+ from psycache.sqlalchemy import SQLAlchemyCachePool
79
+
80
+
81
+ with psycopg.connect(
82
+ "postgresql://psycache@127.0.0.1/psycache", autocommit=True
83
+ ) as conn:
84
+ conn.execute("CREATE SCHEMA IF NOT EXISTS app_cache")
85
+ psycache.init_db(conn, schema="app_cache")
86
+
87
+ engine = create_engine("postgresql+psycopg://psycache@127.0.0.1/psycache")
88
+ cache = PostgresCache(SQLAlchemyCachePool(engine), schema="app_cache")
89
+ ```
90
+
91
+ From the command line, use `--schema`:
92
+
93
+ ```console
94
+ $ python -Im psycache init-db --schema app_cache postgresql://psycache@127.0.0.1/psycache
95
+ ```
96
+
97
+ Without a DSN, `--schema` qualifies the printed SQL instead.
98
+
99
+
61
100
  ## Store and retrieve
62
101
 
63
102
  Assuming you already have a SQLAlchemy [`Engine`][sqlalchemy.engine.Engine] in your application, wrap it in a [`SQLAlchemyCachePool`][psycache.sqlalchemy.SQLAlchemyCachePool] and hand it to [`PostgresCache`][psycache.PostgresCache]:
@@ -4,7 +4,7 @@
4
4
 
5
5
  ---
6
6
 
7
- **psycache** is a simple key-value cache that stores JSON in PostgreSQL through [*psycopg*](https://www.psycopg.org/psycopg3/docs/) 3, with TTL-based expiration, and pluggable instrumentation.
7
+ **_psycache_** is a simple key-value cache that stores JSON in PostgreSQL through [*psycopg*](https://www.psycopg.org/psycopg3/docs/) 3, with TTL-based expiration, and pluggable instrumentation.
8
8
 
9
9
  - **Sync and async**: [`PostgresCache`][psycache.PostgresCache] and a fully async [`AsyncPostgresCache`][psycache.AsyncPostgresCache] that mirrors its API.
10
10
 
@@ -9,14 +9,24 @@ from collections.abc import Sequence
9
9
 
10
10
  import psycopg
11
11
 
12
+ from . import _sql
12
13
  from ._tables import init_db
13
14
 
14
15
 
15
- def _do_init_db(dsn: str) -> int:
16
+ def _dump_init_db_sql(schema: str | None = None) -> None:
17
+ print(f"{_sql.create_table(schema).as_string().rstrip()};")
18
+ print(f"{_sql.create_index(schema).as_string().rstrip()};")
19
+
20
+
21
+ def _do_init_db(dsn: str | None, schema: str | None = None) -> int:
16
22
  try:
23
+ if dsn is None:
24
+ _dump_init_db_sql(schema)
25
+ return 0
26
+
17
27
  with psycopg.connect(dsn, autocommit=True) as conn:
18
- init_db(conn)
19
- except psycopg.Error as e:
28
+ init_db(conn, schema=schema)
29
+ except (ValueError, psycopg.Error) as e:
20
30
  print(f"psycache: init-db failed: {e}", file=sys.stderr)
21
31
  return 1
22
32
 
@@ -35,12 +45,18 @@ def _build_parser() -> argparse.ArgumentParser:
35
45
  "init-db",
36
46
  help="Create the psycache table and index.",
37
47
  description="Create the psycache table and index in the database "
38
- "identified by DSN.",
48
+ "identified by DSN, or print the SQL to stdout if DSN is omitted.",
49
+ )
50
+ init_db_parser.add_argument(
51
+ "--schema",
52
+ help="PostgreSQL schema in which to create the cache table.",
39
53
  )
40
54
  init_db_parser.add_argument(
41
55
  "dsn",
56
+ nargs="?",
42
57
  metavar="DSN",
43
- help="A libpq connection string, e.g. postgresql://user@host/db.",
58
+ help="A libpq connection string, e.g. postgresql://user@host/db. "
59
+ "If omitted, print the SQL to stdout.",
44
60
  )
45
61
 
46
62
  return parser
@@ -50,7 +66,7 @@ def main(argv: Sequence[str] | None = None) -> int:
50
66
  parser = _build_parser()
51
67
  args = parser.parse_args(argv)
52
68
 
53
- return _do_init_db(args.dsn)
69
+ return _do_init_db(args.dsn, schema=args.schema)
54
70
 
55
71
 
56
72
  if __name__ == "__main__": # pragma: no cover
@@ -100,18 +100,28 @@ class AsyncPostgresCache:
100
100
  An asyncio-based Postgres cache.
101
101
  """
102
102
 
103
- __slots__ = ("_instrumentations", "_pool")
103
+ __slots__ = ("_instrumentations", "_pool", "_queries")
104
104
 
105
105
  _pool: AsyncCachePool
106
106
  _instrumentations: Sequence[CacheInstrumentation]
107
+ _queries: _sql.CacheQueries
107
108
 
108
109
  def __init__(
109
110
  self,
110
111
  pool: AsyncCachePool,
111
112
  *,
113
+ schema: str | None = None,
112
114
  instrumentations: Sequence[CacheInstrumentation] = (),
113
115
  ):
116
+ """
117
+ Same parameters as [`PostgresCache`][psycache.PostgresCache].
118
+ """
114
119
  self._pool = pool
120
+ self._queries = (
121
+ _sql.DEFAULT_QUERIES
122
+ if schema is None
123
+ else _sql.CacheQueries(schema)
124
+ )
115
125
  self._instrumentations = instrumentations
116
126
 
117
127
  async def get_raw(
@@ -123,7 +133,7 @@ class AsyncPostgresCache:
123
133
  """
124
134
  with _lookup_span(self._instrumentations, key, span_name) as span:
125
135
  async with self._pool.connect() as conn:
126
- cur = await conn.execute(_sql.GET, (key,))
136
+ cur = await conn.execute(self._queries.get, (key,))
127
137
  row = await cur.fetchone()
128
138
 
129
139
  if row is None:
@@ -153,7 +163,7 @@ class AsyncPostgresCache:
153
163
 
154
164
  async with self._pool.connect() as conn:
155
165
  cur = await conn.execute(
156
- _sql.PUT, (key, Jsonb(value), expires_at)
166
+ self._queries.put, (key, Jsonb(value), expires_at)
157
167
  )
158
168
  row = await cur.fetchone()
159
169
 
@@ -166,7 +176,7 @@ class AsyncPostgresCache:
166
176
  """
167
177
  with _remove_span(self._instrumentations, key) as span:
168
178
  async with self._pool.connect() as conn:
169
- await conn.execute(_sql.REMOVE, (key,))
179
+ await conn.execute(self._queries.remove, (key,))
170
180
 
171
181
  span.record_removed()
172
182
 
@@ -177,7 +187,7 @@ class AsyncPostgresCache:
177
187
  """
178
188
  with _cleanup_span(self._instrumentations) as span:
179
189
  async with self._pool.connect() as conn:
180
- cur = await conn.execute(_sql.CLEANUP_EXPIRED)
190
+ cur = await conn.execute(self._queries.cleanup_expired)
181
191
  num_deleted: int = cur.rowcount
182
192
 
183
193
  span.record_cleanup(num_deleted)
@@ -221,7 +231,7 @@ class AsyncPostgresCache:
221
231
  """
222
232
  with _flush_span(self._instrumentations) as span:
223
233
  async with self._pool.connect() as conn:
224
- cur = await conn.execute(_sql.FLUSH)
234
+ cur = await conn.execute(self._queries.flush)
225
235
  num_flushed: int = cur.rowcount
226
236
 
227
237
  span.record_flush(num_flushed)
@@ -0,0 +1,87 @@
1
+ # SPDX-FileCopyrightText: 2026 Hynek Schlawack <hs@ox.cx>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from psycopg import sql
6
+
7
+
8
+ _TABLE_NAME = "psycache"
9
+ _EXPIRES_AT_INDEX_NAME = "ix_psycache_expires_at"
10
+
11
+
12
+ def _cache_table(schema: str | None = None) -> sql.Identifier:
13
+ if schema == "":
14
+ msg = "schema must not be empty"
15
+ raise ValueError(msg)
16
+
17
+ if schema is None:
18
+ return sql.Identifier(_TABLE_NAME)
19
+
20
+ return sql.Identifier(schema, _TABLE_NAME)
21
+
22
+
23
+ def create_table(schema: str | None = None) -> sql.Composed:
24
+ return sql.SQL("""\
25
+ CREATE UNLOGGED TABLE IF NOT EXISTS {} (
26
+ key text PRIMARY KEY,
27
+ value jsonb NOT NULL,
28
+ expires_at timestamptz NOT NULL
29
+ )
30
+ """).format(_cache_table(schema))
31
+
32
+
33
+ def create_index(schema: str | None = None) -> sql.Composed:
34
+ return sql.SQL("""\
35
+ CREATE INDEX IF NOT EXISTS {}
36
+ ON {} (expires_at)
37
+ """).format(sql.Identifier(_EXPIRES_AT_INDEX_NAME), _cache_table(schema))
38
+
39
+
40
+ class CacheQueries:
41
+ """
42
+ SQL queries for a cache table.
43
+ """
44
+
45
+ __slots__ = ("cleanup_expired", "flush", "get", "put", "remove")
46
+
47
+ cleanup_expired: sql.Composed
48
+ flush: sql.Composed
49
+ get: sql.Composed
50
+ put: sql.Composed
51
+ remove: sql.Composed
52
+
53
+ def __init__(self, schema: str | None) -> None:
54
+ table = _cache_table(schema)
55
+
56
+ self.get = sql.SQL("""\
57
+ SELECT value, pg_column_size(value)
58
+ FROM {}
59
+ WHERE key = %s
60
+ AND expires_at > statement_timestamp()
61
+ """).format(table)
62
+
63
+ self.put = sql.SQL("""\
64
+ INSERT INTO {} (key, value, expires_at)
65
+ VALUES (%s, %s, %s)
66
+ ON CONFLICT (key) DO UPDATE SET
67
+ value = EXCLUDED.value,
68
+ expires_at = EXCLUDED.expires_at
69
+ RETURNING pg_column_size(value)
70
+ """).format(table)
71
+
72
+ self.remove = sql.SQL("""\
73
+ DELETE FROM {}
74
+ WHERE key = %s
75
+ """).format(table)
76
+
77
+ self.cleanup_expired = sql.SQL("""\
78
+ DELETE FROM {}
79
+ WHERE expires_at < statement_timestamp()
80
+ """).format(table)
81
+
82
+ self.flush = sql.SQL("""\
83
+ DELETE FROM {}
84
+ """).format(table)
85
+
86
+
87
+ DEFAULT_QUERIES = CacheQueries(None)
@@ -94,23 +94,38 @@ class PostgresCache:
94
94
  A Postgres-based cache.
95
95
  """
96
96
 
97
- __slots__ = ("_instrumentations", "_pool")
97
+ __slots__ = ("_instrumentations", "_pool", "_queries")
98
98
 
99
99
  _pool: CachePool
100
100
  _instrumentations: Sequence[CacheInstrumentation]
101
+ _queries: _sql.CacheQueries
101
102
 
102
103
  def __init__(
103
104
  self,
104
105
  pool: CachePool,
105
106
  *,
107
+ schema: str | None = None,
106
108
  instrumentations: Sequence[CacheInstrumentation] = (),
107
109
  ):
108
110
  """
109
111
  Args:
110
112
  pool: The cache pool to use.
113
+
114
+ schema:
115
+ The PostgreSQL schema that contains the cache table. If
116
+ `None`, queries use the connection's current default schema.
117
+
111
118
  instrumentations: Sequence of instrumentations to use.
119
+
120
+ Changes:
121
+ - **26.3.0**: added *schema* parameter
112
122
  """
113
123
  self._pool = pool
124
+ self._queries = (
125
+ _sql.DEFAULT_QUERIES
126
+ if schema is None
127
+ else _sql.CacheQueries(schema)
128
+ )
114
129
  self._instrumentations = instrumentations
115
130
 
116
131
  def get_raw(
@@ -130,7 +145,7 @@ class PostgresCache:
130
145
  """
131
146
  with _lookup_span(self._instrumentations, key, span_name) as span:
132
147
  with self._pool.connect() as conn:
133
- row = conn.execute(_sql.GET, (key,)).fetchone()
148
+ row = conn.execute(self._queries.get, (key,)).fetchone()
134
149
 
135
150
  if row is None:
136
151
  span.record_cache_miss()
@@ -167,7 +182,7 @@ class PostgresCache:
167
182
 
168
183
  with self._pool.connect() as conn:
169
184
  row = conn.execute(
170
- _sql.PUT, (key, Jsonb(value), expires_at)
185
+ self._queries.put, (key, Jsonb(value), expires_at)
171
186
  ).fetchone()
172
187
 
173
188
  span.record_put(row[0]) # type: ignore[index] # ty: ignore[not-subscriptable]
@@ -183,7 +198,7 @@ class PostgresCache:
183
198
  """
184
199
  with _remove_span(self._instrumentations, key) as span:
185
200
  with self._pool.connect() as conn:
186
- conn.execute(_sql.REMOVE, (key,))
201
+ conn.execute(self._queries.remove, (key,))
187
202
 
188
203
  span.record_removed()
189
204
 
@@ -195,7 +210,9 @@ class PostgresCache:
195
210
  """
196
211
  with _cleanup_span(self._instrumentations) as span:
197
212
  with self._pool.connect() as conn:
198
- num_deleted: int = conn.execute(_sql.CLEANUP_EXPIRED).rowcount
213
+ num_deleted: int = conn.execute(
214
+ self._queries.cleanup_expired
215
+ ).rowcount
199
216
 
200
217
  span.record_cleanup(num_deleted)
201
218
 
@@ -209,7 +226,7 @@ class PostgresCache:
209
226
  """
210
227
  with _flush_span(self._instrumentations) as span:
211
228
  with self._pool.connect() as conn:
212
- num_flushed: int = conn.execute(_sql.FLUSH).rowcount
229
+ num_flushed: int = conn.execute(self._queries.flush).rowcount
213
230
 
214
231
  span.record_flush(num_flushed)
215
232
 
@@ -0,0 +1,26 @@
1
+ # SPDX-FileCopyrightText: 2026 Hynek Schlawack <hs@ox.cx>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ import psycopg
6
+
7
+ from . import _sql
8
+
9
+
10
+ def init_db(conn: psycopg.Connection, *, schema: str | None = None) -> None:
11
+ """
12
+ Create the *psycache* table if it doesn't exist.
13
+
14
+ Args:
15
+ conn: A psycopg connection.
16
+
17
+ schema:
18
+ The PostgreSQL schema in which to create the cache table. If
19
+ `None`, the table is created using the connection's current
20
+ default schema.
21
+
22
+ Changes:
23
+ - **26.3.0**: added *schema* parameter
24
+ """
25
+ conn.execute(_sql.create_table(schema))
26
+ conn.execute(_sql.create_index(schema))
@@ -0,0 +1,118 @@
1
+ # SPDX-FileCopyrightText: 2026 Hynek Schlawack <hs@ox.cx>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ import psycopg
6
+ import pytest
7
+
8
+ from psycache.__main__ import main
9
+
10
+
11
+ def test_init_db_creates_table(db_dsn: str):
12
+ """
13
+ `init-db` creates the psycache table and is idempotent.
14
+ """
15
+ with psycopg.connect(db_dsn, autocommit=True) as conn:
16
+ conn.execute("DROP TABLE IF EXISTS psycache")
17
+
18
+ assert 0 == main(["init-db", db_dsn])
19
+
20
+ with psycopg.connect(db_dsn, autocommit=True) as conn:
21
+ regclass = conn.execute("SELECT to_regclass('psycache')").fetchone()[0]
22
+
23
+ assert "psycache" == regclass
24
+
25
+ # Running it again against an existing table is a no-op.
26
+ assert 0 == main(["init-db", db_dsn])
27
+
28
+
29
+ def test_init_db_creates_table_in_schema(db_dsn: str):
30
+ """
31
+ `init-db --schema` creates the psycache table in that schema.
32
+ """
33
+ schema = "psycache_cli_test"
34
+
35
+ with psycopg.connect(db_dsn, autocommit=True) as conn:
36
+ conn.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE")
37
+ conn.execute(f"CREATE SCHEMA {schema}")
38
+
39
+ assert 0 == main(["init-db", "--schema", schema, db_dsn])
40
+
41
+ with psycopg.connect(db_dsn, autocommit=True) as conn:
42
+ regclass = conn.execute(
43
+ "SELECT to_regclass('psycache_cli_test.psycache')"
44
+ ).fetchone()[0]
45
+ index_regclass = conn.execute(
46
+ "SELECT to_regclass('psycache_cli_test.ix_psycache_expires_at')"
47
+ ).fetchone()[0]
48
+
49
+ assert "psycache_cli_test.psycache" == regclass
50
+ assert "psycache_cli_test.ix_psycache_expires_at" == index_regclass
51
+
52
+ # Running it again against an existing table is a no-op.
53
+ assert 0 == main(["init-db", "--schema", schema, db_dsn])
54
+
55
+
56
+ def test_init_db_without_dsn_prints_sql(
57
+ capsys: pytest.CaptureFixture[str],
58
+ ):
59
+ """
60
+ `init-db` prints the SQL to initialize the cache if no DSN is passed.
61
+ """
62
+ assert 0 == main(["init-db"])
63
+
64
+ out = capsys.readouterr().out
65
+ assert 'CREATE UNLOGGED TABLE IF NOT EXISTS "psycache" (' in out
66
+ assert (
67
+ 'CREATE INDEX IF NOT EXISTS "ix_psycache_expires_at"\n'
68
+ ' ON "psycache" (expires_at);'
69
+ ) in out
70
+
71
+
72
+ def test_init_db_without_dsn_prints_schema_sql(
73
+ capsys: pytest.CaptureFixture[str],
74
+ ):
75
+ """
76
+ `init-db --schema` prints schema-qualified SQL if no DSN is passed.
77
+ """
78
+ assert 0 == main(["init-db", "--schema", "app_cache"])
79
+
80
+ out = capsys.readouterr().out
81
+ assert (
82
+ 'CREATE UNLOGGED TABLE IF NOT EXISTS "app_cache"."psycache" (' in out
83
+ )
84
+ assert (
85
+ 'CREATE INDEX IF NOT EXISTS "ix_psycache_expires_at"\n'
86
+ ' ON "app_cache"."psycache" (expires_at);'
87
+ ) in out
88
+
89
+
90
+ def test_init_db_reports_connection_failure(
91
+ capsys: pytest.CaptureFixture[str],
92
+ ):
93
+ """
94
+ A connection error is reported on stderr and exits non-zero.
95
+ """
96
+ assert 1 == main(["init-db", "postgresql://nope@127.0.0.1:1/nope"])
97
+
98
+ assert "init-db failed" in capsys.readouterr().err
99
+
100
+
101
+ def test_init_db_reports_empty_schema(
102
+ db_dsn: str,
103
+ capsys: pytest.CaptureFixture[str],
104
+ ):
105
+ """
106
+ An empty schema name is reported on stderr and exits non-zero.
107
+ """
108
+ assert 1 == main(["init-db", "--schema", "", db_dsn])
109
+
110
+ assert "schema must not be empty" in capsys.readouterr().err
111
+
112
+
113
+ def test_requires_a_command():
114
+ """
115
+ Invoking without a subcommand is an argparse usage error.
116
+ """
117
+ with pytest.raises(SystemExit):
118
+ main([])
@@ -5,7 +5,9 @@
5
5
  import datetime as dt
6
6
  import secrets
7
7
 
8
- from psycache import PostgresCache
8
+ import pytest
9
+
10
+ from psycache import PostgresCache, init_db
9
11
 
10
12
 
11
13
  def test_raw_get_and_set(cache: PostgresCache):
@@ -61,3 +63,42 @@ def test_remove(cache: PostgresCache):
61
63
  cache.remove(key)
62
64
 
63
65
  assert cache.get_raw(key) is None
66
+
67
+
68
+ def test_schema_is_isolated(cache: PostgresCache):
69
+ """
70
+ A cache configured with a schema uses that schema's table.
71
+ """
72
+ schema = "psycache_raw_test"
73
+
74
+ with cache._pool.connect() as conn:
75
+ conn.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE")
76
+ conn.execute(f"CREATE SCHEMA {schema}")
77
+ init_db(conn, schema=schema)
78
+
79
+ schema_cache = PostgresCache(
80
+ cache._pool,
81
+ schema=schema,
82
+ instrumentations=cache._instrumentations,
83
+ )
84
+ key = secrets.token_urlsafe()
85
+
86
+ cache.put_raw(key, {"schema": False}, ttl=10)
87
+ schema_cache.put_raw(key, {"schema": True}, ttl=10)
88
+
89
+ assert {"schema": False} == cache.get_raw(key)
90
+ assert {"schema": True} == schema_cache.get_raw(key)
91
+
92
+
93
+ def test_empty_schema_is_rejected(cache: PostgresCache):
94
+ """
95
+ An empty schema name is rejected.
96
+ """
97
+ with pytest.raises(ValueError, match="schema must not be empty"):
98
+ PostgresCache(cache._pool, schema="")
99
+
100
+ with (
101
+ cache._pool.connect() as conn,
102
+ pytest.raises(ValueError, match="schema must not be empty"),
103
+ ):
104
+ init_db(conn, schema="")
@@ -5,8 +5,11 @@
5
5
  import datetime as dt
6
6
  import secrets
7
7
 
8
+ import psycopg
8
9
  import pytest
9
10
 
11
+ from psycache import AsyncPostgresCache, init_db
12
+
10
13
 
11
14
  pytestmark = pytest.mark.asyncio
12
15
 
@@ -67,6 +70,31 @@ async def test_remove(acache):
67
70
  assert await acache.get_raw(key) is None
68
71
 
69
72
 
73
+ async def test_schema_is_isolated(acache, db_dsn):
74
+ """
75
+ A cache configured with a schema uses that schema's table.
76
+ """
77
+ schema = "psycache_raw_async_test"
78
+
79
+ with psycopg.connect(db_dsn, autocommit=True) as conn:
80
+ conn.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE")
81
+ conn.execute(f"CREATE SCHEMA {schema}")
82
+ init_db(conn, schema=schema)
83
+
84
+ schema_cache = AsyncPostgresCache(
85
+ acache._pool,
86
+ schema=schema,
87
+ instrumentations=acache._instrumentations,
88
+ )
89
+ key = secrets.token_urlsafe()
90
+
91
+ await acache.put_raw(key, {"schema": False}, ttl=10)
92
+ await schema_cache.put_raw(key, {"schema": True}, ttl=10)
93
+
94
+ assert {"schema": False} == await acache.get_raw(key)
95
+ assert {"schema": True} == await schema_cache.get_raw(key)
96
+
97
+
70
98
  async def test_cleanup_expired(acache):
71
99
  """
72
100
  Expired cache entries are deleted. Unexpired aren't touched.
@@ -50,6 +50,7 @@ commands =
50
50
 
51
51
  [testenv:lint]
52
52
  skip_install = true
53
+ dependency_groups =
53
54
  deps = prek
54
55
  commands = prek run --all-files {posargs}
55
56
 
@@ -1,33 +0,0 @@
1
- # SPDX-FileCopyrightText: 2026 Hynek Schlawack <hs@ox.cx>
2
- #
3
- # SPDX-License-Identifier: MIT
4
-
5
- GET = """\
6
- SELECT value, pg_column_size(value)
7
- FROM psycache
8
- WHERE key = %s
9
- AND expires_at > statement_timestamp()
10
- """
11
-
12
- PUT = """\
13
- INSERT INTO psycache (key, value, expires_at)
14
- VALUES (%s, %s, %s)
15
- ON CONFLICT (key) DO UPDATE SET
16
- value = EXCLUDED.value,
17
- expires_at = EXCLUDED.expires_at
18
- RETURNING pg_column_size(value)
19
- """
20
-
21
- REMOVE = """\
22
- DELETE FROM psycache
23
- WHERE key = %s
24
- """
25
-
26
- CLEANUP_EXPIRED = """\
27
- DELETE FROM psycache
28
- WHERE expires_at < statement_timestamp()
29
- """
30
-
31
- FLUSH = """\
32
- DELETE FROM psycache
33
- """
@@ -1,30 +0,0 @@
1
- # SPDX-FileCopyrightText: 2026 Hynek Schlawack <hs@ox.cx>
2
- #
3
- # SPDX-License-Identifier: MIT
4
-
5
- import psycopg
6
-
7
-
8
- _CREATE_TABLE = """\
9
- CREATE UNLOGGED TABLE IF NOT EXISTS psycache (
10
- key text PRIMARY KEY,
11
- value jsonb NOT NULL,
12
- expires_at timestamptz NOT NULL
13
- )
14
- """
15
-
16
- _CREATE_INDEX = """\
17
- CREATE INDEX IF NOT EXISTS ix_psycache_expires_at
18
- ON psycache (expires_at)
19
- """
20
-
21
-
22
- def init_db(conn: psycopg.Connection) -> None:
23
- """
24
- Create the *psycache* table if it doesn't exist.
25
-
26
- Args:
27
- conn: A psycopg connection.
28
- """
29
- conn.execute(_CREATE_TABLE)
30
- conn.execute(_CREATE_INDEX)
@@ -1,45 +0,0 @@
1
- # SPDX-FileCopyrightText: 2026 Hynek Schlawack <hs@ox.cx>
2
- #
3
- # SPDX-License-Identifier: MIT
4
-
5
- import psycopg
6
- import pytest
7
-
8
- from psycache.__main__ import main
9
-
10
-
11
- def test_init_db_creates_table(db_dsn: str):
12
- """
13
- `init-db` creates the psycache table and is idempotent.
14
- """
15
- with psycopg.connect(db_dsn, autocommit=True) as conn:
16
- conn.execute("DROP TABLE IF EXISTS psycache")
17
-
18
- assert 0 == main(["init-db", db_dsn])
19
-
20
- with psycopg.connect(db_dsn, autocommit=True) as conn:
21
- regclass = conn.execute("SELECT to_regclass('psycache')").fetchone()[0]
22
-
23
- assert "psycache" == regclass
24
-
25
- # Running it again against an existing table is a no-op.
26
- assert 0 == main(["init-db", db_dsn])
27
-
28
-
29
- def test_init_db_reports_connection_failure(
30
- capsys: pytest.CaptureFixture[str],
31
- ):
32
- """
33
- A connection error is reported on stderr and exits non-zero.
34
- """
35
- assert 1 == main(["init-db", "postgresql://nope@127.0.0.1:1/nope"])
36
-
37
- assert "init-db failed" in capsys.readouterr().err
38
-
39
-
40
- def test_requires_a_command():
41
- """
42
- Invoking without a subcommand is an argparse usage error.
43
- """
44
- with pytest.raises(SystemExit):
45
- main([])
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes