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,362 @@
1
+ """The Harlequin adapter: SQLite on this machine, or on a remote host over SSH.
2
+
3
+ `HarlequinSqliteSshAdapter` is Harlequin's own SQLite adapter
4
+ (`harlequin_sqlite.HarlequinSqliteAdapter`) with one addition: when the
5
+ connection strings name a remote host (see `locations`), the database is
6
+ opened there, by an agent started over SSH (see `transport`), and the
7
+ connection Harlequin works with forwards every call to it (see `remote`).
8
+
9
+ For local databases nothing changes: `connect()` is the parent's, line for
10
+ line. For remote ones, `connect()` follows the same steps in the same order
11
+ (open, attach, extensions, init script), with the same options and error
12
+ messages, so that the two behave alike. The connection object Harlequin
13
+ receives is the parent's `HarlequinSqliteConnection` in both cases, so the
14
+ catalog, catalog search, completions, transactions and cancellation are
15
+ Harlequin's own code.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import sqlite3
22
+ from collections.abc import Sequence
23
+ from pathlib import Path
24
+ from typing import Any, Literal, cast
25
+
26
+ from harlequin.exception import HarlequinConfigError, HarlequinConnectionError
27
+ from harlequin.options import HarlequinAdapterOption
28
+ from harlequin_sqlite.adapter import (
29
+ IN_MEMORY_CONN_STR,
30
+ HarlequinSqliteAdapter,
31
+ HarlequinSqliteConnection,
32
+ )
33
+
34
+ from harlequin_sqlite_ssh import transport
35
+ from harlequin_sqlite_ssh.cli_options import SQLITE_SSH_OPTIONS
36
+ from harlequin_sqlite_ssh.errors import AgentStartError
37
+ from harlequin_sqlite_ssh.locations import CONFIG_ERROR_TITLE, split_conn_str
38
+ from harlequin_sqlite_ssh.remote import RemoteConnection, connection_for
39
+
40
+ CONNECT_ERROR_TITLE = "SQLite couldn't connect to your database."
41
+ """The title Harlequin's SQLite adapter uses; kept for remote databases."""
42
+
43
+ START_ERROR_TITLE = "Harlequin could not start SQLite on the remote host."
44
+
45
+
46
+ class HarlequinSqliteSshAdapter(HarlequinSqliteAdapter):
47
+ """Harlequin's SQLite adapter, for local files and files on SSH hosts.
48
+
49
+ Select it with ``harlequin -a sqlite-ssh`` or ``adapter = "sqlite-ssh"`` in
50
+ a `harlequin.toml` profile.
51
+ """
52
+
53
+ ADAPTER_OPTIONS: list[HarlequinAdapterOption] | None = SQLITE_SSH_OPTIONS
54
+ IMPLEMENTS_CANCEL = True
55
+ IMPLEMENTS_CATALOG_SEARCH = True
56
+ IMPLEMENTS_READ_ONLY = True
57
+ ADAPTER_DETAILS = (
58
+ "The SQLite adapter of Harlequin core, extended by harlequin-sqlite-ssh "
59
+ "to open databases on remote hosts over SSH "
60
+ "(ssh://[user@]host[:port]/path or [user@]host:path)."
61
+ )
62
+
63
+ def __init__(
64
+ self,
65
+ conn_str: Sequence[str],
66
+ init_path: Path | str | None = None,
67
+ no_init: bool | str = False,
68
+ read_only: bool = False,
69
+ mode: Literal["ro", "rw", "rwc", "memory"] | None = None,
70
+ lock_timeout: str | float = 5.0,
71
+ detect_types: str | int = 0,
72
+ isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = None,
73
+ cached_statements: str | int = 128,
74
+ extension: list[str] | None = None,
75
+ remote_python: str | None = None,
76
+ remote_ssh_option: Sequence[str] | str | None = None,
77
+ remote_timeout: str | float | None = None,
78
+ **options: Any,
79
+ ) -> None:
80
+ """Read the options; nothing is opened until `connect()`.
81
+
82
+ Args:
83
+ conn_str: Connection strings: all local, or all on one remote
84
+ host (see `locations`).
85
+ init_path: A SQLite init script, ``~/.sqliterc`` by default. For
86
+ a remote database it is read here and run there, so paths in
87
+ its ``.open`` and ``.load`` commands are remote paths.
88
+ no_init: Skip the init script.
89
+ read_only: Open every database with ``mode=ro``.
90
+ mode: ``ro``, ``rw``, ``rwc`` or ``memory``, as for Harlequin's
91
+ SQLite adapter.
92
+ lock_timeout: Seconds to wait for a locked database.
93
+ detect_types: `sqlite3.connect()`'s `detect_types`, applied by
94
+ the Python that opens the database.
95
+ isolation_level: `sqlite3.connect()`'s legacy
96
+ `isolation_level`. Left unset for a remote Python older than
97
+ 3.12, the remote connection runs in autocommit mode (see
98
+ `_prepare_remote`).
99
+ cached_statements: `sqlite3.connect()`'s `cached_statements`.
100
+ extension: Extensions to load; remote paths for a remote
101
+ database.
102
+ remote_python: The remote interpreter (default ``python3``).
103
+ remote_ssh_option: ``Keyword=value`` options for `ssh`, from the
104
+ allow-list in `transport.ALLOWED_SSH_OPTIONS`.
105
+ remote_timeout: Seconds to wait for the agent to start
106
+ (default 60).
107
+ **options: Options of other adapters, ignored, as Harlequin
108
+ requires.
109
+
110
+ Raises:
111
+ HarlequinConfigError: If an option has a bad value, or the
112
+ connection strings mix local and remote databases or name
113
+ several hosts.
114
+ """
115
+ self.target, paths = split_conn_str(conn_str)
116
+ self.isolation_level_given = isolation_level
117
+ super().__init__(
118
+ # a tuple, as Harlequin passes it: the parent compares it to tuples
119
+ conn_str=tuple(paths),
120
+ init_path=init_path,
121
+ no_init=no_init,
122
+ read_only=read_only,
123
+ mode=mode,
124
+ lock_timeout=lock_timeout,
125
+ detect_types=detect_types,
126
+ isolation_level=isolation_level or "DEFERRED",
127
+ cached_statements=cached_statements,
128
+ # remote extensions are checked against the remote Python, later
129
+ extension=extension if self.target is None else None,
130
+ **options,
131
+ )
132
+ if self.target is None:
133
+ return
134
+ self.extensions = list(extension or [])
135
+ try:
136
+ self.remote_python = transport.validate_python(
137
+ transport.DEFAULT_PYTHON
138
+ if remote_python is None
139
+ else str(remote_python)
140
+ )
141
+ self.remote_ssh_options = [
142
+ transport.validate_ssh_option(str(option))
143
+ for option in _as_list(remote_ssh_option)
144
+ ]
145
+ self.remote_timeout = transport.validate_timeout(
146
+ transport.DEFAULT_TIMEOUT if remote_timeout is None else remote_timeout
147
+ )
148
+ except (TypeError, ValueError) as e:
149
+ raise HarlequinConfigError(msg=str(e), title=CONFIG_ERROR_TITLE) from e
150
+
151
+ @property
152
+ def connection_id(self) -> str | None:
153
+ """A stable id for Harlequin's catalog and history cache.
154
+
155
+ Local databases get the parent's id. Remote ones are identified by
156
+ host and paths as given, since they cannot be resolved before
157
+ connecting; an in-memory database gets none, as locally.
158
+
159
+ Everything that decides which files are opened is in it, each in a
160
+ field of its own: the destination, the port, the `ssh` options (a
161
+ `Port` or `HostName` option changes the server) and the paths, which
162
+ keep their order, because the first one is ``main``. Serialized as
163
+ JSON, so that no value can be mistaken for two. Settings in
164
+ `~/.ssh/config` are not known here, and are not part of it.
165
+ """
166
+ if self.target is None:
167
+ return super().connection_id
168
+ if self.conn_str == IN_MEMORY_CONN_STR:
169
+ return ""
170
+ return "sqlite-ssh:" + json.dumps(
171
+ {
172
+ "destination": self.target.destination,
173
+ "port": self.target.port,
174
+ "ssh_options": list(self.remote_ssh_options),
175
+ "paths": list(self.conn_str),
176
+ },
177
+ separators=(",", ":"),
178
+ )
179
+
180
+ def connect(self) -> HarlequinSqliteConnection:
181
+ """Open the databases and return Harlequin's SQLite connection.
182
+
183
+ Raises:
184
+ HarlequinConnectionError: If SSH, the remote agent, SQLite, an
185
+ extension or the init script fails.
186
+ """
187
+ if self.target is None:
188
+ return super().connect()
189
+ return self._connect_remote()
190
+
191
+ # -- remote ---------------------------------------------------------------
192
+
193
+ def _connect_remote(self) -> HarlequinSqliteConnection:
194
+ """`connect()` for a remote host: the parent's steps, over SSH."""
195
+ assert self.target is not None
196
+ if self.read_only and self.mode is not None and self.mode != "ro":
197
+ raise HarlequinConnectionError(
198
+ "Cannot specify readonly flag and a connection mode."
199
+ )
200
+ mode = "ro" if self.read_only else self.mode
201
+ if mode == "memory":
202
+ mode = None
203
+
204
+ conn = self._start_agent()
205
+ try:
206
+ init_message = self._prepare_remote(conn, mode)
207
+ except BaseException:
208
+ conn.close()
209
+ raise
210
+ hello = conn.hello
211
+ if hello.noise:
212
+ init_message = "\n".join(
213
+ filter(
214
+ None,
215
+ [
216
+ init_message,
217
+ f"Ignored {len(hello.noise)} line(s) your remote shell "
218
+ "printed on startup.",
219
+ ],
220
+ )
221
+ )
222
+ self.ADAPTER_DRIVER_DETAILS = (
223
+ f"Connected to `{self.target.label}` over SSH: remote Python "
224
+ f"{hello.python}, SQLite {hello.sqlite}.\n\n"
225
+ f"Databases: {', '.join(f'`{path}`' for path in self.conn_str)}"
226
+ )
227
+ return HarlequinSqliteConnection(
228
+ # a duck-typed stand-in: see harlequin_sqlite_ssh.remote
229
+ conn=cast(sqlite3.Connection, conn),
230
+ init_message=init_message,
231
+ )
232
+
233
+ def _start_agent(self) -> RemoteConnection:
234
+ """Run `ssh`, start the agent, and return its connection."""
235
+ assert self.target is not None
236
+ keepalive = transport.needs_keepalive(self.target, self.remote_ssh_options)
237
+ argv = transport.session_argv(
238
+ self.target, self.remote_python, self.remote_ssh_options, keepalive
239
+ )
240
+ try:
241
+ process = transport.AgentProcess(argv, self.target.label)
242
+ hello = process.handshake(transport.agent_payload(), self.remote_timeout)
243
+ except AgentStartError as e:
244
+ raise HarlequinConnectionError(msg=str(e), title=START_ERROR_TITLE) from e
245
+ return connection_for(process, hello)
246
+
247
+ def _prepare_remote(self, conn: RemoteConnection, mode: str | None) -> str:
248
+ """Open, attach, load extensions and run the init script, remotely.
249
+
250
+ Returns:
251
+ The message Harlequin shows once connected (init script count).
252
+ """
253
+ primary, *others = self.conn_str
254
+ isolation_level: str | None = self.isolation_level
255
+ if not conn.hello.autocommit and self.isolation_level_given is None:
256
+ # Before Python 3.12, Harlequin offers no Auto/Manual modes and
257
+ # nothing ever commits: with sqlite3's default implicit
258
+ # transactions, a write would be rolled back when the session
259
+ # ends. Autocommit is what the Auto mode means on 3.12+.
260
+ isolation_level = None
261
+ try:
262
+ conn.open(
263
+ primary,
264
+ mode,
265
+ timeout=self.lock_timeout,
266
+ detect_types=self.detect_types,
267
+ isolation_level=isolation_level,
268
+ cached_statements=self.cached_statements,
269
+ )
270
+ except sqlite3.Error as e:
271
+ raise HarlequinConnectionError(
272
+ msg=f"{e} ({primary} on {conn.process.description})",
273
+ title=CONNECT_ERROR_TITLE,
274
+ ) from e
275
+
276
+ # Python 3.12 added an autocommit attribute, which should be turned on
277
+ # by default (as the parent does)
278
+ if conn.hello.autocommit:
279
+ conn.autocommit = True # type: ignore[attr-defined]
280
+
281
+ for path in others:
282
+ try:
283
+ conn.attach(path, mode)
284
+ except sqlite3.Error as e:
285
+ raise HarlequinConnectionError(
286
+ msg=f"{e} ({path} on {conn.process.description})",
287
+ title=CONNECT_ERROR_TITLE,
288
+ ) from e
289
+
290
+ self._load_remote_extensions(conn)
291
+ return self._run_remote_init_script(conn)
292
+
293
+ def _load_remote_extensions(self, conn: RemoteConnection) -> None:
294
+ """Enable extension loading where possible, and load the requested ones."""
295
+ if self.extensions and not conn.hello.load_extension:
296
+ raise HarlequinConnectionError(
297
+ title="SQLite couldn't load your extension.",
298
+ msg=(
299
+ "The adapter received --extension, but the Python on "
300
+ f"{conn.process.description} cannot load SQLite extensions. "
301
+ "See https://harlequin.sh/docs/sqlite/extensions"
302
+ ),
303
+ )
304
+ try:
305
+ if conn.hello.load_extension:
306
+ conn.enable_load_extension(True)
307
+ for extension in self.extensions:
308
+ conn.load_extension(extension)
309
+ except sqlite3.Error as e:
310
+ raise HarlequinConnectionError(
311
+ str(e), title="SQLite couldn't load your extension."
312
+ ) from e
313
+
314
+ def _run_remote_init_script(self, conn: RemoteConnection) -> str:
315
+ """Run the local init script on the remote database.
316
+
317
+ The same parsing as the parent (`_split_script`,
318
+ `_rewrite_init_command`) and the same messages. Paths in ``.open`` and
319
+ ``.load`` commands are remote paths.
320
+
321
+ Returns:
322
+ The init message, or the empty string when nothing ran.
323
+ """
324
+ if self.init_path is None or self.no_init:
325
+ return ""
326
+ init_script = self._read_init_script(self.init_path)
327
+ count = 0
328
+ for command in self._split_script(init_script):
329
+ rewritten_command = self._rewrite_init_command(command)
330
+ for cmd in rewritten_command.split(";"):
331
+ if not cmd.strip():
332
+ continue
333
+ try:
334
+ conn.execute(cmd)
335
+ except sqlite3.Error as e:
336
+ raise HarlequinConnectionError(
337
+ f"Attempted to execute script at {self.init_path}. "
338
+ f"Contents:\n{command}\nRewritten to:\n"
339
+ f"{rewritten_command}\nCurrently executing:\n"
340
+ f"{cmd}\nError:\n{e}",
341
+ title="SQLite could not execute your initialization script.",
342
+ ) from e
343
+ count += 1
344
+ if count == 0:
345
+ return ""
346
+ return (
347
+ f"Executed {count} {'command' if count == 1 else 'commands'} "
348
+ f"from {self.init_path} on {conn.process.description}"
349
+ )
350
+
351
+
352
+ def _as_list(value: Sequence[str] | str | None) -> list[str]:
353
+ """A list option's value, whether it came from the CLI, TOML or code.
354
+
355
+ The CLI gives a tuple, a TOML profile a list, and a single string is
356
+ accepted as a one-item list.
357
+ """
358
+ if value is None:
359
+ return []
360
+ if isinstance(value, str):
361
+ return [value]
362
+ return list(value)
@@ -0,0 +1,105 @@
1
+ """The options the sqlite-ssh adapter declares to Harlequin.
2
+
3
+ Every option of Harlequin's own SQLite adapter is declared unchanged, so a
4
+ profile written for ``adapter = "sqlite"`` keeps working with
5
+ ``adapter = "sqlite-ssh"``. Three options are added for remote databases, all
6
+ prefixed ``remote-``: Harlequin reserves the ``ssh_*`` keys of a profile for
7
+ its own SSH tunnels and removes them before an adapter sees its options.
8
+
9
+ In `harlequin.toml`, an option is spelled with underscores::
10
+
11
+ [profiles.prod-db]
12
+ adapter = "sqlite-ssh"
13
+ conn_str = ["ssh://deploy@db.example.com/srv/app/app.db"]
14
+ read_only = true
15
+ remote_python = "/usr/bin/python3.11"
16
+ remote_ssh_option = ["IdentityFile=~/.ssh/deploy_ed25519", "ConnectTimeout=10"]
17
+ remote_timeout = "30"
18
+
19
+ On the command line, with dashes: ``--remote-python``,
20
+ ``--remote-ssh-option`` (repeatable) and ``--remote-timeout``.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from harlequin.options import HarlequinAdapterOption, ListOption, TextOption
26
+ from harlequin_sqlite.cli_options import SQLITE_OPTIONS
27
+
28
+ from harlequin_sqlite_ssh.transport import (
29
+ DEFAULT_PYTHON,
30
+ DEFAULT_TIMEOUT,
31
+ validate_python,
32
+ validate_timeout,
33
+ )
34
+
35
+
36
+ def _python_validator(raw: str | None) -> tuple[bool, str]:
37
+ """Accept an executable name or path for `remote-python`."""
38
+ if raw is None:
39
+ return True, ""
40
+ try:
41
+ validate_python(raw)
42
+ except ValueError as e:
43
+ return False, str(e)
44
+ return True, ""
45
+
46
+
47
+ def _timeout_validator(raw: str | None) -> tuple[bool, str]:
48
+ """Accept a finite, positive number of seconds for `remote-timeout`."""
49
+ if raw is None:
50
+ return True, ""
51
+ try:
52
+ validate_timeout(raw)
53
+ except ValueError as e:
54
+ return False, str(e)
55
+ return True, ""
56
+
57
+
58
+ remote_python = TextOption(
59
+ name="remote-python",
60
+ description=(
61
+ "The Python interpreter to run on the remote host, by name or path. "
62
+ "It needs Python 3.8 or later and its standard sqlite3 module; nothing "
63
+ f"is installed on the remote host. Default: {DEFAULT_PYTHON}."
64
+ ),
65
+ default=DEFAULT_PYTHON,
66
+ validator=_python_validator,
67
+ )
68
+
69
+ remote_ssh_option = ListOption(
70
+ name="remote-ssh-option",
71
+ description=(
72
+ "An option for ssh, as ssh -o takes it, e.g. IdentityFile=~/.ssh/id_db "
73
+ "or ProxyJump=bastion. Repeat for more than one. Options that run a local "
74
+ "command, weaken host key checking or use a local socket are refused; set "
75
+ "them in ~/.ssh/config. "
76
+ "ssh always runs with BatchMode=yes, because Harlequin cannot show a "
77
+ "password or passphrase prompt."
78
+ ),
79
+ )
80
+ """Checked by the adapter when it starts (a list option has no validator
81
+ here), with `transport.validate_ssh_option`."""
82
+
83
+ remote_timeout = TextOption(
84
+ name="remote-timeout",
85
+ description=(
86
+ "Seconds to wait for the SSH connection and the remote agent to start. "
87
+ f"Default: {DEFAULT_TIMEOUT:g}."
88
+ ),
89
+ validator=_timeout_validator,
90
+ )
91
+
92
+ REMOTE_OPTIONS: list[HarlequinAdapterOption] = [
93
+ remote_python,
94
+ remote_ssh_option,
95
+ remote_timeout,
96
+ ]
97
+ """The options this adapter adds to the SQLite adapter's."""
98
+
99
+ SQLITE_SSH_OPTIONS: list[HarlequinAdapterOption] = [*SQLITE_OPTIONS, *REMOTE_OPTIONS]
100
+ """Everything the adapter declares: SQLite's options, then the remote ones.
101
+
102
+ Read from `harlequin_sqlite` rather than copied, so that the set follows
103
+ Harlequin's: it already depends on the local Python (`extension` exists only
104
+ where sqlite3 can load extensions, `isolation-level` only before 3.12).
105
+ """
@@ -0,0 +1,71 @@
1
+ """Exceptions raised by the remote side of the adapter.
2
+
3
+ Harlequin's SQLite adapter, whose connection and cursor classes this package
4
+ reuses, catches `sqlite3.Error` around every call it makes. So every failure
5
+ that can happen after the connection is open is raised as a `sqlite3.Error`
6
+ subclass: an error SQLite raised on the remote host comes back as the very
7
+ same class, and a failure of the SSH session itself is an `InterfaceError`.
8
+ Failures while connecting are `AgentStartError`, which the adapter turns into
9
+ a `HarlequinConnectionError`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import sqlite3
15
+ from collections.abc import Mapping
16
+ from typing import Any
17
+
18
+ _WIRE_TYPES: dict[str, type[sqlite3.Error]] = {
19
+ "Error": sqlite3.Error,
20
+ "InterfaceError": sqlite3.InterfaceError,
21
+ "DatabaseError": sqlite3.DatabaseError,
22
+ "DataError": sqlite3.DataError,
23
+ "OperationalError": sqlite3.OperationalError,
24
+ "IntegrityError": sqlite3.IntegrityError,
25
+ "InternalError": sqlite3.InternalError,
26
+ "ProgrammingError": sqlite3.ProgrammingError,
27
+ "NotSupportedError": sqlite3.NotSupportedError,
28
+ # Before Python 3.12, sqlite3 raised Warning, which is not an Error, for
29
+ # "You can only execute one statement at a time."; 3.12 made that a
30
+ # ProgrammingError. A remote Python may be older than the local one, so
31
+ # the error is raised as the newer class, which Harlequin catches.
32
+ "Warning": sqlite3.ProgrammingError,
33
+ }
34
+ """sqlite3 exception classes by the name the agent reports them under."""
35
+
36
+
37
+ class AgentStartError(Exception):
38
+ """The agent could not be started or did not complete its handshake."""
39
+
40
+
41
+ class ConnectionLostError(sqlite3.InterfaceError):
42
+ """The SSH session ended, or sent something that is not the protocol.
43
+
44
+ Nothing can be sent over this connection any more: reconnect.
45
+ """
46
+
47
+
48
+ class RemoteAgentError(sqlite3.InterfaceError):
49
+ """The agent failed on a request for a reason other than SQLite.
50
+
51
+ That is a bug in this package; the message names the Python exception the
52
+ agent caught. The session itself is still usable.
53
+ """
54
+
55
+
56
+ def error_from_wire(error: Mapping[str, Any]) -> sqlite3.Error:
57
+ """Rebuild the exception the agent reported.
58
+
59
+ Args:
60
+ error: The `error` object of a failed answer, with `type` and
61
+ `message` keys.
62
+
63
+ Returns:
64
+ An instance of the sqlite3 class named by `type` (or of
65
+ `RemoteAgentError` for an agent failure), carrying `message`.
66
+ """
67
+ name = str(error.get("type", "Error"))
68
+ message = str(error.get("message", "unknown error"))
69
+ if name == "AgentError":
70
+ return RemoteAgentError(message)
71
+ return _WIRE_TYPES.get(name, sqlite3.Error)(message)