Debian Codegraph @

src/harlequin_sqlite/adapter.py

raw
1 from __future__ import annotations
2
3 import sqlite3
4 from contextlib import suppress
5 from itertools import cycle, zip_longest
6 from pathlib import Path
7 from typing import TYPE_CHECKING, Any, Literal, Sequence
8 from urllib.parse import unquote, urlparse
9
10 from harlequin.adapter import HarlequinAdapter, HarlequinConnection, HarlequinCursor
11 from harlequin.autocomplete.completion import HarlequinCompletion
12 from harlequin.catalog import (
13 Catalog,
14 CatalogItem,
15 CatalogSearchKind,
16 CatalogSearchResult,
17 )
18 from harlequin.exception import (
19 HarlequinConfigError,
20 HarlequinConnectionError,
21 HarlequinQueryError,
22 )
23 from harlequin.options import HarlequinAdapterOption, HarlequinCopyFormat
24 from harlequin.transaction_mode import HarlequinTransactionMode
25 from harlequin_sqlite.catalog import (
26 ColumnCatalogItem,
27 DatabaseCatalogItem,
28 RelationCatalogItem,
29 TableCatalogItem,
30 ViewCatalogItem,
31 )
32 from harlequin_sqlite.cli_options import SQLITE_OPTIONS
33 from harlequin_sqlite.completions import get_completion_data
34
35 if TYPE_CHECKING:
36 from textual_fastdatatable.backend import AutoBackendType
37
38 IN_MEMORY_CONN_STR = (":memory:",)
39
40 _LIKE_ESCAPE = "\\"
41 """What escapes a LIKE metacharacter in a term the caller typed."""
42
43 _SEARCH_DATABASES = """
44 select name from pragma_database_list where name like ? escape '\\'
45 """
46 """The attached databases whose name matches, which is SQLite's top level.
47
48 Its own query rather than a branch of the one below: the others are per
49 database, and this one asks about all of them at once.
50 """
51
52 _SEARCH_RELATIONS = """
53 select m.name, m.type, null, null
54 from {db}.sqlite_schema m
55 where m.type in ('table', 'view') and m.name like ? escape '\\'
56 """
57
58 _SEARCH_COLUMNS = """
59 select m.name, m.type, p.name, p.type
60 from {db}.sqlite_schema m
61 join pragma_table_info(m.name, ?) p
62 where m.type in ('table', 'view') and p.name like ? escape '\\'
63 """
64
65 _SEARCH_BRANCHES = {
66 "relations": (_SEARCH_RELATIONS,),
67 "columns": (_SEARCH_COLUMNS,),
68 "all": (_SEARCH_RELATIONS, _SEARCH_COLUMNS),
69 }
70 """Which levels each kind unions, both branches in the same four columns.
71
72 The database level is not here: it is one query for all of them rather than
73 one per database, so `_matched_databases()` asks it separately.
74 `_search_parameters()` binds in this order.
75 """
76
77 _SEARCH_SQL = {
78 # `nulls first` explicitly rather than on SQLite's default, so that both
79 # bundled adapters promise the same thing about their order.
80 kind: " union all ".join(branches) + " order by 1, 3 nulls first"
81 for kind, branches in _SEARCH_BRANCHES.items()
82 }
83 """One query per kind, per attached database, which is what SQLite has.
84
85 `pragma_table_info` is the table-valued form of the pragma, so every relation's
86 columns come back in one query rather than one per relation. Ordered so that a
87 relation arrives before its own columns.
88 """
89
90
91 def _search_parameters(kind: CatalogSearchKind, db_name: str, term: str) -> list[str]:
92 """What `_SEARCH_SQL[kind]` binds, in the order it binds them."""
93 pattern = _contains_pattern(term)
94 relation_parameters = [pattern]
95 # the pragma's schema argument sits ahead of the pattern in the query text
96 column_parameters = [db_name, pattern]
97 if kind == "relations":
98 return relation_parameters
99 if kind == "columns":
100 return column_parameters
101 return [*relation_parameters, *column_parameters]
102
103
104 def _contains_pattern(term: str) -> str:
105 """A term as the LIKE pattern that matches any label containing it."""
106 escaped = term
107 for character in (_LIKE_ESCAPE, "%", "_"):
108 escaped = escaped.replace(character, f"{_LIKE_ESCAPE}{character}")
109 return f"%{escaped}%"
110
111
112 class HarlequinSqliteCursor(HarlequinCursor):
113 def __init__(self, conn: HarlequinSqliteConnection, cur: sqlite3.Cursor) -> None:
114 self.conn = conn
115 self.cur = cur
116 self._limit: int | None = None
117 try:
118 _first_row = cur.fetchone()
119 except sqlite3.Error: # maybe canceled query here
120 _first_row = None
121 self.has_records = _first_row is not None
122 self._first_row: tuple[Any, ...] = _first_row or tuple(
123 [None] * len(cur.description)
124 )
125
126 def columns(self) -> list[tuple[str, str]]:
127 col_names = [col[0] for col in self.cur.description]
128 col_types = [
129 self.conn._short_column_type_from_python_object(value)
130 for value in self._first_row
131 ]
132 return list(zip_longest(col_names, col_types, fillvalue="?"))
133
134 def set_limit(self, limit: int) -> "HarlequinSqliteCursor":
135 self._limit = limit
136 return self
137
138 def fetchall(self) -> AutoBackendType | None:
139 if not self.has_records or self._limit == 0:
140 # A result with no rows still has columns, and a caller handed None
141 # has no way to learn what they were -- so an export or a headless
142 # render would lose the header. An Arrow table carries the names,
143 # duplicates included, which a dict of columns would not.
144 #
145 # pyarrow is deferred: it is a guaranteed dependency, but importing
146 # it at module scope would put ~100ms on every `import
147 # harlequin_sqlite`, which the adapter API is careful not to cost.
148 import pyarrow as pa
149
150 names = [col[0] for col in self.cur.description]
151 return pa.Table.from_arrays(
152 [pa.array([], type=pa.string()) for _ in names], names=names
153 )
154
155 try:
156 if self._limit is None:
157 remaining_rows = self.cur.fetchall()
158 elif self._limit > 1:
159 # the first row is already in hand, so one fewer is wanted here
160 remaining_rows = self.cur.fetchmany(self._limit - 1)
161 else:
162 # `fetchmany(0)` reads as "all of them" in sqlite3, so a limit
163 # of one row is a call that must not be made at all.
164 remaining_rows = []
165 except sqlite3.OperationalError: # maybe canceled here
166 return None
167 except sqlite3.Error as e:
168 raise HarlequinQueryError(
169 msg=str(e),
170 title=("SQLite raised an error when fetching results for your query:"),
171 ) from e
172 return [self._first_row, *remaining_rows]
173
174 def fetchone(self) -> tuple | None:
175 return self._first_row
176
177
178 class HarlequinSqliteConnection(HarlequinConnection):
179 def __init__(self, conn: sqlite3.Connection, init_message: str = "") -> None:
180 self.conn = conn
181 self.init_message = init_message
182 self._transaction_modes: list[HarlequinTransactionMode | None] = (
183 [
184 HarlequinTransactionMode(label="Auto"),
185 HarlequinTransactionMode(
186 label="Manual", commit=self.conn.commit, rollback=self.conn.rollback
187 ),
188 ]
189 if hasattr(conn, "autocommit")
190 else [None]
191 )
192 self._transaction_mode_gen = cycle(self._transaction_modes)
193 self._transaction_mode = next(self._transaction_mode_gen)
194 self._sync_connection_transaction_mode()
195
196 def execute(self, query: str) -> HarlequinSqliteCursor | None:
197 # the behavior on manual mode is really counter-intuitive; if a
198 # transaction isn't explicitly began, it's basically the same as
199 # auto. By forcing an explicit begin, the behavior is more like
200 # manual mode on other databases.
201 if (
202 self.transaction_mode
203 and self.transaction_mode.label == "Manual"
204 and not self.conn.in_transaction
205 ):
206 with suppress(sqlite3.Error):
207 self.conn.execute("begin;")
208 try:
209 cur = self.conn.execute(query)
210 except sqlite3.Error as e:
211 # no-op if user ran a begin; statement, since we already started the txn
212 if (
213 isinstance(e, sqlite3.OperationalError)
214 and str(e) == "cannot start a transaction within a transaction"
215 ):
216 return None
217 raise HarlequinQueryError(
218 msg=str(e),
219 title="SQLite raised an error when compiling or running your query:",
220 ) from e
221
222 if cur.description is not None:
223 return HarlequinSqliteCursor(conn=self, cur=cur)
224 else:
225 return None
226
227 def cancel(self) -> None:
228 self.conn.interrupt()
229
230 def get_catalog(self) -> Catalog:
231 catalog_items: list[CatalogItem] = []
232 databases = self._get_databases()
233 for database_label in databases:
234 catalog_items.append(
235 DatabaseCatalogItem.from_label(label=database_label, connection=self)
236 )
237 return Catalog(items=catalog_items)
238
239 def search_catalog(
240 self, term: str, kind: CatalogSearchKind = "all"
241 ) -> list[CatalogSearchResult]:
242 results: list[CatalogSearchResult] = []
243 matched_databases = self._matched_databases(term) if kind == "all" else set()
244 for db_name in self._get_databases():
245 database_item = DatabaseCatalogItem.from_label(
246 label=db_name, connection=self
247 )
248 if db_name in matched_databases:
249 results.append(CatalogSearchResult(item=database_item))
250 relations: dict[str, RelationCatalogItem] = {}
251 quoted_db = '"' + db_name.replace('"', '""') + '"'
252 try:
253 found = self.conn.execute(
254 _SEARCH_SQL[kind].format(db=quoted_db),
255 _search_parameters(kind, db_name, term),
256 ).fetchall()
257 except sqlite3.Error as e:
258 raise HarlequinQueryError(
259 msg=str(e),
260 title="SQLite raised an error searching the catalog:",
261 ) from e
262 for relation, relation_type, column, column_type in found:
263 relation_item = relations.setdefault(
264 relation,
265 self._relation_item(database_item, relation, relation_type),
266 )
267 if column is None:
268 results.append(
269 CatalogSearchResult(item=relation_item, parents=(db_name,))
270 )
271 else:
272 results.append(
273 CatalogSearchResult(
274 item=ColumnCatalogItem.from_parent(
275 parent=relation_item,
276 label=column,
277 type_label=self._short_column_type(column_type),
278 # a column can be declared without a type, and
279 # an empty string is not one
280 type_name=column_type or None,
281 ),
282 parents=(db_name, relation),
283 )
284 )
285 return results
286
287 def _matched_databases(self, term: str) -> set[str]:
288 """The attached databases whose name contains term.
289
290 Asked in SQL rather than compared here, so that the top level matches a
291 term the same way every level below it does.
292 """
293 try:
294 found = self.conn.execute(
295 _SEARCH_DATABASES, [_contains_pattern(term)]
296 ).fetchall()
297 except sqlite3.Error as e:
298 raise HarlequinQueryError(
299 msg=str(e),
300 title="SQLite raised an error searching the catalog:",
301 ) from e
302 return {name for (name,) in found}
303
304 def get_completions(self) -> list[HarlequinCompletion]:
305 return get_completion_data(self.conn)
306
307 @property
308 def transaction_mode(self) -> HarlequinTransactionMode | None:
309 return self._transaction_mode
310
311 def toggle_transaction_mode(self) -> HarlequinTransactionMode | None:
312 new_mode = next(self._transaction_mode_gen)
313 self._transaction_mode = new_mode
314 self._sync_connection_transaction_mode()
315 return new_mode
316
317 def close(self) -> None:
318 self.conn.close()
319
320 def _sync_connection_transaction_mode(self) -> None:
321 if not self._transaction_mode or not hasattr(self.conn, "autocommit"):
322 return
323
324 if self.conn.in_transaction:
325 self.conn.commit()
326
327 if self.transaction_mode and self.transaction_mode.label == "Auto":
328 self.conn.autocommit = True
329 else:
330 self.conn.autocommit = False
331
332 def _get_databases(self) -> list[str]:
333 objects: list[tuple[str, str, str]] = self.conn.execute(
334 "pragma database_list"
335 ).fetchall()
336 return [db_name for _, db_name, _ in objects]
337
338 def _get_relations(self, db_name: str) -> list[tuple[str, str]]:
339 objects = self.conn.execute(
340 f'select type, name from "{db_name}".sqlite_schema'
341 ).fetchall()
342 relations = [(name, typ) for typ, name in objects if typ in ("table", "view")]
343 return relations
344
345 def _get_columns(self, db_name: str, rel_name: str) -> list[tuple[str, str, str]]:
346 return self.conn.execute(
347 f"pragma {db_name}.table_info('{rel_name}')"
348 ).fetchall()
349
350 @staticmethod
351 def _relation_item(
352 parent: DatabaseCatalogItem, label: str, relation_type: str
353 ) -> RelationCatalogItem:
354 """A relation of the class `fetch_children()` would have built for it."""
355 item_class = ViewCatalogItem if relation_type == "view" else TableCatalogItem
356 return item_class.from_parent(
357 parent=parent, label=label, type_name=relation_type
358 )
359
360 @staticmethod
361 def _short_column_type(raw_type: str) -> str:
362 # first get the storage affinity for a type decl
363 if raw_type is None or raw_type == "":
364 affinity = ""
365
366 typ = raw_type.lower()
367 if "int" in typ:
368 affinity = "INTEGER"
369 elif any([x in typ for x in ["char", "clob", "text"]]):
370 affinity = "TEXT"
371 elif "blob" in typ:
372 affinity = "BLOB"
373 elif any([x in typ for x in ["real", "floa", "doub"]]):
374 affinity = "REAL"
375 else:
376 affinity = "NUMERIC"
377
378 # then lookup the abbreviation for the affinity
379 mapping = {
380 "": "",
381 "TEXT": "s",
382 "NUMERIC": "#.#",
383 "INTEGER": "##",
384 "REAL": "#.#",
385 "BLOB": "b",
386 }
387 return mapping.get(affinity, "?")
388
389 @staticmethod
390 def _short_column_type_from_python_object(obj: object) -> str:
391 mapping: dict[type | None, str] = {
392 None: "",
393 str: "s",
394 float: "#.#",
395 int: "##",
396 object: "b",
397 }
398 return mapping.get(type(obj), "?")
399
400 @staticmethod
401 def _short_relation_type(raw_type: str) -> str:
402 mapping = {"table": "t", "view": "v"}
403 return mapping.get(raw_type, "?")
404
405 def copy(
406 self, query: str, path: Path, format_name: str, options: dict[str, Any]
407 ) -> None:
408 raise NotImplementedError
409
410 def validate_sql(self, text: str) -> str:
411 raise NotImplementedError
412
413
414 class HarlequinSqliteAdapter(HarlequinAdapter):
415 ADAPTER_OPTIONS: list[HarlequinAdapterOption] | None = SQLITE_OPTIONS
416 COPY_FORMATS: list[HarlequinCopyFormat] | None = None
417 IMPLEMENTS_CANCEL = True
418 IMPLEMENTS_CATALOG_SEARCH = True
419 IMPLEMENTS_READ_ONLY = True
420 ADAPTER_DETAILS = "This is an SQLite adapter part of Harlequin core."
421
422 def __init__(
423 self,
424 conn_str: Sequence[str],
425 init_path: Path | str | None = None,
426 no_init: bool | str = False,
427 read_only: bool = False,
428 mode: Literal["ro", "rw", "rwc", "memory"] | None = None,
429 lock_timeout: str | float = 5.0,
430 detect_types: str | int = 0,
431 isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] = "DEFERRED",
432 cached_statements: str | int = 128,
433 extension: list[str] | None = None,
434 **_: Any,
435 ) -> None:
436 try:
437 self.conn_str = (
438 conn_str
439 if conn_str and conn_str != ("",) and mode != "memory"
440 else IN_MEMORY_CONN_STR
441 )
442 self.init_path = (
443 Path(init_path).expanduser().resolve()
444 if init_path is not None
445 else Path.home() / ".sqliterc"
446 )
447 self.no_init = bool(no_init)
448 self.read_only = bool(read_only)
449 self.mode = mode
450 self.lock_timeout = float(lock_timeout)
451 self.detect_types = int(detect_types)
452 self.isolation_level = isolation_level
453 self.cached_statements = int(cached_statements)
454 self.extensions = extension if extension is not None else []
455 self.can_load_extensions = hasattr(
456 sqlite3.Connection, "enable_load_extension"
457 )
458 except (ValueError, TypeError) as e:
459 raise HarlequinConfigError(
460 msg=f"SQLite adapter received bad config value: {e}",
461 title="Harlequin could not initialize the selected adapter.",
462 ) from e
463
464 if self.extensions and not self.can_load_extensions:
465 raise HarlequinConfigError(
466 title="Harlequin could not initialize the selected adapter.",
467 msg=(
468 "SQLite adapter received --extension option, but extensions "
469 "are disabled on this SQLite distribution. See "
470 "https://harlequin.sh/docs/sqlite/extensions"
471 ),
472 )
473
474 @property
475 def connection_id(self) -> str | None:
476 if self.conn_str == IN_MEMORY_CONN_STR:
477 return ""
478 return ",".join(
479 [Path(conn).resolve().as_posix() for conn in sorted(self.conn_str)]
480 )
481
482 def connect(self) -> HarlequinSqliteConnection:
483 if self.read_only and self.mode is not None and self.mode != "ro":
484 raise HarlequinConnectionError(
485 "Cannot specify readonly flag and a connection mode."
486 )
487 elif self.read_only:
488 mode_str = "?mode=ro"
489 elif self.mode is not None:
490 mode_str = f"?mode={self.mode}"
491 else:
492 mode_str = ""
493
494 # build db strings
495 db_uris: list[str] = []
496 db_names: list[str] = []
497 for s in self.conn_str:
498 if s == ":memory:":
499 db_uris.append(s)
500 db_names.append("memory")
501 elif s.startswith("file:"):
502 db_uris.append(s)
503 db_names.append(Path(unquote(urlparse(s).path)).stem)
504 else:
505 try:
506 p = Path(s).resolve()
507 db = f"{p.as_uri()}{mode_str}"
508 db_uris.append(db)
509 db_names.append(p.stem)
510 except ValueError as e:
511 raise HarlequinConnectionError(
512 f"Cannot build URI from connection string {s}.",
513 title="SQLite couldn't connect to your database.",
514 ) from e
515 primary_db, *other_dbs = db_uris
516 try:
517 conn = sqlite3.connect(
518 database=primary_db,
519 timeout=self.lock_timeout,
520 detect_types=self.detect_types,
521 isolation_level=self.isolation_level,
522 cached_statements=self.cached_statements,
523 check_same_thread=False,
524 uri=True,
525 )
526 # sqlite won't error on connect if you open a file that isn't a sqlite db
527 # running pragma database_list will raise, though:
528 _ = conn.execute("pragma database_list")
529 except sqlite3.Error as e:
530 if "file is not a database" in (msg := str(e)):
531 msg = (
532 "sqlite raised the following error when trying to open "
533 f"{primary_db}:\n---\n{msg}\n---\n\n"
534 "Did you mean to use Harlequin's DuckDB adapter instead? "
535 f"Maybe try:\nharlequin -a duckdb {' '.join(self.conn_str)}\n"
536 f"or:\nharlequin -P None {' '.join(self.conn_str)}"
537 )
538 raise HarlequinConnectionError(
539 msg=msg,
540 title="SQLite couldn't connect to your database.",
541 ) from e
542
543 # Python 3.12 added an autocommit attribute, which should be
544 # turned on by default
545 if hasattr(conn, "autocommit"):
546 conn.autocommit = True
547
548 for uri, name in zip(other_dbs, db_names[1:], strict=False):
549 try:
550 conn.execute(f"attach database '{uri}' as {name}")
551 except sqlite3.Error as e:
552 if "file is not a database" in (msg := str(e)):
553 msg = (
554 "sqlite raised the following error when trying to open "
555 f"{uri}:\n---\n{msg}\n---\n\n"
556 "Did you mean to use Harlequin's DuckDB adapter instead? "
557 f"Maybe try:\nharlequin -a duckdb {' '.join(self.conn_str)}\n"
558 f"or:\nharlequin -P None {' '.join(self.conn_str)}"
559 )
560 raise HarlequinConnectionError(
561 msg=msg, title="SQLite couldn't connect to your database."
562 ) from e
563
564 if self.can_load_extensions:
565 conn.enable_load_extension(True)
566
567 for extension in self.extensions:
568 try:
569 conn.load_extension(extension)
570 except sqlite3.Error as e:
571 raise HarlequinConnectionError(
572 str(e), title="SQLite couldn't load your extension."
573 ) from e
574
575 init_msg = ""
576 if self.init_path is not None and not self.no_init:
577 init_script = self._read_init_script(self.init_path)
578 count = 0
579 for command in self._split_script(init_script):
580 rewritten_command = self._rewrite_init_command(command)
581 for cmd in rewritten_command.split(";"):
582 if cmd.strip():
583 try:
584 conn.execute(cmd)
585 except sqlite3.Error as e:
586 msg = (
587 f"Attempted to execute script at {self.init_path}. "
588 f"Contents:\n{command}\nRewritten to:\n"
589 f"{rewritten_command}\nCurrently executing:\n"
590 f"{cmd}\nError:\n{e}"
591 )
592 if not self.can_load_extensions and isinstance(
593 e, sqlite3.OperationalError
594 ):
595 msg += (
596 "\nWarning: Cannot load extensions with this "
597 "SQLite distribution. See "
598 "https://harlequin.sh/docs/sqlite/extensions"
599 )
600 raise HarlequinConnectionError(
601 msg,
602 title=(
603 "SQLite could not execute your initialization "
604 "script."
605 ),
606 ) from e
607 else:
608 count += 1
609 if count > 0:
610 init_msg = (
611 f"Executed {count} {'command' if count == 1 else 'commands'} "
612 f"from {self.init_path}"
613 )
614 self.ADAPTER_DRIVER_DETAILS = f"""
615 Connected to database `{primary_db}`
616 """
617 return HarlequinSqliteConnection(conn=conn, init_message=init_msg)
618
619 @staticmethod
620 def _read_init_script(init_path: Path) -> str:
621 try:
622 with open(init_path.expanduser(), "r") as f:
623 init_script = f.read()
624 except OSError:
625 init_script = ""
626 return init_script
627
628 @staticmethod
629 def _split_script(script: str) -> list[str]:
630 """
631 SQLite init scripts can contain SQL queries or dot commands. The SQL
632 queries may contain newlines, but the dot commands are newline-terminated.
633 This takes a raw script and returns a list of executable commands
634 """
635 lines = script.splitlines()
636 commands: list[str] = []
637 i = 0
638 for j, line in enumerate(lines):
639 if line.startswith("."):
640 commands.append("\n".join(lines[i:j]))
641 commands.append(line)
642 i = j + 1
643 # queries can be terminated by / or "go" on a line
644 # by itself
645 elif line in ("/", "go"):
646 commands.append("\n".join(lines[i:j]))
647 i = j + 1
648 commands.append("\n".join(lines[i:]))
649 return [command.strip() for command in commands if command]
650
651 @classmethod
652 def _rewrite_init_command(cls, command: str) -> str:
653 """
654 SQLite init scripts can contain dot commands, which can only be executed
655 by the CLI, not the python API. Here, we rewrite some common ones into
656 SQL, and rewrite the others to be no-ops.
657 """
658 if not command.startswith("."):
659 return command
660 elif command.startswith(".open"):
661 return cls._rewrite_dot_open(command)
662 elif command.startswith(".load"):
663 return cls._rewrite_dot_load(command)
664 else:
665 return ""
666
667 @staticmethod
668 def _rewrite_dot_open(command: str) -> str:
669 """
670 Rewrites .open command into its approx SQL equivalent.
671 (This attaches databases instead of opening a new connection).
672
673 Options (--readonly, etc.) are not supported.
674 """
675 args = command.split()[1:]
676 if not args:
677 return "attach ''"
678 elif args[-1] == ":memory:":
679 return "attach ':memory:';"
680 else:
681 # options are not supported.
682 db_path = Path(args[-1])
683 return f"attach '{db_path}' as {db_path.stem};"
684
685 @staticmethod
686 def _rewrite_dot_load(command: str) -> str:
687 """
688 Rewrites .load command into its SQL equivalent, load_extension().
689 """
690 args = command.split()[1:]
691 if not args:
692 raise sqlite3.ProgrammingError("Could not execute .load with no args.")
693 elif len(args) == 1:
694 return f"select load_extension('{args[0]}');"
695 elif len(args) == 2:
696 return f"select load_extension('{args[0]}', '{args[1]}');"
697 else:
698 raise sqlite3.ProgrammingError(
699 f"Could not execute .load with following args: {args}"
700 )