PyGreSQL 6.1.0__cp313-cp313-win32.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.
- PyGreSQL-6.1.0.dist-info/LICENSE.txt +30 -0
- PyGreSQL-6.1.0.dist-info/METADATA +112 -0
- PyGreSQL-6.1.0.dist-info/RECORD +27 -0
- PyGreSQL-6.1.0.dist-info/WHEEL +5 -0
- PyGreSQL-6.1.0.dist-info/top_level.txt +2 -0
- pg/__init__.py +186 -0
- pg/_pg.cp313-win32.pyd +0 -0
- pg/_pg.pyi +638 -0
- pg/adapt.py +686 -0
- pg/attrs.py +35 -0
- pg/cast.py +446 -0
- pg/core.py +180 -0
- pg/db.py +1502 -0
- pg/error.py +59 -0
- pg/helpers.py +124 -0
- pg/notify.py +149 -0
- pg/py.typed +4 -0
- pg/tz.py +21 -0
- pgdb/__init__.py +182 -0
- pgdb/adapt.py +261 -0
- pgdb/cast.py +594 -0
- pgdb/connect.py +74 -0
- pgdb/connection.py +156 -0
- pgdb/constants.py +14 -0
- pgdb/cursor.py +645 -0
- pgdb/py.typed +1 -0
- pgdb/typecode.py +34 -0
pgdb/cursor.py
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
"""The DB API 2 Cursor object."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import namedtuple
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from datetime import date, datetime, time, timedelta
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from math import isinf, isnan
|
|
10
|
+
from typing import TYPE_CHECKING, Any, Callable, Generator, Mapping, Sequence
|
|
11
|
+
from uuid import UUID as Uuid # noqa: N811
|
|
12
|
+
|
|
13
|
+
from pg.core import (
|
|
14
|
+
RESULT_DQL,
|
|
15
|
+
DatabaseError,
|
|
16
|
+
Error,
|
|
17
|
+
InterfaceError,
|
|
18
|
+
NotSupportedError,
|
|
19
|
+
)
|
|
20
|
+
from pg.core import Connection as Cnx
|
|
21
|
+
from pg.error import db_error, if_error, op_error
|
|
22
|
+
from pg.helpers import QuoteDict, RowCache
|
|
23
|
+
|
|
24
|
+
from .adapt import Binary, Hstore, Json, Literal
|
|
25
|
+
from .cast import TypeCache
|
|
26
|
+
from .typecode import TypeCode
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from .connection import Connection
|
|
30
|
+
|
|
31
|
+
__all__ = ['Cursor', 'CursorDescription']
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Cursor:
|
|
35
|
+
"""Cursor object."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, connection: Connection) -> None:
|
|
38
|
+
"""Create a cursor object for the database connection."""
|
|
39
|
+
self.connection = self._connection = connection
|
|
40
|
+
cnx = connection._cnx
|
|
41
|
+
if not cnx:
|
|
42
|
+
raise op_error("Connection has been closed")
|
|
43
|
+
self._cnx: Cnx = cnx
|
|
44
|
+
self.type_cache: TypeCache = connection.type_cache
|
|
45
|
+
self._src = self._cnx.source()
|
|
46
|
+
# the official attribute for describing the result columns
|
|
47
|
+
self._description: list[CursorDescription] | bool | None = None
|
|
48
|
+
if self.row_factory is Cursor.row_factory:
|
|
49
|
+
# the row factory needs to be determined dynamically
|
|
50
|
+
self.row_factory = None # type: ignore
|
|
51
|
+
else:
|
|
52
|
+
self.build_row_factory = None # type: ignore
|
|
53
|
+
self.rowcount: int | None = -1
|
|
54
|
+
self.arraysize: int = 1
|
|
55
|
+
self.lastrowid: int | None = None
|
|
56
|
+
|
|
57
|
+
def __iter__(self) -> Cursor:
|
|
58
|
+
"""Make cursor compatible to the iteration protocol."""
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def __enter__(self) -> Cursor:
|
|
62
|
+
"""Enter the runtime context for the cursor object."""
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
def __exit__(self, et: type[BaseException] | None,
|
|
66
|
+
ev: BaseException | None, tb: Any) -> None:
|
|
67
|
+
"""Exit the runtime context for the cursor object."""
|
|
68
|
+
self.close()
|
|
69
|
+
|
|
70
|
+
def _quote(self, value: Any) -> Any:
|
|
71
|
+
"""Quote value depending on its type."""
|
|
72
|
+
if value is None:
|
|
73
|
+
return 'NULL'
|
|
74
|
+
if isinstance(value, (Hstore, Json)):
|
|
75
|
+
value = str(value)
|
|
76
|
+
if isinstance(value, (bytes, str)):
|
|
77
|
+
cnx = self._cnx
|
|
78
|
+
if isinstance(value, Binary):
|
|
79
|
+
value = cnx.escape_bytea(value).decode('ascii')
|
|
80
|
+
else:
|
|
81
|
+
value = cnx.escape_string(value)
|
|
82
|
+
return f"'{value}'"
|
|
83
|
+
if isinstance(value, float):
|
|
84
|
+
if isinf(value):
|
|
85
|
+
return "'-Infinity'" if value < 0 else "'Infinity'"
|
|
86
|
+
if isnan(value):
|
|
87
|
+
return "'NaN'"
|
|
88
|
+
return value
|
|
89
|
+
if isinstance(value, (int, Decimal, Literal)):
|
|
90
|
+
return value
|
|
91
|
+
if isinstance(value, datetime):
|
|
92
|
+
if value.tzinfo:
|
|
93
|
+
return f"'{value}'::timestamptz"
|
|
94
|
+
return f"'{value}'::timestamp"
|
|
95
|
+
if isinstance(value, date):
|
|
96
|
+
return f"'{value}'::date"
|
|
97
|
+
if isinstance(value, time):
|
|
98
|
+
if value.tzinfo:
|
|
99
|
+
return f"'{value}'::timetz"
|
|
100
|
+
return f"'{value}'::time"
|
|
101
|
+
if isinstance(value, timedelta):
|
|
102
|
+
return f"'{value}'::interval"
|
|
103
|
+
if isinstance(value, Uuid):
|
|
104
|
+
return f"'{value}'::uuid"
|
|
105
|
+
if isinstance(value, list):
|
|
106
|
+
# Quote value as an ARRAY constructor. This is better than using
|
|
107
|
+
# an array literal because it carries the information that this is
|
|
108
|
+
# an array and not a string. One issue with this syntax is that
|
|
109
|
+
# you need to add an explicit typecast when passing empty arrays.
|
|
110
|
+
# The ARRAY keyword is actually only necessary at the top level.
|
|
111
|
+
if not value: # exception for empty array
|
|
112
|
+
return "'{}'"
|
|
113
|
+
q = self._quote
|
|
114
|
+
v = ','.join(str(q(v)) for v in value)
|
|
115
|
+
return f'ARRAY[{v}]'
|
|
116
|
+
if isinstance(value, tuple):
|
|
117
|
+
# Quote as a ROW constructor. This is better than using a record
|
|
118
|
+
# literal because it carries the information that this is a record
|
|
119
|
+
# and not a string. We don't use the keyword ROW in order to make
|
|
120
|
+
# this usable with the IN syntax as well. It is only necessary
|
|
121
|
+
# when the records has a single column which is not really useful.
|
|
122
|
+
q = self._quote
|
|
123
|
+
v = ','.join(str(q(v)) for v in value)
|
|
124
|
+
return f'({v})'
|
|
125
|
+
try: # noinspection PyUnresolvedReferences
|
|
126
|
+
value = value.__pg_repr__()
|
|
127
|
+
except AttributeError as e:
|
|
128
|
+
raise InterfaceError(
|
|
129
|
+
f'Do not know how to adapt type {type(value)}') from e
|
|
130
|
+
if isinstance(value, (tuple, list)):
|
|
131
|
+
value = self._quote(value)
|
|
132
|
+
return value
|
|
133
|
+
|
|
134
|
+
def _quoteparams(self, string: str,
|
|
135
|
+
parameters: Mapping | Sequence | None) -> str:
|
|
136
|
+
"""Quote parameters.
|
|
137
|
+
|
|
138
|
+
This function works for both mappings and sequences.
|
|
139
|
+
|
|
140
|
+
The function should be used even when there are no parameters,
|
|
141
|
+
so that we have a consistent behavior regarding percent signs.
|
|
142
|
+
"""
|
|
143
|
+
if not parameters:
|
|
144
|
+
try:
|
|
145
|
+
return string % () # unescape literal quotes if possible
|
|
146
|
+
except (TypeError, ValueError):
|
|
147
|
+
return string # silently accept unescaped quotes
|
|
148
|
+
if isinstance(parameters, dict):
|
|
149
|
+
parameters = QuoteDict(parameters)
|
|
150
|
+
parameters.quote = self._quote
|
|
151
|
+
else:
|
|
152
|
+
parameters = tuple(map(self._quote, parameters))
|
|
153
|
+
return string % parameters
|
|
154
|
+
|
|
155
|
+
def _make_description(self, info: tuple[int, str, int, int, int]
|
|
156
|
+
) -> CursorDescription:
|
|
157
|
+
"""Make the description tuple for the given field info."""
|
|
158
|
+
name, typ, size, mod = info[1:]
|
|
159
|
+
type_code = self.type_cache[typ]
|
|
160
|
+
if mod > 0:
|
|
161
|
+
mod -= 4
|
|
162
|
+
precision: int | None
|
|
163
|
+
scale: int | None
|
|
164
|
+
if type_code == 'numeric':
|
|
165
|
+
precision, scale = mod >> 16, mod & 0xffff
|
|
166
|
+
size = precision
|
|
167
|
+
else:
|
|
168
|
+
if not size:
|
|
169
|
+
size = type_code.size
|
|
170
|
+
if size == -1:
|
|
171
|
+
size = mod
|
|
172
|
+
precision = scale = None
|
|
173
|
+
return CursorDescription(
|
|
174
|
+
name, type_code, None, size, precision, scale, None)
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def description(self) -> list[CursorDescription] | None:
|
|
178
|
+
"""Read-only attribute describing the result columns."""
|
|
179
|
+
description = self._description
|
|
180
|
+
if description is None:
|
|
181
|
+
return None
|
|
182
|
+
if not isinstance(description, list):
|
|
183
|
+
make = self._make_description
|
|
184
|
+
description = [make(info) for info in self._src.listinfo()]
|
|
185
|
+
self._description = description
|
|
186
|
+
return description
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def colnames(self) -> Sequence[str] | None:
|
|
190
|
+
"""Unofficial convenience method for getting the column names."""
|
|
191
|
+
description = self.description
|
|
192
|
+
return None if description is None else [d[0] for d in description]
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def coltypes(self) -> Sequence[TypeCode] | None:
|
|
196
|
+
"""Unofficial convenience method for getting the column types."""
|
|
197
|
+
description = self.description
|
|
198
|
+
return None if description is None else [d[1] for d in description]
|
|
199
|
+
|
|
200
|
+
def close(self) -> None:
|
|
201
|
+
"""Close the cursor object."""
|
|
202
|
+
self._src.close()
|
|
203
|
+
|
|
204
|
+
def execute(self, operation: str, parameters: Sequence | None = None
|
|
205
|
+
) -> Cursor:
|
|
206
|
+
"""Prepare and execute a database operation (query or command)."""
|
|
207
|
+
# The parameters may also be specified as list of tuples to e.g.
|
|
208
|
+
# insert multiple rows in a single operation, but this kind of
|
|
209
|
+
# usage is deprecated. We make several plausibility checks because
|
|
210
|
+
# tuples can also be passed with the meaning of ROW constructors.
|
|
211
|
+
if (parameters and isinstance(parameters, list)
|
|
212
|
+
and len(parameters) > 1
|
|
213
|
+
and all(isinstance(p, tuple) for p in parameters)
|
|
214
|
+
and all(len(p) == len(parameters[0]) for p in parameters[1:])):
|
|
215
|
+
return self.executemany(operation, parameters)
|
|
216
|
+
# not a list of tuples
|
|
217
|
+
return self.executemany(operation, [parameters])
|
|
218
|
+
|
|
219
|
+
def executemany(self, operation: str,
|
|
220
|
+
seq_of_parameters: Sequence[Sequence | None]) -> Cursor:
|
|
221
|
+
"""Prepare operation and execute it against a parameter sequence."""
|
|
222
|
+
if not seq_of_parameters:
|
|
223
|
+
# don't do anything without parameters
|
|
224
|
+
return self
|
|
225
|
+
self._description = None
|
|
226
|
+
self.rowcount = -1
|
|
227
|
+
# first try to execute all queries
|
|
228
|
+
rowcount = 0
|
|
229
|
+
sql = "BEGIN"
|
|
230
|
+
try:
|
|
231
|
+
if not self._connection._tnx and not self._connection.autocommit:
|
|
232
|
+
try:
|
|
233
|
+
self._src.execute(sql)
|
|
234
|
+
except DatabaseError:
|
|
235
|
+
raise # database provides error message
|
|
236
|
+
except Exception as e:
|
|
237
|
+
raise op_error("Can't start transaction") from e
|
|
238
|
+
else:
|
|
239
|
+
self._connection._tnx = True
|
|
240
|
+
for parameters in seq_of_parameters:
|
|
241
|
+
sql = operation
|
|
242
|
+
sql = self._quoteparams(sql, parameters)
|
|
243
|
+
rows = self._src.execute(sql)
|
|
244
|
+
if rows: # true if not DML
|
|
245
|
+
rowcount += rows
|
|
246
|
+
else:
|
|
247
|
+
self.rowcount = -1
|
|
248
|
+
except DatabaseError:
|
|
249
|
+
raise # database provides error message
|
|
250
|
+
except Error as err:
|
|
251
|
+
# noinspection PyTypeChecker
|
|
252
|
+
raise if_error(f"Error in '{sql}': '{err}'") from err
|
|
253
|
+
except Exception as err:
|
|
254
|
+
raise op_error(f"Internal error in '{sql}': {err}") from err
|
|
255
|
+
# then initialize result raw count and description
|
|
256
|
+
if self._src.resulttype == RESULT_DQL:
|
|
257
|
+
self._description = True # fetch on demand
|
|
258
|
+
self.rowcount = self._src.ntuples
|
|
259
|
+
self.lastrowid = None
|
|
260
|
+
build_row_factory = self.build_row_factory
|
|
261
|
+
if build_row_factory: # type: ignore
|
|
262
|
+
self.row_factory = build_row_factory() # type: ignore
|
|
263
|
+
else:
|
|
264
|
+
self.rowcount = rowcount
|
|
265
|
+
self.lastrowid = self._src.oidstatus()
|
|
266
|
+
# return the cursor object, so you can write statements such as
|
|
267
|
+
# "cursor.execute(...).fetchall()" or "for row in cursor.execute(...)"
|
|
268
|
+
return self
|
|
269
|
+
|
|
270
|
+
def fetchone(self) -> Sequence | None:
|
|
271
|
+
"""Fetch the next row of a query result set."""
|
|
272
|
+
res = self.fetchmany(1, False)
|
|
273
|
+
try:
|
|
274
|
+
return res[0]
|
|
275
|
+
except IndexError:
|
|
276
|
+
return None
|
|
277
|
+
|
|
278
|
+
def fetchall(self) -> Sequence[Sequence]:
|
|
279
|
+
"""Fetch all (remaining) rows of a query result."""
|
|
280
|
+
return self.fetchmany(-1, False)
|
|
281
|
+
|
|
282
|
+
def fetchmany(self, size: int | None = None, keep: bool = False
|
|
283
|
+
) -> Sequence[Sequence]:
|
|
284
|
+
"""Fetch the next set of rows of a query result.
|
|
285
|
+
|
|
286
|
+
The number of rows to fetch per call is specified by the
|
|
287
|
+
size parameter. If it is not given, the cursor's arraysize
|
|
288
|
+
determines the number of rows to be fetched. If you set
|
|
289
|
+
the keep parameter to true, this is kept as new arraysize.
|
|
290
|
+
"""
|
|
291
|
+
if size is None:
|
|
292
|
+
size = self.arraysize
|
|
293
|
+
if keep:
|
|
294
|
+
self.arraysize = size
|
|
295
|
+
try:
|
|
296
|
+
result = self._src.fetch(size)
|
|
297
|
+
except DatabaseError:
|
|
298
|
+
raise
|
|
299
|
+
except Error as err:
|
|
300
|
+
raise db_error(str(err)) from err
|
|
301
|
+
row_factory = self.row_factory
|
|
302
|
+
coltypes = self.coltypes
|
|
303
|
+
if coltypes is None:
|
|
304
|
+
# cannot determine column types, return raw result
|
|
305
|
+
return [row_factory(row) for row in result]
|
|
306
|
+
if len(result) > 5:
|
|
307
|
+
# optimize the case where we really fetch many values
|
|
308
|
+
# by looking up all type casting functions upfront
|
|
309
|
+
cast_row = self.type_cache.get_row_caster(coltypes)
|
|
310
|
+
return [row_factory(cast_row(row)) for row in result]
|
|
311
|
+
cast_value = self.type_cache.typecast
|
|
312
|
+
return [row_factory([cast_value(value, typ)
|
|
313
|
+
for typ, value in zip(coltypes, row)]) for row in result]
|
|
314
|
+
|
|
315
|
+
def callproc(self, procname: str, parameters: Sequence | None = None
|
|
316
|
+
) -> Sequence | None:
|
|
317
|
+
"""Call a stored database procedure with the given name.
|
|
318
|
+
|
|
319
|
+
The sequence of parameters must contain one entry for each input
|
|
320
|
+
argument that the procedure expects. The result of the call is the
|
|
321
|
+
same as this input sequence; replacement of output and input/output
|
|
322
|
+
parameters in the return value is currently not supported.
|
|
323
|
+
|
|
324
|
+
The procedure may also provide a result set as output. These can be
|
|
325
|
+
requested through the standard fetch methods of the cursor.
|
|
326
|
+
"""
|
|
327
|
+
n = len(parameters) if parameters else 0
|
|
328
|
+
s = ','.join(n * ['%s'])
|
|
329
|
+
query = f'select * from "{procname}"({s})' # noqa: S608
|
|
330
|
+
self.execute(query, parameters)
|
|
331
|
+
return parameters
|
|
332
|
+
|
|
333
|
+
# noinspection PyShadowingBuiltins
|
|
334
|
+
def copy_from(self, stream: Any, table: str,
|
|
335
|
+
format: str | None = None, sep: str | None = None,
|
|
336
|
+
null: str | None = None, size: int | None = None,
|
|
337
|
+
columns: Sequence[str] | None = None) -> Cursor:
|
|
338
|
+
"""Copy data from an input stream to the specified table.
|
|
339
|
+
|
|
340
|
+
The input stream can be a file-like object with a read() method or
|
|
341
|
+
it can also be an iterable returning a row or multiple rows of input
|
|
342
|
+
on each iteration.
|
|
343
|
+
|
|
344
|
+
The format must be 'text', 'csv' or 'binary'. The sep option sets the
|
|
345
|
+
column separator (delimiter) used in the non binary formats.
|
|
346
|
+
The null option sets the textual representation of NULL in the input.
|
|
347
|
+
|
|
348
|
+
The size option sets the size of the buffer used when reading data
|
|
349
|
+
from file-like objects.
|
|
350
|
+
|
|
351
|
+
The copy operation can be restricted to a subset of columns. If no
|
|
352
|
+
columns are specified, all of them will be copied.
|
|
353
|
+
"""
|
|
354
|
+
binary_format = format == 'binary'
|
|
355
|
+
try:
|
|
356
|
+
read = stream.read
|
|
357
|
+
except AttributeError as e:
|
|
358
|
+
if size:
|
|
359
|
+
raise ValueError(
|
|
360
|
+
"Size must only be set for file-like objects") from e
|
|
361
|
+
input_type: type | tuple[type, ...]
|
|
362
|
+
type_name: str
|
|
363
|
+
if binary_format:
|
|
364
|
+
input_type = bytes
|
|
365
|
+
type_name = 'byte strings'
|
|
366
|
+
else:
|
|
367
|
+
input_type = (bytes, str)
|
|
368
|
+
type_name = 'strings'
|
|
369
|
+
|
|
370
|
+
if isinstance(stream, (bytes, str)):
|
|
371
|
+
if not isinstance(stream, input_type):
|
|
372
|
+
raise ValueError(f"The input must be {type_name}") from e
|
|
373
|
+
if not binary_format:
|
|
374
|
+
if isinstance(stream, str):
|
|
375
|
+
if not stream.endswith('\n'):
|
|
376
|
+
stream += '\n'
|
|
377
|
+
else:
|
|
378
|
+
if not stream.endswith(b'\n'):
|
|
379
|
+
stream += b'\n'
|
|
380
|
+
|
|
381
|
+
def chunks() -> Generator:
|
|
382
|
+
yield stream
|
|
383
|
+
|
|
384
|
+
elif isinstance(stream, Iterable):
|
|
385
|
+
|
|
386
|
+
def chunks() -> Generator:
|
|
387
|
+
for chunk in stream:
|
|
388
|
+
if not isinstance(chunk, input_type):
|
|
389
|
+
raise ValueError(
|
|
390
|
+
f"Input stream must consist of {type_name}")
|
|
391
|
+
if isinstance(chunk, str):
|
|
392
|
+
if not chunk.endswith('\n'):
|
|
393
|
+
chunk += '\n'
|
|
394
|
+
else:
|
|
395
|
+
if not chunk.endswith(b'\n'):
|
|
396
|
+
chunk += b'\n'
|
|
397
|
+
yield chunk
|
|
398
|
+
|
|
399
|
+
else:
|
|
400
|
+
raise TypeError("Need an input stream to copy from") from e
|
|
401
|
+
else:
|
|
402
|
+
if size is None:
|
|
403
|
+
size = 8192
|
|
404
|
+
elif not isinstance(size, int):
|
|
405
|
+
raise TypeError("The size option must be an integer")
|
|
406
|
+
if size > 0:
|
|
407
|
+
|
|
408
|
+
def chunks() -> Generator:
|
|
409
|
+
while True:
|
|
410
|
+
buffer = read(size)
|
|
411
|
+
yield buffer
|
|
412
|
+
if not buffer or len(buffer) < size:
|
|
413
|
+
break
|
|
414
|
+
|
|
415
|
+
else:
|
|
416
|
+
|
|
417
|
+
def chunks() -> Generator:
|
|
418
|
+
yield read()
|
|
419
|
+
|
|
420
|
+
if not table or not isinstance(table, str):
|
|
421
|
+
raise TypeError("Need a table to copy to")
|
|
422
|
+
if table.lower().startswith('select '):
|
|
423
|
+
raise ValueError("Must specify a table, not a query")
|
|
424
|
+
cnx = self._cnx
|
|
425
|
+
table = '.'.join(map(cnx.escape_identifier, table.split('.', 1)))
|
|
426
|
+
operation_parts = [f'copy {table}']
|
|
427
|
+
options = []
|
|
428
|
+
parameters = []
|
|
429
|
+
if format is not None:
|
|
430
|
+
if not isinstance(format, str):
|
|
431
|
+
raise TypeError("The format option must be be a string")
|
|
432
|
+
if format not in ('text', 'csv', 'binary'):
|
|
433
|
+
raise ValueError("Invalid format")
|
|
434
|
+
options.append(f'format {format}')
|
|
435
|
+
if sep is not None:
|
|
436
|
+
if not isinstance(sep, str):
|
|
437
|
+
raise TypeError("The sep option must be a string")
|
|
438
|
+
if format == 'binary':
|
|
439
|
+
raise ValueError(
|
|
440
|
+
"The sep option is not allowed with binary format")
|
|
441
|
+
if len(sep) != 1:
|
|
442
|
+
raise ValueError(
|
|
443
|
+
"The sep option must be a single one-byte character")
|
|
444
|
+
options.append('delimiter %s')
|
|
445
|
+
parameters.append(sep)
|
|
446
|
+
if null is not None:
|
|
447
|
+
if not isinstance(null, str):
|
|
448
|
+
raise TypeError("The null option must be a string")
|
|
449
|
+
options.append('null %s')
|
|
450
|
+
parameters.append(null)
|
|
451
|
+
if columns:
|
|
452
|
+
if not isinstance(columns, str):
|
|
453
|
+
columns = ','.join(map(cnx.escape_identifier, columns))
|
|
454
|
+
operation_parts.append(f'({columns})')
|
|
455
|
+
operation_parts.append("from stdin")
|
|
456
|
+
if options:
|
|
457
|
+
operation_parts.append(f"({','.join(options)})")
|
|
458
|
+
operation = ' '.join(operation_parts)
|
|
459
|
+
|
|
460
|
+
putdata = self._src.putdata
|
|
461
|
+
self.execute(operation, parameters)
|
|
462
|
+
|
|
463
|
+
try:
|
|
464
|
+
for chunk in chunks():
|
|
465
|
+
putdata(chunk)
|
|
466
|
+
except BaseException as error:
|
|
467
|
+
self.rowcount = -1
|
|
468
|
+
# the following call will re-raise the error
|
|
469
|
+
putdata(error)
|
|
470
|
+
else:
|
|
471
|
+
rowcount = putdata(None)
|
|
472
|
+
self.rowcount = -1 if rowcount is None else rowcount
|
|
473
|
+
|
|
474
|
+
# return the cursor object, so you can chain operations
|
|
475
|
+
return self
|
|
476
|
+
|
|
477
|
+
# noinspection PyShadowingBuiltins
|
|
478
|
+
def copy_to(self, stream: Any, table: str,
|
|
479
|
+
format: str | None = None, sep: str | None = None,
|
|
480
|
+
null: str | None = None, decode: bool | None = None,
|
|
481
|
+
columns: Sequence[str] | None = None) -> Cursor | Generator:
|
|
482
|
+
"""Copy data from the specified table to an output stream.
|
|
483
|
+
|
|
484
|
+
The output stream can be a file-like object with a write() method or
|
|
485
|
+
it can also be None, in which case the method will return a generator
|
|
486
|
+
yielding a row on each iteration.
|
|
487
|
+
|
|
488
|
+
Output will be returned as byte strings unless you set decode to true.
|
|
489
|
+
|
|
490
|
+
Note that you can also use a select query instead of the table name.
|
|
491
|
+
|
|
492
|
+
The format must be 'text', 'csv' or 'binary'. The sep option sets the
|
|
493
|
+
column separator (delimiter) used in the non binary formats.
|
|
494
|
+
The null option sets the textual representation of NULL in the output.
|
|
495
|
+
|
|
496
|
+
The copy operation can be restricted to a subset of columns. If no
|
|
497
|
+
columns are specified, all of them will be copied.
|
|
498
|
+
"""
|
|
499
|
+
binary_format = format == 'binary'
|
|
500
|
+
if stream is None:
|
|
501
|
+
write = None
|
|
502
|
+
else:
|
|
503
|
+
try:
|
|
504
|
+
write = stream.write
|
|
505
|
+
except AttributeError as e:
|
|
506
|
+
raise TypeError("Need an output stream to copy to") from e
|
|
507
|
+
if not table or not isinstance(table, str):
|
|
508
|
+
raise TypeError("Need a table to copy to")
|
|
509
|
+
cnx = self._cnx
|
|
510
|
+
if table.lower().startswith('select '):
|
|
511
|
+
if columns:
|
|
512
|
+
raise ValueError("Columns must be specified in the query")
|
|
513
|
+
table = f'({table})'
|
|
514
|
+
else:
|
|
515
|
+
table = '.'.join(map(cnx.escape_identifier, table.split('.', 1)))
|
|
516
|
+
operation_parts = [f'copy {table}']
|
|
517
|
+
options = []
|
|
518
|
+
parameters = []
|
|
519
|
+
if format is not None:
|
|
520
|
+
if not isinstance(format, str):
|
|
521
|
+
raise TypeError("The format option must be a string")
|
|
522
|
+
if format not in ('text', 'csv', 'binary'):
|
|
523
|
+
raise ValueError("Invalid format")
|
|
524
|
+
options.append(f'format {format}')
|
|
525
|
+
if sep is not None:
|
|
526
|
+
if not isinstance(sep, str):
|
|
527
|
+
raise TypeError("The sep option must be a string")
|
|
528
|
+
if binary_format:
|
|
529
|
+
raise ValueError(
|
|
530
|
+
"The sep option is not allowed with binary format")
|
|
531
|
+
if len(sep) != 1:
|
|
532
|
+
raise ValueError(
|
|
533
|
+
"The sep option must be a single one-byte character")
|
|
534
|
+
options.append('delimiter %s')
|
|
535
|
+
parameters.append(sep)
|
|
536
|
+
if null is not None:
|
|
537
|
+
if not isinstance(null, str):
|
|
538
|
+
raise TypeError("The null option must be a string")
|
|
539
|
+
options.append('null %s')
|
|
540
|
+
parameters.append(null)
|
|
541
|
+
if decode is None:
|
|
542
|
+
decode = format != 'binary'
|
|
543
|
+
else:
|
|
544
|
+
if not isinstance(decode, (int, bool)):
|
|
545
|
+
raise TypeError("The decode option must be a boolean")
|
|
546
|
+
if decode and binary_format:
|
|
547
|
+
raise ValueError(
|
|
548
|
+
"The decode option is not allowed with binary format")
|
|
549
|
+
if columns:
|
|
550
|
+
if not isinstance(columns, str):
|
|
551
|
+
columns = ','.join(map(cnx.escape_identifier, columns))
|
|
552
|
+
operation_parts.append(f'({columns})')
|
|
553
|
+
|
|
554
|
+
operation_parts.append("to stdout")
|
|
555
|
+
if options:
|
|
556
|
+
operation_parts.append(f"({','.join(options)})")
|
|
557
|
+
operation = ' '.join(operation_parts)
|
|
558
|
+
|
|
559
|
+
getdata = self._src.getdata
|
|
560
|
+
self.execute(operation, parameters)
|
|
561
|
+
|
|
562
|
+
def copy() -> Generator:
|
|
563
|
+
self.rowcount = 0
|
|
564
|
+
while True:
|
|
565
|
+
row = getdata(decode)
|
|
566
|
+
if isinstance(row, int):
|
|
567
|
+
if self.rowcount != row:
|
|
568
|
+
self.rowcount = row
|
|
569
|
+
break
|
|
570
|
+
self.rowcount += 1
|
|
571
|
+
yield row
|
|
572
|
+
|
|
573
|
+
if write is None:
|
|
574
|
+
# no input stream, return the generator
|
|
575
|
+
return copy()
|
|
576
|
+
|
|
577
|
+
# write the rows to the file-like input stream
|
|
578
|
+
for row in copy():
|
|
579
|
+
# noinspection PyUnboundLocalVariable
|
|
580
|
+
write(row)
|
|
581
|
+
|
|
582
|
+
# return the cursor object, so you can chain operations
|
|
583
|
+
return self
|
|
584
|
+
|
|
585
|
+
def __next__(self) -> Sequence:
|
|
586
|
+
"""Return the next row (support for the iteration protocol)."""
|
|
587
|
+
res = self.fetchone()
|
|
588
|
+
if res is None:
|
|
589
|
+
raise StopIteration
|
|
590
|
+
return res
|
|
591
|
+
|
|
592
|
+
# Note that the iterator protocol now uses __next()__ instead of next(),
|
|
593
|
+
# but we keep it for backward compatibility of pgdb.
|
|
594
|
+
next = __next__
|
|
595
|
+
|
|
596
|
+
@staticmethod
|
|
597
|
+
def nextset() -> bool | None:
|
|
598
|
+
"""Not supported."""
|
|
599
|
+
raise NotSupportedError("The nextset() method is not supported")
|
|
600
|
+
|
|
601
|
+
@staticmethod
|
|
602
|
+
def setinputsizes(sizes: Sequence[int]) -> None:
|
|
603
|
+
"""Not supported."""
|
|
604
|
+
pass # unsupported, but silently passed
|
|
605
|
+
|
|
606
|
+
@staticmethod
|
|
607
|
+
def setoutputsize(size: int, column: int = 0) -> None:
|
|
608
|
+
"""Not supported."""
|
|
609
|
+
pass # unsupported, but silently passed
|
|
610
|
+
|
|
611
|
+
@staticmethod
|
|
612
|
+
def row_factory(row: Sequence) -> Sequence:
|
|
613
|
+
"""Process rows before they are returned.
|
|
614
|
+
|
|
615
|
+
You can overwrite this statically with a custom row factory, or
|
|
616
|
+
you can build a row factory dynamically with build_row_factory().
|
|
617
|
+
|
|
618
|
+
For example, you can create a Cursor class that returns rows as
|
|
619
|
+
Python dictionaries like this:
|
|
620
|
+
|
|
621
|
+
class DictCursor(pgdb.Cursor):
|
|
622
|
+
|
|
623
|
+
def row_factory(self, row):
|
|
624
|
+
return {desc[0]: value
|
|
625
|
+
for desc, value in zip(self.description, row)}
|
|
626
|
+
|
|
627
|
+
cur = DictCursor(con) # get one DictCursor instance or
|
|
628
|
+
con.cursor_type = DictCursor # always use DictCursor instances
|
|
629
|
+
"""
|
|
630
|
+
raise NotImplementedError
|
|
631
|
+
|
|
632
|
+
def build_row_factory(self) -> Callable[[Sequence], Sequence] | None:
|
|
633
|
+
"""Build a row factory based on the current description.
|
|
634
|
+
|
|
635
|
+
This implementation builds a row factory for creating named tuples.
|
|
636
|
+
You can overwrite this method if you want to dynamically create
|
|
637
|
+
different row factories whenever the column description changes.
|
|
638
|
+
"""
|
|
639
|
+
names = self.colnames
|
|
640
|
+
return RowCache.row_factory(tuple(names)) if names else None
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
CursorDescription = namedtuple('CursorDescription', (
|
|
644
|
+
'name', 'type_code', 'display_size', 'internal_size',
|
|
645
|
+
'precision', 'scale', 'null_ok'))
|
pgdb/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Marker file for PEP 561. The pgdb package uses inline types.
|
pgdb/typecode.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Support for DB API 2 type codes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = ['TypeCode']
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TypeCode(str):
|
|
9
|
+
"""Class representing the type_code used by the DB-API 2.0.
|
|
10
|
+
|
|
11
|
+
TypeCode objects are strings equal to the PostgreSQL type name,
|
|
12
|
+
but carry some additional information.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
oid: int
|
|
16
|
+
len: int
|
|
17
|
+
type: str
|
|
18
|
+
category: str
|
|
19
|
+
delim: str
|
|
20
|
+
relid: int
|
|
21
|
+
|
|
22
|
+
# noinspection PyShadowingBuiltins
|
|
23
|
+
@classmethod
|
|
24
|
+
def create(cls, oid: int, name: str, len: int, type: str, category: str,
|
|
25
|
+
delim: str, relid: int) -> TypeCode:
|
|
26
|
+
"""Create a type code for a PostgreSQL data type."""
|
|
27
|
+
self = cls(name)
|
|
28
|
+
self.oid = oid
|
|
29
|
+
self.len = len
|
|
30
|
+
self.type = type
|
|
31
|
+
self.category = category
|
|
32
|
+
self.delim = delim
|
|
33
|
+
self.relid = relid
|
|
34
|
+
return self
|