harlequin-sqlite-ssh 0.1.0__py3-none-any.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.
@@ -0,0 +1,693 @@
1
+ """The program that runs on the remote host and owns the SQLite connection.
2
+
3
+ This module is never imported on the remote host. Its source text is read by
4
+ `harlequin_sqlite_ssh.transport`, sent over the SSH channel, and executed by
5
+ the remote Python interpreter through a one-line bootstrap (see
6
+ `transport.BOOTSTRAP`). Nothing is installed or written on the remote host.
7
+
8
+ Constraints that follow from where this code runs:
9
+
10
+ - Standard library only, and compatible with Python 3.8, because it runs on
11
+ whatever `python3` the remote host provides. No `X | Y` unions, no
12
+ `match`, no `str.removeprefix`, no annotations evaluated at run time.
13
+ - It must never print anything but protocol messages on stdout. Diagnostics
14
+ go to stderr, which the client keeps for its error messages.
15
+
16
+ Protocol (version `PROTOCOL_VERSION`), newline-delimited JSON, UTF-8:
17
+
18
+ 1. On start, the agent writes one *hello* message::
19
+
20
+ {"hello": "harlequin-sqlite-ssh", "protocol": 1, "python": "3.11.2",
21
+ "sqlite": "3.40.1", "autocommit": true, "load_extension": true}
22
+
23
+ 2. The client then sends requests, one per line, and waits for each answer
24
+ before sending the next one::
25
+
26
+ {"id": 7, "op": "execute", "sql": "select 1", "params": [], "prefetch": 256}
27
+
28
+ Any request may also carry ``"release": [3, 4]``, the ids of cursors the
29
+ client dropped, which the agent closes before handling the request.
30
+
31
+ The agent answers with the same `id`::
32
+
33
+ {"id": 7, "ok": true, "result": {...}}
34
+ {"id": 7, "ok": false, "error": {"type": "OperationalError",
35
+ "message": "no such table: foo"}}
36
+
37
+ 3. The only message the client may send while a request is in flight is
38
+ ``{"op": "interrupt", "target": 7}``, naming the request to stop. It gets
39
+ no answer of its own: a reader thread calls
40
+ `sqlite3.Connection.interrupt()` as soon as it arrives, so the running
41
+ statement fails with ``OperationalError: interrupted``. A request that is
42
+ interrupted before it starts fails the same way without running.
43
+
44
+ 4. End of input (the client closed the pipe, or SSH dropped) closes the
45
+ database and ends the process.
46
+
47
+ Values in rows and parameters are JSON scalars, except the types JSON cannot
48
+ carry, which travel as one-key objects (see `encode_value`).
49
+ """
50
+
51
+ import base64
52
+ import datetime
53
+ import json
54
+ import os
55
+ import sqlite3
56
+ import sys
57
+ import threading
58
+ from collections import OrderedDict
59
+ from urllib.parse import unquote, urlparse
60
+
61
+ PROTOCOL_VERSION = 1
62
+ """Bumped on any change the other side must know about."""
63
+
64
+ HELLO = "harlequin-sqlite-ssh"
65
+ """The value of the `hello` key, which tells the handshake from shell noise."""
66
+
67
+ PROGRESS_STEPS = 1000
68
+ """How many SQLite virtual machine steps between two checks for a cancel.
69
+
70
+ `sqlite3.Connection.interrupt()` alone can be lost: SQLite clears the
71
+ interrupt flag when a statement starts while no other statement is active,
72
+ so an interrupt that lands between the agent taking a request and SQLite
73
+ starting to run it would do nothing (https://sqlite.org/c3ref/interrupt.html).
74
+ A progress handler that checks the agent's own flag cannot be cleared that
75
+ way. A statement shorter than this many steps may still complete.
76
+ """
77
+
78
+ MAX_OPEN_CURSORS = 256
79
+ """How many partly-read cursors the agent keeps before closing the oldest.
80
+
81
+ A cursor read to its end is closed at once. One that is not (a result cut
82
+ short by Harlequin's row limit, for instance) stays open until the client
83
+ releases it, which it does as soon as it drops the cursor (see
84
+ `Agent.release`). This limit is only a safety net against a client that never
85
+ does: reading a cursor that was pushed out raises the same
86
+ `ProgrammingError` as reading a closed cursor.
87
+ """
88
+
89
+ _SQLITE_ERRORS = (
90
+ "NotSupportedError",
91
+ "ProgrammingError",
92
+ "InternalError",
93
+ "IntegrityError",
94
+ "OperationalError",
95
+ "DataError",
96
+ "DatabaseError",
97
+ "InterfaceError",
98
+ "Warning",
99
+ "Error",
100
+ )
101
+ """sqlite3 exception class names, most specific first, so that the first
102
+ match in `_error_type()` is the class the exception actually has."""
103
+
104
+
105
+ def encode_value(value):
106
+ """Return `value` in a form `json.dumps` accepts without losing its type.
107
+
108
+ Args:
109
+ value: A value read from SQLite, or produced by a converter registered
110
+ for `detect_types`.
111
+
112
+ Returns:
113
+ The value itself for `None`, `int`, `float` and `str`; otherwise a
114
+ one-key dict: ``{"$b": base64}`` for bytes, ``{"$date": iso}`` and
115
+ ``{"$datetime": iso}`` for the types the default sqlite3 converters
116
+ produce, and ``{"$str": str(value)}`` for anything else.
117
+ """
118
+ if value is None or isinstance(value, (int, float, str)):
119
+ return value
120
+ if isinstance(value, (bytes, bytearray, memoryview)):
121
+ return {"$b": base64.b64encode(bytes(value)).decode("ascii")}
122
+ if isinstance(value, datetime.datetime):
123
+ return {"$datetime": value.isoformat()}
124
+ if isinstance(value, datetime.date):
125
+ return {"$date": value.isoformat()}
126
+ return {"$str": str(value)}
127
+
128
+
129
+ def decode_value(value):
130
+ """Return the Python value `encode_value` encoded.
131
+
132
+ Args:
133
+ value: A JSON-decoded scalar, or a one-key dict from `encode_value`.
134
+
135
+ Returns:
136
+ The decoded value. ``{"$str": ...}`` decodes to the string itself.
137
+
138
+ Raises:
139
+ ValueError: If `value` is a dict that `encode_value` cannot produce.
140
+ """
141
+ if not isinstance(value, dict):
142
+ return value
143
+ if len(value) == 1:
144
+ ((tag, payload),) = value.items()
145
+ if tag == "$b":
146
+ return base64.b64decode(payload)
147
+ if tag == "$datetime":
148
+ return datetime.datetime.fromisoformat(payload)
149
+ if tag == "$date":
150
+ return datetime.date.fromisoformat(payload)
151
+ if tag == "$str":
152
+ return payload
153
+ raise ValueError("Unknown encoded value: {!r}".format(value))
154
+
155
+
156
+ def database_uri(path, mode):
157
+ """Return the URI and catalog name SQLite should open `path` with.
158
+
159
+ This mirrors what Harlequin's own SQLite adapter does with a local path,
160
+ but runs on the remote host, so that `~` and relative paths are resolved
161
+ there: relative to the remote user's home directory, which is the
162
+ working directory of a command run over SSH.
163
+
164
+ Args:
165
+ path: ``:memory:``, a ``file:`` URI, or a path.
166
+ mode: ``ro``, ``rw``, ``rwc`` or ``None``, appended as ``?mode=`` to
167
+ a plain path, like the local adapter does. A ``file:`` URI is
168
+ used as it is, except with ``ro`` (see `_file_uri`): unlike the
169
+ local adapter, read-only is never dropped.
170
+
171
+ Returns:
172
+ A ``(uri, name)`` tuple. `name` is the file's stem, the name an
173
+ attached database gets in the catalog.
174
+
175
+ Raises:
176
+ sqlite3.ProgrammingError: If `mode` is ``ro`` and a ``file:`` URI
177
+ asks for another mode.
178
+ """
179
+ if path == ":memory:":
180
+ return path, "memory"
181
+ if path.startswith("file:"):
182
+ return _file_uri(path, mode)
183
+ resolved = os.path.realpath(os.path.expanduser(path))
184
+ uri = "file:" + _quote_path(resolved)
185
+ if mode:
186
+ uri += "?mode=" + mode
187
+ return uri, os.path.splitext(os.path.basename(resolved))[0]
188
+
189
+
190
+ def _file_uri(uri, mode):
191
+ """Return a ``file:`` URI and its catalog name, read-only if `mode` is ``ro``.
192
+
193
+ For read-only, the URI is rebuilt rather than appended to, following
194
+ SQLite's own URI rules (https://sqlite.org/uri.html): the fragment, which
195
+ SQLite ignores, is dropped, so that ``mode=ro`` cannot end up inside it;
196
+ parameter names and values are percent-decoded before they are compared,
197
+ as SQLite decodes them; and any ``mode`` other than ``ro`` is refused.
198
+
199
+ Args:
200
+ uri: A URI starting with ``file:``.
201
+ mode: The requested mode; only ``ro`` changes the URI.
202
+
203
+ Returns:
204
+ A ``(uri, name)`` tuple, as `database_uri` returns.
205
+
206
+ Raises:
207
+ sqlite3.ProgrammingError: If `mode` is ``ro`` and the URI asks for
208
+ another mode.
209
+ """
210
+ base = uri.split("#", 1)[0]
211
+ location, _, query = base.partition("?")
212
+ name = os.path.splitext(os.path.basename(unquote(urlparse(location).path)))[0]
213
+ if mode != "ro":
214
+ return uri, name
215
+ params = [part for part in query.split("&") if part]
216
+ modes = [
217
+ unquote(value)
218
+ for key, value in (part.partition("=")[::2] for part in params)
219
+ if unquote(key) == "mode"
220
+ ]
221
+ if any(value != "ro" for value in modes):
222
+ raise sqlite3.ProgrammingError(
223
+ "Cannot open {} read-only: the URI asks for mode={}.".format(
224
+ uri, ",".join(modes)
225
+ )
226
+ )
227
+ if not modes:
228
+ params.append("mode=ro")
229
+ return location + "?" + "&".join(params), name
230
+
231
+
232
+ def _quote_path(path):
233
+ """Percent-encode the characters a ``file:`` URI path may not hold."""
234
+ from urllib.parse import quote
235
+
236
+ return quote(path, safe="/")
237
+
238
+
239
+ def _quote_identifier(name):
240
+ """Return `name` as a double-quoted SQLite identifier."""
241
+ return '"' + name.replace('"', '""') + '"'
242
+
243
+
244
+ def _error_type(exc):
245
+ """Return the name of the most specific sqlite3 class `exc` belongs to."""
246
+ for name in _SQLITE_ERRORS:
247
+ if isinstance(exc, getattr(sqlite3, name)):
248
+ return name
249
+ return "Error"
250
+
251
+
252
+ class Agent:
253
+ """Owns the connection and the open cursors, and answers requests.
254
+
255
+ Requests are handled one at a time, in the order they arrive, by
256
+ `serve()`. Only `interrupt()` is called from another thread.
257
+ """
258
+
259
+ def __init__(self, reader, writer):
260
+ """Set up an agent that reads requests and writes answers.
261
+
262
+ Args:
263
+ reader: A binary file to read request lines from (stdin).
264
+ writer: A binary file to write answer lines to (stdout).
265
+ """
266
+ self.reader = reader
267
+ self.writer = writer
268
+ self.conn = None
269
+ self.cursors = OrderedDict()
270
+ self.next_cursor = 1
271
+ self.requests = []
272
+ self.requests_ready = threading.Condition()
273
+ self.finished = False
274
+ self.running = None
275
+ """The id of the request being handled, guarded by `requests_ready`."""
276
+ self.cancelled = set()
277
+ """Ids of queued requests an interrupt arrived for before they ran."""
278
+ self.stop_running = False
279
+ """Set when an interrupt arrives for the running request; read by the
280
+ progress handler and before each statement starts."""
281
+
282
+ # -- plumbing ---------------------------------------------------------
283
+
284
+ def send(self, message):
285
+ """Write one message as a JSON line and flush it."""
286
+ line = json.dumps(message, separators=(",", ":"), ensure_ascii=False)
287
+ self.writer.write(line.encode("utf-8") + b"\n")
288
+ self.writer.flush()
289
+
290
+ def hello(self):
291
+ """Send the handshake message that tells the client what is here."""
292
+ self.send(
293
+ {
294
+ "hello": HELLO,
295
+ "protocol": PROTOCOL_VERSION,
296
+ "python": "{}.{}.{}".format(*sys.version_info[:3]),
297
+ "sqlite": sqlite3.sqlite_version,
298
+ "autocommit": hasattr(sqlite3.Connection, "autocommit"),
299
+ "load_extension": hasattr(sqlite3.Connection, "enable_load_extension"),
300
+ }
301
+ )
302
+
303
+ def read_loop(self):
304
+ """Read requests until end of input, in a thread of its own.
305
+
306
+ An ``interrupt`` request is acted on here, at once, because the
307
+ thread that would otherwise read it is busy running the statement it
308
+ is meant to stop. Every other request is queued for `serve()`.
309
+ """
310
+ try:
311
+ for line in self.reader:
312
+ if not line.strip():
313
+ continue
314
+ try:
315
+ request = json.loads(line.decode("utf-8"))
316
+ except ValueError:
317
+ sys.stderr.write("harlequin-sqlite-ssh agent: bad request line\n")
318
+ continue
319
+ with self.requests_ready:
320
+ if request.get("op") == "interrupt":
321
+ self.interrupt(request.get("target"))
322
+ continue
323
+ self.requests.append(request)
324
+ self.requests_ready.notify()
325
+ finally:
326
+ with self.requests_ready:
327
+ self.finished = True
328
+ self.requests_ready.notify()
329
+ # Nobody is left to read an answer: the client quit, was
330
+ # killed, or the SSH connection dropped. A statement still
331
+ # running must not hold the database (and its locks) any
332
+ # longer.
333
+ if self.running is not None:
334
+ self.stop_running = True
335
+ if self.conn is not None:
336
+ self.conn.interrupt()
337
+
338
+ def next_request(self):
339
+ """Return the next queued request, or None once input has ended.
340
+
341
+ The request becomes the `running` one before the lock is released,
342
+ so that an interrupt for it is either seen here (it was already in
343
+ `cancelled`) or acted on by `interrupt()` (it arrives later).
344
+ """
345
+ with self.requests_ready:
346
+ self.running = None
347
+ while not self.requests and not self.finished:
348
+ self.requests_ready.wait()
349
+ if not self.requests:
350
+ return None
351
+ request = self.requests.pop(0)
352
+ self.running = request.get("id")
353
+ self.stop_running = False
354
+ if self.running in self.cancelled:
355
+ self.cancelled.discard(self.running)
356
+ request = dict(request, cancelled=True)
357
+ return request
358
+
359
+ def serve(self):
360
+ """Answer requests until input ends or the client sends ``close``."""
361
+ while True:
362
+ request = self.next_request()
363
+ if request is None:
364
+ break
365
+ answer = self.handle(request)
366
+ try:
367
+ self.send(answer)
368
+ except (OSError, ValueError):
369
+ break # the client is gone
370
+ if request.get("op") == "close":
371
+ break
372
+ self.shutdown()
373
+
374
+ def handle(self, request):
375
+ """Run one request taken by `next_request()`; return its answer.
376
+
377
+ Args:
378
+ request: The decoded request.
379
+
380
+ Returns:
381
+ The answer message, a success or an error, never an exception:
382
+ an error in a request must not end the session.
383
+ """
384
+ request_id = request.get("id")
385
+ op = request.get("op")
386
+ self.release(request.get("release"))
387
+ handler = getattr(self, "op_" + str(op), None)
388
+ try:
389
+ if request.get("cancelled"):
390
+ raise sqlite3.OperationalError("interrupted")
391
+ self.check_stop()
392
+ if handler is None:
393
+ raise sqlite3.InterfaceError("Unknown operation: {!r}".format(op))
394
+ return {"id": request_id, "ok": True, "result": handler(request)}
395
+ except (sqlite3.Error, sqlite3.Warning) as e:
396
+ # Warning is not an Error: before Python 3.12, sqlite3 raises it
397
+ # for "You can only execute one statement at a time."
398
+ return {
399
+ "id": request_id,
400
+ "ok": False,
401
+ "error": {"type": _error_type(e), "message": str(e)},
402
+ }
403
+ except Exception as e:
404
+ return {
405
+ "id": request_id,
406
+ "ok": False,
407
+ "error": {
408
+ "type": "AgentError",
409
+ "message": "{}: {}".format(type(e).__name__, e),
410
+ },
411
+ }
412
+
413
+ def release(self, cursor_ids):
414
+ """Close the cursors the client let go of.
415
+
416
+ Every request may carry a ``release`` list: the ids of cursors the
417
+ client dropped without reading them to the end. Closing them ends
418
+ their statements, which releases the read lock they hold on the
419
+ database and lets SQLite clear an interrupt flag.
420
+ """
421
+ for cursor_id in cursor_ids or ():
422
+ cursor = self.cursors.pop(cursor_id, None)
423
+ if cursor is not None:
424
+ try:
425
+ cursor.close()
426
+ except sqlite3.Error:
427
+ pass
428
+
429
+ def interrupt(self, target):
430
+ """Stop request `target`: now if it is running, or before it starts.
431
+
432
+ Called by the reader thread with `requests_ready` held. An interrupt
433
+ for a request that already finished does nothing, so that it cannot
434
+ stop the next one.
435
+
436
+ Args:
437
+ target: The id of the request to stop.
438
+ """
439
+ if target is None:
440
+ return
441
+ if target == self.running:
442
+ self.stop_running = True
443
+ conn = self.conn
444
+ if conn is not None:
445
+ conn.interrupt()
446
+ elif any(queued.get("id") == target for queued in self.requests):
447
+ self.cancelled.add(target)
448
+
449
+ def check_stop(self):
450
+ """Fail with ``interrupted`` if the running request was cancelled.
451
+
452
+ Raises:
453
+ sqlite3.OperationalError: ``interrupted``, as SQLite raises it.
454
+ """
455
+ if self.stop_running:
456
+ raise sqlite3.OperationalError("interrupted")
457
+
458
+ def progress(self):
459
+ """SQLite progress handler: a non-zero answer aborts the statement."""
460
+ return 1 if self.stop_running else 0
461
+
462
+ def shutdown(self):
463
+ """Close every cursor and the connection."""
464
+ for cursor in self.cursors.values():
465
+ try:
466
+ cursor.close()
467
+ except sqlite3.Error:
468
+ pass
469
+ self.cursors.clear()
470
+ if self.conn is not None:
471
+ try:
472
+ self.conn.close()
473
+ except sqlite3.Error:
474
+ pass
475
+ self.conn = None
476
+
477
+ def connection(self):
478
+ """Return the open connection.
479
+
480
+ Raises:
481
+ sqlite3.ProgrammingError: If no ``open`` request succeeded yet.
482
+ """
483
+ if self.conn is None:
484
+ raise sqlite3.ProgrammingError("No database is open.")
485
+ return self.conn
486
+
487
+ # -- operations -------------------------------------------------------
488
+
489
+ def op_open(self, request):
490
+ """Open the primary database.
491
+
492
+ Request keys: `path`, `mode`, and the `sqlite3.connect()` arguments
493
+ `timeout`, `detect_types`, `isolation_level`, `cached_statements`.
494
+ Returns the URI that was opened and its catalog name.
495
+ """
496
+ if self.conn is not None:
497
+ raise sqlite3.ProgrammingError("A database is already open.")
498
+ uri, name = database_uri(request["path"], request.get("mode"))
499
+ conn = sqlite3.connect(
500
+ uri,
501
+ timeout=float(request.get("timeout", 5.0)),
502
+ detect_types=int(request.get("detect_types", 0)),
503
+ isolation_level=request.get("isolation_level", "DEFERRED"),
504
+ cached_statements=int(request.get("cached_statements", 128)),
505
+ check_same_thread=False,
506
+ uri=True,
507
+ )
508
+ conn.set_progress_handler(self.progress, PROGRESS_STEPS)
509
+ try:
510
+ # SQLite does not complain about a file that is not a database
511
+ # until something reads its header, which `pragma database_list`
512
+ # does not do; `pragma schema_version` does.
513
+ conn.execute("pragma schema_version").fetchall()
514
+ except sqlite3.Error:
515
+ conn.close()
516
+ raise
517
+ self.conn = conn
518
+ return {"uri": uri, "name": name}
519
+
520
+ def op_attach(self, request):
521
+ """Attach another database under the name its file stem gives.
522
+
523
+ Request keys: `path`, `mode`. Returns the URI and the schema name.
524
+ """
525
+ uri, name = database_uri(request["path"], request.get("mode"))
526
+ self.connection().execute(
527
+ "attach database ? as " + _quote_identifier(name), (uri,)
528
+ )
529
+ return {"uri": uri, "name": name}
530
+
531
+ def op_enable_load_extension(self, request):
532
+ """Allow or forbid `load_extension()`. Request key: `enabled`."""
533
+ self.connection().enable_load_extension(bool(request["enabled"]))
534
+ return None
535
+
536
+ def op_load_extension(self, request):
537
+ """Load a SQLite extension from a remote path. Request key: `path`."""
538
+ self.connection().load_extension(request["path"])
539
+ return None
540
+
541
+ def op_execute(self, request):
542
+ """Run one statement and return its first rows.
543
+
544
+ Request keys: `sql`, `params` (list of encoded values), `prefetch`
545
+ (how many rows to return right away).
546
+
547
+ Returns:
548
+ A dict with `description` (None for a statement that returns no
549
+ rows), `rowcount`, `lastrowid`, `rows` (up to `prefetch` encoded
550
+ rows), `done` (no rows remain), and `cursor` (the id to fetch the
551
+ rest with, or None when done).
552
+ """
553
+ params = [decode_value(p) for p in request.get("params") or []]
554
+ connection = self.connection()
555
+ self.check_stop()
556
+ cursor = connection.execute(request["sql"], params)
557
+ description = (
558
+ None
559
+ if cursor.description is None
560
+ else [column[0] for column in cursor.description]
561
+ )
562
+ rows, done = self._read(cursor, int(request.get("prefetch", 0)))
563
+ cursor_id = None
564
+ if done:
565
+ cursor.close()
566
+ else:
567
+ cursor_id = self._keep(cursor)
568
+ return {
569
+ "description": description,
570
+ "rowcount": cursor.rowcount,
571
+ "lastrowid": cursor.lastrowid,
572
+ "rows": rows,
573
+ "done": done,
574
+ "cursor": cursor_id,
575
+ }
576
+
577
+ def op_fetch(self, request):
578
+ """Return the next rows of an open cursor.
579
+
580
+ Request keys: `cursor`, `size` (a positive number of rows).
581
+ Returns `rows` and `done`; a cursor that is done is closed.
582
+ """
583
+ cursor_id = request["cursor"]
584
+ cursor = self.cursors.get(cursor_id)
585
+ if cursor is None:
586
+ raise sqlite3.ProgrammingError("Cannot operate on a closed cursor.")
587
+ self.cursors.move_to_end(cursor_id)
588
+ rows, done = self._read(cursor, int(request["size"]))
589
+ if done:
590
+ del self.cursors[cursor_id]
591
+ cursor.close()
592
+ return {"rows": rows, "done": done}
593
+
594
+ def op_close_cursor(self, request):
595
+ """Close a cursor the client no longer needs. Request key: `cursor`."""
596
+ cursor = self.cursors.pop(request["cursor"], None)
597
+ if cursor is not None:
598
+ cursor.close()
599
+ return None
600
+
601
+ def op_in_transaction(self, request):
602
+ """Return `Connection.in_transaction`."""
603
+ return self.connection().in_transaction
604
+
605
+ def op_get_autocommit(self, request):
606
+ """Return `Connection.autocommit` (Python 3.12 and later)."""
607
+ return _autocommit_to_json(self.connection().autocommit)
608
+
609
+ def op_set_autocommit(self, request):
610
+ """Set `Connection.autocommit` (Python 3.12 and later).
611
+
612
+ Request key: `value`, true, false, or the string ``legacy`` for
613
+ `sqlite3.LEGACY_TRANSACTION_CONTROL`.
614
+ """
615
+ value = request["value"]
616
+ if value == "legacy":
617
+ # only reached on Python 3.12+, where the constant exists; spelled
618
+ # with getattr so that type checkers set to 3.10 accept it
619
+ value = getattr(sqlite3, "LEGACY_TRANSACTION_CONTROL") # noqa: B009
620
+ self.connection().autocommit = value
621
+ return None
622
+
623
+ def op_commit(self, request):
624
+ """Commit the open transaction, if any."""
625
+ self.connection().commit()
626
+ return None
627
+
628
+ def op_rollback(self, request):
629
+ """Roll back the open transaction, if any."""
630
+ self.connection().rollback()
631
+ return None
632
+
633
+ def op_ping(self, request):
634
+ """Answer, so that the client can tell the agent is alive."""
635
+ return "pong"
636
+
637
+ def op_close(self, request):
638
+ """Close everything; `serve()` stops after answering."""
639
+ self.shutdown()
640
+ return None
641
+
642
+ # -- helpers ----------------------------------------------------------
643
+
644
+ def _read(self, cursor, size):
645
+ """Read up to `size` rows, and tell whether the cursor is exhausted.
646
+
647
+ One row more than `size` is never read: the cursor is known to be
648
+ exhausted only when `fetchmany` returns fewer rows than asked for, or
649
+ when `size` is 0 and the statement returns no rows at all.
650
+ """
651
+ if cursor.description is None:
652
+ return [], True
653
+ if size <= 0:
654
+ return [], False
655
+ rows = cursor.fetchmany(size)
656
+ encoded = [[encode_value(value) for value in row] for row in rows]
657
+ return encoded, len(rows) < size
658
+
659
+ def _keep(self, cursor):
660
+ """Store a cursor that still has rows; return its id."""
661
+ cursor_id = self.next_cursor
662
+ self.next_cursor += 1
663
+ self.cursors[cursor_id] = cursor
664
+ while len(self.cursors) > MAX_OPEN_CURSORS:
665
+ _, oldest = self.cursors.popitem(last=False)
666
+ oldest.close()
667
+ return cursor_id
668
+
669
+
670
+ def _autocommit_to_json(value):
671
+ """Return `Connection.autocommit` as JSON: true, false or ``legacy``."""
672
+ if value is True or value is False:
673
+ return value
674
+ return "legacy"
675
+
676
+
677
+ def main():
678
+ """Run the agent on stdin and stdout until the client goes away."""
679
+ agent = Agent(sys.stdin.buffer, sys.stdout.buffer)
680
+ agent.hello()
681
+ reader = threading.Thread(target=agent.read_loop, name="reader")
682
+ reader.daemon = True
683
+ reader.start()
684
+ agent.serve()
685
+ # Exit without interpreter finalization: the reader thread is blocked in a
686
+ # read on stdin and holds its lock, and finalization would wait for it,
687
+ # then abort with "could not acquire lock for <stdin>".
688
+ sys.stdout.flush()
689
+ os._exit(0)
690
+
691
+
692
+ if __name__ == "__main__":
693
+ main()