-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
cursor_async.py
197 lines (168 loc) · 5.93 KB
/
cursor_async.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""
psycopg async cursor objects
"""
# Copyright (C) 2020 The Psycopg Team
from types import TracebackType
from typing import Any, AsyncIterator, Iterable, List
from typing import Optional, Type, TypeVar, TYPE_CHECKING
from contextlib import asynccontextmanager
from . import errors as e
from .abc import Query, Params
from .copy import AsyncCopy
from .rows import Row, RowMaker, AsyncRowFactory
from .cursor import BaseCursor
from ._pipeline import Pipeline
if TYPE_CHECKING:
from .connection_async import AsyncConnection
_C = TypeVar("_C", bound="AsyncCursor[Any]")
class AsyncCursor(BaseCursor["AsyncConnection[Any]", Row]):
__module__ = "psycopg"
__slots__ = ()
def __init__(
self,
connection: "AsyncConnection[Any]",
*,
row_factory: AsyncRowFactory[Row],
):
super().__init__(connection)
self._row_factory = row_factory
async def __aenter__(self: _C) -> _C:
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
await self.close()
async def close(self) -> None:
self._close()
@property
def row_factory(self) -> AsyncRowFactory[Row]:
return self._row_factory
@row_factory.setter
def row_factory(self, row_factory: AsyncRowFactory[Row]) -> None:
self._row_factory = row_factory
if self.pgresult:
self._make_row = row_factory(self)
def _make_row_maker(self) -> RowMaker[Row]:
return self._row_factory(self)
async def execute(
self: _C,
query: Query,
params: Optional[Params] = None,
*,
prepare: Optional[bool] = None,
binary: Optional[bool] = None,
) -> _C:
try:
async with self._conn.lock:
await self._conn.wait(
self._execute_gen(query, params, prepare=prepare, binary=binary)
)
except e.Error as ex:
raise ex.with_traceback(None)
return self
async def executemany(
self,
query: Query,
params_seq: Iterable[Params],
*,
returning: bool = False,
) -> None:
try:
if Pipeline.is_supported():
# If there is already a pipeline, ride it, in order to avoid
# sending unnecessary Sync.
async with self._conn.lock:
p = self._conn._pipeline
if p:
await self._conn.wait(
self._executemany_gen_pipeline(query, params_seq, returning)
)
# Otherwise, make a new one
if not p:
async with self._conn.pipeline(), self._conn.lock:
await self._conn.wait(
self._executemany_gen_pipeline(query, params_seq, returning)
)
else:
await self._conn.wait(
self._executemany_gen_no_pipeline(query, params_seq, returning)
)
except e.Error as ex:
raise ex.with_traceback(None)
async def stream(
self,
query: Query,
params: Optional[Params] = None,
*,
binary: Optional[bool] = None,
) -> AsyncIterator[Row]:
if self._pgconn.pipeline_status:
raise e.ProgrammingError("stream() cannot be used in pipeline mode")
async with self._conn.lock:
await self._conn.wait(self._stream_send_gen(query, params, binary=binary))
first = True
while await self._conn.wait(self._stream_fetchone_gen(first)):
rec = self._tx.load_row(0, self._make_row)
assert rec is not None
yield rec
first = False
async def fetchone(self) -> Optional[Row]:
await self._fetch_pipeline()
self._check_result_for_fetch()
rv = self._tx.load_row(self._pos, self._make_row)
if rv is not None:
self._pos += 1
return rv
async def fetchmany(self, size: int = 0) -> List[Row]:
await self._fetch_pipeline()
self._check_result_for_fetch()
assert self.pgresult
if not size:
size = self.arraysize
records = self._tx.load_rows(
self._pos,
min(self._pos + size, self.pgresult.ntuples),
self._make_row,
)
self._pos += len(records)
return records
async def fetchall(self) -> List[Row]:
await self._fetch_pipeline()
self._check_result_for_fetch()
assert self.pgresult
records = self._tx.load_rows(self._pos, self.pgresult.ntuples, self._make_row)
self._pos = self.pgresult.ntuples
return records
async def __aiter__(self) -> AsyncIterator[Row]:
await self._fetch_pipeline()
self._check_result_for_fetch()
def load(pos: int) -> Optional[Row]:
return self._tx.load_row(pos, self._make_row)
while 1:
row = load(self._pos)
if row is None:
break
self._pos += 1
yield row
async def scroll(self, value: int, mode: str = "relative") -> None:
self._scroll(value, mode)
@asynccontextmanager
async def copy(self, statement: Query) -> AsyncIterator[AsyncCopy]:
"""
:rtype: AsyncCopy
"""
async with self._conn.lock:
await self._conn.wait(self._start_copy_gen(statement))
async with self._conn._copycls(self) as copy:
yield copy
async def _fetch_pipeline(self) -> None:
if (
self._execmany_returning is not False
and not self.pgresult
and self._conn._pipeline
):
async with self._conn.lock:
await self._conn.wait(self._conn._pipeline._fetch_gen(flush=True))