@@ -160,8 +160,8 @@ def get_max_lsn(credentials: ConnectionStringCredentials) -> Optional[int]:
160
160
Returns None if the replication slot is empty.
161
161
Does not consume the slot, i.e. messages are not flushed.
162
162
"""
163
- with _get_conn (credentials ) as conn :
164
- cur = conn . cursor ()
163
+ cur = _get_conn (credentials ). cursor ()
164
+ try :
165
165
loc_fn = (
166
166
"pg_current_xlog_location"
167
167
if get_pg_version (cur ) < 100000
@@ -171,6 +171,8 @@ def get_max_lsn(credentials: ConnectionStringCredentials) -> Optional[int]:
171
171
cur .execute (f"SELECT { loc_fn } () - '0/0' as max_lsn;" )
172
172
lsn : int = cur .fetchone ()[0 ]
173
173
return lsn
174
+ finally :
175
+ cur .connection .close ()
174
176
175
177
176
178
def lsn_int_to_hex (lsn : int ) -> str :
@@ -192,13 +194,15 @@ def advance_slot(
192
194
the behavior of that method seems odd when used outside of `consume_stream`.
193
195
"""
194
196
assert upto_lsn > 0
195
- with _get_conn (credentials ) as conn :
196
- cur = conn . cursor ()
197
+ cur = _get_conn (credentials ). cursor ()
198
+ try :
197
199
# There is unfortunately no way in pg9.6 to manually advance the replication slot
198
200
if get_pg_version (cur ) > 100000 :
199
201
cur .execute (
200
202
f"SELECT * FROM pg_replication_slot_advance('{ slot_name } ', '{ lsn_int_to_hex (upto_lsn )} ');"
201
203
)
204
+ finally :
205
+ cur .connection .close ()
202
206
203
207
204
208
def _get_conn (
@@ -382,19 +386,20 @@ def __iter__(self) -> Iterator[TableItems]:
382
386
Maintains LSN of last consumed commit message in object state.
383
387
Advances the slot only when all messages have been consumed.
384
388
"""
385
- with get_rep_conn (self .credentials ) as conn :
386
- cur = conn .cursor ()
389
+ cur = get_rep_conn (self .credentials ).cursor ()
390
+ consumer = MessageConsumer (
391
+ upto_lsn = self .upto_lsn ,
392
+ table_qnames = self .table_qnames ,
393
+ repl_options = self .repl_options ,
394
+ target_batch_size = self .target_batch_size ,
395
+ )
396
+ try :
387
397
cur .start_replication (slot_name = self .slot_name , start_lsn = self .start_lsn )
388
- consumer = MessageConsumer (
389
- upto_lsn = self .upto_lsn ,
390
- table_qnames = self .table_qnames ,
391
- repl_options = self .repl_options ,
392
- target_batch_size = self .target_batch_size ,
393
- )
394
- try :
395
- cur .consume_stream (consumer )
396
- except StopReplication : # completed batch or reached `upto_lsn`
397
- yield from self .flush_batch (cur , consumer )
398
+ cur .consume_stream (consumer )
399
+ except StopReplication : # completed batch or reached `upto_lsn`
400
+ yield from self .flush_batch (cur , consumer )
401
+ finally :
402
+ cur .connection .close ()
398
403
399
404
def flush_batch (
400
405
self , cur : ReplicationCursor , consumer : MessageConsumer
0 commit comments