snapdelta-postgres 0.2.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.
- snapdelta_postgres-0.2.0/.gitignore +5 -0
- snapdelta_postgres-0.2.0/LICENSE +202 -0
- snapdelta_postgres-0.2.0/PKG-INFO +50 -0
- snapdelta_postgres-0.2.0/README.md +22 -0
- snapdelta_postgres-0.2.0/pyproject.toml +41 -0
- snapdelta_postgres-0.2.0/src/snapdelta_postgres/__init__.py +5 -0
- snapdelta_postgres-0.2.0/src/snapdelta_postgres/py.typed +0 -0
- snapdelta_postgres-0.2.0/src/snapdelta_postgres/store.py +258 -0
- snapdelta_postgres-0.2.0/tests/test_postgres.py +73 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: snapdelta-postgres
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: PostgreSQL store backend for snapdelta: snapshots, diffs and runs in a database that many servers share
|
|
5
|
+
Project-URL: Homepage, https://github.com/antoinekh/snapdelta
|
|
6
|
+
Project-URL: Documentation, https://github.com/antoinekh/snapdelta/blob/main/docs/stores.md
|
|
7
|
+
Project-URL: Issues, https://github.com/antoinekh/snapdelta/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/antoinekh/snapdelta/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Antoine Keranflec'h <antoine.keranflech@gmail.com>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: diff,netdevops,network-automation,plugin-architecture,postgresql,snapshot
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: System Administrators
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Database
|
|
21
|
+
Classifier: Topic :: System :: Networking
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.13
|
|
24
|
+
Requires-Dist: psycopg-pool<4,>=3.2
|
|
25
|
+
Requires-Dist: psycopg[binary]<4,>=3.2
|
|
26
|
+
Requires-Dist: snapdelta<0.3,>=0.2.0
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# snapdelta-postgres
|
|
30
|
+
|
|
31
|
+
A PostgreSQL store backend for [snapdelta](https://github.com/antoinekh/snapdelta): the snapshots, the diffs and the runs in a database, which many snapdelta servers and workers can share.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install snapdelta-postgres
|
|
35
|
+
snapdelta --store postgresql://snapdelta@db.example.net/snapdelta info
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The location is a libpq URI without its password, such as `postgresql://USER@HOST:PORT/DATABASE?sslmode=require`; snapdelta shows the location in its pages and its runs. Give the password in the settings, or in `PGPASSWORD` or `~/.pgpass`:
|
|
39
|
+
|
|
40
|
+
```toml
|
|
41
|
+
[store]
|
|
42
|
+
location = "postgresql://snapdelta@db.example.net/snapdelta"
|
|
43
|
+
|
|
44
|
+
[stores.postgresql]
|
|
45
|
+
password = { env = "SNAPDELTA_DB_PASSWORD" }
|
|
46
|
+
connect_timeout_s = 10
|
|
47
|
+
pool_size = 4
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The store creates its three tables, `snapdelta_snapshots`, `snapdelta_outputs` and `snapdelta_runs`, at its first use; the user needs the right to create tables in the database. The bodies are the JSON documents of the file store, as `json`, which keeps their order. See [docs/stores.md](https://github.com/antoinekh/snapdelta/blob/main/docs/stores.md).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# snapdelta-postgres
|
|
2
|
+
|
|
3
|
+
A PostgreSQL store backend for [snapdelta](https://github.com/antoinekh/snapdelta): the snapshots, the diffs and the runs in a database, which many snapdelta servers and workers can share.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install snapdelta-postgres
|
|
7
|
+
snapdelta --store postgresql://snapdelta@db.example.net/snapdelta info
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
The location is a libpq URI without its password, such as `postgresql://USER@HOST:PORT/DATABASE?sslmode=require`; snapdelta shows the location in its pages and its runs. Give the password in the settings, or in `PGPASSWORD` or `~/.pgpass`:
|
|
11
|
+
|
|
12
|
+
```toml
|
|
13
|
+
[store]
|
|
14
|
+
location = "postgresql://snapdelta@db.example.net/snapdelta"
|
|
15
|
+
|
|
16
|
+
[stores.postgresql]
|
|
17
|
+
password = { env = "SNAPDELTA_DB_PASSWORD" }
|
|
18
|
+
connect_timeout_s = 10
|
|
19
|
+
pool_size = 4
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The store creates its three tables, `snapdelta_snapshots`, `snapdelta_outputs` and `snapdelta_runs`, at its first use; the user needs the right to create tables in the database. The bodies are the JSON documents of the file store, as `json`, which keeps their order. See [docs/stores.md](https://github.com/antoinekh/snapdelta/blob/main/docs/stores.md).
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "snapdelta-postgres"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "PostgreSQL store backend for snapdelta: snapshots, diffs and runs in a database that many servers share"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.13"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
authors = [{ name = "Antoine Keranflec'h", email = "antoine.keranflech@gmail.com" }]
|
|
9
|
+
keywords = ["network-automation", "netdevops", "snapshot", "diff", "postgresql", "plugin-architecture"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 3 - Alpha",
|
|
12
|
+
"Intended Audience :: System Administrators",
|
|
13
|
+
"Operating System :: OS Independent",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Programming Language :: Python :: 3.13",
|
|
17
|
+
"Programming Language :: Python :: 3.14",
|
|
18
|
+
"Topic :: Database",
|
|
19
|
+
"Topic :: System :: Networking",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
dependencies = ["snapdelta>=0.2.0,<0.3", "psycopg[binary]>=3.2,<4", "psycopg-pool>=3.2,<4"]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/antoinekh/snapdelta"
|
|
26
|
+
Documentation = "https://github.com/antoinekh/snapdelta/blob/main/docs/stores.md"
|
|
27
|
+
Issues = "https://github.com/antoinekh/snapdelta/issues"
|
|
28
|
+
Changelog = "https://github.com/antoinekh/snapdelta/blob/main/CHANGELOG.md"
|
|
29
|
+
|
|
30
|
+
[project.entry-points."snapdelta.stores"]
|
|
31
|
+
postgresql = "snapdelta_postgres:PostgresStore"
|
|
32
|
+
|
|
33
|
+
[tool.uv.sources]
|
|
34
|
+
snapdelta = { workspace = true }
|
|
35
|
+
|
|
36
|
+
[build-system]
|
|
37
|
+
requires = ["hatchling"]
|
|
38
|
+
build-backend = "hatchling.build"
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.wheel]
|
|
41
|
+
packages = ["src/snapdelta_postgres"]
|
|
File without changes
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""The store `postgresql://`: the tables of the SQLite store in a PostgreSQL database, with the bodies as json.
|
|
2
|
+
|
|
3
|
+
json and not jsonb: jsonb sorts the keys, and the order of the models and objects of a diff is the order to show.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from typing import Any, LiteralString
|
|
12
|
+
|
|
13
|
+
import psycopg
|
|
14
|
+
from psycopg.conninfo import conninfo_to_dict
|
|
15
|
+
from psycopg.types.json import Json
|
|
16
|
+
from psycopg_pool import ConnectionPool, PoolTimeout
|
|
17
|
+
from pydantic import Field
|
|
18
|
+
|
|
19
|
+
from snapdelta.activity import Run
|
|
20
|
+
from snapdelta.errors import NotFoundError, SnapdeltaError
|
|
21
|
+
from snapdelta.output import Output
|
|
22
|
+
from snapdelta.settings import Secret, StoreBackendSettings
|
|
23
|
+
from snapdelta.snapshot import SnapshotFile
|
|
24
|
+
from snapdelta.store import (
|
|
25
|
+
OutputEntry,
|
|
26
|
+
SnapshotEntry,
|
|
27
|
+
Store,
|
|
28
|
+
StoreInfo,
|
|
29
|
+
output_entry,
|
|
30
|
+
parse_output,
|
|
31
|
+
parse_run,
|
|
32
|
+
parse_snapshot,
|
|
33
|
+
snapshot_entry,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
SCHEME = "postgresql"
|
|
37
|
+
TABLES = """
|
|
38
|
+
create table if not exists snapdelta_snapshots (
|
|
39
|
+
reference text primary key,
|
|
40
|
+
target text not null,
|
|
41
|
+
captured_at timestamptz not null,
|
|
42
|
+
label text,
|
|
43
|
+
source text not null,
|
|
44
|
+
body json not null
|
|
45
|
+
);
|
|
46
|
+
create index if not exists snapdelta_snapshots_by_target on snapdelta_snapshots (target, reference);
|
|
47
|
+
create table if not exists snapdelta_outputs (
|
|
48
|
+
name text primary key,
|
|
49
|
+
created_at timestamptz not null,
|
|
50
|
+
left_target text not null,
|
|
51
|
+
right_target text not null,
|
|
52
|
+
body json not null
|
|
53
|
+
);
|
|
54
|
+
create index if not exists snapdelta_outputs_by_time on snapdelta_outputs (created_at);
|
|
55
|
+
create table if not exists snapdelta_runs (
|
|
56
|
+
id text primary key,
|
|
57
|
+
body json not null
|
|
58
|
+
);
|
|
59
|
+
"""
|
|
60
|
+
# Two servers that start at the same time must not create the tables twice.
|
|
61
|
+
LOCK_ID = 0x736E6170
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class PostgresSettings(StoreBackendSettings):
|
|
65
|
+
password: Secret | None = Field(
|
|
66
|
+
default=None,
|
|
67
|
+
description="The password of the database user; never in the location, which the pages and the runs show.",
|
|
68
|
+
)
|
|
69
|
+
connect_timeout_s: float = Field(default=10, gt=0, description="How long a connection may take, in seconds.")
|
|
70
|
+
pool_size: int = Field(
|
|
71
|
+
default=4, ge=1, le=100, description="The connections that the store keeps open, for the requests at once."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class PostgresStore(Store):
|
|
76
|
+
"""`postgresql://USER@HOST:PORT/DATABASE?OPTIONS`: any libpq URI, without its password."""
|
|
77
|
+
|
|
78
|
+
backend = SCHEME
|
|
79
|
+
settings_class = PostgresSettings
|
|
80
|
+
|
|
81
|
+
def __init__(self, address: str, settings: PostgresSettings) -> None:
|
|
82
|
+
conninfo = f"{SCHEME}://{address}"
|
|
83
|
+
try:
|
|
84
|
+
parts = conninfo_to_dict(conninfo)
|
|
85
|
+
except psycopg.ProgrammingError as error:
|
|
86
|
+
raise SnapdeltaError(f"{SCHEME}://{_without_password(address)}: not a valid location ({error})") from error
|
|
87
|
+
if "password" in parts:
|
|
88
|
+
raise SnapdeltaError(
|
|
89
|
+
"the location of a postgresql store holds a password, and snapdelta shows the location: "
|
|
90
|
+
"put the password in [stores.postgresql] password, or in PGPASSWORD or ~/.pgpass"
|
|
91
|
+
)
|
|
92
|
+
self.address = address
|
|
93
|
+
connection: dict[str, Any] = {"connect_timeout": math.ceil(settings.connect_timeout_s)}
|
|
94
|
+
if settings.password is not None:
|
|
95
|
+
connection["password"] = settings.password.value()
|
|
96
|
+
self.pool = ConnectionPool(conninfo, kwargs=connection, min_size=1, max_size=settings.pool_size, open=False)
|
|
97
|
+
try:
|
|
98
|
+
self.pool.open(wait=True, timeout=settings.connect_timeout_s)
|
|
99
|
+
except PoolTimeout as error:
|
|
100
|
+
self.pool.close()
|
|
101
|
+
raise SnapdeltaError(f"{self.location}: no connection within {settings.connect_timeout_s} s") from error
|
|
102
|
+
with self._connect() as db:
|
|
103
|
+
db.execute("select pg_advisory_xact_lock(%s)", (LOCK_ID,))
|
|
104
|
+
db.execute(TABLES)
|
|
105
|
+
|
|
106
|
+
@classmethod
|
|
107
|
+
def open(cls, address: str, settings: StoreBackendSettings) -> PostgresStore:
|
|
108
|
+
return cls(address, settings if isinstance(settings, PostgresSettings) else PostgresSettings())
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def location(self) -> str:
|
|
112
|
+
return f"{SCHEME}://{self.address}"
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
self.pool.close()
|
|
116
|
+
|
|
117
|
+
@contextmanager
|
|
118
|
+
def _connect(self) -> Iterator[psycopg.Connection[Any]]:
|
|
119
|
+
"""A connection of the pool, in one transaction that commits at the end of the block."""
|
|
120
|
+
with self.pool.connection() as db:
|
|
121
|
+
yield db
|
|
122
|
+
|
|
123
|
+
def targets(self, query: str = "") -> list[str]:
|
|
124
|
+
wanted = query.strip().lower()
|
|
125
|
+
with self._connect() as db:
|
|
126
|
+
rows = db.execute(
|
|
127
|
+
"select distinct target from snapdelta_snapshots where strpos(lower(target), %s) > 0 order by target",
|
|
128
|
+
(wanted,),
|
|
129
|
+
).fetchall()
|
|
130
|
+
return [row[0] for row in rows]
|
|
131
|
+
|
|
132
|
+
def snapshot_entries(self, target: str) -> list[SnapshotEntry]:
|
|
133
|
+
with self._connect() as db:
|
|
134
|
+
rows = db.execute(
|
|
135
|
+
"select reference from snapdelta_snapshots where target = %s order by reference desc", (target,)
|
|
136
|
+
).fetchall()
|
|
137
|
+
return [entry for (reference,) in rows if (entry := snapshot_entry(reference))]
|
|
138
|
+
|
|
139
|
+
def output_entries(self, query: str = "") -> list[OutputEntry]:
|
|
140
|
+
wanted = query.strip().lower()
|
|
141
|
+
with self._connect() as db:
|
|
142
|
+
rows = db.execute(
|
|
143
|
+
"select name from snapdelta_outputs "
|
|
144
|
+
"where strpos(lower(left_target), %s) > 0 or strpos(lower(right_target), %s) > 0 order by name desc",
|
|
145
|
+
(wanted, wanted),
|
|
146
|
+
).fetchall()
|
|
147
|
+
return [entry for (name,) in rows if (entry := output_entry(name))]
|
|
148
|
+
|
|
149
|
+
def info(self) -> StoreInfo:
|
|
150
|
+
with self._connect() as db:
|
|
151
|
+
row = db.execute(
|
|
152
|
+
"select (select count(distinct target) from snapdelta_snapshots), "
|
|
153
|
+
"(select count(*) from snapdelta_snapshots), (select count(*) from snapdelta_outputs), "
|
|
154
|
+
"(select count(*) from snapdelta_runs), "
|
|
155
|
+
"pg_total_relation_size('snapdelta_snapshots') + pg_total_relation_size('snapdelta_outputs') "
|
|
156
|
+
"+ pg_total_relation_size('snapdelta_runs')"
|
|
157
|
+
).fetchone()
|
|
158
|
+
assert row is not None
|
|
159
|
+
targets, snapshots, outputs, runs, size = row
|
|
160
|
+
return StoreInfo(self.backend, self.location, targets, snapshots, outputs, size, runs)
|
|
161
|
+
|
|
162
|
+
def _has_snapshot(self, reference: str) -> bool:
|
|
163
|
+
with self._connect() as db:
|
|
164
|
+
found = db.execute("select 1 from snapdelta_snapshots where reference = %s", (reference,)).fetchone()
|
|
165
|
+
return found is not None
|
|
166
|
+
|
|
167
|
+
def _write_snapshot(self, reference: str, snapshot: SnapshotFile) -> None:
|
|
168
|
+
values = (
|
|
169
|
+
reference,
|
|
170
|
+
reference.partition("/")[0],
|
|
171
|
+
snapshot.captured_at,
|
|
172
|
+
snapshot.label,
|
|
173
|
+
snapshot.source,
|
|
174
|
+
Json(snapshot.model_dump(mode="json", by_alias=True)),
|
|
175
|
+
)
|
|
176
|
+
try:
|
|
177
|
+
with self._connect() as db:
|
|
178
|
+
db.execute(
|
|
179
|
+
"insert into snapdelta_snapshots (reference, target, captured_at, label, source, body) "
|
|
180
|
+
"values (%s, %s, %s, %s, %s, %s)",
|
|
181
|
+
values,
|
|
182
|
+
)
|
|
183
|
+
except psycopg.errors.UniqueViolation as error:
|
|
184
|
+
# Another writer saved the same reference between the check and this insert.
|
|
185
|
+
raise SnapdeltaError(f"snapshot {reference} already exists: give another label") from error
|
|
186
|
+
|
|
187
|
+
def _read_snapshot(self, reference: str) -> SnapshotFile:
|
|
188
|
+
body = self._body("select body from snapdelta_snapshots where reference = %s", reference, "snapshot")
|
|
189
|
+
return parse_snapshot(body, reference)
|
|
190
|
+
|
|
191
|
+
def _delete_snapshot(self, reference: str) -> None:
|
|
192
|
+
with self._connect() as db:
|
|
193
|
+
db.execute("delete from snapdelta_snapshots where reference = %s", (reference,))
|
|
194
|
+
|
|
195
|
+
def _has_output(self, name: str) -> bool:
|
|
196
|
+
with self._connect() as db:
|
|
197
|
+
return db.execute("select 1 from snapdelta_outputs where name = %s", (name,)).fetchone() is not None
|
|
198
|
+
|
|
199
|
+
def _write_output(self, name: str, output: Output) -> None:
|
|
200
|
+
values = (
|
|
201
|
+
name,
|
|
202
|
+
output.created_at,
|
|
203
|
+
output.left.target,
|
|
204
|
+
output.right.target,
|
|
205
|
+
Json(output.model_dump(mode="json", by_alias=True)),
|
|
206
|
+
)
|
|
207
|
+
with self._connect() as db:
|
|
208
|
+
db.execute(
|
|
209
|
+
"insert into snapdelta_outputs (name, created_at, left_target, right_target, body) "
|
|
210
|
+
"values (%s, %s, %s, %s, %s)",
|
|
211
|
+
values,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def _read_output(self, name: str) -> Output:
|
|
215
|
+
return parse_output(self._body("select body from snapdelta_outputs where name = %s", name, "output"), name)
|
|
216
|
+
|
|
217
|
+
def _replace_output(self, name: str, output: Output) -> None:
|
|
218
|
+
with self._connect() as db:
|
|
219
|
+
db.execute(
|
|
220
|
+
"update snapdelta_outputs set body = %s where name = %s",
|
|
221
|
+
(Json(output.model_dump(mode="json", by_alias=True)), name),
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
def _delete_output(self, name: str) -> None:
|
|
225
|
+
with self._connect() as db:
|
|
226
|
+
db.execute("delete from snapdelta_outputs where name = %s", (name,))
|
|
227
|
+
|
|
228
|
+
def _write_run(self, run: Run) -> None:
|
|
229
|
+
with self._connect() as db:
|
|
230
|
+
db.execute(
|
|
231
|
+
"insert into snapdelta_runs (id, body) values (%s, %s) "
|
|
232
|
+
"on conflict (id) do update set body = excluded.body",
|
|
233
|
+
(run.id, Json(run.model_dump(mode="json"))),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
def _read_run(self, run_id: str) -> Run:
|
|
237
|
+
return parse_run(self._body("select body from snapdelta_runs where id = %s", run_id, "run"), run_id)
|
|
238
|
+
|
|
239
|
+
def _run_ids(self) -> list[str]:
|
|
240
|
+
with self._connect() as db:
|
|
241
|
+
return [row[0] for row in db.execute("select id from snapdelta_runs order by id desc").fetchall()]
|
|
242
|
+
|
|
243
|
+
def _delete_run(self, run_id: str) -> None:
|
|
244
|
+
with self._connect() as db:
|
|
245
|
+
db.execute("delete from snapdelta_runs where id = %s", (run_id,))
|
|
246
|
+
|
|
247
|
+
def _body(self, query: LiteralString, key: str, kind: str) -> dict[str, Any]:
|
|
248
|
+
with self._connect() as db:
|
|
249
|
+
row = db.execute(query, (key,)).fetchone()
|
|
250
|
+
# Another process can delete the row between the existence check and this read.
|
|
251
|
+
if row is None:
|
|
252
|
+
raise NotFoundError(f"no {kind} {key!r} in {self.location}")
|
|
253
|
+
return row[0]
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _without_password(address: str) -> str:
|
|
257
|
+
user, at, rest = address.rpartition("@")
|
|
258
|
+
return f"{user.partition(':')[0]}{at}{rest}" if at else address
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The PostgreSQL store against a server: set SNAPDELTA_POSTGRES_URL, such as `make test-postgres` does."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import uuid
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
|
|
7
|
+
import psycopg
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from snapdelta.errors import SnapdeltaError
|
|
11
|
+
from snapdelta.settings import Secret
|
|
12
|
+
from snapdelta.store import open_store
|
|
13
|
+
from snapdelta.testing import StoreContract, sample
|
|
14
|
+
from snapdelta_postgres import PostgresSettings, PostgresStore
|
|
15
|
+
|
|
16
|
+
# An administrator of a server, which may create and drop a database for each test.
|
|
17
|
+
SERVER = os.environ.get("SNAPDELTA_POSTGRES_URL", "")
|
|
18
|
+
needs_server = pytest.mark.skipif(not SERVER, reason="set SNAPDELTA_POSTGRES_URL to test against PostgreSQL")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture
|
|
22
|
+
def database() -> Iterator[str]:
|
|
23
|
+
"""The address of a new, empty database, dropped after the test."""
|
|
24
|
+
name = f"snapdelta_test_{uuid.uuid4().hex[:12]}"
|
|
25
|
+
with psycopg.connect(SERVER, autocommit=True) as admin:
|
|
26
|
+
admin.execute(f'create database "{name}"')
|
|
27
|
+
yield SERVER.removeprefix("postgresql://").rsplit("/", 1)[0] + f"/{name}"
|
|
28
|
+
with psycopg.connect(SERVER, autocommit=True) as admin:
|
|
29
|
+
admin.execute(f'drop database "{name}" with (force)')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@needs_server
|
|
33
|
+
class TestPostgresStore(StoreContract):
|
|
34
|
+
@pytest.fixture
|
|
35
|
+
def store(self, database: str) -> Iterator[PostgresStore]:
|
|
36
|
+
store = PostgresStore.open(database, PostgresSettings())
|
|
37
|
+
yield store
|
|
38
|
+
store.close()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@needs_server
|
|
42
|
+
def test_the_scheme_opens_the_backend_and_two_stores_share_the_tables(database: str) -> None:
|
|
43
|
+
first = open_store(f"postgresql://{database}")
|
|
44
|
+
second = open_store(f"postgresql://{database}")
|
|
45
|
+
try:
|
|
46
|
+
assert isinstance(first, PostgresStore) and first.info().backend == "postgresql"
|
|
47
|
+
reference = first.save_snapshot(sample())
|
|
48
|
+
assert second.resolve_snapshot("R1@latest") == reference
|
|
49
|
+
with pytest.raises(SnapdeltaError, match="already exists"):
|
|
50
|
+
second.save_snapshot(sample())
|
|
51
|
+
finally:
|
|
52
|
+
first.close()
|
|
53
|
+
second.close()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@needs_server
|
|
57
|
+
def test_a_password_of_the_settings_is_used(database: str, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
58
|
+
password = os.environ.get("PGPASSWORD")
|
|
59
|
+
if password is None:
|
|
60
|
+
pytest.skip("the test server needs no password")
|
|
61
|
+
monkeypatch.delenv("PGPASSWORD")
|
|
62
|
+
store = PostgresStore.open(database, PostgresSettings(password=Secret(plain=password)))
|
|
63
|
+
store.close()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_a_location_with_a_password_is_refused() -> None:
|
|
67
|
+
with pytest.raises(SnapdeltaError, match=r"put the password in \[stores.postgresql\] password"):
|
|
68
|
+
PostgresStore.open("snapdelta:s3cret@db.example.net/snapdelta", PostgresSettings())
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_a_server_that_does_not_answer_is_an_error_message() -> None:
|
|
72
|
+
with pytest.raises(SnapdeltaError, match="no connection within 1.0 s"):
|
|
73
|
+
PostgresStore.open("snapdelta@127.0.0.1:9/snapdelta", PostgresSettings(connect_timeout_s=1))
|