PyGreSQL 6.3.0b1__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pg/__init__.py +192 -0
- pg/_pg.cp315-win_amd64.pyd +0 -0
- pg/_pg.pyi +739 -0
- pg/adapt.py +1033 -0
- pg/attrs.py +29 -0
- pg/cast.py +544 -0
- pg/core.py +180 -0
- pg/db.py +1557 -0
- pg/error.py +59 -0
- pg/helpers.py +283 -0
- pg/notify.py +158 -0
- pg/py.typed +4 -0
- pg/tz.py +21 -0
- pgdb/__init__.py +153 -0
- pgdb/adapt.py +329 -0
- pgdb/cast.py +775 -0
- pgdb/connect.py +73 -0
- pgdb/connection.py +164 -0
- pgdb/constants.py +14 -0
- pgdb/cursor.py +861 -0
- pgdb/py.typed +1 -0
- pgdb/typecode.py +40 -0
- pygresql-6.3.0b1.dist-info/METADATA +81 -0
- pygresql-6.3.0b1.dist-info/RECORD +27 -0
- pygresql-6.3.0b1.dist-info/WHEEL +5 -0
- pygresql-6.3.0b1.dist-info/licenses/LICENSE.txt +30 -0
- pygresql-6.3.0b1.dist-info/top_level.txt +2 -0
pg/error.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Error helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TypeVar
|
|
6
|
+
|
|
7
|
+
from .core import (
|
|
8
|
+
DatabaseError,
|
|
9
|
+
Error,
|
|
10
|
+
InterfaceError,
|
|
11
|
+
InternalError,
|
|
12
|
+
OperationalError,
|
|
13
|
+
ProgrammingError,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
'db_error',
|
|
18
|
+
'error',
|
|
19
|
+
'if_error',
|
|
20
|
+
'int_error',
|
|
21
|
+
'op_error',
|
|
22
|
+
'prg_error'
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
# Error messages
|
|
26
|
+
|
|
27
|
+
E = TypeVar('E', bound=Error)
|
|
28
|
+
|
|
29
|
+
def error(msg: str, cls: type[E]) -> E:
|
|
30
|
+
"""Return specified error object with empty sqlstate attribute."""
|
|
31
|
+
error = cls(msg)
|
|
32
|
+
if isinstance(error, DatabaseError):
|
|
33
|
+
error.sqlstate = None
|
|
34
|
+
return error
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def db_error(msg: str) -> DatabaseError:
|
|
38
|
+
"""Return DatabaseError."""
|
|
39
|
+
return error(msg, DatabaseError)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def int_error(msg: str) -> InternalError:
|
|
43
|
+
"""Return InternalError."""
|
|
44
|
+
return error(msg, InternalError)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def prg_error(msg: str) -> ProgrammingError:
|
|
48
|
+
"""Return ProgrammingError."""
|
|
49
|
+
return error(msg, ProgrammingError)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def if_error(msg: str) -> InterfaceError:
|
|
53
|
+
"""Return InterfaceError."""
|
|
54
|
+
return error(msg, InterfaceError)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def op_error(msg: str) -> OperationalError:
|
|
58
|
+
"""Return OperationalError."""
|
|
59
|
+
return error(msg, OperationalError)
|
pg/helpers.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""Helper functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import namedtuple
|
|
6
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
from json import loads as jsondecode
|
|
10
|
+
from typing import Any, NamedTuple, TypeAlias
|
|
11
|
+
|
|
12
|
+
from .core import (
|
|
13
|
+
InterfaceError,
|
|
14
|
+
Query,
|
|
15
|
+
set_decimal,
|
|
16
|
+
set_jsondecode,
|
|
17
|
+
set_query_helpers,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
SomeNamedTuple: TypeAlias = Any # alias for accessing arbitrary named tuples
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
'QuoteDict',
|
|
24
|
+
'RowCache',
|
|
25
|
+
'dictiter',
|
|
26
|
+
'format_text',
|
|
27
|
+
'join_text',
|
|
28
|
+
'namediter',
|
|
29
|
+
'namednext',
|
|
30
|
+
'scalariter'
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Small helper functions
|
|
35
|
+
|
|
36
|
+
def adapt_error(value: Any) -> InterfaceError:
|
|
37
|
+
"""Create the error for a value whose type cannot be adapted.
|
|
38
|
+
|
|
39
|
+
Plain dicts are not adapted, since they could be meant as json or
|
|
40
|
+
hstore values, so the message suggests to make this explicit.
|
|
41
|
+
"""
|
|
42
|
+
msg = f'Do not know how to adapt type {type(value)}'
|
|
43
|
+
if isinstance(value, dict):
|
|
44
|
+
msg += ', wrap dicts with Json() or Hstore()'
|
|
45
|
+
return InterfaceError(msg)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def format_text(command: str | bytes, params: tuple | dict,
|
|
49
|
+
encoding: Callable[[], str]) -> str | bytes:
|
|
50
|
+
"""Format a command with literals, as bytes if any of them is bytes.
|
|
51
|
+
|
|
52
|
+
A command or literals given as bytes are raw text in the client
|
|
53
|
+
encoding. In this case, the command, the other literals and the keys
|
|
54
|
+
of the literals given as a dict are encoded with the codec returned
|
|
55
|
+
by the given encoding function.
|
|
56
|
+
"""
|
|
57
|
+
values = params.values() if isinstance(params, dict) else params
|
|
58
|
+
if isinstance(command, str) and not any(
|
|
59
|
+
isinstance(value, bytes) for value in values):
|
|
60
|
+
return command % params
|
|
61
|
+
codec = encoding()
|
|
62
|
+
|
|
63
|
+
def encode(value: Any) -> bytes:
|
|
64
|
+
if isinstance(value, bytes):
|
|
65
|
+
return value
|
|
66
|
+
return str(value).encode(codec)
|
|
67
|
+
|
|
68
|
+
if isinstance(params, dict):
|
|
69
|
+
params = {encode(key): encode(value)
|
|
70
|
+
for key, value in params.items()}
|
|
71
|
+
else:
|
|
72
|
+
params = tuple(map(encode, params))
|
|
73
|
+
return encode(command) % params
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def join_text(parts: Sequence[str | bytes], sep: str,
|
|
77
|
+
encoding: Callable[[], str],
|
|
78
|
+
start: str = '', end: str = '') -> str | bytes:
|
|
79
|
+
"""Join parts of a literal, as bytes if any of the parts is bytes.
|
|
80
|
+
|
|
81
|
+
Parts given as bytes are raw text in the client encoding. In this case,
|
|
82
|
+
the parts given as str are encoded with the codec returned by the given
|
|
83
|
+
encoding function (raising a UnicodeEncodeError if that is impossible).
|
|
84
|
+
"""
|
|
85
|
+
if not any(isinstance(part, bytes) for part in parts):
|
|
86
|
+
return start + sep.join(parts) + end # type: ignore[arg-type]
|
|
87
|
+
codec = encoding()
|
|
88
|
+
return start.encode() + sep.encode().join(
|
|
89
|
+
part if isinstance(part, bytes) else part.encode(codec)
|
|
90
|
+
for part in parts) + end.encode()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def split_qualified_name(name: str) -> list[str]:
|
|
94
|
+
"""Split a possibly schema-qualified name into its parts.
|
|
95
|
+
|
|
96
|
+
The name is split at dots. A part can be enclosed in double quotes,
|
|
97
|
+
with a double quote inside written twice; it can then contain dots.
|
|
98
|
+
All parts are taken literally (case is preserved), so that they can
|
|
99
|
+
be escaped individually. Empty parts, unterminated quotes and text
|
|
100
|
+
after a closing quote raise a ValueError.
|
|
101
|
+
"""
|
|
102
|
+
parts: list[str] = []
|
|
103
|
+
end = len(name)
|
|
104
|
+
pos = 0
|
|
105
|
+
while True:
|
|
106
|
+
if name.startswith('"', pos):
|
|
107
|
+
chars: list[str] = []
|
|
108
|
+
pos += 1
|
|
109
|
+
while True:
|
|
110
|
+
quote = name.find('"', pos)
|
|
111
|
+
if quote < 0:
|
|
112
|
+
raise ValueError(
|
|
113
|
+
f'Unterminated quoted part in name {name!r}')
|
|
114
|
+
chars.append(name[pos:quote])
|
|
115
|
+
pos = quote + 1
|
|
116
|
+
if not name.startswith('"', pos):
|
|
117
|
+
break
|
|
118
|
+
chars.append('"')
|
|
119
|
+
pos += 1
|
|
120
|
+
if pos < end and name[pos] != '.':
|
|
121
|
+
raise ValueError(
|
|
122
|
+
f'Unexpected text after quoted part in name {name!r}')
|
|
123
|
+
part = ''.join(chars)
|
|
124
|
+
else:
|
|
125
|
+
dot = name.find('.', pos)
|
|
126
|
+
if dot < 0:
|
|
127
|
+
dot = end
|
|
128
|
+
part = name[pos:dot]
|
|
129
|
+
pos = dot
|
|
130
|
+
if not part:
|
|
131
|
+
raise ValueError(f'Empty part in name {name!r}')
|
|
132
|
+
parts.append(part)
|
|
133
|
+
if pos >= end:
|
|
134
|
+
return parts
|
|
135
|
+
pos += 1 # skip the dot
|
|
136
|
+
|
|
137
|
+
class QuoteDict(dict):
|
|
138
|
+
"""Dictionary with auto quoting of its items.
|
|
139
|
+
|
|
140
|
+
The quote attribute must be set to the desired quote function.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
quote: Callable[[Any], Any]
|
|
144
|
+
quoted: dict[str, Any] # the quoted values that have been accessed
|
|
145
|
+
|
|
146
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
147
|
+
"""Initialize the dictionary."""
|
|
148
|
+
super().__init__(*args, **kwargs)
|
|
149
|
+
self.quoted = {}
|
|
150
|
+
|
|
151
|
+
def __getitem__(self, key: str) -> Any:
|
|
152
|
+
"""Get a quoted value."""
|
|
153
|
+
value = self.quoted[key] = self.quote(super().__getitem__(key))
|
|
154
|
+
return value
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class RowCache:
|
|
158
|
+
"""Global cache for the named tuples used for table rows.
|
|
159
|
+
|
|
160
|
+
The result rows for database operations are returned as named tuples
|
|
161
|
+
by default. Since creating namedtuple classes is a somewhat expensive
|
|
162
|
+
operation, we cache up to 1024 of these classes by default.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
@lru_cache(maxsize=1024)
|
|
167
|
+
def row_factory(names: Sequence[str]) -> Callable[[Sequence], NamedTuple]:
|
|
168
|
+
"""Get a namedtuple factory for row results with the given names."""
|
|
169
|
+
try:
|
|
170
|
+
return namedtuple('Row', names, rename=True)._make # type: ignore[attr-defined]
|
|
171
|
+
except ValueError: # pragma: no cover (not with rename=True)
|
|
172
|
+
names = [f'column_{n}' for n in range(len(names))]
|
|
173
|
+
return namedtuple('Row', names)._make # type: ignore[attr-defined]
|
|
174
|
+
|
|
175
|
+
@classmethod
|
|
176
|
+
def clear(cls) -> None:
|
|
177
|
+
"""Clear the namedtuple factory cache."""
|
|
178
|
+
cls.row_factory.cache_clear()
|
|
179
|
+
|
|
180
|
+
@classmethod
|
|
181
|
+
def change_size(cls, maxsize: int | None) -> None:
|
|
182
|
+
"""Change the size of the namedtuple factory cache.
|
|
183
|
+
|
|
184
|
+
If maxsize is set to None, the cache can grow without bound.
|
|
185
|
+
"""
|
|
186
|
+
row_factory = cls.row_factory.__wrapped__
|
|
187
|
+
cls.row_factory = lru_cache(maxsize)(row_factory) # type: ignore[method-assign]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# Helper functions used by the query object
|
|
191
|
+
|
|
192
|
+
def is_array_type(name: str, typlen: int, elem: int) -> bool:
|
|
193
|
+
"""Check whether a type is an array type with the usual text format.
|
|
194
|
+
|
|
195
|
+
Some types like int2vector, oidvector, name and point also have an
|
|
196
|
+
element type, but are not cast like arrays. PostgreSQL always names
|
|
197
|
+
array types with a leading underscore, while composite types or
|
|
198
|
+
domains with such names have no element type or are handled first.
|
|
199
|
+
The category is not checked, since it is 'P' for _record.
|
|
200
|
+
"""
|
|
201
|
+
return bool(elem) and typlen == -1 and name.startswith('_')
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def type_lookup_condition(key: int | str | bytes
|
|
205
|
+
) -> tuple[str, Sequence[int | str | bytes]]:
|
|
206
|
+
"""Get a condition for looking up a type in pg_type by OID or name.
|
|
207
|
+
|
|
208
|
+
Returns the condition for the pg_type table aliased as t, with the
|
|
209
|
+
placeholders $1 and $2, and the list of the values for these.
|
|
210
|
+
|
|
211
|
+
Integer keys are type OIDs. Names are split like table names with
|
|
212
|
+
split_qualified_name(), so that parts are taken literally. Names
|
|
213
|
+
without a schema are looked up in the search path, the schema pg_temp
|
|
214
|
+
means the temporary schema of the session. Since the name is not
|
|
215
|
+
parsed by the server, the lookup cannot raise an error there, which
|
|
216
|
+
would abort the current transaction. Names given as bytes are raw
|
|
217
|
+
names in the client encoding.
|
|
218
|
+
|
|
219
|
+
Invalid names and OIDs out of range raise a ValueError, keys of other
|
|
220
|
+
types raise a TypeError.
|
|
221
|
+
"""
|
|
222
|
+
if isinstance(key, int) and not isinstance(key, bool):
|
|
223
|
+
if not 0 <= key <= 0xffffffff:
|
|
224
|
+
raise ValueError(f'Invalid type OID {key!r}')
|
|
225
|
+
return 't.oid OPERATOR(pg_catalog.=) $1', [key]
|
|
226
|
+
parts: Sequence[str | bytes]
|
|
227
|
+
if isinstance(key, str):
|
|
228
|
+
parts = split_qualified_name(key)
|
|
229
|
+
elif isinstance(key, bytes):
|
|
230
|
+
# quotes and dots are ASCII, so the raw name can be split this way
|
|
231
|
+
parts = [part.encode('latin-1') for part in
|
|
232
|
+
split_qualified_name(key.decode('latin-1'))]
|
|
233
|
+
else:
|
|
234
|
+
raise TypeError(f'Invalid type key {key!r}')
|
|
235
|
+
if len(parts) == 1:
|
|
236
|
+
return ('t.typname OPERATOR(pg_catalog.=) $1::pg_catalog.name'
|
|
237
|
+
' AND pg_catalog.pg_type_is_visible(t.oid)'), parts
|
|
238
|
+
if len(parts) == 2:
|
|
239
|
+
return ("t.typnamespace OPERATOR(pg_catalog.=) CASE"
|
|
240
|
+
" WHEN $1::pg_catalog.name OPERATOR(pg_catalog.=) 'pg_temp'"
|
|
241
|
+
" THEN pg_catalog.pg_my_temp_schema()"
|
|
242
|
+
" ELSE (SELECT n.oid FROM pg_catalog.pg_namespace n"
|
|
243
|
+
" WHERE n.nspname OPERATOR(pg_catalog.=) $1::pg_catalog.name)"
|
|
244
|
+
" END AND t.typname OPERATOR(pg_catalog.=) $2::pg_catalog.name"
|
|
245
|
+
), parts
|
|
246
|
+
raise ValueError(f'Invalid type name {key!r}')
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def dictiter(q: Query) -> Iterator[dict[str, Any]]:
|
|
250
|
+
"""Get query result as an iterator of dictionaries."""
|
|
251
|
+
fields: tuple[str, ...] = q.listfields()
|
|
252
|
+
for r in q:
|
|
253
|
+
yield dict(zip(fields, r, strict=True))
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def namediter(q: Query) -> Iterator[SomeNamedTuple]:
|
|
257
|
+
"""Get query result as an iterator of named tuples."""
|
|
258
|
+
row = RowCache.row_factory(q.listfields())
|
|
259
|
+
for r in q:
|
|
260
|
+
yield row(r)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def namednext(q: Query) -> SomeNamedTuple:
|
|
264
|
+
"""Get next row from query result as a named tuple."""
|
|
265
|
+
return RowCache.row_factory(q.listfields())(next(q))
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def scalariter(q: Query) -> Iterator[Any]:
|
|
269
|
+
"""Get query result as an iterator of scalar values."""
|
|
270
|
+
for r in q:
|
|
271
|
+
yield r[0]
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# Initialization
|
|
275
|
+
|
|
276
|
+
def init_core() -> None:
|
|
277
|
+
"""Initialize the C extension module."""
|
|
278
|
+
# not at the top since it imports this module
|
|
279
|
+
from .adapt import Bytea, Hstore
|
|
280
|
+
set_decimal(Decimal)
|
|
281
|
+
set_jsondecode(jsondecode)
|
|
282
|
+
set_query_helpers(
|
|
283
|
+
dictiter, namediter, namednext, scalariter, Bytea, Hstore)
|
pg/notify.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Handling of notifications."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import select
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from .core import Query
|
|
10
|
+
from .error import db_error
|
|
11
|
+
from .helpers import join_text
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from .db import DB
|
|
15
|
+
|
|
16
|
+
__all__ = ['NotificationHandler']
|
|
17
|
+
|
|
18
|
+
# The notification handler
|
|
19
|
+
|
|
20
|
+
class NotificationHandler:
|
|
21
|
+
"""A PostgreSQL client-side asynchronous notification handler."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, db: DB, event: str, callback: Callable,
|
|
24
|
+
arg_dict: dict | None = None,
|
|
25
|
+
timeout: int | float | None = None,
|
|
26
|
+
stop_event: str | None = None):
|
|
27
|
+
"""Initialize the notification handler.
|
|
28
|
+
|
|
29
|
+
You must pass a PyGreSQL database connection, the name of an
|
|
30
|
+
event (notification channel) to listen for and a callback function.
|
|
31
|
+
|
|
32
|
+
You can also specify a dictionary arg_dict that will be passed as
|
|
33
|
+
the single argument to the callback function, and a timeout value
|
|
34
|
+
in seconds (a floating point number denotes fractions of seconds).
|
|
35
|
+
If it is absent or None, the callers will never time out. If the
|
|
36
|
+
timeout is reached, the handler stops listening and the callback
|
|
37
|
+
function will be called with a single argument that is None. If
|
|
38
|
+
you set the timeout to zero, the handler will poll notifications
|
|
39
|
+
synchronously and return.
|
|
40
|
+
|
|
41
|
+
You can specify the name of the event that will be used to signal
|
|
42
|
+
the handler to stop listening as stop_event. By default, it will
|
|
43
|
+
be the event name prefixed with 'stop_'.
|
|
44
|
+
"""
|
|
45
|
+
self.db: DB | None = db
|
|
46
|
+
self.event = event
|
|
47
|
+
self.stop_event = stop_event or f'stop_{event}'
|
|
48
|
+
self.listening = False
|
|
49
|
+
self.callback = callback
|
|
50
|
+
if arg_dict is None:
|
|
51
|
+
arg_dict = {}
|
|
52
|
+
self.arg_dict = arg_dict
|
|
53
|
+
self.timeout = timeout
|
|
54
|
+
|
|
55
|
+
def __del__(self) -> None:
|
|
56
|
+
"""Delete the notification handler."""
|
|
57
|
+
self.unlisten()
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
"""Stop listening and close the connection."""
|
|
61
|
+
if self.db:
|
|
62
|
+
self.unlisten()
|
|
63
|
+
self.db.close()
|
|
64
|
+
self.db = None
|
|
65
|
+
|
|
66
|
+
def listen(self) -> None:
|
|
67
|
+
"""Start listening for the event and the stop event."""
|
|
68
|
+
db = self.db
|
|
69
|
+
if db and not self.listening:
|
|
70
|
+
for event in (self.event, self.stop_event):
|
|
71
|
+
db.query('listen ' + db.escape_identifier(event))
|
|
72
|
+
self.listening = True
|
|
73
|
+
|
|
74
|
+
def unlisten(self) -> None:
|
|
75
|
+
"""Stop listening for the event and the stop event."""
|
|
76
|
+
db = self.db
|
|
77
|
+
if db and self.listening:
|
|
78
|
+
for event in (self.event, self.stop_event):
|
|
79
|
+
db.query('unlisten ' + db.escape_identifier(event))
|
|
80
|
+
self.listening = False
|
|
81
|
+
|
|
82
|
+
def notify(self, db: DB | None = None, stop: bool = False,
|
|
83
|
+
payload: str | bytes | None = None) -> Query | None:
|
|
84
|
+
"""Generate a notification.
|
|
85
|
+
|
|
86
|
+
Optionally, you can pass a payload with the notification. A payload
|
|
87
|
+
given as bytes is raw text in the client encoding.
|
|
88
|
+
|
|
89
|
+
If you set the stop flag, a stop notification will be sent that
|
|
90
|
+
will cause the handler to stop listening.
|
|
91
|
+
|
|
92
|
+
The notification is only sent while the handler is listening,
|
|
93
|
+
otherwise this method does nothing and returns None.
|
|
94
|
+
|
|
95
|
+
Note: If the notification handler is running in another thread, you
|
|
96
|
+
must pass a different database connection since PyGreSQL database
|
|
97
|
+
connections are not thread-safe.
|
|
98
|
+
"""
|
|
99
|
+
if not self.listening:
|
|
100
|
+
return None
|
|
101
|
+
if not db:
|
|
102
|
+
db = self.db
|
|
103
|
+
if not db:
|
|
104
|
+
return None
|
|
105
|
+
event = self.stop_event if stop else self.event
|
|
106
|
+
parts: list[str | bytes] = ['notify ' + db.escape_identifier(event)]
|
|
107
|
+
if payload:
|
|
108
|
+
if not isinstance(payload, (str, bytes)):
|
|
109
|
+
payload = str(payload)
|
|
110
|
+
parts.append(db.escape_literal(payload))
|
|
111
|
+
return db.query(join_text(parts, ', ', lambda: db.encoding))
|
|
112
|
+
|
|
113
|
+
def __call__(self) -> None:
|
|
114
|
+
"""Invoke the notification handler.
|
|
115
|
+
|
|
116
|
+
The handler is a loop that listens for notifications on the event
|
|
117
|
+
and stop event channels. When either of these notifications is
|
|
118
|
+
received, its associated 'pid', 'event' and 'extra' (the payload
|
|
119
|
+
passed with the notification) are inserted into its arg_dict
|
|
120
|
+
dictionary and the callback is invoked with this dictionary as
|
|
121
|
+
a single argument. When the handler receives a stop event, it
|
|
122
|
+
stops listening to both events and returns.
|
|
123
|
+
|
|
124
|
+
In the special case that the timeout of the handler has been set
|
|
125
|
+
to zero, the handler will poll all events synchronously and return.
|
|
126
|
+
It will keep listening until it receives a stop event.
|
|
127
|
+
|
|
128
|
+
Note: If you run this loop in another thread, don't use the same
|
|
129
|
+
database connection for database operations in the main thread.
|
|
130
|
+
"""
|
|
131
|
+
if not self.db:
|
|
132
|
+
return
|
|
133
|
+
self.listen()
|
|
134
|
+
poll = self.timeout == 0
|
|
135
|
+
rlist = [] if poll else [self.db.fileno()]
|
|
136
|
+
while self.db and self.listening:
|
|
137
|
+
# noinspection PyUnboundLocalVariable
|
|
138
|
+
if poll or select.select(rlist, [], [], self.timeout)[0]:
|
|
139
|
+
while self.db and self.listening:
|
|
140
|
+
notice = self.db.getnotify()
|
|
141
|
+
if not notice: # no more messages
|
|
142
|
+
break
|
|
143
|
+
event, pid, extra = notice
|
|
144
|
+
if event not in (self.event, self.stop_event):
|
|
145
|
+
self.unlisten()
|
|
146
|
+
raise db_error(
|
|
147
|
+
f'Listening for "{self.event}"'
|
|
148
|
+
f' and "{self.stop_event}",'
|
|
149
|
+
f' but notified of "{event}"')
|
|
150
|
+
if event == self.stop_event:
|
|
151
|
+
self.unlisten()
|
|
152
|
+
self.arg_dict.update(pid=pid, event=event, extra=extra)
|
|
153
|
+
self.callback(self.arg_dict)
|
|
154
|
+
if poll:
|
|
155
|
+
break
|
|
156
|
+
else: # we timed out
|
|
157
|
+
self.unlisten()
|
|
158
|
+
self.callback(None)
|
pg/py.typed
ADDED
pg/tz.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Timezone helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = ['timezone_as_offset']
|
|
6
|
+
|
|
7
|
+
# time zones used in Postgres timestamptz output
|
|
8
|
+
_timezone_offsets: dict[str, str] = {
|
|
9
|
+
'CET': '+0100', 'EET': '+0200', 'EST': '-0500',
|
|
10
|
+
'GMT': '+0000', 'HST': '-1000', 'MET': '+0100', 'MST': '-0700',
|
|
11
|
+
'UCT': '+0000', 'UTC': '+0000', 'WET': '+0000'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def timezone_as_offset(tz: str) -> str:
|
|
16
|
+
"""Convert timezone abbreviation to offset."""
|
|
17
|
+
if tz.startswith(('+', '-')):
|
|
18
|
+
if len(tz) < 5:
|
|
19
|
+
return tz + '00'
|
|
20
|
+
return tz.replace(':', '')
|
|
21
|
+
return _timezone_offsets.get(tz, '+0000')
|
pgdb/__init__.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
#
|
|
3
|
+
# PyGreSQL - a Python interface for the PostgreSQL database.
|
|
4
|
+
#
|
|
5
|
+
# This file contains the DB-API 2 compatible pgdb module.
|
|
6
|
+
#
|
|
7
|
+
# Copyright (c) 2026 by the PyGreSQL Development Team
|
|
8
|
+
#
|
|
9
|
+
# Please see the LICENSE.txt file for specific restrictions.
|
|
10
|
+
|
|
11
|
+
"""pgdb - DB-API 2.0 compliant module for PyGreSQL.
|
|
12
|
+
|
|
13
|
+
(c) 1999, Pascal Andre <andre@chimay.via.ecp.fr>.
|
|
14
|
+
See package documentation for further information on copyright.
|
|
15
|
+
|
|
16
|
+
This module implements the Python Database API Specification v2.0
|
|
17
|
+
(PEP 249, https://peps.python.org/pep-0249/) on top of the classic
|
|
18
|
+
pg module. Basic usage:
|
|
19
|
+
|
|
20
|
+
con = pgdb.connect(host='localhost:5432', database='test')
|
|
21
|
+
cur = con.cursor()
|
|
22
|
+
cur.execute("SELECT * FROM fruits WHERE name = %(name)s",
|
|
23
|
+
{'name': 'apple'})
|
|
24
|
+
rows = cur.fetchall() # list of named tuples
|
|
25
|
+
con.commit()
|
|
26
|
+
con.close()
|
|
27
|
+
|
|
28
|
+
Parameters are passed separately as a sequence or a mapping and are
|
|
29
|
+
properly quoted by the module (paramstyle 'pyformat').
|
|
30
|
+
|
|
31
|
+
See the documentation at https://pygresql.github.io/contents/
|
|
32
|
+
for details and for the extensions to the DB-API 2.0.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from pg.core import (
|
|
36
|
+
ConnectError,
|
|
37
|
+
DatabaseError,
|
|
38
|
+
DataError,
|
|
39
|
+
Error,
|
|
40
|
+
IntegrityError,
|
|
41
|
+
InterfaceError,
|
|
42
|
+
InternalError,
|
|
43
|
+
NotSupportedError,
|
|
44
|
+
OperationalError,
|
|
45
|
+
ProgrammingError,
|
|
46
|
+
Warning,
|
|
47
|
+
version,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
from .adapt import (
|
|
51
|
+
ARRAY,
|
|
52
|
+
BINARY,
|
|
53
|
+
BOOL,
|
|
54
|
+
DATE,
|
|
55
|
+
DATETIME,
|
|
56
|
+
FLOAT,
|
|
57
|
+
HSTORE,
|
|
58
|
+
INTEGER,
|
|
59
|
+
INTERVAL,
|
|
60
|
+
JSON,
|
|
61
|
+
LONG,
|
|
62
|
+
MONEY,
|
|
63
|
+
NUMBER,
|
|
64
|
+
NUMERIC,
|
|
65
|
+
RECORD,
|
|
66
|
+
ROWID,
|
|
67
|
+
SMALLINT,
|
|
68
|
+
STRING,
|
|
69
|
+
TIME,
|
|
70
|
+
TIMESTAMP,
|
|
71
|
+
UUID,
|
|
72
|
+
Binary,
|
|
73
|
+
Date,
|
|
74
|
+
DateFromTicks,
|
|
75
|
+
DbType,
|
|
76
|
+
Hstore,
|
|
77
|
+
Interval,
|
|
78
|
+
Json,
|
|
79
|
+
Literal,
|
|
80
|
+
Time,
|
|
81
|
+
TimeFromTicks,
|
|
82
|
+
Timestamp,
|
|
83
|
+
TimestampFromTicks,
|
|
84
|
+
Uuid,
|
|
85
|
+
)
|
|
86
|
+
from .cast import TypeCache, get_typecast, reset_typecast, set_typecast
|
|
87
|
+
from .connect import connect
|
|
88
|
+
from .connection import Connection
|
|
89
|
+
from .constants import apilevel, paramstyle, shortcutmethods, threadsafety
|
|
90
|
+
from .cursor import Cursor
|
|
91
|
+
|
|
92
|
+
__all__ = [
|
|
93
|
+
'ARRAY',
|
|
94
|
+
'BINARY',
|
|
95
|
+
'BOOL',
|
|
96
|
+
'DATE',
|
|
97
|
+
'DATETIME',
|
|
98
|
+
'FLOAT',
|
|
99
|
+
'HSTORE',
|
|
100
|
+
'INTEGER',
|
|
101
|
+
'INTERVAL',
|
|
102
|
+
'JSON',
|
|
103
|
+
'LONG',
|
|
104
|
+
'MONEY',
|
|
105
|
+
'NUMBER',
|
|
106
|
+
'NUMERIC',
|
|
107
|
+
'RECORD',
|
|
108
|
+
'ROWID',
|
|
109
|
+
'SMALLINT',
|
|
110
|
+
'STRING',
|
|
111
|
+
'TIME',
|
|
112
|
+
'TIMESTAMP',
|
|
113
|
+
'UUID',
|
|
114
|
+
'Binary',
|
|
115
|
+
'ConnectError',
|
|
116
|
+
'Connection',
|
|
117
|
+
'Cursor',
|
|
118
|
+
'DataError',
|
|
119
|
+
'DatabaseError',
|
|
120
|
+
'Date',
|
|
121
|
+
'DateFromTicks',
|
|
122
|
+
'DbType',
|
|
123
|
+
'Error',
|
|
124
|
+
'Hstore',
|
|
125
|
+
'IntegrityError',
|
|
126
|
+
'InterfaceError',
|
|
127
|
+
'InternalError',
|
|
128
|
+
'Interval',
|
|
129
|
+
'Json',
|
|
130
|
+
'Literal',
|
|
131
|
+
'NotSupportedError',
|
|
132
|
+
'OperationalError',
|
|
133
|
+
'ProgrammingError',
|
|
134
|
+
'Time',
|
|
135
|
+
'TimeFromTicks',
|
|
136
|
+
'Timestamp',
|
|
137
|
+
'TimestampFromTicks',
|
|
138
|
+
'TypeCache',
|
|
139
|
+
'Uuid',
|
|
140
|
+
'Warning',
|
|
141
|
+
'__version__',
|
|
142
|
+
'apilevel',
|
|
143
|
+
'connect',
|
|
144
|
+
'get_typecast',
|
|
145
|
+
'paramstyle',
|
|
146
|
+
'reset_typecast',
|
|
147
|
+
'set_typecast',
|
|
148
|
+
'shortcutmethods',
|
|
149
|
+
'threadsafety',
|
|
150
|
+
'version',
|
|
151
|
+
]
|
|
152
|
+
|
|
153
|
+
__version__ = version
|