hoie-database-client 0.1.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.
- hoie_database_client-0.1.0/LICENSE +202 -0
- hoie_database_client-0.1.0/PKG-INFO +243 -0
- hoie_database_client-0.1.0/README.md +226 -0
- hoie_database_client-0.1.0/hoie_database_client/__init__.py +159 -0
- hoie_database_client-0.1.0/hoie_database_client/ast.py +613 -0
- hoie_database_client-0.1.0/hoie_database_client/builders.py +1112 -0
- hoie_database_client-0.1.0/hoie_database_client/client.py +633 -0
- hoie_database_client-0.1.0/hoie_database_client/codec.py +1075 -0
- hoie_database_client-0.1.0/hoie_database_client/conn.py +548 -0
- hoie_database_client-0.1.0/hoie_database_client/errors.py +100 -0
- hoie_database_client-0.1.0/hoie_database_client/py.typed +0 -0
- hoie_database_client-0.1.0/hoie_database_client/values.py +132 -0
- hoie_database_client-0.1.0/hoie_database_client.egg-info/PKG-INFO +243 -0
- hoie_database_client-0.1.0/hoie_database_client.egg-info/SOURCES.txt +20 -0
- hoie_database_client-0.1.0/hoie_database_client.egg-info/dependency_links.txt +1 -0
- hoie_database_client-0.1.0/hoie_database_client.egg-info/top_level.txt +1 -0
- hoie_database_client-0.1.0/pyproject.toml +34 -0
- hoie_database_client-0.1.0/setup.cfg +4 -0
- hoie_database_client-0.1.0/tests/test_builders.py +258 -0
- hoie_database_client-0.1.0/tests/test_integration.py +977 -0
- hoie_database_client-0.1.0/tests/test_values.py +288 -0
- hoie_database_client-0.1.0/tests/test_vectors.py +155 -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,243 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hoie-database-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The Python client for the database server
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/hoiekim/database/tree/main/clients/python#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/hoiekim/database
|
|
8
|
+
Project-URL: Issues, https://github.com/hoiekim/database/issues
|
|
9
|
+
Keywords: database,client
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Database :: Front-Ends
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# The Python client
|
|
19
|
+
|
|
20
|
+
A synchronous client for the database server, on the standard library
|
|
21
|
+
alone: no dependency to install, nothing compiled. Python 3.9 or later.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
pip install hoie-database-client
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from hoie_database_client import *
|
|
29
|
+
|
|
30
|
+
db = Client.connect("database://shop:secret@database:5454")
|
|
31
|
+
|
|
32
|
+
db.create_table_if_not_exists(
|
|
33
|
+
TableDef("mails")
|
|
34
|
+
.column(ColumnDef("mail_id", Type.UUID).default_random_uuid())
|
|
35
|
+
.column(ColumnDef("user_id", Type.UUID))
|
|
36
|
+
.column(ColumnDef("subject", Type.TEXT).default(""))
|
|
37
|
+
.column(ColumnDef("date", Type.TIMESTAMP).default_now())
|
|
38
|
+
.column(ColumnDef("read", Type.BOOL).default(False))
|
|
39
|
+
.primary_key(["mail_id"])
|
|
40
|
+
.index(IndexDef("mails_user_date").on(["user_id"]).on_desc("date").on(["mail_id"]))
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# The newest 50 mails of a user: 50 index entries read, 50 rows fetched.
|
|
44
|
+
page = db.query(Query.table("mails").index("mails_user_date", KeyRange.eq([user_id])).limit(50))
|
|
45
|
+
for mail in page:
|
|
46
|
+
print(mail["subject"], mail["date"])
|
|
47
|
+
|
|
48
|
+
# Several statements as one, as if nothing else wrote while it ran.
|
|
49
|
+
def mark_read(tx: Transaction) -> int:
|
|
50
|
+
unread = tx.query_one(
|
|
51
|
+
Query.table("mails").index("mails_user_date", KeyRange.eq([user_id]))
|
|
52
|
+
.select("n", count().filter(col("read").eq(False)))
|
|
53
|
+
)["n"]
|
|
54
|
+
tx.update(Update.table("users").key([user_id]).set("unread", unread))
|
|
55
|
+
return unread
|
|
56
|
+
|
|
57
|
+
unread = db.transaction(mark_read)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The vocabulary is the Rust client's, name for name: `docs/CLIENT.md`
|
|
61
|
+
describes what each piece means and how the things usually said in SQL
|
|
62
|
+
are said here. The bytes on the wire are `docs/PROTOCOL.md`.
|
|
63
|
+
|
|
64
|
+
## What differs from the Rust client
|
|
65
|
+
|
|
66
|
+
- **Names the language takes get an underscore:** `and_`, `or_`, `not_`,
|
|
67
|
+
`KeyRange.is_`, `Delete.from_`, `all_`, `any_`, `list_`, `sum_`, `min_`,
|
|
68
|
+
`max_`. `Expr.Depth` and `Expr.Rank` are `depth()` and `rank()`.
|
|
69
|
+
Constructors are plain calls: `TableDef("t")`, `ColumnDef("c", Type.INT)`,
|
|
70
|
+
`IndexDef("i")`.
|
|
71
|
+
- **Expressions are built with methods, not `and`/`or`/`not`:**
|
|
72
|
+
`col("a").eq(1).and_(col("b").gt(2))`. Python's own `and` cannot be
|
|
73
|
+
overloaded, so using an expression as a truth value raises `TypeError`
|
|
74
|
+
instead of silently dropping half a filter. `+ - * / %` and unary `-`
|
|
75
|
+
work on expressions.
|
|
76
|
+
- **Builders do not change:** each method returns a new builder, so a
|
|
77
|
+
query kept in a variable can be narrowed twice.
|
|
78
|
+
- **It greets the server with protocol version 2** (`PROTOCOL_VERSION`),
|
|
79
|
+
so it has none of what later versions added: no prepared statements
|
|
80
|
+
or `param(n)`, no transaction that begins with its first statement in
|
|
81
|
+
one request, no batches, and no `explain`. It cannot set `keep_start`
|
|
82
|
+
on a column, and a table that uses `keep_start` is described to it
|
|
83
|
+
without the setting.
|
|
84
|
+
- **Calls block.** A `Client` may be shared between threads; it keeps a
|
|
85
|
+
pool of connections (8 by default, `?pool=n` in the URL). A
|
|
86
|
+
transaction is used by one thread at a time.
|
|
87
|
+
- **A transaction is a context manager:** it commits when the block
|
|
88
|
+
ends and rolls back if the block raises. `db.transaction(work)` is the
|
|
89
|
+
one that runs `work` again after a conflict, as in the Rust client:
|
|
90
|
+
twice beside other writers, then as the database's only writer.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
with db.begin() as tx: # exclusive; begin_optimistic(), begin_read()
|
|
94
|
+
tx.insert(Insert.into("audit").set("action", "user.create"))
|
|
95
|
+
|
|
96
|
+
with db.lock("shop.migrate"): # a named lock, held until the block ends
|
|
97
|
+
migrate(db)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Values
|
|
101
|
+
|
|
102
|
+
| Database | Python |
|
|
103
|
+
|---|---|
|
|
104
|
+
| NULL | `None` |
|
|
105
|
+
| bool | `bool` |
|
|
106
|
+
| int (64-bit) | `int`; one that does not fit 64 bits raises `ValueError` |
|
|
107
|
+
| float | `float` |
|
|
108
|
+
| decimal | `decimal.Decimal`, exact; at most 30 digits after the point |
|
|
109
|
+
| text | `str` |
|
|
110
|
+
| bytes | `bytes` (`bytearray` and `memoryview` are accepted) |
|
|
111
|
+
| uuid | `uuid.UUID` |
|
|
112
|
+
| timestamp | `datetime.datetime` |
|
|
113
|
+
| date | `datetime.date` |
|
|
114
|
+
| json | read: the parsed value. Written: a `dict`, or `Json(value)` for anything else |
|
|
115
|
+
| list | `list` (a `tuple` is accepted) |
|
|
116
|
+
|
|
117
|
+
**Timestamps** are microseconds since 1970-01-01T00:00:00Z. One read
|
|
118
|
+
from the server is a `datetime` with `tzinfo=timezone.utc`. One written
|
|
119
|
+
may be in any zone and is converted exactly, to the microsecond; a
|
|
120
|
+
`datetime` *without* a zone is taken to be UTC, not local time. The
|
|
121
|
+
database holds times and days far outside the years 1 to 9999 that
|
|
122
|
+
`datetime` can express; those are read as `Timestamp(micros)` and
|
|
123
|
+
`Date(days)`, which may also be written.
|
|
124
|
+
|
|
125
|
+
**JSON** must be told from text and from lists when written: `"x"` is
|
|
126
|
+
text and `[1, 2]` is a list, so a JSON string or array is written
|
|
127
|
+
`Json("x")` or `Json([1, 2])`. A `dict` can only be JSON and needs no
|
|
128
|
+
wrapper. Object keys come back in the order the server stores them: by
|
|
129
|
+
length, then by bytes. The server keeps an integer inside JSON exactly
|
|
130
|
+
from -2^63 to 2^64-1 and reads a larger one as a float, so one beyond
|
|
131
|
+
that raises `ValueError`; `float(n)` writes the float.
|
|
132
|
+
|
|
133
|
+
## TLS
|
|
134
|
+
|
|
135
|
+
Without a setting a connection is in the clear, the password included,
|
|
136
|
+
which is right only on a network nobody else can listen on; a server
|
|
137
|
+
started with a certificate refuses such a connection unless it was told
|
|
138
|
+
`DATABASE_TLS=optional`. The settings go in the URL, or in the `tls` of
|
|
139
|
+
a `Config`:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
# The server's certificate must be signed by an authority in this file, and by no other.
|
|
143
|
+
Client.connect("database://shop:secret@database:5454?tls_ca=%2Fetc%2Fdatabase%2Fca.pem")
|
|
144
|
+
# Reached by an address, or by a name the certificate does not carry.
|
|
145
|
+
Client.connect(Config("10.0.0.5", 5454, "shop", "secret", tls=Tls(ca="/etc/database/ca.pem", name="database.example.com")))
|
|
146
|
+
# Signed by a public authority.
|
|
147
|
+
Client.connect("database://shop:secret@database.example.com?tls=on")
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
| URL | `Config.tls` | |
|
|
151
|
+
|---|---|---|
|
|
152
|
+
| `tls=on` | `Tls()` | TLS, the server verified against the system's certificate authorities |
|
|
153
|
+
| `tls_ca=<file>` | `Tls(ca=...)` | verified against the authorities in that PEM file, and no other |
|
|
154
|
+
| `tls_name=<name>` | `Tls(name=...)` | the name or address the certificate must be for, where that is not the host |
|
|
155
|
+
| `tls=off` | `None` | in the clear: the default |
|
|
156
|
+
|
|
157
|
+
`tls_ca` and `tls_name` turn TLS on by themselves, and `tls=off` beside
|
|
158
|
+
either is an invalid URL. A client that asks for TLS always verifies the
|
|
159
|
+
certificate and the name it is for: there is no setting that encrypts
|
|
160
|
+
without verifying, and no falling back to a connection in the clear. A
|
|
161
|
+
server that cannot be verified, or that serves no TLS, raises a
|
|
162
|
+
`DbError` of code `CONNECTION` before the password is sent. Only
|
|
163
|
+
TLS 1.3 is spoken. The Rust client's `tls_cert`, which takes one exact
|
|
164
|
+
certificate for the server's, is not here.
|
|
165
|
+
|
|
166
|
+
## Errors
|
|
167
|
+
|
|
168
|
+
Everything the server refuses raises `DbError`, with `code` (an
|
|
169
|
+
`ErrorCode`), `message`, and for the constraint errors `constraint` and
|
|
170
|
+
`table`. A value Python holds that the database has no kind for raises
|
|
171
|
+
`TypeError` or `ValueError` before anything is sent.
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
try:
|
|
175
|
+
db.insert(Insert.into("users").set("email", email))
|
|
176
|
+
except DbError as e:
|
|
177
|
+
if e.violates("users_email"):
|
|
178
|
+
...
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Administration
|
|
182
|
+
|
|
183
|
+
`db.admin` has `create_database`, `drop_database`, `set_password`,
|
|
184
|
+
`list_databases`, `checkpoint`, `check`, `stats`, `dump(out)` and
|
|
185
|
+
`restore(source, replace=False)`; all but `checkpoint`, `check`, `stats`
|
|
186
|
+
and a dump of the connection's own database need the administrator's
|
|
187
|
+
password (`Client.connect("database://<admin password>@host")`).
|
|
188
|
+
|
|
189
|
+
## Roles
|
|
190
|
+
|
|
191
|
+
A role of a database has a password of its own and rights on tables:
|
|
192
|
+
read, insert, update, delete, schema. A client connects as one by naming
|
|
193
|
+
it, with the role's password where the database's would be:
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
db = Client.connect("database://shop:<role password>@database:5454?role=reader")
|
|
197
|
+
# or, with a Config: Config("database", 5454, "shop", "<role password>", role="reader")
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
A wrong password, the database's own password with a role named, and a
|
|
201
|
+
role that is not there are all refused at `connect` with
|
|
202
|
+
`ErrorCode.ACCESS_DENIED`. A statement that needs a right the role lacks
|
|
203
|
+
raises `DbError` with the same code, and a message that names the role
|
|
204
|
+
and the table: `role "reader" may not read table "orders"`. A revoke
|
|
205
|
+
binds the next statement of a client that is already connected.
|
|
206
|
+
|
|
207
|
+
This client cannot make a role or grant it anything: those requests are
|
|
208
|
+
of a later protocol version than it greets with. Roles are made and
|
|
209
|
+
granted with the Rust client or on the server's command line (`database
|
|
210
|
+
role create|grant|revoke|drop ...`).
|
|
211
|
+
|
|
212
|
+
## In the application's process
|
|
213
|
+
|
|
214
|
+
The package `hoie-database` holds the database in the application's own process
|
|
215
|
+
and gives this client of it (`bindings/python` in the repository). It
|
|
216
|
+
does so with `Client.connect(config, connector)`: the connector opens a
|
|
217
|
+
`Transport` for each of the client's connections, which answers the
|
|
218
|
+
frames the client writes as a server would, and the address in
|
|
219
|
+
`config` is not used.
|
|
220
|
+
|
|
221
|
+
## Tests
|
|
222
|
+
|
|
223
|
+
```sh
|
|
224
|
+
cargo build -p hoie-database --features tls # the integration tests start target/debug/database, and ask TLS of it
|
|
225
|
+
cd clients/python
|
|
226
|
+
python -m unittest discover -s tests -t .
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
- `tests/test_vectors.py`: every message of
|
|
230
|
+
`protocol/fixtures/vectors.json` (the golden vectors, kept by the Rust
|
|
231
|
+
crate's own tests) encodes to the same bytes here, and every response
|
|
232
|
+
in it decodes to what it describes.
|
|
233
|
+
- `tests/test_builders.py`: the builders say what the Rust builders say.
|
|
234
|
+
- `tests/test_values.py`: Python values, URLs and rows, without a server.
|
|
235
|
+
- `tests/test_integration.py`: every kind of request against a real
|
|
236
|
+
server, in the clear and under TLS with the certificates of
|
|
237
|
+
`protocol/fixtures/tls`, and connecting as a role (the roles themselves
|
|
238
|
+
are made with the server binary's `database role` commands). Skipped if
|
|
239
|
+
no server binary is found; `DATABASE_BIN` names one. With
|
|
240
|
+
`DATABASE_TEST_EMBEDDED=1` the same tests run against a directory held
|
|
241
|
+
in the test's process by the package `hoie-database`, built in
|
|
242
|
+
`bindings/python` and installed, but for those about what only a server
|
|
243
|
+
has.
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# The Python client
|
|
2
|
+
|
|
3
|
+
A synchronous client for the database server, on the standard library
|
|
4
|
+
alone: no dependency to install, nothing compiled. Python 3.9 or later.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pip install hoie-database-client
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from hoie_database_client import *
|
|
12
|
+
|
|
13
|
+
db = Client.connect("database://shop:secret@database:5454")
|
|
14
|
+
|
|
15
|
+
db.create_table_if_not_exists(
|
|
16
|
+
TableDef("mails")
|
|
17
|
+
.column(ColumnDef("mail_id", Type.UUID).default_random_uuid())
|
|
18
|
+
.column(ColumnDef("user_id", Type.UUID))
|
|
19
|
+
.column(ColumnDef("subject", Type.TEXT).default(""))
|
|
20
|
+
.column(ColumnDef("date", Type.TIMESTAMP).default_now())
|
|
21
|
+
.column(ColumnDef("read", Type.BOOL).default(False))
|
|
22
|
+
.primary_key(["mail_id"])
|
|
23
|
+
.index(IndexDef("mails_user_date").on(["user_id"]).on_desc("date").on(["mail_id"]))
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# The newest 50 mails of a user: 50 index entries read, 50 rows fetched.
|
|
27
|
+
page = db.query(Query.table("mails").index("mails_user_date", KeyRange.eq([user_id])).limit(50))
|
|
28
|
+
for mail in page:
|
|
29
|
+
print(mail["subject"], mail["date"])
|
|
30
|
+
|
|
31
|
+
# Several statements as one, as if nothing else wrote while it ran.
|
|
32
|
+
def mark_read(tx: Transaction) -> int:
|
|
33
|
+
unread = tx.query_one(
|
|
34
|
+
Query.table("mails").index("mails_user_date", KeyRange.eq([user_id]))
|
|
35
|
+
.select("n", count().filter(col("read").eq(False)))
|
|
36
|
+
)["n"]
|
|
37
|
+
tx.update(Update.table("users").key([user_id]).set("unread", unread))
|
|
38
|
+
return unread
|
|
39
|
+
|
|
40
|
+
unread = db.transaction(mark_read)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The vocabulary is the Rust client's, name for name: `docs/CLIENT.md`
|
|
44
|
+
describes what each piece means and how the things usually said in SQL
|
|
45
|
+
are said here. The bytes on the wire are `docs/PROTOCOL.md`.
|
|
46
|
+
|
|
47
|
+
## What differs from the Rust client
|
|
48
|
+
|
|
49
|
+
- **Names the language takes get an underscore:** `and_`, `or_`, `not_`,
|
|
50
|
+
`KeyRange.is_`, `Delete.from_`, `all_`, `any_`, `list_`, `sum_`, `min_`,
|
|
51
|
+
`max_`. `Expr.Depth` and `Expr.Rank` are `depth()` and `rank()`.
|
|
52
|
+
Constructors are plain calls: `TableDef("t")`, `ColumnDef("c", Type.INT)`,
|
|
53
|
+
`IndexDef("i")`.
|
|
54
|
+
- **Expressions are built with methods, not `and`/`or`/`not`:**
|
|
55
|
+
`col("a").eq(1).and_(col("b").gt(2))`. Python's own `and` cannot be
|
|
56
|
+
overloaded, so using an expression as a truth value raises `TypeError`
|
|
57
|
+
instead of silently dropping half a filter. `+ - * / %` and unary `-`
|
|
58
|
+
work on expressions.
|
|
59
|
+
- **Builders do not change:** each method returns a new builder, so a
|
|
60
|
+
query kept in a variable can be narrowed twice.
|
|
61
|
+
- **It greets the server with protocol version 2** (`PROTOCOL_VERSION`),
|
|
62
|
+
so it has none of what later versions added: no prepared statements
|
|
63
|
+
or `param(n)`, no transaction that begins with its first statement in
|
|
64
|
+
one request, no batches, and no `explain`. It cannot set `keep_start`
|
|
65
|
+
on a column, and a table that uses `keep_start` is described to it
|
|
66
|
+
without the setting.
|
|
67
|
+
- **Calls block.** A `Client` may be shared between threads; it keeps a
|
|
68
|
+
pool of connections (8 by default, `?pool=n` in the URL). A
|
|
69
|
+
transaction is used by one thread at a time.
|
|
70
|
+
- **A transaction is a context manager:** it commits when the block
|
|
71
|
+
ends and rolls back if the block raises. `db.transaction(work)` is the
|
|
72
|
+
one that runs `work` again after a conflict, as in the Rust client:
|
|
73
|
+
twice beside other writers, then as the database's only writer.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
with db.begin() as tx: # exclusive; begin_optimistic(), begin_read()
|
|
77
|
+
tx.insert(Insert.into("audit").set("action", "user.create"))
|
|
78
|
+
|
|
79
|
+
with db.lock("shop.migrate"): # a named lock, held until the block ends
|
|
80
|
+
migrate(db)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Values
|
|
84
|
+
|
|
85
|
+
| Database | Python |
|
|
86
|
+
|---|---|
|
|
87
|
+
| NULL | `None` |
|
|
88
|
+
| bool | `bool` |
|
|
89
|
+
| int (64-bit) | `int`; one that does not fit 64 bits raises `ValueError` |
|
|
90
|
+
| float | `float` |
|
|
91
|
+
| decimal | `decimal.Decimal`, exact; at most 30 digits after the point |
|
|
92
|
+
| text | `str` |
|
|
93
|
+
| bytes | `bytes` (`bytearray` and `memoryview` are accepted) |
|
|
94
|
+
| uuid | `uuid.UUID` |
|
|
95
|
+
| timestamp | `datetime.datetime` |
|
|
96
|
+
| date | `datetime.date` |
|
|
97
|
+
| json | read: the parsed value. Written: a `dict`, or `Json(value)` for anything else |
|
|
98
|
+
| list | `list` (a `tuple` is accepted) |
|
|
99
|
+
|
|
100
|
+
**Timestamps** are microseconds since 1970-01-01T00:00:00Z. One read
|
|
101
|
+
from the server is a `datetime` with `tzinfo=timezone.utc`. One written
|
|
102
|
+
may be in any zone and is converted exactly, to the microsecond; a
|
|
103
|
+
`datetime` *without* a zone is taken to be UTC, not local time. The
|
|
104
|
+
database holds times and days far outside the years 1 to 9999 that
|
|
105
|
+
`datetime` can express; those are read as `Timestamp(micros)` and
|
|
106
|
+
`Date(days)`, which may also be written.
|
|
107
|
+
|
|
108
|
+
**JSON** must be told from text and from lists when written: `"x"` is
|
|
109
|
+
text and `[1, 2]` is a list, so a JSON string or array is written
|
|
110
|
+
`Json("x")` or `Json([1, 2])`. A `dict` can only be JSON and needs no
|
|
111
|
+
wrapper. Object keys come back in the order the server stores them: by
|
|
112
|
+
length, then by bytes. The server keeps an integer inside JSON exactly
|
|
113
|
+
from -2^63 to 2^64-1 and reads a larger one as a float, so one beyond
|
|
114
|
+
that raises `ValueError`; `float(n)` writes the float.
|
|
115
|
+
|
|
116
|
+
## TLS
|
|
117
|
+
|
|
118
|
+
Without a setting a connection is in the clear, the password included,
|
|
119
|
+
which is right only on a network nobody else can listen on; a server
|
|
120
|
+
started with a certificate refuses such a connection unless it was told
|
|
121
|
+
`DATABASE_TLS=optional`. The settings go in the URL, or in the `tls` of
|
|
122
|
+
a `Config`:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
# The server's certificate must be signed by an authority in this file, and by no other.
|
|
126
|
+
Client.connect("database://shop:secret@database:5454?tls_ca=%2Fetc%2Fdatabase%2Fca.pem")
|
|
127
|
+
# Reached by an address, or by a name the certificate does not carry.
|
|
128
|
+
Client.connect(Config("10.0.0.5", 5454, "shop", "secret", tls=Tls(ca="/etc/database/ca.pem", name="database.example.com")))
|
|
129
|
+
# Signed by a public authority.
|
|
130
|
+
Client.connect("database://shop:secret@database.example.com?tls=on")
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
| URL | `Config.tls` | |
|
|
134
|
+
|---|---|---|
|
|
135
|
+
| `tls=on` | `Tls()` | TLS, the server verified against the system's certificate authorities |
|
|
136
|
+
| `tls_ca=<file>` | `Tls(ca=...)` | verified against the authorities in that PEM file, and no other |
|
|
137
|
+
| `tls_name=<name>` | `Tls(name=...)` | the name or address the certificate must be for, where that is not the host |
|
|
138
|
+
| `tls=off` | `None` | in the clear: the default |
|
|
139
|
+
|
|
140
|
+
`tls_ca` and `tls_name` turn TLS on by themselves, and `tls=off` beside
|
|
141
|
+
either is an invalid URL. A client that asks for TLS always verifies the
|
|
142
|
+
certificate and the name it is for: there is no setting that encrypts
|
|
143
|
+
without verifying, and no falling back to a connection in the clear. A
|
|
144
|
+
server that cannot be verified, or that serves no TLS, raises a
|
|
145
|
+
`DbError` of code `CONNECTION` before the password is sent. Only
|
|
146
|
+
TLS 1.3 is spoken. The Rust client's `tls_cert`, which takes one exact
|
|
147
|
+
certificate for the server's, is not here.
|
|
148
|
+
|
|
149
|
+
## Errors
|
|
150
|
+
|
|
151
|
+
Everything the server refuses raises `DbError`, with `code` (an
|
|
152
|
+
`ErrorCode`), `message`, and for the constraint errors `constraint` and
|
|
153
|
+
`table`. A value Python holds that the database has no kind for raises
|
|
154
|
+
`TypeError` or `ValueError` before anything is sent.
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
try:
|
|
158
|
+
db.insert(Insert.into("users").set("email", email))
|
|
159
|
+
except DbError as e:
|
|
160
|
+
if e.violates("users_email"):
|
|
161
|
+
...
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Administration
|
|
165
|
+
|
|
166
|
+
`db.admin` has `create_database`, `drop_database`, `set_password`,
|
|
167
|
+
`list_databases`, `checkpoint`, `check`, `stats`, `dump(out)` and
|
|
168
|
+
`restore(source, replace=False)`; all but `checkpoint`, `check`, `stats`
|
|
169
|
+
and a dump of the connection's own database need the administrator's
|
|
170
|
+
password (`Client.connect("database://<admin password>@host")`).
|
|
171
|
+
|
|
172
|
+
## Roles
|
|
173
|
+
|
|
174
|
+
A role of a database has a password of its own and rights on tables:
|
|
175
|
+
read, insert, update, delete, schema. A client connects as one by naming
|
|
176
|
+
it, with the role's password where the database's would be:
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
db = Client.connect("database://shop:<role password>@database:5454?role=reader")
|
|
180
|
+
# or, with a Config: Config("database", 5454, "shop", "<role password>", role="reader")
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
A wrong password, the database's own password with a role named, and a
|
|
184
|
+
role that is not there are all refused at `connect` with
|
|
185
|
+
`ErrorCode.ACCESS_DENIED`. A statement that needs a right the role lacks
|
|
186
|
+
raises `DbError` with the same code, and a message that names the role
|
|
187
|
+
and the table: `role "reader" may not read table "orders"`. A revoke
|
|
188
|
+
binds the next statement of a client that is already connected.
|
|
189
|
+
|
|
190
|
+
This client cannot make a role or grant it anything: those requests are
|
|
191
|
+
of a later protocol version than it greets with. Roles are made and
|
|
192
|
+
granted with the Rust client or on the server's command line (`database
|
|
193
|
+
role create|grant|revoke|drop ...`).
|
|
194
|
+
|
|
195
|
+
## In the application's process
|
|
196
|
+
|
|
197
|
+
The package `hoie-database` holds the database in the application's own process
|
|
198
|
+
and gives this client of it (`bindings/python` in the repository). It
|
|
199
|
+
does so with `Client.connect(config, connector)`: the connector opens a
|
|
200
|
+
`Transport` for each of the client's connections, which answers the
|
|
201
|
+
frames the client writes as a server would, and the address in
|
|
202
|
+
`config` is not used.
|
|
203
|
+
|
|
204
|
+
## Tests
|
|
205
|
+
|
|
206
|
+
```sh
|
|
207
|
+
cargo build -p hoie-database --features tls # the integration tests start target/debug/database, and ask TLS of it
|
|
208
|
+
cd clients/python
|
|
209
|
+
python -m unittest discover -s tests -t .
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
- `tests/test_vectors.py`: every message of
|
|
213
|
+
`protocol/fixtures/vectors.json` (the golden vectors, kept by the Rust
|
|
214
|
+
crate's own tests) encodes to the same bytes here, and every response
|
|
215
|
+
in it decodes to what it describes.
|
|
216
|
+
- `tests/test_builders.py`: the builders say what the Rust builders say.
|
|
217
|
+
- `tests/test_values.py`: Python values, URLs and rows, without a server.
|
|
218
|
+
- `tests/test_integration.py`: every kind of request against a real
|
|
219
|
+
server, in the clear and under TLS with the certificates of
|
|
220
|
+
`protocol/fixtures/tls`, and connecting as a role (the roles themselves
|
|
221
|
+
are made with the server binary's `database role` commands). Skipped if
|
|
222
|
+
no server binary is found; `DATABASE_BIN` names one. With
|
|
223
|
+
`DATABASE_TEST_EMBEDDED=1` the same tests run against a directory held
|
|
224
|
+
in the test's process by the package `hoie-database`, built in
|
|
225
|
+
`bindings/python` and installed, but for those about what only a server
|
|
226
|
+
has.
|