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,219 @@
1
+ """Tell local databases from remote ones, from the connection strings alone.
2
+
3
+ A connection string names a remote database in one of two spellings:
4
+
5
+ - ``ssh://[user@]host[:port]/absolute/path.db``, where a path starting with
6
+ ``/~`` is relative to the remote home directory
7
+ (``ssh://host/~/data/app.db``). Percent-escapes in the path are decoded.
8
+ - ``[user@]host:path``, as `scp` spells it, where a relative path is
9
+ relative to the remote home directory (``host:data/app.db``) and the path
10
+ may be a SQLite ``file:`` URI (``host:file:/srv/app.db?mode=ro``).
11
+
12
+ Everything else is a local database, handled exactly as Harlequin's own
13
+ SQLite adapter handles it: a path, ``:memory:``, or a ``file:`` URI. To open a
14
+ local file whose name contains a colon, prefix it with ``./``, as with `scp`.
15
+
16
+ The decision is made from the text alone, never by looking for a file, so
17
+ that the same string always means the same thing.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from collections.abc import Sequence
24
+ from dataclasses import dataclass
25
+ from urllib.parse import unquote, urlsplit
26
+
27
+ from harlequin.exception import HarlequinConfigError
28
+
29
+ CONFIG_ERROR_TITLE = "Harlequin could not initialize the sqlite-ssh adapter."
30
+
31
+ _SCP_LIKE = re.compile(
32
+ r"^(?:(?P<user>[^@/:\s]+)@)?(?P<host>\[[^\]/\s]+\]|[^@/:\[\]\s]+):(?P<path>.*)$",
33
+ re.DOTALL,
34
+ )
35
+ """``[user@]host:path``; an IPv6 host must be in brackets, like `scp` wants."""
36
+
37
+ _SAFE_HOST = re.compile(r"^[A-Za-z0-9._:%-]+$")
38
+ _SAFE_USER = re.compile(r"^[A-Za-z0-9._-]+$")
39
+ """What a host and a user may hold. `ssh` pastes them into the command of a
40
+ `ProxyCommand` (``%h``, ``%r``) and a connection string may come from a
41
+ `harlequin.toml` in the current directory, so no shell metacharacter gets
42
+ through. A host alias from `~/.ssh/config` covers any other need."""
43
+
44
+ _LOCAL_PREFIXES = ("/", "./", "../", "~", "file:", ":memory:", "\\")
45
+ """Starts that always mean a local database."""
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class RemoteTarget:
50
+ """The SSH destination of one or more remote databases."""
51
+
52
+ destination: str
53
+ """``host`` or ``user@host``, as `ssh` takes it: a host may be an alias
54
+ from `~/.ssh/config`."""
55
+
56
+ port: int | None = None
57
+ """The port from an ``ssh://`` connection string; None lets `ssh` decide."""
58
+
59
+ @property
60
+ def label(self) -> str:
61
+ """The destination as shown to users, with the port if one was given.
62
+
63
+ An IPv6 host is put back in brackets when a port follows it, so that
64
+ ``[::1]:2222`` and the host ``::1:2222`` read differently. For display
65
+ only: the cache key does not rely on it.
66
+ """
67
+ if self.port is None:
68
+ return self.destination
69
+ user, at, host = self.destination.rpartition("@")
70
+ if ":" in host:
71
+ host = f"[{host}]"
72
+ return f"{user}{at}{host}:{self.port}"
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class RemoteDatabase:
77
+ """One database file on a remote host."""
78
+
79
+ target: RemoteTarget
80
+ """Where it is."""
81
+
82
+ path: str
83
+ """Its path on the remote host, as the agent receives it: absolute,
84
+ relative to the remote home directory, ``~``-prefixed, or a ``file:``
85
+ URI."""
86
+
87
+
88
+ def parse_location(raw: str) -> str | RemoteDatabase:
89
+ """Return a remote database for a remote connection string, else `raw`.
90
+
91
+ Args:
92
+ raw: One connection string.
93
+
94
+ Returns:
95
+ A `RemoteDatabase`, or the string unchanged when it names a local
96
+ database.
97
+
98
+ Raises:
99
+ HarlequinConfigError: If the string is remote but malformed: no path,
100
+ a password, a bad port, a query string, or a destination `ssh`
101
+ would read as an option.
102
+ """
103
+ if raw.lower().startswith("ssh://"):
104
+ return _parse_ssh_url(raw)
105
+ if raw.startswith(_LOCAL_PREFIXES):
106
+ return raw
107
+ match = _SCP_LIKE.match(raw)
108
+ if match is None:
109
+ return raw
110
+ user, host, path = match.group("user", "host", "path")
111
+ if user is None and len(host) == 1:
112
+ # a Windows drive letter: C:\data\app.db, or C:app.db
113
+ return raw
114
+ if not path:
115
+ raise _config_error(
116
+ f"{raw!r} names a host but no database path after the colon."
117
+ )
118
+ return RemoteDatabase(
119
+ target=_target(raw, user, _strip_brackets(host), None), path=path
120
+ )
121
+
122
+
123
+ def split_conn_str(conn_str: Sequence[str]) -> tuple[RemoteTarget | None, list[str]]:
124
+ """Sort connection strings into local ones, or remote ones on one host.
125
+
126
+ Args:
127
+ conn_str: Every connection string Harlequin received.
128
+
129
+ Returns:
130
+ ``(None, strings)`` when all are local, the strings unchanged; or
131
+ ``(target, paths)`` when all are on the same remote host, with the
132
+ remote paths in the order given.
133
+
134
+ Raises:
135
+ HarlequinConfigError: If local and remote databases are mixed, or
136
+ remote databases are on different hosts. One SQLite connection
137
+ runs in one place, and attached databases must be reachable from
138
+ it.
139
+ """
140
+ parsed = [parse_location(raw) for raw in conn_str]
141
+ remote = [item for item in parsed if isinstance(item, RemoteDatabase)]
142
+ if not remote:
143
+ return None, list(conn_str)
144
+ if len(remote) != len(parsed):
145
+ local = [item for item in parsed if not isinstance(item, RemoteDatabase)]
146
+ raise _config_error(
147
+ "Cannot open local and remote databases in the same session: the "
148
+ f"local ones ({', '.join(map(str, local))}) would have to be "
149
+ "attached to a connection that runs on the remote host. Start one "
150
+ "Harlequin session for each."
151
+ )
152
+ targets = {item.target for item in remote}
153
+ if len(targets) > 1:
154
+ raise _config_error(
155
+ "Cannot open databases on more than one remote host in the same "
156
+ f"session ({', '.join(sorted(t.label for t in targets))}). Start one "
157
+ "Harlequin session for each host."
158
+ )
159
+ return remote[0].target, [item.path for item in remote]
160
+
161
+
162
+ def _parse_ssh_url(raw: str) -> RemoteDatabase:
163
+ """Parse ``ssh://[user@]host[:port]/path``."""
164
+ parts = urlsplit(raw)
165
+ if parts.query or parts.fragment:
166
+ raise _config_error(
167
+ f"{raw!r}: an ssh:// connection string takes no query or fragment. "
168
+ "To pass SQLite URI parameters, use the host:file:/path?... form."
169
+ )
170
+ if parts.password is not None:
171
+ raise _config_error(
172
+ f"{raw!r}: passwords are not supported. Use a key or an ssh-agent."
173
+ )
174
+ netloc = parts.netloc
175
+ user, _, hostport = netloc.rpartition("@")
176
+ try:
177
+ port = parts.port
178
+ except ValueError as e:
179
+ raise _config_error(f"{raw!r}: {e}.") from e
180
+ host = hostport
181
+ if port is not None:
182
+ host = hostport[: hostport.rfind(":")]
183
+ host = _strip_brackets(host)
184
+ if not host:
185
+ raise _config_error(f"{raw!r} names no host.")
186
+ path = unquote(parts.path)
187
+ if path.startswith("/~"):
188
+ path = path[1:]
189
+ if path in ("", "/", "~", "~/"):
190
+ raise _config_error(f"{raw!r} names no database path after the host.")
191
+ return RemoteDatabase(target=_target(raw, user or None, host, port), path=path)
192
+
193
+
194
+ def _target(raw: str, user: str | None, host: str, port: int | None) -> RemoteTarget:
195
+ """Build and check the destination `ssh` will be given."""
196
+ destination = f"{user}@{host}" if user else host
197
+ if (
198
+ not _SAFE_HOST.match(host)
199
+ or host.startswith("-")
200
+ or (user is not None and (not _SAFE_USER.match(user) or user.startswith("-")))
201
+ ):
202
+ raise _config_error(
203
+ f"{raw!r}: {destination!r} is not a valid SSH destination. A host may "
204
+ "hold letters, digits and . _ - : %, a user letters, digits and . _ -; "
205
+ "use an alias from ~/.ssh/config for anything else."
206
+ )
207
+ return RemoteTarget(destination=destination, port=port)
208
+
209
+
210
+ def _strip_brackets(host: str) -> str:
211
+ """``[::1]`` becomes ``::1``; other hosts are returned unchanged."""
212
+ if host.startswith("[") and host.endswith("]"):
213
+ return host[1:-1]
214
+ return host
215
+
216
+
217
+ def _config_error(message: str) -> HarlequinConfigError:
218
+ """A configuration error with this adapter's title."""
219
+ return HarlequinConfigError(msg=message, title=CONFIG_ERROR_TITLE)
File without changes
@@ -0,0 +1,359 @@
1
+ """Stand-ins for `sqlite3.Connection` and `sqlite3.Cursor` that run remotely.
2
+
3
+ Harlequin's SQLite adapter wraps a `sqlite3.Connection` in its
4
+ `HarlequinSqliteConnection`, and everything it does with it (queries, the
5
+ catalog, catalog search, completions, transactions, cancellation) goes
6
+ through a small part of the DB-API: `execute()`, the cursor's `description`
7
+ and `fetch*()` methods, `interrupt()`, `commit()`, `rollback()`,
8
+ `in_transaction`, `autocommit` and `close()`.
9
+
10
+ `RemoteConnection` implements exactly that part, forwarding each call to the
11
+ agent on the remote host. Handing one to `HarlequinSqliteConnection` gives a
12
+ remote database the behaviour of a local one, without copying any of
13
+ Harlequin's code. Errors are raised as the same `sqlite3` exception classes,
14
+ so the adapter's error handling works unchanged.
15
+
16
+ These classes are not a general-purpose DB-API driver: what Harlequin does
17
+ not call is not implemented.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import queue
23
+ import sqlite3
24
+ import threading
25
+ import weakref
26
+ from collections import deque
27
+ from collections.abc import Callable, Iterator, Sequence
28
+ from typing import Any
29
+
30
+ from harlequin_sqlite_ssh import _agent
31
+ from harlequin_sqlite_ssh.errors import ConnectionLostError
32
+ from harlequin_sqlite_ssh.transport import AgentProcess, Hello
33
+
34
+ PREFETCH_ROWS = 256
35
+ """Rows the agent returns with the answer to `execute()`, so that a small
36
+ result, such as every catalog query, costs a single round trip."""
37
+
38
+ FETCH_ROWS = 2000
39
+ """Rows asked for per round trip when more are wanted than are buffered."""
40
+
41
+ _CLOSED_CURSOR = "Cannot operate on a closed cursor."
42
+
43
+ _STOP_RELEASER = -1
44
+ """Put in the release queue to end the releaser thread."""
45
+
46
+ encode_value: Callable[[Any], Any] = _agent.encode_value
47
+ """The agent's value encoding (the agent module is untyped: it runs on 3.8)."""
48
+
49
+ decode_value: Callable[[Any], Any] = _agent.decode_value
50
+ """The agent's value decoding."""
51
+
52
+ Row = tuple[Any, ...]
53
+
54
+
55
+ class RemoteCursor:
56
+ """The rows of one statement, fetched from the agent as they are read.
57
+
58
+ Rows arrive in batches and wait in a local buffer. The agent closes the
59
+ remote cursor as soon as its last row has been sent. A cursor dropped
60
+ before that (Harlequin reads results up to its row limit, and never
61
+ closes a cursor) is released when it is garbage-collected, as a local
62
+ sqlite3 cursor is: until then its statement holds a read lock on the
63
+ remote database.
64
+ """
65
+
66
+ arraysize: int = 1
67
+ """Rows `fetchmany()` returns when called without a size, as in sqlite3."""
68
+
69
+ def __init__(self, connection: RemoteConnection, answer: dict[str, Any]) -> None:
70
+ """Build a cursor from the agent's answer to an ``execute`` request.
71
+
72
+ Args:
73
+ connection: The connection the statement ran on.
74
+ answer: The `result` of the ``execute`` request.
75
+ """
76
+ self._connection = connection
77
+ names = answer.get("description")
78
+ self.description: tuple[tuple[Any, ...], ...] | None = (
79
+ None
80
+ if names is None
81
+ else tuple((name, None, None, None, None, None, None) for name in names)
82
+ )
83
+ """Like `sqlite3.Cursor.description`: one 7-tuple per column, of
84
+ which only the name is set; None for a statement without rows."""
85
+ self.rowcount: int = int(answer.get("rowcount", -1))
86
+ """Like `sqlite3.Cursor.rowcount`."""
87
+ self.lastrowid: int | None = answer.get("lastrowid")
88
+ """Like `sqlite3.Cursor.lastrowid`."""
89
+ self._buffer: deque[Row] = deque(_decode_rows(answer.get("rows") or []))
90
+ self._done = bool(answer.get("done", True))
91
+ self._cursor_id: int | None = answer.get("cursor")
92
+ self._closed = False
93
+ self._interrupts = connection._interrupts
94
+ self._finalizer: weakref.finalize[Any, RemoteCursor] | None = None
95
+ if not self._done and self._cursor_id is not None:
96
+ # Called by the garbage collector, possibly in the middle of
97
+ # another request on this very thread: it only queues the id
98
+ # (SimpleQueue.put is reentrant), the releaser thread sends it.
99
+ self._finalizer = weakref.finalize(
100
+ self, connection._released.put, self._cursor_id
101
+ )
102
+
103
+ def fetchone(self) -> Row | None:
104
+ """Return the next row, or None when there are no more."""
105
+ self._check_open()
106
+ if not self._buffer:
107
+ self._fill(FETCH_ROWS)
108
+ if not self._buffer:
109
+ return None
110
+ return self._buffer.popleft()
111
+
112
+ def fetchmany(self, size: int | None = None) -> list[Row]:
113
+ """Return up to `size` more rows (`arraysize` by default).
114
+
115
+ A `size` below 1 returns every remaining row, as `sqlite3` does.
116
+ """
117
+ self._check_open()
118
+ wanted = self.arraysize if size is None else size
119
+ if wanted < 1:
120
+ return self.fetchall()
121
+ while len(self._buffer) < wanted and not self._done:
122
+ self._fill(max(wanted - len(self._buffer), 1))
123
+ return [self._buffer.popleft() for _ in range(min(wanted, len(self._buffer)))]
124
+
125
+ def fetchall(self) -> list[Row]:
126
+ """Return every remaining row."""
127
+ self._check_open()
128
+ while not self._done:
129
+ self._fill(FETCH_ROWS)
130
+ rows = list(self._buffer)
131
+ self._buffer.clear()
132
+ return rows
133
+
134
+ def close(self) -> None:
135
+ """Release the cursor here and on the remote host."""
136
+ if self._closed:
137
+ return
138
+ self._closed = True
139
+ self._buffer.clear()
140
+ if not self._done and self._cursor_id is not None:
141
+ self._set_done()
142
+ self._connection._request("close_cursor", cursor=self._cursor_id)
143
+
144
+ def __iter__(self) -> Iterator[Row]:
145
+ return self
146
+
147
+ def __next__(self) -> Row:
148
+ row = self.fetchone()
149
+ if row is None:
150
+ raise StopIteration
151
+ return row
152
+
153
+ def _fill(self, size: int) -> None:
154
+ """Ask the agent for up to `size` more rows into the buffer.
155
+
156
+ Raises:
157
+ sqlite3.OperationalError: ``interrupted``, if the connection was
158
+ interrupted since this cursor was created. Locally, an
159
+ interrupt also stops every statement still being read; here
160
+ it would otherwise be lost when it comes between two fetches.
161
+ """
162
+ if self._done or self._cursor_id is None:
163
+ self._set_done()
164
+ return
165
+ if self._connection._interrupts != self._interrupts:
166
+ self._set_done()
167
+ self._connection._released.put(self._cursor_id)
168
+ raise sqlite3.OperationalError("interrupted")
169
+ answer = self._connection._request(
170
+ "fetch", cursor=self._cursor_id, size=min(size, FETCH_ROWS)
171
+ )
172
+ self._buffer.extend(_decode_rows(answer.get("rows") or []))
173
+ if answer.get("done"):
174
+ self._set_done()
175
+
176
+ def _set_done(self) -> None:
177
+ """Mark the remote cursor as gone: nothing is left to release."""
178
+ self._done = True
179
+ if self._finalizer is not None:
180
+ self._finalizer.detach()
181
+ self._finalizer = None
182
+
183
+ def _check_open(self) -> None:
184
+ if self._closed:
185
+ raise sqlite3.ProgrammingError(_CLOSED_CURSOR)
186
+
187
+
188
+ class RemoteConnection:
189
+ """A SQLite connection held open by the agent on a remote host."""
190
+
191
+ def __init__(self, process: AgentProcess, hello: Hello) -> None:
192
+ """Wrap a started agent; the database is opened by `open()`.
193
+
194
+ Args:
195
+ process: The running agent.
196
+ hello: What the agent reported in its handshake.
197
+ """
198
+ self.process = process
199
+ self.hello = hello
200
+ self._interrupts = 0
201
+ """How many times `interrupt()` was called; cursors compare it."""
202
+ self._released: queue.SimpleQueue[int] = queue.SimpleQueue()
203
+ """Ids of cursors dropped before their last row, to close remotely."""
204
+ threading.Thread(
205
+ target=self._release_loop,
206
+ name="harlequin-sqlite-ssh-releaser",
207
+ daemon=True,
208
+ ).start()
209
+
210
+ # -- set-up, used by the adapter -----------------------------------------
211
+
212
+ def open(self, path: str, mode: str | None, **connect_arguments: Any) -> str:
213
+ """Open the primary database; return the URI SQLite opened.
214
+
215
+ Args:
216
+ path: The remote path (see `RemoteDatabase.path`).
217
+ mode: ``ro``, ``rw``, ``rwc`` or None.
218
+ **connect_arguments: `timeout`, `detect_types`,
219
+ `isolation_level` and `cached_statements`, as
220
+ `sqlite3.connect()` takes them.
221
+ """
222
+ result = self._request("open", path=path, mode=mode, **connect_arguments)
223
+ return str(result["uri"])
224
+
225
+ def attach(self, path: str, mode: str | None) -> str:
226
+ """Attach another database, named after its file stem; return its URI."""
227
+ result = self._request("attach", path=path, mode=mode)
228
+ return str(result["uri"])
229
+
230
+ def enable_load_extension(self, enabled: bool) -> None:
231
+ """Like `sqlite3.Connection.enable_load_extension`."""
232
+ self._request("enable_load_extension", enabled=enabled)
233
+
234
+ def load_extension(self, path: str) -> None:
235
+ """Like `sqlite3.Connection.load_extension`, with a remote path."""
236
+ self._request("load_extension", path=path)
237
+
238
+ # -- the part of sqlite3.Connection Harlequin uses -------------------------
239
+
240
+ def execute(self, sql: str, parameters: Sequence[Any] = ()) -> RemoteCursor:
241
+ """Run one statement on the remote host and return its cursor.
242
+
243
+ Raises:
244
+ sqlite3.Error: As `sqlite3.Connection.execute` would.
245
+ """
246
+ answer = self._request(
247
+ "execute",
248
+ sql=sql,
249
+ params=[encode_value(value) for value in parameters],
250
+ prefetch=PREFETCH_ROWS,
251
+ )
252
+ return RemoteCursor(self, answer)
253
+
254
+ def interrupt(self) -> None:
255
+ """Abort the statement running on the remote host, if any.
256
+
257
+ Also makes every cursor created before this call fail with
258
+ ``interrupted`` on its next fetch from the agent, as statements that
259
+ are still being read do with a local connection.
260
+ """
261
+ self._interrupts += 1
262
+ self.process.interrupt()
263
+
264
+ def commit(self) -> None:
265
+ """Commit the open transaction, if any."""
266
+ self._request("commit")
267
+
268
+ def rollback(self) -> None:
269
+ """Roll back the open transaction, if any."""
270
+ self._request("rollback")
271
+
272
+ @property
273
+ def in_transaction(self) -> bool:
274
+ """Like `sqlite3.Connection.in_transaction`; asks the remote host."""
275
+ return bool(self._request("in_transaction"))
276
+
277
+ def close(self) -> None:
278
+ """Close the database and end the SSH session. Never raises."""
279
+ self._released.put(_STOP_RELEASER)
280
+ self.process.close()
281
+
282
+ def _request(self, op: str, release: Sequence[int] = (), **arguments: Any) -> Any:
283
+ """Send one request to the agent and return its result.
284
+
285
+ Cursors waiting to be released travel with it, so that the agent
286
+ closes them before it runs the request.
287
+ """
288
+ pending = [*release, *self._take_released()]
289
+ if pending:
290
+ arguments["release"] = pending
291
+ return self.process.request(op, **arguments)
292
+
293
+ def _take_released(self) -> list[int]:
294
+ """Empty the release queue; return the cursor ids it held."""
295
+ ids: list[int] = []
296
+ while True:
297
+ try:
298
+ cursor_id = self._released.get_nowait()
299
+ except queue.Empty:
300
+ return ids
301
+ if cursor_id == _STOP_RELEASER:
302
+ # not ours to consume: the releaser thread must see it
303
+ self._released.put(cursor_id)
304
+ return ids
305
+ ids.append(cursor_id)
306
+
307
+ def _release_loop(self) -> None:
308
+ """Release dropped cursors without waiting for the next query.
309
+
310
+ Runs in a thread of its own, so that a cursor dropped while the
311
+ session is idle does not keep its read lock until the user's next
312
+ query.
313
+ """
314
+ while True:
315
+ cursor_id = self._released.get()
316
+ if cursor_id == _STOP_RELEASER:
317
+ return
318
+ try:
319
+ self._request("ping", release=[cursor_id])
320
+ except ConnectionLostError:
321
+ return
322
+ except sqlite3.Error:
323
+ continue
324
+
325
+
326
+ class RemoteAutocommitConnection(RemoteConnection):
327
+ """A remote connection whose Python has `Connection.autocommit` (3.12+).
328
+
329
+ A separate class, because Harlequin's adapter decides whether to offer
330
+ its Auto/Manual transaction modes with ``hasattr(conn, "autocommit")``:
331
+ the attribute exists exactly when the remote sqlite3 module has it.
332
+ """
333
+
334
+ @property
335
+ def autocommit(self) -> bool | int:
336
+ """Like `sqlite3.Connection.autocommit`; asks the remote host."""
337
+ value = self._request("get_autocommit")
338
+ if value == "legacy":
339
+ return int(getattr(sqlite3, "LEGACY_TRANSACTION_CONTROL", -1))
340
+ return bool(value)
341
+
342
+ @autocommit.setter
343
+ def autocommit(self, value: bool | int) -> None:
344
+ if value is True or value is False:
345
+ self._request("set_autocommit", value=value)
346
+ else:
347
+ self._request("set_autocommit", value="legacy")
348
+
349
+
350
+ def connection_for(process: AgentProcess, hello: Hello) -> RemoteConnection:
351
+ """Return the connection class that matches the remote Python."""
352
+ if hello.autocommit:
353
+ return RemoteAutocommitConnection(process, hello)
354
+ return RemoteConnection(process, hello)
355
+
356
+
357
+ def _decode_rows(rows: list[list[Any]]) -> list[Row]:
358
+ """Turn encoded rows from the agent into tuples of Python values."""
359
+ return [tuple(decode_value(value) for value in row) for row in rows]