Debian Codegraph @

src/harlequin_mysql/adapter.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import re
4 from contextlib import suppress
5 from typing import Any, Sequence
6
7 from harlequin import (
8 HarlequinAdapter,
9 HarlequinConnection,
10 HarlequinCursor,
11 )
12 from harlequin.autocomplete.completion import HarlequinCompletion
13 from harlequin.catalog import (
14 Catalog,
15 CatalogItem,
16 CatalogSearchKind,
17 CatalogSearchResult,
18 )
19 from harlequin.exception import (
20 HarlequinConfigError,
21 HarlequinConnectionError,
22 HarlequinQueryError,
23 )
24 from mysql.connector import FieldType
25 from mysql.connector.constants import ClientFlag
26 from mysql.connector.cursor import MySQLCursor
27 from mysql.connector.errors import Error as MySQLError
28 from mysql.connector.errors import InternalError, PoolError
29 from mysql.connector.pooling import (
30 MySQLConnectionPool,
31 PooledMySQLConnection,
32 )
33 from textual_fastdatatable.backend import AutoBackendType
34
35 from harlequin_mysql.catalog import (
36 ColumnCatalogItem,
37 DatabaseCatalogItem,
38 RelationCatalogItem,
39 relation_catalog_item,
40 )
41 from harlequin_mysql.cli_options import MYSQLADAPTER_OPTIONS
42 from harlequin_mysql.completions import load_completions
43
44 USE_DATABASE_PROG = re.compile(r"\s*use\s+\S", flags=re.IGNORECASE)
45 QUERY_INTERRUPT_MSG = "1317 (70100): Query execution was interrupted"
46 READ_ONLY_STMT = "set session transaction read only"
47
48 POOL_EXHAUSTED_MSG = (
49 "Connection pool exhausted. Try restarting Harlequin "
50 "with a larger pool or running fewer queries at once."
51 )
52
53 _SYSTEM_DATABASES = "'sys', 'information_schema', 'performance_schema', 'mysql'"
54 """The databases the catalog does not show, as a list for an `in` predicate."""
55
56 _LIKE_ESCAPE = "!"
57 """What escapes a LIKE metacharacter in a term the caller typed.
58
59 Not a backslash, whose meaning inside a string literal depends on the server's
60 sql_mode: with NO_BACKSLASH_ESCAPES set, `escape '\\\\'` is two characters and
61 the server rejects it.
62 """
63
64 _SEARCH_DATABASES = f"""
65 select s.schema_name, null, null, null, null, null
66 from information_schema.schemata s
67 where s.schema_name not in ({_SYSTEM_DATABASES})
68 and lower(s.schema_name) like lower(%s) escape '{_LIKE_ESCAPE}'
69 """
70
71 _SEARCH_RELATIONS = f"""
72 select t.table_schema, t.table_name, t.table_type, null, null, null
73 from information_schema.tables t
74 where t.table_schema not in ({_SYSTEM_DATABASES})
75 and t.table_type != 'SYSTEM VIEW'
76 and lower(t.table_name) like lower(%s) escape '{_LIKE_ESCAPE}'
77 """
78
79 _SEARCH_COLUMNS = f"""
80 select
81 c.table_schema, c.table_name, t.table_type,
82 c.column_name, c.data_type, c.column_type
83 from information_schema.columns c
84 join information_schema.tables t
85 on t.table_schema = c.table_schema
86 and t.table_name = c.table_name
87 where c.table_schema not in ({_SYSTEM_DATABASES})
88 and t.table_type != 'SYSTEM VIEW'
89 and c.extra not like '%%INVISIBLE%%'
90 and lower(c.column_name) like lower(%s) escape '{_LIKE_ESCAPE}'
91 """
92
93 _SEARCH_BRANCHES = {
94 "relations": (_SEARCH_RELATIONS,),
95 "columns": (_SEARCH_COLUMNS,),
96 "all": (_SEARCH_DATABASES, _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 below a
102 database. `information_schema` is server-wide, so one query finds everything in
103 every database.
104
105 The predicates match what `_get_databases()`, `_get_relations()` and
106 `_get_columns()` ask for, so that a search and the catalog tree agree about
107 which objects exist. `%` is doubled because these queries are parameterized:
108 the connector interpolates the parameters with Python's own %-formatting.
109 """
110
111 _SEARCH_SQL = {
112 # MySQL sorts nulls first ascending, so an item arrives before its children
113 kind: " union all ".join(branches) + " order by 1, 2, 4"
114 for kind, branches in _SEARCH_BRANCHES.items()
115 }
116 """One query per kind, ordered so that an item arrives before its children."""
117
118
119 def _contains_pattern(term: str) -> str:
120 """A term as the LIKE pattern that matches any label containing it."""
121 escaped = term
122 for character in (_LIKE_ESCAPE, "%", "_"):
123 escaped = escaped.replace(character, f"{_LIKE_ESCAPE}{character}")
124 return f"%{escaped}%"
125
126
127 class HarlequinMySQLCursor(HarlequinCursor):
128 def __init__(
129 self,
130 cur: MySQLCursor,
131 conn: PooledMySQLConnection,
132 harlequin_conn: HarlequinMySQLConnection,
133 *_: Any,
134 **__: Any,
135 ) -> None:
136 self.cur = cur
137
138 # copy description in case the cursor is closed before columns() is called
139 assert cur.description is not None
140 self.description = cur.description.copy()
141
142 self.conn = conn
143 self.harlequin_conn = harlequin_conn
144 self.connection_id = conn._cnx.connection_id
145 self._limit: int | None = None
146
147 def columns(self) -> list[tuple[str, str]]:
148 return [(col[0], self._get_short_type(col[1])) for col in self.description]
149
150 def set_limit(self, limit: int) -> "HarlequinMySQLCursor":
151 self._limit = limit
152 return self
153
154 def fetchall(self) -> AutoBackendType:
155 try:
156 if self._limit is None:
157 results = self.cur.fetchall()
158 else:
159 results = self.cur.fetchmany(self._limit)
160 return results
161 except Exception as e:
162 if str(e) == QUERY_INTERRUPT_MSG:
163 return []
164 else:
165 raise HarlequinQueryError(
166 msg=str(e),
167 title="Harlequin encountered an error while executing your query.",
168 ) from e
169 finally:
170 self.conn.consume_results()
171 self.cur.close()
172 self.conn.close()
173 if self.connection_id:
174 self.harlequin_conn._in_use_connections.discard(self.connection_id)
175
176 @staticmethod
177 def _get_short_type(type_id: int) -> str:
178 mapping = {
179 FieldType.BIT: "010",
180 FieldType.BLOB: "0b",
181 FieldType.DATE: "d",
182 FieldType.DATETIME: "dt",
183 FieldType.DECIMAL: "#.#",
184 FieldType.DOUBLE: "#.#",
185 FieldType.ENUM: "enum",
186 FieldType.FLOAT: "#.#",
187 FieldType.GEOMETRY: "▽□",
188 FieldType.INT24: "###",
189 FieldType.JSON: "{}",
190 FieldType.LONG: "##",
191 FieldType.LONGLONG: "##",
192 FieldType.LONG_BLOB: "00b",
193 FieldType.MEDIUM_BLOB: "00b",
194 FieldType.NEWDATE: "d",
195 FieldType.NEWDECIMAL: "#.#",
196 FieldType.NULL: "∅",
197 FieldType.SET: "set",
198 FieldType.SHORT: "#",
199 FieldType.STRING: "s",
200 FieldType.TIME: "t",
201 FieldType.TIMESTAMP: "#ts",
202 FieldType.TINY: "#",
203 FieldType.TINY_BLOB: "b",
204 FieldType.VARCHAR: "s",
205 FieldType.VAR_STRING: "s",
206 FieldType.YEAR: "y",
207 }
208 return mapping.get(type_id, "?")
209
210
211 class HarlequinMySQLConnection(HarlequinConnection):
212 def __init__(
213 self,
214 conn_str: Sequence[str],
215 *_: Any,
216 init_message: str = "",
217 options: dict[str, Any],
218 read_only: bool = False,
219 ) -> None:
220 self.init_message = init_message
221 self.read_only = read_only
222 self._in_use_connections: set[int] = set()
223 if read_only:
224 # the server only refuses the writes it is asked to make, one
225 # statement at a time; a single execute() that sends
226 # "set session transaction read write; insert ..." would slip a
227 # write past it. Harlequin splits its buffers into single
228 # statements, so nothing legitimate needs multiple statements
229 # per execute().
230 options = {**options, "client_flags": [-ClientFlag.MULTI_STATEMENTS]}
231 try:
232 self._pool: MySQLConnectionPool = MySQLConnectionPool(
233 pool_name="harlequin",
234 pool_reset_session=False,
235 autocommit=True,
236 **options,
237 )
238 except Exception as e:
239 raise HarlequinConnectionError(
240 msg=str(e), title="Harlequin could not connect to your database."
241 ) from e
242
243 def safe_get_mysql_cursor(
244 self, buffered: bool = False
245 ) -> tuple[PooledMySQLConnection | None, MySQLCursor | None]:
246 """
247 Return None if the connection pool is exhausted, to avoid getting
248 in an unrecoverable state.
249 """
250 try:
251 conn = self._pool.get_connection()
252 except (InternalError, PoolError):
253 # if we're out of connections, we can't raise a query error,
254 # or we get in a state where we have cursors without fetched
255 # results, which requires a restart of Harlequin. Instead,
256 # just return None and silently fail (there isn't a sensible
257 # way to show an error to the user without aborting processing
258 # all the other cursors).
259 return None, None
260 except MySQLError as e:
261 # the pool reconfigures and reconnects its connections lazily, so
262 # a bad config (e.g., a database that has since been dropped) shows
263 # up here. Raise a query error so Harlequin shows the message
264 # instead of crashing.
265 raise HarlequinQueryError(
266 msg=str(e),
267 title="Harlequin could not connect to your database.",
268 ) from e
269
270 try:
271 cur: MySQLCursor = conn.cursor(buffered=buffered)
272 except InternalError:
273 # cursor has an unread result. Try to consume the results,
274 # and try again.
275 conn.consume_results()
276 cur = conn.cursor(buffered=buffered)
277
278 if self.read_only:
279 self._set_session_read_only(conn, cur)
280
281 return conn, cur
282
283 def _set_session_read_only(
284 self, conn: PooledMySQLConnection, cur: MySQLCursor
285 ) -> None:
286 """
287 Asks the server to refuse writes (both DML and DDL) on this connection,
288 with error 1792, ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION.
289
290 The pool creates its connections lazily and does not reset their
291 sessions, so this has to run every time a connection is checked out,
292 not just once per connection: that covers every connection the pool
293 hands out, and undoes a `set session transaction read write` from an
294 earlier query. The setting only applies to the next transaction, so a
295 transaction left open by an earlier query is rolled back first; that
296 cannot lose any work, since it could not have written anything.
297 """
298 try:
299 if conn.in_transaction:
300 conn.rollback()
301 cur.execute(READ_ONLY_STMT)
302 except MySQLError as e:
303 # never hand back a connection that may accept writes
304 with suppress(MySQLError):
305 cur.close()
306 conn.close()
307 raise HarlequinQueryError(
308 msg=str(e),
309 title="Harlequin could not put your connection in read-only mode.",
310 ) from e
311
312 def set_pool_config(self, **config: Any) -> None:
313 """
314 Updates the config of the MySQL connection pool.
315 """
316 self._pool.set_config(**config)
317
318 def execute(self, query: str) -> HarlequinCursor | None:
319 retval: HarlequinCursor | None = None
320
321 conn, cur = self.safe_get_mysql_cursor()
322 if conn is None or cur is None:
323 return None
324 else:
325 connection_id = conn._cnx.connection_id
326 if connection_id:
327 self._in_use_connections.add(connection_id)
328
329 try:
330 cur.execute(query)
331 except Exception as e:
332 cur.close()
333 conn.close()
334 if connection_id:
335 self._in_use_connections.discard(connection_id)
336 if str(e) == QUERY_INTERRUPT_MSG:
337 return None
338 else:
339 raise HarlequinQueryError(
340 msg=str(e),
341 title="Harlequin encountered an error while executing your query.",
342 ) from e
343 else:
344 if cur.description is not None:
345 retval = HarlequinMySQLCursor(cur, conn=conn, harlequin_conn=self)
346 else:
347 cur.close()
348 if USE_DATABASE_PROG.match(query):
349 self._sync_pool_database(conn)
350 conn.close()
351 if connection_id:
352 self._in_use_connections.discard(connection_id)
353
354 return retval
355
356 def _sync_pool_database(self, conn: PooledMySQLConnection) -> None:
357 """
358 This is a hack to update all connections in the pool if the user
359 changes the database for the active connection.
360 It is impossible to check the database or other config
361 of a connection with an open cursor, and we can't use a dedicated
362 connection for user queries, since mysql only supports a single
363 (unfetched) cursor per connection.
364
365 The active database is read back from the server, since parsing it out
366 of the query is error-prone (the query may end with a semicolon, the
367 name may be quoted, etc.).
368 """
369 with suppress(MySQLError):
370 if new_db := conn.database:
371 self.set_pool_config(database=new_db)
372
373 def cancel(self) -> None:
374 # get a new cursor to execute the KILL statements
375 try:
376 conn, cur = self.safe_get_mysql_cursor()
377 except HarlequinQueryError:
378 return None
379 if conn is None or cur is None:
380 return None
381
382 # loop through in-use connections and kill each of them
383 for connection_id in self._in_use_connections:
384 try:
385 cur.execute("KILL QUERY %s", (connection_id,))
386 except BaseException:
387 continue
388
389 cur.close()
390 conn.close()
391 self._in_use_connections = set()
392
393 def close(self) -> None:
394 with suppress(PoolError):
395 self._pool._remove_connections()
396
397 def get_catalog(self) -> Catalog:
398 databases = self._get_databases()
399 db_items: list[CatalogItem] = [
400 DatabaseCatalogItem.from_label(label=db, connection=self)
401 for (db,) in databases
402 ]
403 return Catalog(items=db_items)
404
405 def search_catalog(
406 self, term: str, kind: CatalogSearchKind = "all"
407 ) -> list[CatalogSearchResult]:
408 conn, cur = self.safe_get_mysql_cursor(buffered=True)
409 if conn is None or cur is None:
410 raise HarlequinConnectionError(
411 title="Connection pool exhausted",
412 msg=POOL_EXHAUSTED_MSG,
413 )
414 try:
415 cur.execute(
416 _SEARCH_SQL[kind],
417 [_contains_pattern(term)] * len(_SEARCH_BRANCHES[kind]),
418 )
419 # a row is (database, relation, relation_type, column, data_type,
420 # column_type), null below the level it names
421 found: list[tuple[Any, ...]] = cur.fetchall()
422 except MySQLError as e:
423 raise HarlequinQueryError(
424 msg=str(e),
425 title="MySQL raised an error searching the catalog:",
426 ) from e
427 finally:
428 cur.close()
429 conn.close()
430
431 databases: dict[str, DatabaseCatalogItem] = {}
432 relations: dict[tuple[str, str], RelationCatalogItem] = {}
433 results: list[CatalogSearchResult] = []
434 # a row names the deepest level it fills in, and carries its ancestors
435 # so that each one is built once and the match knows its own path
436 for database, relation, relation_type, column, data_type, column_type in found:
437 database_item = databases.setdefault(
438 database,
439 DatabaseCatalogItem.from_label(label=database, connection=self),
440 )
441 if relation is None:
442 results.append(CatalogSearchResult(item=database_item))
443 continue
444 relation_item = relations.setdefault(
445 (database, relation),
446 relation_catalog_item(
447 parent=database_item, label=relation, type_name=relation_type
448 ),
449 )
450 if column is None:
451 results.append(
452 CatalogSearchResult(item=relation_item, parents=(database,))
453 )
454 continue
455 results.append(
456 CatalogSearchResult(
457 item=ColumnCatalogItem.from_parent(
458 parent=relation_item,
459 label=column,
460 type_label=self._short_column_type(data_type),
461 type_name=column_type,
462 ),
463 parents=(database, relation),
464 )
465 )
466 return results
467
468 def get_completions(self) -> list[HarlequinCompletion]:
469 return load_completions()
470
471 def _get_databases(self) -> list[tuple[str]]:
472 conn, cur = self.safe_get_mysql_cursor(buffered=True)
473 if conn is None or cur is None:
474 raise HarlequinConnectionError(
475 title="Connection pool exhausted",
476 msg=POOL_EXHAUSTED_MSG,
477 )
478 cur.execute(
479 f"""
480 show databases
481 where `Database` not in ({_SYSTEM_DATABASES})
482 """
483 )
484 results: list[tuple[str]] = cur.fetchall() # type: ignore
485 cur.close()
486 conn.close()
487 return results
488
489 def _get_relations(self, db_name: str) -> list[tuple[str, str]]:
490 conn, cur = self.safe_get_mysql_cursor(buffered=True)
491 if conn is None or cur is None:
492 raise HarlequinConnectionError(
493 title="Connection pool exhausted",
494 msg=POOL_EXHAUSTED_MSG,
495 )
496 cur.execute(
497 f"""
498 select
499 table_name,
500 table_type
501 from information_schema.tables
502 where table_schema = '{db_name}'
503 and table_type != 'SYSTEM VIEW'
504 order by table_name asc
505 ;"""
506 )
507 results: list[tuple[str, str]] = cur.fetchall() # type: ignore
508 cur.close()
509 conn.close()
510 return results
511
512 def _get_columns(self, db_name: str, rel_name: str) -> list[tuple[str, str, str]]:
513 conn, cur = self.safe_get_mysql_cursor(buffered=True)
514 if conn is None or cur is None:
515 raise HarlequinConnectionError(
516 title="Connection pool exhausted",
517 msg=POOL_EXHAUSTED_MSG,
518 )
519 cur.execute(
520 f"""
521 select column_name, data_type, column_type
522 from information_schema.columns
523 where
524 table_schema = '{db_name}'
525 and table_name = '{rel_name}'
526 and extra not like '%INVISIBLE%'
527 order by ordinal_position asc
528 ;"""
529 )
530 results: list[tuple[str, str, str]] = cur.fetchall() # type: ignore
531 cur.close()
532 conn.close()
533 return results
534
535 @staticmethod
536 def _short_column_type(info_schema_type: str) -> str:
537 mapping = {
538 "bigint": "###",
539 "binary": "010",
540 "blob": "0b",
541 "char": "c",
542 "datetime": "dt",
543 "decimal": "#.#",
544 "double": "#.#",
545 "enum": "enum",
546 "float": "#.#",
547 "int": "##",
548 "json": "{}",
549 "longblob": "00b",
550 "longtext": "ss",
551 "mediumblob": "00b",
552 "mediumint": "##",
553 "mediumtext": "s",
554 "set": "set",
555 "smallint": "#",
556 "text": "s",
557 "time": "t",
558 "timestamp": "ts",
559 "tinyint": "#",
560 "varbinary": "010",
561 "varchar": "s",
562 }
563 return mapping.get(info_schema_type, "?")
564
565
566 class HarlequinMySQLAdapter(HarlequinAdapter):
567 ADAPTER_OPTIONS = MYSQLADAPTER_OPTIONS
568 IMPLEMENTS_CANCEL = True
569 # information_schema is server-wide, so one query searches every database
570 IMPLEMENTS_CATALOG_SEARCH = True
571 # enforced by the server, with `set session transaction read only`
572 IMPLEMENTS_READ_ONLY = True
573
574 def __init__(
575 self,
576 conn_str: Sequence[str],
577 read_only: bool = False,
578 host: str | None = None,
579 port: str | int | None = 3306,
580 unix_socket: str | None = None,
581 database: str | None = None,
582 user: str | None = None,
583 password: str | None = None,
584 password2: str | None = None,
585 password3: str | None = None,
586 connection_timeout: str | int | None = None,
587 ssl_ca: str | None = None,
588 ssl_cert: str | None = None,
589 ssl_disabled: str | bool | None = False,
590 ssl_key: str | None = None,
591 openid_token_file: str | None = None,
592 pool_size: str | int | None = 5,
593 enable_cleartext_plugin: str | bool | None = False,
594 **_: Any,
595 ) -> None:
596 if conn_str:
597 raise HarlequinConnectionError(
598 f"Cannot provide a DSN to the MySQL adapter. Got:\n{conn_str}"
599 )
600 # Harlequin casts read_only to a bool before passing it here. It is
601 # not a mysql-connector connection argument, so it is kept out of
602 # self.options, which is passed to the connection pool.
603 self.read_only = bool(read_only)
604 try:
605 self.options = {
606 "host": host,
607 "port": int(port) if port is not None else 3306,
608 "unix_socket": unix_socket,
609 "database": database,
610 "user": user,
611 "password": password,
612 "password2": password2,
613 "password3": password3,
614 "connection_timeout": int(connection_timeout)
615 if connection_timeout is not None
616 else None,
617 "ssl_ca": ssl_ca,
618 "ssl_cert": ssl_cert,
619 "ssl_disabled": ssl_disabled if ssl_disabled is not None else False,
620 "ssl_key": ssl_key,
621 "openid_token_file": openid_token_file,
622 "pool_size": int(pool_size) if pool_size is not None else 5,
623 "allow_local_infile": enable_cleartext_plugin
624 if enable_cleartext_plugin is not None
625 else False,
626 }
627 except (ValueError, TypeError) as e:
628 raise HarlequinConfigError(
629 msg=f"MySQL adapter received bad config value: {e}",
630 title="Harlequin could not initialize the selected adapter.",
631 ) from e
632
633 @property
634 def connection_id(self) -> str | None:
635 host = self.options.get("host", "") or ""
636 sock = self.options.get("unix_socket", "") or ""
637 host = host if host or sock else "127.0.0.1"
638
639 port = self.options.get("port", 3306)
640 database = self.options.get("database", "") or ""
641
642 return f"{host}{sock}:{port}/{database}"
643
644 def connect(self) -> HarlequinMySQLConnection:
645 conn = HarlequinMySQLConnection(
646 conn_str=tuple(), options=self.options, read_only=self.read_only
647 )
648 return conn