Debian Codegraph @

src/harlequin_duckdb/adapter.py

raw
1 from __future__ import annotations
2
3 import json
4 from pathlib import Path
5 from typing import TYPE_CHECKING, Any, Sequence
6
7 import duckdb
8
9 try:
10 from duckdb.sqltypes import DuckDBPyType
11 except ImportError:
12 from duckdb.typing import DuckDBPyType # type: ignore[import-not-found,no-redef]
13
14 from harlequin.adapter import HarlequinAdapter, HarlequinConnection, HarlequinCursor
15 from harlequin.autocomplete.completion import HarlequinCompletion
16 from harlequin.catalog import (
17 Catalog,
18 CatalogItem,
19 CatalogSearchKind,
20 CatalogSearchResult,
21 )
22 from harlequin.exception import (
23 HarlequinConfigError,
24 HarlequinConnectionError,
25 HarlequinQueryError,
26 )
27 from harlequin_duckdb.catalog import (
28 ColumnCatalogItem,
29 DatabaseCatalogItem,
30 RelationCatalogItem,
31 SchemaCatalogItem,
32 TableCatalogItem,
33 TempTableCatalogItem,
34 ViewCatalogItem,
35 )
36 from harlequin_duckdb.cli_options import DUCKDB_OPTIONS
37 from harlequin_duckdb.completions import get_completion_data
38
39 if TYPE_CHECKING:
40 from textual_fastdatatable.backend import AutoBackendType
41
42 IN_MEMORY_CONN_STR = (":memory:",)
43
44 _LIKE_ESCAPE = "\\"
45 """What escapes a LIKE metacharacter in a term the caller typed."""
46
47 _ATTACHED = """
48 in (select database_name from duckdb_databases() where not internal)
49 """
50 """The catalogs `pragma show_databases` reports, as a predicate.
51
52 Every search is scoped to them so that each path it reports is one
53 `--catalog --path` walks: duckdb's temp catalog holds objects the catalog tree
54 never shows.
55 """
56
57 _SEARCH_DATABASES = """
58 select d.database_name, null, null, null, null, null
59 from duckdb_databases() d
60 where not d.internal and d.database_name ilike ? escape '\\'
61 """
62
63 _SEARCH_SCHEMAS = f"""
64 select s.catalog_name, s.schema_name, null, null, null, null
65 from information_schema.schemata s
66 where s.schema_name not in ('pg_catalog', 'information_schema')
67 and s.catalog_name {_ATTACHED}
68 and s.schema_name ilike ? escape '\\'
69 """
70
71 _SEARCH_RELATIONS = f"""
72 select t.table_catalog, t.table_schema, t.table_name, t.table_type, null, null
73 from information_schema.tables t
74 where t.table_schema not in ('pg_catalog', 'information_schema')
75 and t.table_catalog {_ATTACHED}
76 and t.table_name ilike ? escape '\\'
77 """
78
79 _SEARCH_COLUMNS = f"""
80 select
81 c.table_catalog, c.table_schema, c.table_name, t.table_type,
82 c.column_name, c.data_type
83 from information_schema.columns c
84 join information_schema.tables t
85 on t.table_catalog = c.table_catalog
86 and t.table_schema = c.table_schema
87 and t.table_name = c.table_name
88 where c.table_schema not in ('pg_catalog', 'information_schema')
89 and c.table_catalog {_ATTACHED}
90 and c.column_name ilike ? escape '\\'
91 """
92
93 _SEARCH_BRANCHES = {
94 "relations": (_SEARCH_RELATIONS,),
95 "columns": (_SEARCH_COLUMNS,),
96 "all": (_SEARCH_DATABASES, _SEARCH_SCHEMAS, _SEARCH_RELATIONS, _SEARCH_COLUMNS),
97 }
98 """Which levels each kind unions, every branch in the same six columns.
99
100 A row names one item by filling in the levels above it and leaving the rest
101 null, so `all` is every level of the catalog rather than the two at the bottom.
102 """
103
104 _SEARCH_SQL = {
105 kind: " union all ".join(branches)
106 # `nulls first` explicitly, because duckdb's default for ascending is
107 # `nulls last`: without it a schema would sort after the columns under it.
108 + " order by 1, 2 nulls first, 3 nulls first, 5 nulls first"
109 for kind, branches in _SEARCH_BRANCHES.items()
110 }
111 """One query per kind, ordered so that an item arrives before its children."""
112
113
114 def _contains_pattern(term: str) -> str:
115 """A term as the LIKE pattern that matches any label containing it."""
116 escaped = term
117 for character in (_LIKE_ESCAPE, "%", "_"):
118 escaped = escaped.replace(character, f"{_LIKE_ESCAPE}{character}")
119 return f"%{escaped}%"
120
121
122 class DuckDbCursor(HarlequinCursor):
123 def __init__(
124 self, conn: DuckDbConnection, relation: duckdb.DuckDBPyRelation
125 ) -> None:
126 self.conn = conn
127 self.relation = relation
128
129 def columns(self) -> list[tuple[str, str]]:
130 return list(
131 zip(
132 self.relation.columns,
133 map(self.conn._short_column_type, self.relation.dtypes),
134 strict=False,
135 )
136 )
137
138 def set_limit(self, limit: int) -> HarlequinCursor:
139 try:
140 self.relation = self.relation.limit(limit)
141 except duckdb.Error:
142 pass
143 return self
144
145 def fetchall(self) -> AutoBackendType | None:
146 try:
147 result = self.relation.to_arrow_table()
148 except duckdb.InterruptException:
149 return None
150 except duckdb.Error as e:
151 raise HarlequinQueryError(
152 msg=str(e), title="DuckDB raised an error when running your query:"
153 ) from e
154 return result
155
156 def fetchone(self) -> tuple | None:
157 try:
158 result = self.relation.fetchone()
159 except duckdb.InterruptException:
160 return None
161 except duckdb.Error as e:
162 raise HarlequinQueryError(
163 msg=str(e), title="DuckDB raised an error when running your query:"
164 ) from e
165 return result
166
167
168 class DuckDbConnection(HarlequinConnection):
169 RELATION_TYPE_MAPPING = {
170 "BASE TABLE": "t",
171 "LOCAL TEMPORARY": "tmp",
172 "VIEW": "v",
173 }
174
175 COLUMN_TYPE_MAPPING = {
176 "SQLNULL": "\\n",
177 "BOOLEAN": "t/f",
178 "TINYINT": "#",
179 "UTINYINT": "u#",
180 "SMALLINT": "#",
181 "USMALLINT": "u#",
182 "INTEGER": "#",
183 "UINTEGER": "u#",
184 "BIGINT": "##",
185 "UBIGINT": "u##",
186 "HUGEINT": "###",
187 "UUID": "uid",
188 "FLOAT": "#.#",
189 "DOUBLE": "#.#",
190 "DATE": "d",
191 "TIMESTAMP": "ts",
192 "TIMESTAMP_MS": "ts",
193 "TIMESTAMP_NS": "ts",
194 "TIMESTAMP_S": "ts",
195 "TIME": "t",
196 "TIME_TZ": "ttz",
197 "TIMESTAMP_TZ": "ttz",
198 "TIMESTAMP WITH TIME ZONE": "ttz",
199 "VARCHAR": "s",
200 "BLOB": "0b",
201 "BIT": "010",
202 "INTERVAL": "|-|",
203 # these types don't have python classes
204 "DECIMAL": "#.#",
205 "REAL": "#.#",
206 "STRUCT": "{}",
207 "MAP": "{m}",
208 }
209
210 UNKNOWN_TYPE = "?"
211
212 def __init__(self, conn: duckdb.DuckDBPyConnection, init_message: str = "") -> None:
213 self.conn: duckdb.DuckDBPyConnection = conn
214 self.init_message = init_message
215
216 def execute(self, query: str) -> DuckDbCursor | None:
217 try:
218 rel = self.conn.sql(query)
219 except duckdb.InterruptException:
220 return None
221 except duckdb.Error as e:
222 raise HarlequinQueryError(
223 msg=str(e),
224 title="DuckDB raised an error when compiling or running your query:",
225 ) from e
226
227 if rel is not None:
228 return DuckDbCursor(conn=self, relation=rel)
229 else:
230 return None
231
232 def cancel(self) -> None:
233 self.conn.interrupt()
234
235 def get_catalog(self) -> Catalog:
236 catalog_items: list[CatalogItem] = []
237 databases = self._get_databases()
238 for (database_label,) in databases:
239 catalog_items.append(
240 DatabaseCatalogItem.from_label(label=database_label, connection=self)
241 )
242 return Catalog(items=catalog_items)
243
244 def search_catalog(
245 self, term: str, kind: CatalogSearchKind = "all"
246 ) -> list[CatalogSearchResult]:
247 cur = self.conn.cursor()
248 pattern = _contains_pattern(term)
249 parameters = [pattern] * len(_SEARCH_BRANCHES[kind])
250 try:
251 found = cur.execute(_SEARCH_SQL[kind], parameters).fetchall()
252 except duckdb.Error as e:
253 raise HarlequinQueryError(
254 msg=str(e), title="DuckDB raised an error searching the catalog:"
255 ) from e
256 databases: dict[str, DatabaseCatalogItem] = {}
257 schemas: dict[tuple[str, str], SchemaCatalogItem] = {}
258 relations: dict[tuple[str, str, str], RelationCatalogItem] = {}
259 results: list[CatalogSearchResult] = []
260 # a row names the deepest level it fills in, and carries its ancestors
261 # so that each one is built once and the match knows its own path
262 for catalog, schema, relation, relation_type, column, column_type in found:
263 database_item = databases.setdefault(
264 catalog, DatabaseCatalogItem.from_label(label=catalog, connection=self)
265 )
266 if schema is None:
267 results.append(CatalogSearchResult(item=database_item))
268 continue
269 schema_item = schemas.setdefault(
270 (catalog, schema),
271 SchemaCatalogItem.from_parent(parent=database_item, label=schema),
272 )
273 if relation is None:
274 results.append(
275 CatalogSearchResult(item=schema_item, parents=(catalog,))
276 )
277 continue
278 relation_item = relations.setdefault(
279 (catalog, schema, relation),
280 self._relation_item(schema_item, relation, relation_type),
281 )
282 if column is None:
283 results.append(
284 CatalogSearchResult(item=relation_item, parents=(catalog, schema))
285 )
286 continue
287 results.append(
288 CatalogSearchResult(
289 item=ColumnCatalogItem.from_parent(
290 parent=relation_item,
291 label=column,
292 type_label=self._short_column_type(column_type),
293 type_name=column_type,
294 ),
295 parents=(catalog, schema, relation),
296 )
297 )
298 return results
299
300 def get_completions(self) -> list[HarlequinCompletion]:
301 cur = self.conn.cursor()
302 return [
303 HarlequinCompletion(
304 label=label,
305 type_label=type_label,
306 value=label,
307 priority=priority,
308 context=context,
309 )
310 for label, type_label, priority, context in get_completion_data(cur)
311 ]
312
313 def validate_sql(self, text: str) -> str:
314 cur = self.conn.cursor()
315 escaped = text.replace("'", "''")
316 try:
317 (parsed,) = cur.sql( # type: ignore
318 f"select json_serialize_sql('{escaped}')"
319 ).fetchone()
320 except HarlequinQueryError:
321 return ""
322 result = json.loads(parsed)
323 # DDL statements return an error of type "not implemented"
324 if result.get("error", True) and result.get("error_type", "") == "parser":
325 return ""
326 else:
327 return text
328
329 def _get_databases(self) -> list[tuple[str]]:
330 cur = self.conn.cursor()
331 return cur.execute("pragma show_databases").fetchall()
332
333 def _get_schemas(self, database: str) -> list[tuple[str]]:
334 cur = self.conn.cursor()
335 schemas = cur.execute(
336 "select schema_name "
337 "from information_schema.schemata "
338 "where "
339 " catalog_name = ? "
340 " and schema_name not in ('pg_catalog', 'information_schema') "
341 "order by 1",
342 [database],
343 ).fetchall()
344 return schemas
345
346 def _get_tables(self, database: str, schema: str) -> list[tuple[str, str]]:
347 cur = self.conn.cursor()
348 tables = cur.execute(
349 "select table_name, table_type "
350 "from information_schema.tables "
351 "where "
352 " table_catalog = ? "
353 " and table_schema = ? "
354 "order by 1",
355 [database, schema],
356 ).fetchall()
357 return tables
358
359 def _get_columns(
360 self, database: str, schema: str, table: str
361 ) -> list[tuple[str, str]]:
362 cur = self.conn.cursor()
363 columns = cur.execute(
364 "select column_name, data_type "
365 "from information_schema.columns "
366 "where "
367 " table_catalog = ? "
368 " and table_schema = ? "
369 " and table_name = ? "
370 "order by 1",
371 [database, schema, table],
372 ).fetchall()
373 return columns
374
375 @staticmethod
376 def _relation_item(
377 parent: SchemaCatalogItem, label: str, relation_type: str
378 ) -> RelationCatalogItem:
379 """A relation of the class `fetch_children()` would have built for it."""
380 if relation_type == "VIEW":
381 return ViewCatalogItem.from_parent(
382 parent=parent, label=label, type_name=relation_type
383 )
384 if relation_type == "LOCAL TEMPORARY":
385 return TempTableCatalogItem.from_parent(
386 parent=parent, label=label, type_name=relation_type
387 )
388 return TableCatalogItem.from_parent(
389 parent=parent, label=label, type_name=relation_type
390 )
391
392 @classmethod
393 def _short_relation_type(cls, native_type: str) -> str:
394 return cls.RELATION_TYPE_MAPPING.get(native_type, cls.UNKNOWN_TYPE)
395
396 @classmethod
397 def _short_column_type(cls, native_type: DuckDBPyType | str) -> str:
398 """
399 In duckdb v0.8.0, relation.dtypes started returning a DuckDBPyType,
400 instead of a string. However, this type isn't an ENUM, and there
401 aren't classes for all types, so it's hard
402 to check class members. So we just convert to a string and split
403 complex types on their first paren to match our dictionary.
404 """
405 base_type = str(native_type).split("(")[0].split("[")[0]
406 short_base_type = cls.COLUMN_TYPE_MAPPING.get(base_type, cls.UNKNOWN_TYPE)
407 if str(native_type).endswith("[]"):
408 return f"[{short_base_type}]"
409 else:
410 return short_base_type
411
412
413 class DuckDbAdapter(HarlequinAdapter):
414 ADAPTER_OPTIONS = DUCKDB_OPTIONS
415 COPY_FORMATS = None
416 IMPLEMENTS_CANCEL = True
417 IMPLEMENTS_CATALOG_SEARCH = True
418 IMPLEMENTS_READ_ONLY = True
419 IMPLEMENTS_VALIDATE_SQL = True
420 ADAPTER_DETAILS = "This is a DuckDB 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 | str = False,
428 allow_unsigned_extensions: bool | str = False,
429 extension: list[str] | None = None,
430 force_install_extensions: bool = False,
431 custom_extension_repo: str | None = None,
432 md_token: str | None = None,
433 md_saas: bool = False,
434 **_: Any,
435 ) -> None:
436 try:
437 self.conn_str = (
438 conn_str if conn_str and conn_str != ("",) else IN_MEMORY_CONN_STR
439 )
440 self.init_path = (
441 Path(init_path).expanduser().resolve()
442 if init_path is not None
443 else Path.home() / ".duckdbrc"
444 )
445 self.no_init = bool(no_init)
446 self.read_only = bool(read_only)
447 self.allow_unsigned_extensions = bool(allow_unsigned_extensions)
448 self.extensions = extension if extension is not None else []
449 self.force_install_extensions = force_install_extensions
450 self.custom_extension_repo = custom_extension_repo
451 self.md_token = md_token
452 self.md_saas = md_saas
453 except (ValueError, TypeError) as e:
454 raise HarlequinConfigError(
455 msg=f"DuckDB adapter received bad config value: {e}",
456 title="Harlequin could not initialize the selected adapter.",
457 ) from e
458
459 @property
460 def connection_id(self) -> str | None:
461 if self.conn_str == IN_MEMORY_CONN_STR:
462 return ""
463 return ",".join(
464 [Path(conn).resolve().as_posix() for conn in sorted(self.conn_str)]
465 )
466
467 def connect(self) -> DuckDbConnection:
468 primary_db, *other_dbs = self.conn_str
469 token = f"?token={self.md_token}" if self.md_token else ""
470 saas = "?saas_mode=true" if self.md_saas else ""
471 config: dict[str, str | bool | int | float | list[str]] | None = {
472 "allow_unsigned_extensions": str(self.allow_unsigned_extensions).lower()
473 }
474
475 try:
476 connection = duckdb.connect(
477 database=f"{primary_db}{token}{saas}",
478 read_only=self.read_only,
479 config=config,
480 )
481 for db in other_dbs:
482 connection.execute(
483 f"attach '{db}'{' (READ_ONLY)' if self.read_only else ''}"
484 )
485 except (duckdb.CatalogException, duckdb.IOException) as e:
486 if "sqlite_scanner" in (msg := str(e)):
487 msg = (
488 "DuckDB raised the following error when trying to open "
489 f"one or more database files:\n---\n{msg}\n---\n\n"
490 "Did you mean to use Harlequin's sqlite adapter instead? "
491 f"Maybe try:\nharlequin -a sqlite {' '.join(self.conn_str)}"
492 )
493 raise HarlequinConnectionError(
494 msg, title="DuckDB couldn't connect to your database."
495 ) from e
496
497 if self.custom_extension_repo:
498 connection.execute(
499 f"SET custom_extension_repository='{self.custom_extension_repo}';"
500 )
501
502 for extension in self.extensions:
503 try:
504 # todo: support installing from a URL instead.
505 connection.install_extension(
506 extension=extension, force_install=self.force_install_extensions
507 )
508 connection.load_extension(extension=extension)
509 except (duckdb.HTTPException, duckdb.IOException) as e:
510 raise HarlequinConnectionError(
511 str(e), title="DuckDB couldn't install or load your extension."
512 ) from e
513
514 msg = ""
515 if self.init_path is not None and not self.no_init:
516 init_script = self._read_init_script(self.init_path)
517 try:
518 count = 0
519 for command in self._split_script(init_script):
520 rewritten_command = self._rewrite_init_command(command)
521 for cmd in rewritten_command.split(";"):
522 if cmd.strip():
523 connection.execute(cmd)
524 count += 1
525 except duckdb.Error as e:
526 msg = f"Attempted to execute script at {self.init_path}\n{e}"
527 raise HarlequinConnectionError(
528 msg, title="DuckDB could not execute your initialization script."
529 ) from e
530 else:
531 if count > 0:
532 msg = (
533 f"Executed {count} {'command' if count == 1 else 'commands'} "
534 f"from {self.init_path}"
535 )
536
537 self.ADAPTER_DRIVER_DETAILS = f"""
538 Connected to database `{primary_db}`
539 """
540 return DuckDbConnection(conn=connection, init_message=msg)
541
542 @staticmethod
543 def _read_init_script(init_path: Path) -> str:
544 try:
545 with open(init_path.expanduser(), "r") as f:
546 init_script = f.read()
547 except OSError:
548 init_script = ""
549 return init_script
550
551 @staticmethod
552 def _split_script(script: str) -> list[str]:
553 """
554 DuckDB init scripts can contain SQL queries or dot commands. The SQL
555 queries may contain newlines, but the dot commands are newline-terminated.
556 This takes a raw script and returns a list of executable commands
557 """
558 lines = script.splitlines()
559 commands: list[str] = []
560 i = 0
561 for j, line in enumerate(lines):
562 if line.startswith("."):
563 commands.append("\n".join(lines[i:j]))
564 commands.append(line)
565 i = j + 1
566 commands.append("\n".join(lines[i:]))
567 return [command.strip() for command in commands if command]
568
569 @staticmethod
570 def _rewrite_dot_open(command: str) -> str:
571 """
572 Rewrites .open command into its SQL equivalent.
573 """
574 args = command.split()[1:]
575 if not args:
576 return "attach ':memory:'; use memory;"
577 else:
578 # --readonly is only supported option
579 if len(args) == 2 and args[0] == "--readonly":
580 option = " (READ_ONLY)"
581 db_path = Path(args[1])
582 else:
583 option = ""
584 db_path = Path(args[0])
585
586 return f"attach '{db_path}'{option} as {db_path.stem}; use {db_path.stem};"
587
588 @classmethod
589 def _rewrite_init_command(cls, command: str) -> str:
590 """
591 DuckDB init scripts can contain dot commands, which can only be executed
592 by the CLI, not the python API. Here, we rewrite some common ones into
593 SQL, and rewrite the others to be no-ops.
594 """
595 if not command.startswith("."):
596 return command
597 elif command.startswith(".open"):
598 return cls._rewrite_dot_open(command)
599 else:
600 return ""