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
pgdb/cursor.py
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
"""The DB API 2 Cursor object."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import (
|
|
6
|
+
Callable,
|
|
7
|
+
Generator,
|
|
8
|
+
Iterable,
|
|
9
|
+
Iterator,
|
|
10
|
+
Mapping,
|
|
11
|
+
Sequence,
|
|
12
|
+
)
|
|
13
|
+
from datetime import date, datetime, time, timedelta
|
|
14
|
+
from decimal import Decimal
|
|
15
|
+
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
|
|
16
|
+
from math import isinf, isnan
|
|
17
|
+
from typing import TYPE_CHECKING, Any, AnyStr, NamedTuple
|
|
18
|
+
from uuid import UUID as Uuid # noqa: N811
|
|
19
|
+
|
|
20
|
+
from pg.core import (
|
|
21
|
+
RESULT_DQL,
|
|
22
|
+
DatabaseError,
|
|
23
|
+
DataError,
|
|
24
|
+
Error,
|
|
25
|
+
NotSupportedError,
|
|
26
|
+
)
|
|
27
|
+
from pg.core import Connection as Cnx
|
|
28
|
+
from pg.error import db_error, error, if_error, op_error, prg_error
|
|
29
|
+
from pg.helpers import (
|
|
30
|
+
QuoteDict,
|
|
31
|
+
RowCache,
|
|
32
|
+
adapt_error,
|
|
33
|
+
format_text,
|
|
34
|
+
join_text,
|
|
35
|
+
split_qualified_name,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
from .adapt import Hstore, Json, Literal
|
|
39
|
+
from .cast import TypeCache
|
|
40
|
+
from .typecode import TypeCode
|
|
41
|
+
|
|
42
|
+
if TYPE_CHECKING:
|
|
43
|
+
from .connection import Connection
|
|
44
|
+
|
|
45
|
+
__all__ = ['Cursor', 'CursorDescription']
|
|
46
|
+
|
|
47
|
+
# query for looking up a routine, needs a condition with placeholders
|
|
48
|
+
_query_pg_proc = (
|
|
49
|
+
"SELECT p.prokind, p.pronargs, p.pronargdefaults,"
|
|
50
|
+
" p.provariadic OPERATOR(pg_catalog.<>) 0,"
|
|
51
|
+
" pg_catalog.array_to_string(p.proargmodes, '')"
|
|
52
|
+
" FROM pg_catalog.pg_proc p WHERE {}")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Cursor:
|
|
56
|
+
"""Cursor object."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, connection: Connection) -> None:
|
|
59
|
+
"""Create a cursor object for the database connection."""
|
|
60
|
+
self.connection = self._connection = connection
|
|
61
|
+
cnx = connection._cnx
|
|
62
|
+
if not cnx:
|
|
63
|
+
raise op_error("Connection has been closed")
|
|
64
|
+
self._cnx: Cnx = cnx
|
|
65
|
+
self.type_cache: TypeCache = connection.type_cache
|
|
66
|
+
self._src = self._cnx.source()
|
|
67
|
+
# the official attribute for describing the result columns
|
|
68
|
+
self._description: list[CursorDescription] | bool | None = None
|
|
69
|
+
if self.row_factory is Cursor.row_factory:
|
|
70
|
+
# the row factory needs to be determined dynamically
|
|
71
|
+
self.row_factory = None # type: ignore[assignment, method-assign]
|
|
72
|
+
else:
|
|
73
|
+
self.build_row_factory = None # type: ignore[assignment, method-assign]
|
|
74
|
+
self.rowcount: int | None = -1
|
|
75
|
+
self.arraysize: int = 1
|
|
76
|
+
self.lastrowid: int | None = None
|
|
77
|
+
|
|
78
|
+
def __iter__(self) -> Cursor:
|
|
79
|
+
"""Make cursor compatible to the iteration protocol."""
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
def __enter__(self) -> Cursor:
|
|
83
|
+
"""Enter the runtime context for the cursor object."""
|
|
84
|
+
return self
|
|
85
|
+
|
|
86
|
+
def __exit__(self, et: type[BaseException] | None,
|
|
87
|
+
ev: BaseException | None, tb: Any) -> None:
|
|
88
|
+
"""Exit the runtime context for the cursor object."""
|
|
89
|
+
self.close()
|
|
90
|
+
|
|
91
|
+
def _quote(self, value: Any) -> Any:
|
|
92
|
+
"""Quote value depending on its type."""
|
|
93
|
+
match value:
|
|
94
|
+
case None:
|
|
95
|
+
return 'NULL'
|
|
96
|
+
case bytes():
|
|
97
|
+
value = self._cnx.escape_bytea(value).decode('ascii')
|
|
98
|
+
return f"'{value}'::bytea"
|
|
99
|
+
case str():
|
|
100
|
+
return f"'{self._escape_text(value)}'"
|
|
101
|
+
case Hstore():
|
|
102
|
+
v = value._literal(self._encoding)
|
|
103
|
+
if isinstance(v, bytes): # contains raw text
|
|
104
|
+
return b"'" + self._escape_text(v) + b"'"
|
|
105
|
+
return f"'{self._escape_text(v)}'"
|
|
106
|
+
case Json():
|
|
107
|
+
return f"'{self._escape_text(str(value))}'"
|
|
108
|
+
case float():
|
|
109
|
+
if isinf(value):
|
|
110
|
+
return "'-Infinity'" if value < 0 else "'Infinity'"
|
|
111
|
+
if isnan(value):
|
|
112
|
+
return "'NaN'"
|
|
113
|
+
return value
|
|
114
|
+
case int() | Decimal() | Literal():
|
|
115
|
+
return value
|
|
116
|
+
case datetime(tzinfo=None): # must come before date
|
|
117
|
+
return f"'{value}'::timestamp"
|
|
118
|
+
case datetime():
|
|
119
|
+
return f"'{value}'::timestamptz"
|
|
120
|
+
case date():
|
|
121
|
+
return f"'{value}'::date"
|
|
122
|
+
case time(tzinfo=None):
|
|
123
|
+
return f"'{value}'::time"
|
|
124
|
+
case time():
|
|
125
|
+
return f"'{value}'::timetz"
|
|
126
|
+
case timedelta():
|
|
127
|
+
return f"'{value}'::interval"
|
|
128
|
+
case Uuid():
|
|
129
|
+
return f"'{value}'::uuid"
|
|
130
|
+
case IPv4Address() | IPv6Address(): # or interface
|
|
131
|
+
return f"'{self._escape_text(str(value))}'::inet"
|
|
132
|
+
case IPv4Network() | IPv6Network():
|
|
133
|
+
return f"'{self._escape_text(str(value))}'::cidr"
|
|
134
|
+
case list():
|
|
135
|
+
# Quote value as an ARRAY constructor. This is better than
|
|
136
|
+
# using an array literal because it carries the information
|
|
137
|
+
# that this is an array and not a string. One issue with this
|
|
138
|
+
# syntax is that you need to add an explicit typecast when
|
|
139
|
+
# passing empty arrays. The ARRAY keyword is actually only
|
|
140
|
+
# necessary at the top level.
|
|
141
|
+
if not value: # exception for empty array
|
|
142
|
+
return "'{}'"
|
|
143
|
+
return self._join(value, 'ARRAY[', ']')
|
|
144
|
+
case tuple():
|
|
145
|
+
# Quote as a ROW constructor. This is better than using a
|
|
146
|
+
# record literal because it carries the information that this
|
|
147
|
+
# is a record and not a string. We don't use the keyword ROW
|
|
148
|
+
# in order to make this usable with the IN syntax as well.
|
|
149
|
+
# It is only necessary when the records has a single column
|
|
150
|
+
# which is not really useful.
|
|
151
|
+
return self._join(value, '(', ')')
|
|
152
|
+
try: # noinspection PyUnresolvedReferences
|
|
153
|
+
value = value.__pg_repr__()
|
|
154
|
+
except AttributeError as e:
|
|
155
|
+
raise adapt_error(value) from e
|
|
156
|
+
if isinstance(value, (tuple, list)):
|
|
157
|
+
value = self._quote(value)
|
|
158
|
+
return value
|
|
159
|
+
|
|
160
|
+
def _encoding(self) -> str:
|
|
161
|
+
"""Get the Python codec name of the client encoding."""
|
|
162
|
+
return self._cnx.encoding
|
|
163
|
+
|
|
164
|
+
def _join(self, values: Sequence, start: str, end: str) -> str | bytes:
|
|
165
|
+
"""Quote and join values, as bytes if any of them is quoted as bytes.
|
|
166
|
+
|
|
167
|
+
Values quoted as bytes contain raw text in the client encoding.
|
|
168
|
+
"""
|
|
169
|
+
parts = [v if isinstance(v, (str, bytes)) else str(v)
|
|
170
|
+
for v in map(self._quote, values)]
|
|
171
|
+
return join_text(parts, ',', self._encoding, start, end)
|
|
172
|
+
|
|
173
|
+
def _decode_sql(self, sql: str | bytes) -> str:
|
|
174
|
+
"""Decode a query containing raw text for an error message."""
|
|
175
|
+
if isinstance(sql, str):
|
|
176
|
+
return sql
|
|
177
|
+
try:
|
|
178
|
+
codec = self._encoding()
|
|
179
|
+
# a lost connection fails earlier with a database error
|
|
180
|
+
except Exception: # pragma: no cover (defensive)
|
|
181
|
+
codec = 'utf-8'
|
|
182
|
+
return sql.decode(codec, 'backslashreplace')
|
|
183
|
+
|
|
184
|
+
def _escape_text(self, value: AnyStr) -> AnyStr:
|
|
185
|
+
"""Escape a text value, which must not contain NUL characters."""
|
|
186
|
+
if (b'\0' in value if isinstance(value, bytes)
|
|
187
|
+
else '\0' in value):
|
|
188
|
+
raise error('Text values cannot contain NUL characters', DataError)
|
|
189
|
+
return self._cnx.escape_string(value)
|
|
190
|
+
|
|
191
|
+
def _quoteparams(self, string: str | bytes,
|
|
192
|
+
parameters: Mapping | Sequence | None) -> str | bytes:
|
|
193
|
+
"""Quote parameters.
|
|
194
|
+
|
|
195
|
+
This function works for both mappings and sequences.
|
|
196
|
+
|
|
197
|
+
The function should be used even when there are no parameters,
|
|
198
|
+
so that we have a consistent behavior regarding percent signs.
|
|
199
|
+
|
|
200
|
+
A string given as bytes is raw text in the client encoding. The
|
|
201
|
+
keys of mappings given as str and the quoted parameters are then
|
|
202
|
+
encoded with the client encoding.
|
|
203
|
+
"""
|
|
204
|
+
if not parameters:
|
|
205
|
+
try:
|
|
206
|
+
return string % () # unescape literal quotes if possible
|
|
207
|
+
except (TypeError, ValueError):
|
|
208
|
+
return string # silently accept unescaped quotes
|
|
209
|
+
if isinstance(parameters, dict):
|
|
210
|
+
quote = self._quote
|
|
211
|
+
if isinstance(string, bytes):
|
|
212
|
+
codec = self._encoding()
|
|
213
|
+
parameters = {
|
|
214
|
+
key.encode(codec) if isinstance(key, str) else key: value
|
|
215
|
+
for key, value in parameters.items()}
|
|
216
|
+
|
|
217
|
+
def quote(value: Any) -> bytes:
|
|
218
|
+
value = self._quote(value)
|
|
219
|
+
return (value if isinstance(value, bytes)
|
|
220
|
+
else str(value).encode(codec))
|
|
221
|
+
|
|
222
|
+
quote_dict = QuoteDict(parameters)
|
|
223
|
+
quote_dict.quote = quote
|
|
224
|
+
formatted = string % quote_dict
|
|
225
|
+
quoted = quote_dict.quoted
|
|
226
|
+
if any(isinstance(value, bytes) for value in quoted.values()):
|
|
227
|
+
# some values contain raw text, the query must be bytes
|
|
228
|
+
return format_text(string, quoted, self._encoding)
|
|
229
|
+
return formatted
|
|
230
|
+
return format_text(
|
|
231
|
+
string, tuple(map(self._quote, parameters)), self._encoding)
|
|
232
|
+
|
|
233
|
+
def _make_description(self, info: tuple[int, str, int, int, int]
|
|
234
|
+
) -> CursorDescription:
|
|
235
|
+
"""Make the description tuple for the given field info."""
|
|
236
|
+
name, typ, size, mod = info[1:]
|
|
237
|
+
type_code = self.type_cache[typ]
|
|
238
|
+
if mod > 0:
|
|
239
|
+
mod -= 4
|
|
240
|
+
precision: int | None
|
|
241
|
+
scale: int | None
|
|
242
|
+
if type_code == 'numeric':
|
|
243
|
+
precision, scale = mod >> 16, mod & 0xffff
|
|
244
|
+
size = precision
|
|
245
|
+
else:
|
|
246
|
+
if not size:
|
|
247
|
+
size = type_code.len
|
|
248
|
+
if size == -1:
|
|
249
|
+
size = mod
|
|
250
|
+
precision = scale = None
|
|
251
|
+
return CursorDescription(
|
|
252
|
+
name, type_code, None, size, precision, scale, None)
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def description(self) -> list[CursorDescription] | None:
|
|
256
|
+
"""Read-only attribute describing the result columns."""
|
|
257
|
+
description = self._description
|
|
258
|
+
if description is None:
|
|
259
|
+
return None
|
|
260
|
+
if not isinstance(description, list):
|
|
261
|
+
make = self._make_description
|
|
262
|
+
description = [make(info) for info in self._src.listinfo()]
|
|
263
|
+
self._description = description
|
|
264
|
+
return description
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def colnames(self) -> Sequence[str] | None:
|
|
268
|
+
"""Unofficial convenience attribute with the column names."""
|
|
269
|
+
description = self.description
|
|
270
|
+
return None if description is None else [d[0] for d in description]
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def coltypes(self) -> Sequence[TypeCode] | None:
|
|
274
|
+
"""Unofficial convenience attribute with the column types."""
|
|
275
|
+
description = self.description
|
|
276
|
+
return None if description is None else [d[1] for d in description]
|
|
277
|
+
|
|
278
|
+
def close(self) -> None:
|
|
279
|
+
"""Close the cursor object."""
|
|
280
|
+
self._src.close()
|
|
281
|
+
|
|
282
|
+
def execute(self, operation: str | bytes,
|
|
283
|
+
parameters: Mapping | Sequence | None = None) -> Cursor:
|
|
284
|
+
"""Prepare and execute a database operation (query or command)."""
|
|
285
|
+
# The parameters may also be specified as list of tuples to e.g.
|
|
286
|
+
# insert multiple rows in a single operation, but this kind of
|
|
287
|
+
# usage is deprecated. We make several plausibility checks because
|
|
288
|
+
# tuples can also be passed with the meaning of ROW constructors.
|
|
289
|
+
if (parameters and isinstance(parameters, list)
|
|
290
|
+
and len(parameters) > 1
|
|
291
|
+
and all(isinstance(p, tuple) for p in parameters)
|
|
292
|
+
and all(len(p) == len(parameters[0]) for p in parameters[1:])):
|
|
293
|
+
return self.executemany(operation, parameters)
|
|
294
|
+
# not a list of tuples
|
|
295
|
+
return self.executemany(operation, [parameters])
|
|
296
|
+
|
|
297
|
+
def executemany(self, operation: str | bytes,
|
|
298
|
+
seq_of_parameters: Sequence[Mapping | Sequence | None]
|
|
299
|
+
) -> Cursor:
|
|
300
|
+
"""Prepare operation and execute it against a parameter sequence."""
|
|
301
|
+
if not seq_of_parameters:
|
|
302
|
+
# don't do anything without parameters
|
|
303
|
+
return self
|
|
304
|
+
self._description = None
|
|
305
|
+
self.rowcount = -1
|
|
306
|
+
# first try to execute all queries
|
|
307
|
+
rowcount = 0
|
|
308
|
+
sql: str | bytes = "BEGIN"
|
|
309
|
+
try:
|
|
310
|
+
if not self._connection._tnx and not self._connection.autocommit:
|
|
311
|
+
try:
|
|
312
|
+
self._src.execute(sql)
|
|
313
|
+
except DatabaseError:
|
|
314
|
+
raise # database provides error message
|
|
315
|
+
except Exception as e:
|
|
316
|
+
raise op_error("Can't start transaction") from e
|
|
317
|
+
else:
|
|
318
|
+
self._connection._tnx = True
|
|
319
|
+
for parameters in seq_of_parameters:
|
|
320
|
+
sql = operation # for error messages while quoting
|
|
321
|
+
sql = self._quoteparams(operation, parameters)
|
|
322
|
+
if (b'\0' in sql if isinstance(sql, bytes)
|
|
323
|
+
else '\0' in sql):
|
|
324
|
+
raise error(
|
|
325
|
+
'Queries cannot contain NUL characters', DataError)
|
|
326
|
+
rows = self._src.execute(sql)
|
|
327
|
+
if rows: # true if not DML
|
|
328
|
+
rowcount += rows
|
|
329
|
+
else:
|
|
330
|
+
self.rowcount = -1
|
|
331
|
+
except DatabaseError:
|
|
332
|
+
raise # database provides error message
|
|
333
|
+
except UnicodeError as err: # cannot encode the query or parameters
|
|
334
|
+
sql = self._decode_sql(sql)
|
|
335
|
+
raise error(f"Error in '{sql}': {err}", DataError) from err
|
|
336
|
+
except Error as err:
|
|
337
|
+
sql = self._decode_sql(sql)
|
|
338
|
+
# noinspection PyTypeChecker
|
|
339
|
+
raise if_error(f"Error in '{sql}': '{err}'") from err
|
|
340
|
+
except Exception as err:
|
|
341
|
+
sql = self._decode_sql(sql)
|
|
342
|
+
raise op_error(f"Internal error in '{sql}': {err}") from err
|
|
343
|
+
# then initialize result raw count and description
|
|
344
|
+
if self._src.resulttype == RESULT_DQL:
|
|
345
|
+
self._description = True # fetch on demand
|
|
346
|
+
self.rowcount = self._src.ntuples
|
|
347
|
+
self.lastrowid = None
|
|
348
|
+
build_row_factory = self.build_row_factory
|
|
349
|
+
if build_row_factory: # type: ignore[truthy-function]
|
|
350
|
+
self.row_factory = build_row_factory() # type: ignore[assignment, method-assign]
|
|
351
|
+
else:
|
|
352
|
+
self.rowcount = rowcount
|
|
353
|
+
self.lastrowid = self._src.oidstatus()
|
|
354
|
+
# return the cursor object, so you can write statements such as
|
|
355
|
+
# "cursor.execute(...).fetchall()" or "for row in cursor.execute(...)"
|
|
356
|
+
return self
|
|
357
|
+
|
|
358
|
+
def fetchone(self) -> Sequence | None:
|
|
359
|
+
"""Fetch the next row of a query result set."""
|
|
360
|
+
res = self.fetchmany(1, False)
|
|
361
|
+
try:
|
|
362
|
+
return res[0]
|
|
363
|
+
except IndexError:
|
|
364
|
+
return None
|
|
365
|
+
|
|
366
|
+
def fetchall(self) -> Sequence[Sequence]:
|
|
367
|
+
"""Fetch all (remaining) rows of a query result."""
|
|
368
|
+
return self.fetchmany(-1, False)
|
|
369
|
+
|
|
370
|
+
def fetchmany(self, size: int | None = None, keep: bool = False
|
|
371
|
+
) -> Sequence[Sequence]:
|
|
372
|
+
"""Fetch the next set of rows of a query result.
|
|
373
|
+
|
|
374
|
+
The number of rows to fetch per call is specified by the
|
|
375
|
+
size parameter. If it is not given, the cursor's arraysize
|
|
376
|
+
determines the number of rows to be fetched. If you set
|
|
377
|
+
the keep parameter to true, this is kept as new arraysize.
|
|
378
|
+
"""
|
|
379
|
+
if size is None:
|
|
380
|
+
size = self.arraysize
|
|
381
|
+
if keep:
|
|
382
|
+
self.arraysize = size
|
|
383
|
+
try:
|
|
384
|
+
result = self._src.fetch(size)
|
|
385
|
+
except DatabaseError:
|
|
386
|
+
raise
|
|
387
|
+
# fetch() raises only database errors
|
|
388
|
+
except Error as err: # pragma: no cover (defensive)
|
|
389
|
+
raise db_error(str(err)) from err
|
|
390
|
+
row_factory = self.row_factory
|
|
391
|
+
coltypes = self.coltypes
|
|
392
|
+
# the column types are known if rows could be fetched
|
|
393
|
+
if coltypes is None: # pragma: no cover (defensive)
|
|
394
|
+
# cannot determine column types, return raw result
|
|
395
|
+
return [row_factory(row) for row in result]
|
|
396
|
+
if len(result) > 5:
|
|
397
|
+
# optimize the case where we really fetch many values
|
|
398
|
+
# by looking up all type casting functions upfront
|
|
399
|
+
cast_row = self.type_cache.get_row_caster(coltypes)
|
|
400
|
+
return [row_factory(cast_row(row)) for row in result]
|
|
401
|
+
cast_value = self.type_cache.typecast
|
|
402
|
+
return [row_factory([
|
|
403
|
+
cast_value(value, typ)
|
|
404
|
+
for typ, value in zip(coltypes, row, strict=True)])
|
|
405
|
+
for row in result]
|
|
406
|
+
|
|
407
|
+
def callproc(self, procname: str, parameters: Sequence | None = None
|
|
408
|
+
) -> Sequence | None:
|
|
409
|
+
"""Call a stored database function or procedure with the given name.
|
|
410
|
+
|
|
411
|
+
The name can be schema-qualified. It is split at dots, and its
|
|
412
|
+
parts are taken literally, like table names.
|
|
413
|
+
|
|
414
|
+
The sequence of parameters must contain one entry for each argument
|
|
415
|
+
that the function or procedure expects. For a function, these are
|
|
416
|
+
its input arguments, and the parameters are returned unchanged.
|
|
417
|
+
For a procedure, these are all its arguments, including output
|
|
418
|
+
arguments (pass None for them), and a copy of the parameters is
|
|
419
|
+
returned where output and input/output parameters are replaced
|
|
420
|
+
with the values returned by the procedure.
|
|
421
|
+
|
|
422
|
+
The function or procedure may also provide a result set as output.
|
|
423
|
+
This can be requested through the standard fetch methods.
|
|
424
|
+
"""
|
|
425
|
+
if not isinstance(procname, str):
|
|
426
|
+
raise TypeError("The procedure name must be a string")
|
|
427
|
+
parts = split_qualified_name(procname)
|
|
428
|
+
n = len(parameters) if parameters else 0
|
|
429
|
+
is_procedure, outputs = self._get_routine(procname, parts, n)
|
|
430
|
+
cnx = self._cnx
|
|
431
|
+
# percent signs in the name must not be taken as placeholders
|
|
432
|
+
name = '.'.join(map(cnx.escape_identifier, parts)).replace('%', '%%')
|
|
433
|
+
args = ','.join(n * ['%s'])
|
|
434
|
+
if is_procedure:
|
|
435
|
+
query = f'call {name}({args})'
|
|
436
|
+
else:
|
|
437
|
+
query = f'select * from {name}({args})' # noqa: S608
|
|
438
|
+
self.execute(query, parameters)
|
|
439
|
+
if not is_procedure or parameters is None:
|
|
440
|
+
return parameters
|
|
441
|
+
values = list(parameters)
|
|
442
|
+
if outputs and self._src.resulttype == RESULT_DQL:
|
|
443
|
+
row = self._src.fetch(1)
|
|
444
|
+
# a call with output parameters always returns a row,
|
|
445
|
+
# and then the column types are always known
|
|
446
|
+
if row: # pragma: no branch
|
|
447
|
+
coltypes = self.coltypes
|
|
448
|
+
if coltypes is not None: # pragma: no branch
|
|
449
|
+
typecast = self.type_cache.typecast
|
|
450
|
+
row_values = [typecast(value, typ) for typ, value in
|
|
451
|
+
zip(coltypes, row[0], strict=True)]
|
|
452
|
+
# values of output parameters with defaults that were
|
|
453
|
+
# omitted can only be fetched from the cursor
|
|
454
|
+
for pos, value in zip(outputs, row_values, strict=False):
|
|
455
|
+
if pos < n:
|
|
456
|
+
values[pos] = value
|
|
457
|
+
# the row can still be fetched from the cursor
|
|
458
|
+
self._src.movefirst()
|
|
459
|
+
return tuple(values) if isinstance(parameters, tuple) else values
|
|
460
|
+
|
|
461
|
+
def _get_routine(self, procname: str, parts: Sequence[str], n: int
|
|
462
|
+
) -> tuple[bool, list[int]]:
|
|
463
|
+
"""Check whether the routine to be called is a procedure.
|
|
464
|
+
|
|
465
|
+
Returns whether it is a procedure that must be called with CALL,
|
|
466
|
+
and the positions of its output and input/output arguments.
|
|
467
|
+
Routines that cannot be called with n arguments are disregarded
|
|
468
|
+
if other routines with the same name can be called. If the name is
|
|
469
|
+
not found, it is assumed to be a function, so that the database
|
|
470
|
+
reports the error when calling it.
|
|
471
|
+
"""
|
|
472
|
+
if len(parts) == 1:
|
|
473
|
+
condition = ('p.proname OPERATOR(pg_catalog.=)'
|
|
474
|
+
' %(name)s::pg_catalog.name'
|
|
475
|
+
' AND pg_catalog.pg_function_is_visible(p.oid)')
|
|
476
|
+
params = {'name': parts[0]}
|
|
477
|
+
else:
|
|
478
|
+
# the schema pg_temp means the temporary schema of the session;
|
|
479
|
+
# a database name in front of the schema is checked by the call
|
|
480
|
+
condition = (
|
|
481
|
+
"p.pronamespace OPERATOR(pg_catalog.=) CASE"
|
|
482
|
+
" WHEN %(schema)s::pg_catalog.name"
|
|
483
|
+
" OPERATOR(pg_catalog.=) 'pg_temp'"
|
|
484
|
+
" THEN pg_catalog.pg_my_temp_schema()"
|
|
485
|
+
" ELSE (SELECT n.oid FROM pg_catalog.pg_namespace n"
|
|
486
|
+
" WHERE n.nspname OPERATOR(pg_catalog.=)"
|
|
487
|
+
" %(schema)s::pg_catalog.name) END"
|
|
488
|
+
" AND p.proname OPERATOR(pg_catalog.=)"
|
|
489
|
+
" %(name)s::pg_catalog.name")
|
|
490
|
+
params = {'schema': parts[-2], 'name': parts[-1]}
|
|
491
|
+
# run the lookup with the source object, like the type cache,
|
|
492
|
+
# so that the values are not cast and errors are raised as usual
|
|
493
|
+
cmd = _query_pg_proc.format(condition)
|
|
494
|
+
sql: str | bytes = cmd
|
|
495
|
+
try:
|
|
496
|
+
sql = self._quoteparams(cmd, params)
|
|
497
|
+
self._src.execute(sql)
|
|
498
|
+
routines = self._src.fetch(-1)
|
|
499
|
+
except DatabaseError:
|
|
500
|
+
raise # database provides error message
|
|
501
|
+
except UnicodeError as err: # cannot encode the name
|
|
502
|
+
sql = self._decode_sql(sql)
|
|
503
|
+
raise error(f"Error in '{sql}': {err}", DataError) from err
|
|
504
|
+
except Error as err:
|
|
505
|
+
sql = self._decode_sql(sql)
|
|
506
|
+
raise if_error(f"Error in '{sql}': '{err}'") from err
|
|
507
|
+
except Exception as err:
|
|
508
|
+
sql = self._decode_sql(sql)
|
|
509
|
+
raise op_error(f"Internal error in '{sql}': {err}") from err
|
|
510
|
+
candidates = []
|
|
511
|
+
for kind, nargs_str, ndefaults_str, variadic, modes in routines:
|
|
512
|
+
is_procedure = kind == 'p'
|
|
513
|
+
nargs, ndefaults = int(nargs_str), int(ndefaults_str)
|
|
514
|
+
if is_procedure and modes:
|
|
515
|
+
# output arguments must also be passed to procedures
|
|
516
|
+
nargs = len(modes)
|
|
517
|
+
min_args = nargs - ndefaults
|
|
518
|
+
# a variadic argument without default needs at least one value
|
|
519
|
+
callable_with_n = min_args <= n and (
|
|
520
|
+
variadic == 't' or n <= nargs)
|
|
521
|
+
outputs = [i for i, mode in enumerate(modes or '')
|
|
522
|
+
if mode in 'bo'] if is_procedure else []
|
|
523
|
+
candidates.append((callable_with_n, is_procedure, outputs))
|
|
524
|
+
if any(candidate[0] for candidate in candidates):
|
|
525
|
+
candidates = [candidate for candidate in candidates
|
|
526
|
+
if candidate[0]]
|
|
527
|
+
if not candidates or not all(
|
|
528
|
+
is_procedure for _, is_procedure, _ in candidates):
|
|
529
|
+
# functions are called with SELECT as before
|
|
530
|
+
return False, []
|
|
531
|
+
outputs = candidates[0][2]
|
|
532
|
+
if any(candidate[2] != outputs for candidate in candidates[1:]):
|
|
533
|
+
raise prg_error(
|
|
534
|
+
f"Cannot determine the output parameters of procedure"
|
|
535
|
+
f" {procname!r} with {n} parameters")
|
|
536
|
+
return True, outputs
|
|
537
|
+
|
|
538
|
+
# noinspection PyShadowingBuiltins
|
|
539
|
+
def copy_from(self, stream: Any, table: str,
|
|
540
|
+
format: str | None = None, sep: str | None = None,
|
|
541
|
+
null: str | None = None, size: int | None = None,
|
|
542
|
+
columns: Sequence[str] | None = None) -> Cursor:
|
|
543
|
+
"""Copy data from an input stream to the specified table.
|
|
544
|
+
|
|
545
|
+
The input stream can be a file-like object with a read() method or
|
|
546
|
+
it can also be an iterable returning a row or multiple rows of input
|
|
547
|
+
on each iteration.
|
|
548
|
+
|
|
549
|
+
The format must be 'text', 'csv' or 'binary'. The sep option sets the
|
|
550
|
+
column separator (delimiter) used in the non binary formats.
|
|
551
|
+
The null option sets the textual representation of NULL in the input.
|
|
552
|
+
|
|
553
|
+
The size option sets the size of the buffer used when reading data
|
|
554
|
+
from file-like objects.
|
|
555
|
+
|
|
556
|
+
The copy operation can be restricted to a subset of columns. If no
|
|
557
|
+
columns are specified, all of them will be copied.
|
|
558
|
+
"""
|
|
559
|
+
binary_format = format == 'binary'
|
|
560
|
+
try:
|
|
561
|
+
read = stream.read
|
|
562
|
+
except AttributeError as e:
|
|
563
|
+
if size:
|
|
564
|
+
raise ValueError(
|
|
565
|
+
"Size must only be set for file-like objects") from e
|
|
566
|
+
input_type: type | tuple[type, ...]
|
|
567
|
+
type_name: str
|
|
568
|
+
if binary_format:
|
|
569
|
+
input_type = bytes
|
|
570
|
+
type_name = 'byte strings'
|
|
571
|
+
else:
|
|
572
|
+
input_type = (bytes, str)
|
|
573
|
+
type_name = 'strings'
|
|
574
|
+
|
|
575
|
+
if isinstance(stream, (bytes, str)):
|
|
576
|
+
if not isinstance(stream, input_type):
|
|
577
|
+
raise ValueError(f"The input must be {type_name}") from e
|
|
578
|
+
if not binary_format:
|
|
579
|
+
if isinstance(stream, str):
|
|
580
|
+
if not stream.endswith('\n'):
|
|
581
|
+
stream += '\n'
|
|
582
|
+
else:
|
|
583
|
+
if not stream.endswith(b'\n'):
|
|
584
|
+
stream += b'\n'
|
|
585
|
+
|
|
586
|
+
def chunks() -> Iterator[str | bytes]:
|
|
587
|
+
yield stream
|
|
588
|
+
|
|
589
|
+
elif isinstance(stream, Iterable):
|
|
590
|
+
|
|
591
|
+
def chunks() -> Iterator[str | bytes]:
|
|
592
|
+
for chunk in stream:
|
|
593
|
+
if not isinstance(chunk, input_type):
|
|
594
|
+
raise ValueError(
|
|
595
|
+
f"Input stream must consist of {type_name}")
|
|
596
|
+
if isinstance(chunk, str):
|
|
597
|
+
if not chunk.endswith('\n'):
|
|
598
|
+
chunk += '\n'
|
|
599
|
+
else:
|
|
600
|
+
if not chunk.endswith(b'\n'):
|
|
601
|
+
chunk += b'\n'
|
|
602
|
+
yield chunk
|
|
603
|
+
|
|
604
|
+
else:
|
|
605
|
+
raise TypeError("Need an input stream to copy from") from e
|
|
606
|
+
else:
|
|
607
|
+
if size is None:
|
|
608
|
+
size = 8192
|
|
609
|
+
elif not isinstance(size, int):
|
|
610
|
+
raise TypeError("The size option must be an integer")
|
|
611
|
+
if size > 0:
|
|
612
|
+
|
|
613
|
+
def chunks() -> Iterator[str | bytes]:
|
|
614
|
+
while True:
|
|
615
|
+
buffer = read(size)
|
|
616
|
+
yield buffer
|
|
617
|
+
if not buffer or len(buffer) < size:
|
|
618
|
+
break
|
|
619
|
+
|
|
620
|
+
else:
|
|
621
|
+
|
|
622
|
+
def chunks() -> Iterator[str | bytes]:
|
|
623
|
+
yield read()
|
|
624
|
+
|
|
625
|
+
if not table or not isinstance(table, str):
|
|
626
|
+
raise TypeError("Need a table to copy to")
|
|
627
|
+
if table.lower().startswith('select '):
|
|
628
|
+
raise ValueError("Must specify a table, not a query")
|
|
629
|
+
cnx = self._cnx
|
|
630
|
+
table = '.'.join(map(cnx.escape_identifier,
|
|
631
|
+
split_qualified_name(table)))
|
|
632
|
+
operation_parts = [f'copy {table}']
|
|
633
|
+
options = []
|
|
634
|
+
parameters = []
|
|
635
|
+
if format is not None:
|
|
636
|
+
if not isinstance(format, str):
|
|
637
|
+
raise TypeError("The format option must be a string")
|
|
638
|
+
if format not in ('text', 'csv', 'binary'):
|
|
639
|
+
raise ValueError("Invalid format")
|
|
640
|
+
options.append(f'format {format}')
|
|
641
|
+
if sep is not None:
|
|
642
|
+
if not isinstance(sep, str):
|
|
643
|
+
raise TypeError("The sep option must be a string")
|
|
644
|
+
if format == 'binary':
|
|
645
|
+
raise ValueError(
|
|
646
|
+
"The sep option is not allowed with binary format")
|
|
647
|
+
if len(sep) != 1:
|
|
648
|
+
raise ValueError(
|
|
649
|
+
"The sep option must be a single one-byte character")
|
|
650
|
+
options.append('delimiter %s')
|
|
651
|
+
parameters.append(sep)
|
|
652
|
+
if null is not None:
|
|
653
|
+
if not isinstance(null, str):
|
|
654
|
+
raise TypeError("The null option must be a string")
|
|
655
|
+
options.append('null %s')
|
|
656
|
+
parameters.append(null)
|
|
657
|
+
if columns:
|
|
658
|
+
if not isinstance(columns, str):
|
|
659
|
+
columns = ','.join(map(cnx.escape_identifier, columns))
|
|
660
|
+
operation_parts.append(f'({columns})')
|
|
661
|
+
operation_parts.append("from stdin")
|
|
662
|
+
if options:
|
|
663
|
+
operation_parts.append(f"({','.join(options)})")
|
|
664
|
+
operation = ' '.join(operation_parts)
|
|
665
|
+
|
|
666
|
+
putdata = self._src.putdata
|
|
667
|
+
self.execute(operation, parameters)
|
|
668
|
+
|
|
669
|
+
try:
|
|
670
|
+
for chunk in chunks():
|
|
671
|
+
putdata(chunk)
|
|
672
|
+
except BaseException as error:
|
|
673
|
+
self.rowcount = -1
|
|
674
|
+
# the following call will re-raise the error
|
|
675
|
+
putdata(error)
|
|
676
|
+
else:
|
|
677
|
+
rowcount = putdata(None)
|
|
678
|
+
self.rowcount = -1 if rowcount is None else rowcount
|
|
679
|
+
|
|
680
|
+
# return the cursor object, so you can chain operations
|
|
681
|
+
return self
|
|
682
|
+
|
|
683
|
+
# noinspection PyShadowingBuiltins
|
|
684
|
+
def copy_to(self, stream: Any, table: str,
|
|
685
|
+
format: str | None = None, sep: str | None = None,
|
|
686
|
+
null: str | None = None, decode: bool | None = None,
|
|
687
|
+
columns: Sequence[str] | None = None
|
|
688
|
+
) -> Cursor | Generator[str | bytes, None, None]:
|
|
689
|
+
"""Copy data from the specified table to an output stream.
|
|
690
|
+
|
|
691
|
+
The output stream can be a file-like object with a write() method or
|
|
692
|
+
it can also be None, in which case the method will return a generator
|
|
693
|
+
yielding a row on each iteration.
|
|
694
|
+
|
|
695
|
+
Output will be returned as strings unless you set decode to false
|
|
696
|
+
or use the binary format, which always returns byte strings.
|
|
697
|
+
|
|
698
|
+
Note that you can also use a select query instead of the table name.
|
|
699
|
+
|
|
700
|
+
The format must be 'text', 'csv' or 'binary'. The sep option sets the
|
|
701
|
+
column separator (delimiter) used in the non binary formats.
|
|
702
|
+
The null option sets the textual representation of NULL in the output.
|
|
703
|
+
|
|
704
|
+
The copy operation can be restricted to a subset of columns. If no
|
|
705
|
+
columns are specified, all of them will be copied.
|
|
706
|
+
"""
|
|
707
|
+
binary_format = format == 'binary'
|
|
708
|
+
if stream is None:
|
|
709
|
+
write = None
|
|
710
|
+
else:
|
|
711
|
+
try:
|
|
712
|
+
write = stream.write
|
|
713
|
+
except AttributeError as e:
|
|
714
|
+
raise TypeError("Need an output stream to copy to") from e
|
|
715
|
+
if not table or not isinstance(table, str):
|
|
716
|
+
raise TypeError("Need a table or query to copy from")
|
|
717
|
+
cnx = self._cnx
|
|
718
|
+
if table.lower().startswith('select '):
|
|
719
|
+
if columns:
|
|
720
|
+
raise ValueError("Columns must be specified in the query")
|
|
721
|
+
table = f'({table})'
|
|
722
|
+
else:
|
|
723
|
+
table = '.'.join(map(cnx.escape_identifier,
|
|
724
|
+
split_qualified_name(table)))
|
|
725
|
+
operation_parts = [f'copy {table}']
|
|
726
|
+
options = []
|
|
727
|
+
parameters = []
|
|
728
|
+
if format is not None:
|
|
729
|
+
if not isinstance(format, str):
|
|
730
|
+
raise TypeError("The format option must be a string")
|
|
731
|
+
if format not in ('text', 'csv', 'binary'):
|
|
732
|
+
raise ValueError("Invalid format")
|
|
733
|
+
options.append(f'format {format}')
|
|
734
|
+
if sep is not None:
|
|
735
|
+
if not isinstance(sep, str):
|
|
736
|
+
raise TypeError("The sep option must be a string")
|
|
737
|
+
if binary_format:
|
|
738
|
+
raise ValueError(
|
|
739
|
+
"The sep option is not allowed with binary format")
|
|
740
|
+
if len(sep) != 1:
|
|
741
|
+
raise ValueError(
|
|
742
|
+
"The sep option must be a single one-byte character")
|
|
743
|
+
options.append('delimiter %s')
|
|
744
|
+
parameters.append(sep)
|
|
745
|
+
if null is not None:
|
|
746
|
+
if not isinstance(null, str):
|
|
747
|
+
raise TypeError("The null option must be a string")
|
|
748
|
+
options.append('null %s')
|
|
749
|
+
parameters.append(null)
|
|
750
|
+
if decode is None:
|
|
751
|
+
decode = format != 'binary'
|
|
752
|
+
else:
|
|
753
|
+
if not isinstance(decode, (int, bool)):
|
|
754
|
+
raise TypeError("The decode option must be a boolean")
|
|
755
|
+
if decode and binary_format:
|
|
756
|
+
raise ValueError(
|
|
757
|
+
"The decode option is not allowed with binary format")
|
|
758
|
+
if columns:
|
|
759
|
+
if not isinstance(columns, str):
|
|
760
|
+
columns = ','.join(map(cnx.escape_identifier, columns))
|
|
761
|
+
operation_parts.append(f'({columns})')
|
|
762
|
+
|
|
763
|
+
operation_parts.append("to stdout")
|
|
764
|
+
if options:
|
|
765
|
+
operation_parts.append(f"({','.join(options)})")
|
|
766
|
+
operation = ' '.join(operation_parts)
|
|
767
|
+
|
|
768
|
+
getdata = self._src.getdata
|
|
769
|
+
self.execute(operation, parameters)
|
|
770
|
+
|
|
771
|
+
def copy() -> Generator[str | bytes, None, None]:
|
|
772
|
+
self.rowcount = 0
|
|
773
|
+
while True:
|
|
774
|
+
row = getdata(decode)
|
|
775
|
+
if isinstance(row, int):
|
|
776
|
+
if self.rowcount != row:
|
|
777
|
+
self.rowcount = row
|
|
778
|
+
break
|
|
779
|
+
self.rowcount += 1
|
|
780
|
+
yield row
|
|
781
|
+
|
|
782
|
+
if write is None:
|
|
783
|
+
# no input stream, return the generator
|
|
784
|
+
return copy()
|
|
785
|
+
|
|
786
|
+
# write the rows to the file-like input stream
|
|
787
|
+
for row in copy():
|
|
788
|
+
# noinspection PyUnboundLocalVariable
|
|
789
|
+
write(row)
|
|
790
|
+
|
|
791
|
+
# return the cursor object, so you can chain operations
|
|
792
|
+
return self
|
|
793
|
+
|
|
794
|
+
def __next__(self) -> Sequence:
|
|
795
|
+
"""Return the next row (support for the iteration protocol)."""
|
|
796
|
+
res = self.fetchone()
|
|
797
|
+
if res is None:
|
|
798
|
+
raise StopIteration
|
|
799
|
+
return res
|
|
800
|
+
|
|
801
|
+
# Note that the iterator protocol now uses __next()__ instead of next(),
|
|
802
|
+
# but we keep it for backward compatibility of pgdb.
|
|
803
|
+
next = __next__
|
|
804
|
+
|
|
805
|
+
@staticmethod
|
|
806
|
+
def nextset() -> bool | None:
|
|
807
|
+
"""Not supported."""
|
|
808
|
+
raise NotSupportedError("The nextset() method is not supported")
|
|
809
|
+
|
|
810
|
+
@staticmethod
|
|
811
|
+
def setinputsizes(sizes: Sequence[int]) -> None:
|
|
812
|
+
"""Not supported."""
|
|
813
|
+
pass # unsupported, but silently passed
|
|
814
|
+
|
|
815
|
+
@staticmethod
|
|
816
|
+
def setoutputsize(size: int, column: int = 0) -> None:
|
|
817
|
+
"""Not supported."""
|
|
818
|
+
pass # unsupported, but silently passed
|
|
819
|
+
|
|
820
|
+
@staticmethod
|
|
821
|
+
def row_factory(row: Sequence) -> Sequence:
|
|
822
|
+
"""Process rows before they are returned.
|
|
823
|
+
|
|
824
|
+
You can overwrite this statically with a custom row factory, or
|
|
825
|
+
you can build a row factory dynamically with build_row_factory().
|
|
826
|
+
|
|
827
|
+
For example, you can create a Cursor class that returns rows as
|
|
828
|
+
Python dictionaries like this:
|
|
829
|
+
|
|
830
|
+
class DictCursor(pgdb.Cursor):
|
|
831
|
+
|
|
832
|
+
def row_factory(self, row):
|
|
833
|
+
return {desc[0]: value
|
|
834
|
+
for desc, value in zip(self.description, row)}
|
|
835
|
+
|
|
836
|
+
cur = DictCursor(con) # get one DictCursor instance or
|
|
837
|
+
con.cursor_type = DictCursor # always use DictCursor instances
|
|
838
|
+
"""
|
|
839
|
+
raise NotImplementedError
|
|
840
|
+
|
|
841
|
+
def build_row_factory(self) -> Callable[[Sequence], Sequence] | None:
|
|
842
|
+
"""Build a row factory based on the current description.
|
|
843
|
+
|
|
844
|
+
This implementation builds a row factory for creating named tuples.
|
|
845
|
+
You can overwrite this method if you want to dynamically create
|
|
846
|
+
different row factories whenever the column description changes.
|
|
847
|
+
"""
|
|
848
|
+
names = self.colnames
|
|
849
|
+
return RowCache.row_factory(tuple(names)) if names else None
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
class CursorDescription(NamedTuple):
|
|
853
|
+
"""Description of a result column as specified by the DB-API 2."""
|
|
854
|
+
|
|
855
|
+
name: str
|
|
856
|
+
type_code: TypeCode
|
|
857
|
+
display_size: int | None
|
|
858
|
+
internal_size: int
|
|
859
|
+
precision: int | None
|
|
860
|
+
scale: int | None
|
|
861
|
+
null_ok: bool | None
|