execsql2 2.37.0__py3-none-any.whl → 2.39.1__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.
Files changed (77) hide show
  1. execsql/api.py +95 -45
  2. execsql/cli/commands/run.py +2 -2
  3. execsql/cli/lint.py +46 -9
  4. execsql/cli/run.py +128 -56
  5. execsql/config.py +7 -0
  6. execsql/data/execsql.conf.template +26 -2
  7. execsql/db/base.py +61 -24
  8. execsql/db/dsn.py +2 -3
  9. execsql/db/duckdb.py +43 -4
  10. execsql/db/firebird.py +39 -22
  11. execsql/db/mysql.py +22 -23
  12. execsql/db/oracle.py +11 -4
  13. execsql/db/postgres.py +15 -20
  14. execsql/db/sqlite.py +117 -10
  15. execsql/db/sqlserver.py +11 -7
  16. execsql/db/target_types.py +151 -4
  17. execsql/debug/repl.py +2 -1
  18. execsql/exceptions.py +19 -0
  19. execsql/exporters/html.py +26 -42
  20. execsql/exporters/ods.py +93 -21
  21. execsql/exporters/sqlite.py +82 -47
  22. execsql/format.py +12 -4
  23. execsql/gui/__init__.py +13 -10
  24. execsql/gui/base.py +131 -8
  25. execsql/gui/console.py +77 -30
  26. execsql/gui/desktop.py +290 -119
  27. execsql/gui/tui.py +384 -129
  28. execsql/importers/base.py +15 -19
  29. execsql/importers/csv.py +3 -5
  30. execsql/importers/json.py +37 -13
  31. execsql/importers/ods.py +22 -2
  32. execsql/lsp/document.py +6 -1
  33. execsql/lsp/hover.py +2 -1
  34. execsql/metacommands/conditions.py +3 -1
  35. execsql/metacommands/connect.py +18 -3
  36. execsql/metacommands/control.py +20 -5
  37. execsql/metacommands/data.py +11 -9
  38. execsql/metacommands/dispatch.py +10 -0
  39. execsql/metacommands/io.py +1 -0
  40. execsql/metacommands/io_export.py +1 -2
  41. execsql/metacommands/io_fileops.py +27 -91
  42. execsql/metacommands/io_import.py +26 -8
  43. execsql/metacommands/io_write.py +0 -9
  44. execsql/metacommands/prompt.py +94 -42
  45. execsql/metacommands/reference.py +7 -0
  46. execsql/metacommands/system.py +0 -2
  47. execsql/parser.py +132 -45
  48. execsql/script/control.py +17 -7
  49. execsql/script/engine.py +1 -1
  50. execsql/script/executor.py +184 -37
  51. execsql/script/preparation.py +42 -0
  52. execsql/types.py +6 -5
  53. execsql/utils/auth.py +11 -6
  54. execsql/utils/errors.py +2 -2
  55. execsql/utils/fileio.py +342 -134
  56. execsql/utils/gui.py +162 -53
  57. execsql/utils/spreadsheet.py +74 -0
  58. execsql/utils/strings.py +13 -7
  59. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/README.md +5 -5
  60. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/example_config_prompt.sql +2 -2
  61. {execsql2-2.37.0.dist-info → execsql2-2.39.1.dist-info}/METADATA +32 -119
  62. {execsql2-2.37.0.dist-info → execsql2-2.39.1.dist-info}/RECORD +77 -75
  63. {execsql2-2.37.0.dist-info → execsql2-2.39.1.dist-info}/WHEEL +1 -1
  64. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/config_settings.sqlite +0 -0
  65. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/make_config_db.sql +0 -0
  66. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/md_compare.sql +0 -0
  67. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/md_glossary.sql +0 -0
  68. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/md_upsert.sql +0 -0
  69. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/pg_compare.sql +0 -0
  70. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/pg_glossary.sql +0 -0
  71. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/script_template.sql +0 -0
  72. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/ss_compare.sql +0 -0
  73. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/ss_glossary.sql +0 -0
  74. {execsql2-2.37.0.data → execsql2-2.39.1.data}/data/execsql2_extras/ss_upsert.sql +0 -0
  75. {execsql2-2.37.0.dist-info → execsql2-2.39.1.dist-info}/entry_points.txt +0 -0
  76. {execsql2-2.37.0.dist-info → execsql2-2.39.1.dist-info}/licenses/LICENSE.txt +0 -0
  77. {execsql2-2.37.0.dist-info → execsql2-2.39.1.dist-info}/licenses/NOTICE +0 -0
execsql/gui/tui.py CHANGED
@@ -23,7 +23,7 @@ import queue as _stdlib_queue
23
23
  import threading
24
24
  from typing import Any, Literal, cast
25
25
 
26
- from execsql.gui.base import GuiBackend
26
+ from execsql.gui.base import GuiBackend, selected_row_values
27
27
 
28
28
  # ---------------------------------------------------------------------------
29
29
  # Textual import guard — raises ImportError if not installed so that the
@@ -36,10 +36,11 @@ except ImportError as _e:
36
36
  "Textual is not installed. It is a dependency of execsql2; reinstall execsql2 to restore it.",
37
37
  ) from _e
38
38
 
39
- from textual import on
39
+ from textual import events, on
40
40
  from textual.app import App, ComposeResult
41
41
  from textual.binding import Binding
42
42
  from textual.containers import Container, Horizontal, ScrollableContainer, Vertical
43
+ from textual.message import Message
43
44
  from textual.screen import ModalScreen
44
45
  from textual.widgets import (
45
46
  Button,
@@ -61,7 +62,14 @@ from textual.widgets import (
61
62
 
62
63
  __all__ = ["TextualBackend"]
63
64
 
64
- from execsql.gui.base import DIFF_MARKER, DiffResult, compare_stats as _compare_stats, compute_row_diffs
65
+ from execsql.gui.base import (
66
+ DIFF_MARKER,
67
+ DiffResult,
68
+ _key_column_indices,
69
+ compare_stats as _compare_stats,
70
+ compute_row_diffs,
71
+ normalize_text_entry,
72
+ )
65
73
 
66
74
  # ---------------------------------------------------------------------------
67
75
  # Helpers
@@ -73,9 +81,15 @@ def _row_count_text(n: int) -> str:
73
81
  return f"{n:,} row{'s' if n != 1 else ''}"
74
82
 
75
83
 
76
- def _make_table_widget(table_id: str, headers: list, rows: list) -> DataTable:
84
+ def _make_table_widget(
85
+ table_id: str,
86
+ headers: list,
87
+ rows: list,
88
+ *,
89
+ table_class: type[DataTable] = DataTable,
90
+ ) -> DataTable:
77
91
  """Build a DataTable widget populated with data."""
78
- dt: DataTable = DataTable(id=table_id, zebra_stripes=True, cursor_type="row")
92
+ dt: DataTable = table_class(id=table_id, zebra_stripes=True, cursor_type="row")
79
93
  dt.add_columns(*[str(h) for h in headers])
80
94
  for row in rows:
81
95
  dt.add_row(*[str(c) if c is not None else "" for c in row])
@@ -94,9 +108,9 @@ def _button_row(button_list: list, no_cancel: bool = False) -> list[Button]:
94
108
 
95
109
  A Cancel button (id ``btn_cancel_exit``) is prepended so it appears on the
96
110
  left while the primary action button sits on the far right. Entries in
97
- *button_list* with a falsy value (0 or None) are treated as the cancel
98
- label source and are otherwise excluded from the numbered buttons so that
99
- ``btn_N`` indices stay aligned with ``button_list`` positions.
111
+ *button_list* with value None supply the cancel label and are otherwise
112
+ excluded from numbered buttons. Zero is a real response, such as No in
113
+ ASK prompts. ``btn_N`` indices stay aligned with ``button_list`` positions.
100
114
 
101
115
  When *no_cancel* is set, the Cancel button is omitted — dialogs such as
102
116
  HALT have no meaningful cancel action, and cancelling one would exit with
@@ -106,7 +120,7 @@ def _button_row(button_list: list, no_cancel: bool = False) -> list[Button]:
106
120
  primary_buttons = []
107
121
  for i, btn in enumerate(button_list):
108
122
  label, value = btn[0], btn[1]
109
- if not value and value != 1: # falsy but not accidentally 1
123
+ if value is None:
110
124
  cancel_label = label
111
125
  else:
112
126
  variant: Literal["primary", "default"] = "primary" if i == 0 else "default"
@@ -201,7 +215,7 @@ class _BaseDialog(ModalScreen):
201
215
 
202
216
  @on(Button.Pressed, "#btn_cancel_exit")
203
217
  def _on_cancel_exit(self, event: Button.Pressed) -> None:
204
- """Universal Cancel handler — dismisses with cancelled=True so the sync queue can exit."""
218
+ """Return cancellation to the script's prompt handler."""
205
219
  event.stop()
206
220
  self._result = {"button": None, "cancelled": True}
207
221
  self.dismiss(self._result)
@@ -424,8 +438,26 @@ class DisplayScreen(_BaseDialog):
424
438
  break
425
439
  if value is None:
426
440
  return
441
+ self._submit(value)
442
+
443
+ @on(Input.Submitted, "#text_input")
444
+ def _on_text_submitted(self, event: Input.Submitted) -> None:
445
+ event.stop()
446
+ self.action_submit()
447
+
448
+ def _submit(self, value: int | None) -> None:
427
449
  text_input = self.query_one("#text_input", Input) if self.args.get("textentry") else None
428
450
  return_value = text_input.value if text_input else None
451
+ if value is not None and return_value is not None:
452
+ try:
453
+ return_value = normalize_text_entry(
454
+ return_value,
455
+ self.args.get("textentrytype"),
456
+ self.args.get("textentrycase"),
457
+ )
458
+ except ValueError as exc:
459
+ self.notify(str(exc), title="Invalid entry", severity="error")
460
+ return
429
461
  self._result = {"button": value, "return_value": return_value}
430
462
  self.dismiss(self._result)
431
463
 
@@ -435,10 +467,7 @@ class DisplayScreen(_BaseDialog):
435
467
  idx = int(btn_id.split("_")[1])
436
468
  button_list = self.args.get("button_list", [("Continue", 1)])
437
469
  value = button_list[idx][1]
438
- text_input = self.query_one("#text_input", Input) if self.args.get("textentry") else None
439
- return_value = text_input.value if text_input else None
440
- self._result = {"button": value, "return_value": return_value}
441
- self.dismiss(self._result)
470
+ self._submit(value)
442
471
 
443
472
 
444
473
  # ---------------------------------------------------------------------------
@@ -476,6 +505,7 @@ class EntryFormScreen(_BaseDialog):
476
505
  def __init__(self, args: dict) -> None:
477
506
  super().__init__(args)
478
507
  self._inputs: dict[str, Any] = {}
508
+ self._browse_fields: dict[str, str] = {}
479
509
 
480
510
  def compose(self) -> ComposeResult:
481
511
  title = self.args.get("title", "Entry")
@@ -497,9 +527,9 @@ class EntryFormScreen(_BaseDialog):
497
527
  yield _make_table_widget("form_table", headers, rows)
498
528
  yield Static(_row_count_text(len(rows)), classes="row-count")
499
529
  with ScrollableContainer(id="fields"):
500
- for spec in specs:
530
+ for index, spec in enumerate(specs):
501
531
  etype = (spec.entry_type or "text").lower()
502
- field_id = f"field_{spec.varname}"
532
+ field_id = f"field_{index}"
503
533
  # Compute the display label (radiobuttons uses semicolon-delimited)
504
534
  if etype == "radiobuttons":
505
535
  parts = (spec.label or "").split(";")
@@ -511,8 +541,8 @@ class EntryFormScreen(_BaseDialog):
511
541
  # Multi-row widget — render label + SelectionList vertically
512
542
  yield Static(field_label, classes="row-count")
513
543
  height = spec.default_height or 4
514
- sl = SelectionList[str](
515
- *[(str(v), str(v), False) for v in spec.lookup_list if v is not None],
544
+ sl = SelectionList[tuple[int, str]](
545
+ *[(str(v), (i, str(v)), False) for i, v in enumerate(spec.lookup_list) if v is not None],
516
546
  id=field_id,
517
547
  )
518
548
  sl.styles.height = height + 2
@@ -565,9 +595,11 @@ class EntryFormScreen(_BaseDialog):
565
595
  placeholder="Enter file path or click Browse",
566
596
  )
567
597
  yield inp
598
+ browse_id = f"browse_{index}"
599
+ self._browse_fields[browse_id] = spec.varname
568
600
  yield Button(
569
601
  "Browse…",
570
- id=f"browse_{spec.varname}",
602
+ id=browse_id,
571
603
  variant="default",
572
604
  )
573
605
  self._inputs[spec.varname] = inp
@@ -598,7 +630,7 @@ class EntryFormScreen(_BaseDialog):
598
630
  if not btn_id.startswith("browse_"):
599
631
  return
600
632
  event.stop()
601
- varname = btn_id[len("browse_") :]
633
+ varname = self._browse_fields[btn_id]
602
634
  tree = self.query_one("#file_tree", DirectoryTree)
603
635
  if tree.styles.display == "none":
604
636
  self._browse_target = varname
@@ -627,8 +659,7 @@ class EntryFormScreen(_BaseDialog):
627
659
  if etype == "checkbox":
628
660
  spec.value = "1" if widget.value else "0"
629
661
  elif etype == "listbox" and isinstance(widget, SelectionList):
630
- selected = widget.selected
631
- items = [str(widget.get_option_at_index(i).value) for i in selected]
662
+ items = [value for _, value in widget.selected]
632
663
  spec.value = ",".join(f"'{v.replace(chr(39), chr(39) + chr(39))}'" for v in items)
633
664
  elif etype == "radiobuttons" and isinstance(widget, RadioSet):
634
665
  spec.value = str(widget.pressed_index + 1) if widget.pressed_index >= 0 else "1"
@@ -645,6 +676,10 @@ class EntryFormScreen(_BaseDialog):
645
676
  etype = (spec.entry_type or "text").lower()
646
677
  if spec.required and not val and etype != "checkbox":
647
678
  errors.append(f"{spec.label or spec.varname}: required")
679
+ if etype in ("dropdown", "select") and spec.lookup_list:
680
+ valid = [str(value) for value in spec.lookup_list if value is not None]
681
+ if val not in valid:
682
+ errors.append(f"{spec.label or spec.varname}: choose a valid value")
648
683
  if spec.validation_regex and val and not _re.fullmatch(spec.validation_regex, val):
649
684
  errors.append(f"{spec.label or spec.varname}: does not match pattern")
650
685
  return errors
@@ -785,8 +820,12 @@ class CompareScreen(_BaseDialog):
785
820
  rows1 = self.args.get("rows1", [])
786
821
  rows2 = self.args.get("rows2", [])
787
822
 
788
- self._key_idx1 = [i for i, h in enumerate(headers1) if h in keylist]
789
- self._key_idx2 = [i for i, h in enumerate(headers2) if h in keylist]
823
+ key_idx1 = _key_column_indices(headers1, keylist)
824
+ key_idx2 = _key_column_indices(headers2, keylist)
825
+ if not key_idx1 or not key_idx2:
826
+ return
827
+ self._key_idx1 = key_idx1
828
+ self._key_idx2 = key_idx2
790
829
 
791
830
  # Syncing uses display-consistent string normalization (DataTable
792
831
  # cells are strings). The diff engine in base.py has its own
@@ -936,6 +975,23 @@ class CompareScreen(_BaseDialog):
936
975
  # ---------------------------------------------------------------------------
937
976
 
938
977
 
978
+ class _SelectRowsTable(DataTable):
979
+ """Highlight on a single click; add/remove a row on double-click or Enter."""
980
+
981
+ def on_click(self, event: events.Click) -> None:
982
+ row = event.style.meta.get("row", -1)
983
+ if row == -1 and not event.style.meta.get("out_of_bounds"):
984
+ return
985
+ event.prevent_default()
986
+ event.stop()
987
+ if event.style.meta.get("out_of_bounds") or not 0 <= row < len(self.rows):
988
+ return
989
+ self.focus()
990
+ self.move_cursor(row=row)
991
+ if event.chain == 2:
992
+ self.post_message(DataTable.RowSelected(self, row, self.ordered_rows[row].key))
993
+
994
+
939
995
  class SelectRowsScreen(_BaseDialog):
940
996
  """Row selection dialog: pick rows from source table and add to target."""
941
997
 
@@ -958,6 +1014,12 @@ class SelectRowsScreen(_BaseDialog):
958
1014
  """
959
1015
  )
960
1016
 
1017
+ def __init__(self, args: dict) -> None:
1018
+ super().__init__(args)
1019
+ self._selected_rows: list[list[Any]] = []
1020
+ self._source_rows: dict[Any, list[Any]] = {}
1021
+ self._pending_rows: dict[Any, list[Any]] = {}
1022
+
961
1023
  def compose(self) -> ComposeResult:
962
1024
  title = self.args.get("title", "Select rows")
963
1025
  message = self.args.get("message", "")
@@ -975,33 +1037,47 @@ class SelectRowsScreen(_BaseDialog):
975
1037
  yield help_btn
976
1038
  if message:
977
1039
  yield Static(message, id="message")
978
- yield Static("Double-click or press Enter on a row to add it to the right table.", id="hint")
1040
+ yield Static(
1041
+ "Double-click or press Enter: source adds a copy; an added destination row removes that copy. Existing rows are kept.",
1042
+ id="hint",
1043
+ )
979
1044
  with Horizontal(id="tables"):
980
1045
  with Vertical(classes="sel-table"):
981
1046
  yield Label("Source (select rows)")
982
- yield _make_table_widget("source_table", headers1, rows1)
1047
+ source = _make_table_widget("source_table", headers1, rows1, table_class=_SelectRowsTable)
1048
+ self._source_rows = {key: list(row) for key, row in zip(source.rows, rows1)}
1049
+ yield source
983
1050
  yield Static(_row_count_text(len(rows1)), classes="row-count")
984
1051
  with Vertical(classes="sel-table"):
985
1052
  yield Label("Destination")
986
- yield _make_table_widget("dest_table", headers2, rows2)
987
- yield Static(_row_count_text(len(rows2)), classes="row-count")
1053
+ yield _make_table_widget("dest_table", headers2, rows2, table_class=_SelectRowsTable)
1054
+ yield Static(_row_count_text(len(rows2)), classes="row-count", id="destination_count")
988
1055
  with Horizontal(id="buttons"):
989
1056
  yield from _button_row(button_list)
990
1057
 
991
1058
  def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
1059
+ dest = self.query_one("#dest_table", DataTable)
992
1060
  if event.data_table.id == "source_table":
993
- dest: DataTable = self.query_one("#dest_table", DataTable)
994
1061
  row_key = event.row_key
995
- src: DataTable = self.query_one("#source_table", DataTable)
996
- values = [src.get_cell(row_key, col) for col in src.columns]
997
- dest.add_row(*values)
1062
+ values = self._source_rows[row_key]
1063
+ selected = list(values)
1064
+ self._selected_rows.append(selected)
1065
+ display = selected_row_values(self.args.get("headers1", []), values, self.args.get("headers2", []))
1066
+ key = dest.add_row(*[str(value) if value is not None else "" for value in display])
1067
+ self._pending_rows[key] = selected
1068
+ elif event.data_table.id == "dest_table":
1069
+ removed = self._pending_rows.pop(event.row_key, None)
1070
+ if removed is not None:
1071
+ self._selected_rows = [row for row in self._selected_rows if row is not removed]
1072
+ dest.remove_row(event.row_key)
1073
+ self.query_one("#destination_count", Static).update(_row_count_text(dest.row_count))
998
1074
 
999
1075
  def action_submit(self) -> None:
1000
1076
  """Submit the first primary button value (triggered by Enter key)."""
1001
1077
  button_list = self.args.get("button_list", [("Continue", 1)])
1002
1078
  for btn in button_list:
1003
1079
  if btn[1]:
1004
- self._result = {"button": btn[1]}
1080
+ self._result = {"button": btn[1], "rows": self._selected_rows}
1005
1081
  self.dismiss(self._result)
1006
1082
  return
1007
1083
 
@@ -1010,7 +1086,7 @@ class SelectRowsScreen(_BaseDialog):
1010
1086
  if btn_id and btn_id.startswith("btn_") and btn_id[4:].isdigit():
1011
1087
  idx = int(btn_id.split("_")[1])
1012
1088
  value = self.args.get("button_list", [("Continue", 1)])[idx][1]
1013
- self._result = {"button": value}
1089
+ self._result = {"button": value, "rows": self._selected_rows if value is not None else None}
1014
1090
  self.dismiss(self._result)
1015
1091
 
1016
1092
 
@@ -1019,20 +1095,36 @@ class SelectRowsScreen(_BaseDialog):
1019
1095
  # ---------------------------------------------------------------------------
1020
1096
 
1021
1097
 
1098
+ class _SelectSubTable(DataTable):
1099
+ """Confirm on a double-click, retaining single clicks for highlighting."""
1100
+
1101
+ class Confirmed(Message):
1102
+ def __init__(self, row_key: Any) -> None:
1103
+ super().__init__()
1104
+ self.row_key = row_key
1105
+
1106
+ def on_click(self, event: events.Click) -> None:
1107
+ row_index = event.style.meta.get("row", -1)
1108
+ if event.chain == 2 and not event.style.meta.get("out_of_bounds") and 0 <= row_index < len(self.rows):
1109
+ self.post_message(self.Confirmed(self.ordered_rows[row_index].key))
1110
+
1111
+
1022
1112
  class SelectSubScreen(_BaseDialog):
1023
1113
  """Single-row selection dialog: pick one row and assign column values to vars."""
1024
1114
 
1115
+ BINDINGS = [*_BaseDialog.BINDINGS, Binding("enter", "submit", "Submit", priority=True)]
1116
+
1025
1117
  def __init__(self, args: dict) -> None:
1026
1118
  super().__init__(args)
1027
- self._selected_row: dict | None = None
1028
- self._headers: list = args.get("headers", [])
1119
+ self._selected_row: list | None = None
1120
+ self._source_rows: dict[Any, list] = {}
1029
1121
 
1030
1122
  def compose(self) -> ComposeResult:
1031
1123
  title = self.args.get("title", "Select a row")
1032
1124
  message = self.args.get("message", "")
1033
1125
  headers = self.args.get("headers", [])
1034
1126
  rows = self.args.get("rows", [])
1035
- button_list = self.args.get("button_list", [("OK", 1), ("Cancel", 0)])
1127
+ button_list = self.args.get("button_list", [("OK", 1)])
1036
1128
 
1037
1129
  with Container(id="dialog"):
1038
1130
  if title:
@@ -1044,24 +1136,38 @@ class SelectSubScreen(_BaseDialog):
1044
1136
  yield Static(message, id="message")
1045
1137
  yield Static("Click a row to select it.", id="hint")
1046
1138
  with ScrollableContainer():
1047
- yield _make_table_widget("sel_table", headers, rows)
1139
+ source = _make_table_widget("sel_table", headers, rows, table_class=_SelectSubTable)
1140
+ self._source_rows = {key: list(row) for key, row in zip(source.rows, rows)}
1141
+ yield source
1048
1142
  yield Static(_row_count_text(len(rows)), classes="row-count")
1049
1143
  with Horizontal(id="buttons"):
1050
1144
  yield from _button_row(button_list)
1051
1145
 
1052
1146
  def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
1053
- row_key = event.row_key
1054
- tbl: DataTable = self.query_one("#sel_table", DataTable)
1055
- values = [tbl.get_cell(row_key, col) for col in tbl.columns]
1056
- self._selected_row = dict(zip(self._headers, values))
1147
+ self._selected_row = self._source_rows.get(event.row_key)
1148
+
1149
+ @on(_SelectSubTable.Confirmed)
1150
+ def _on_row_confirmed(self, event: _SelectSubTable.Confirmed) -> None:
1151
+ self._selected_row = self._source_rows.get(event.row_key)
1152
+ self._submit(1)
1153
+
1154
+ def _submit(self, value: int | None) -> None:
1155
+ if value == 1 and self._selected_row is None:
1156
+ return
1157
+ self._result = {"button": value, "row": self._selected_row if value == 1 else None}
1158
+ self.dismiss(self._result)
1159
+
1160
+ def action_submit(self) -> None:
1161
+ buttons = self.args.get("button_list", [("OK", 1)])
1162
+ value = next((b[1] for b in buttons if len(b) > 2 and b[2] == "<Return>"), 1)
1163
+ self._submit(value)
1057
1164
 
1058
1165
  def on_button_pressed(self, event: Button.Pressed) -> None:
1059
1166
  btn_id = event.button.id
1060
1167
  if btn_id and btn_id.startswith("btn_") and btn_id[4:].isdigit():
1061
1168
  idx = int(btn_id.split("_")[1])
1062
- value = self.args.get("button_list", [("OK", 1), ("Cancel", 0)])[idx][1]
1063
- self._result = {"button": value, "row": self._selected_row}
1064
- self.dismiss(self._result)
1169
+ value = self.args.get("button_list", [("OK", 1)])[idx][1]
1170
+ self._submit(value)
1065
1171
 
1066
1172
 
1067
1173
  # ---------------------------------------------------------------------------
@@ -1075,6 +1181,20 @@ class ActionScreen(_BaseDialog):
1075
1181
  BINDINGS = [
1076
1182
  *_BaseDialog.BINDINGS,
1077
1183
  ]
1184
+ AUTO_FOCUS = ""
1185
+ DEFAULT_CSS = (
1186
+ _BaseDialog.DEFAULT_CSS
1187
+ + """
1188
+ #action_buttons { height: auto; }
1189
+ #action_data { height: auto; max-height: 10; }
1190
+ """
1191
+ )
1192
+
1193
+ def __init__(self, args: dict) -> None:
1194
+ super().__init__(args)
1195
+ self._button_specs = args.get("button_specs", [])
1196
+ self._source_rows: dict[Any, list] = {}
1197
+ self._selected_row: list | None = None
1078
1198
 
1079
1199
  def compose(self) -> ComposeResult:
1080
1200
  title = self.args.get("title", "Actions")
@@ -1093,24 +1213,47 @@ class ActionScreen(_BaseDialog):
1093
1213
  if message:
1094
1214
  yield Static(message, id="message")
1095
1215
  if headers and rows:
1096
- with ScrollableContainer():
1097
- yield _make_table_widget("action_table", headers, rows)
1216
+ with ScrollableContainer(id="action_data"):
1217
+ source = _make_table_widget("action_table", headers, rows)
1218
+ self._source_rows = {key: list(row) for key, row in zip(source.rows, rows)}
1219
+ yield source
1098
1220
  yield Static(_row_count_text(len(rows)), classes="row-count")
1099
1221
  with Vertical(id="action_buttons"):
1100
1222
  for i, spec in enumerate(button_specs):
1101
- yield Button(f"{spec.label} — {spec.prompt}", id=f"action_{i}", variant="primary")
1223
+ yield Button(
1224
+ f"{spec.label} — {spec.prompt}",
1225
+ id=f"action_{i}",
1226
+ variant="primary",
1227
+ disabled=spec.data_required,
1228
+ )
1102
1229
  if include_continue:
1103
1230
  yield Button("Continue", id="action_continue", variant="default")
1231
+ yield Button("Cancel", id="btn_cancel_exit", variant="warning")
1232
+
1233
+ def _select_row(self, row_key: Any) -> None:
1234
+ self._selected_row = self._source_rows.get(row_key)
1235
+ for i, spec in enumerate(self._button_specs):
1236
+ self.query_one(f"#action_{i}", Button).disabled = spec.data_required and self._selected_row is None
1237
+
1238
+ def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
1239
+ if event.data_table.has_focus:
1240
+ self._select_row(event.row_key)
1104
1241
 
1105
- self._button_specs = button_specs
1242
+ def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
1243
+ self._select_row(event.row_key)
1106
1244
 
1107
1245
  def on_button_pressed(self, event: Button.Pressed) -> None:
1108
1246
  btn_id = event.button.id
1109
1247
  if btn_id == "action_continue":
1110
- self._result = {"button": 1}
1111
- elif btn_id and btn_id.startswith("action_"):
1248
+ self._result = {"button": 0, "row": None}
1249
+ elif btn_id and btn_id.startswith("action_") and btn_id[7:].isdigit():
1112
1250
  idx = int(btn_id.split("_")[1])
1113
- self._result = {"button": idx + 1}
1251
+ spec = self._button_specs[idx]
1252
+ if spec.data_required and self._selected_row is None:
1253
+ return
1254
+ self._result = {"button": idx + 1, "row": self._selected_row if spec.data_required else None}
1255
+ else:
1256
+ return
1114
1257
  self.dismiss(self._result)
1115
1258
 
1116
1259
 
@@ -1244,9 +1387,9 @@ class CredentialsScreen(_BaseDialog):
1244
1387
  if event.button.id == "btn_ok":
1245
1388
  username = self.query_one("#username_input", Input).value
1246
1389
  password = self.query_one("#password_input", Input).value
1247
- self._result = {"username": username, "password": password}
1390
+ self._result = {"button": 1, "username": username, "password": password}
1248
1391
  else:
1249
- self._result = {"username": "", "password": ""}
1392
+ self._result = {"button": None, "username": "", "password": ""}
1250
1393
  self.dismiss(self._result)
1251
1394
 
1252
1395
 
@@ -1274,12 +1417,15 @@ class ConnectScreen(_BaseDialog):
1274
1417
  DEFAULT_CSS = (
1275
1418
  _BaseDialog.DEFAULT_CSS
1276
1419
  + """
1277
- .field-row {
1420
+ ConnectScreen #connect_fields {
1421
+ height: auto;
1422
+ }
1423
+ ConnectScreen .field-row {
1278
1424
  height: 3;
1279
- margin-bottom: 1;
1425
+ margin-bottom: 0;
1280
1426
  }
1281
- .field-label {
1282
- width: 14;
1427
+ ConnectScreen .field-label {
1428
+ width: 16;
1283
1429
  content-align: right middle;
1284
1430
  padding-right: 1;
1285
1431
  }
@@ -1287,47 +1433,70 @@ class ConnectScreen(_BaseDialog):
1287
1433
  )
1288
1434
 
1289
1435
  def compose(self) -> ComposeResult:
1290
- message = self.args.get("message", "")
1436
+ from execsql.gui.base import CONNECTION_ENCODINGS
1437
+
1291
1438
  with Container(id="dialog"):
1292
1439
  yield Label("Connect to Database", id="title")
1293
1440
  help_btn = _help_button(self.args.get("help_url"))
1294
1441
  if help_btn:
1295
1442
  yield help_btn
1296
- if message:
1297
- yield Static(message, id="message")
1298
- with Horizontal(classes="field-row"):
1299
- yield Label("Database type:", classes="field-label")
1300
- yield Select(
1301
- options=[(v, k) for k, v in _DB_TYPES],
1302
- id="db_type_select",
1303
- )
1304
- with Horizontal(classes="field-row"):
1305
- yield Label("Server:", classes="field-label")
1306
- yield Input(id="server_input", placeholder="Hostname or IP")
1307
- with Horizontal(classes="field-row"):
1308
- yield Label("Database:", classes="field-label")
1309
- yield Input(id="database_input", placeholder="Database name or file path")
1310
- with Horizontal(classes="field-row"):
1311
- yield Label("Username:", classes="field-label")
1312
- yield Input(id="username_input", placeholder="(optional)")
1443
+ if self.args.get("message"):
1444
+ yield Static(self.args["message"], id="message")
1445
+ with Vertical(id="connect_fields"):
1446
+ with Horizontal(classes="field-row"):
1447
+ yield Label("Database type:", classes="field-label")
1448
+ yield Select(
1449
+ options=[(v, k) for k, v in _DB_TYPES],
1450
+ value="p",
1451
+ allow_blank=False,
1452
+ id="db_type_select",
1453
+ )
1454
+ for name, label, placeholder in (
1455
+ ("server", "Server:", "Hostname or IP"),
1456
+ ("database", "Database:", "Database name"),
1457
+ ("username", "Username:", "(optional)"),
1458
+ ("password", "Password:", "Blank: no additional prompt"),
1459
+ ("port", "Port:", "Blank: DBMS default"),
1460
+ ("encoding", "Encoding:", "Blank: driver default; " + ", ".join(CONNECTION_ENCODINGS)),
1461
+ ):
1462
+ with Horizontal(classes="field-row", id=f"{name}_row"):
1463
+ yield Label(label, classes="field-label", id=f"{name}_label")
1464
+ yield Input(id=f"{name}_input", placeholder=placeholder, password=name == "password")
1465
+ yield Static("", id="connect_error")
1313
1466
  with Horizontal(id="buttons"):
1314
1467
  yield Button("Connect", id="btn_ok", variant="primary")
1315
1468
  yield Button("Cancel", id="btn_cancel", variant="default")
1316
1469
 
1470
+ def on_select_changed(self, event: Select.Changed) -> None:
1471
+ from execsql.gui.base import FILE_DATABASES
1472
+
1473
+ if event.select.id != "db_type_select":
1474
+ return
1475
+ kind = str(event.value)
1476
+ file_based = kind in FILE_DATABASES
1477
+ for name in ("server", "username", "password", "port", "encoding"):
1478
+ self.query_one(f"#{name}_row").display = not file_based and not (kind == "d" and name in ("server", "port"))
1479
+ self.query_one("#database_label", Label).update(
1480
+ "File path:" if file_based else "DSN:" if kind == "d" else "Database:",
1481
+ )
1482
+ self.query_one("#database_input", Input).placeholder = (
1483
+ "Existing database file" if file_based else "Database name or DSN"
1484
+ )
1485
+
1317
1486
  def on_button_pressed(self, event: Button.Pressed) -> None:
1487
+ from execsql.gui.base import connection_result
1488
+
1318
1489
  if event.button.id == "btn_ok":
1319
- db_type_sel = self.query_one("#db_type_select", Select)
1320
- db_type = str(db_type_sel.value) if db_type_sel.value else "l"
1321
- server = self.query_one("#server_input", Input).value.strip() or None
1322
- database = self.query_one("#database_input", Input).value.strip() or None
1323
- username = self.query_one("#username_input", Input).value.strip() or None
1324
- self._result = {
1325
- "db_type": db_type,
1326
- "server": server,
1327
- "database": database,
1328
- "db_file": database if db_type in ("l", "k", "a") else None,
1329
- "username": username,
1490
+ values = {
1491
+ name: self.query_one(f"#{name}_input", Input).value
1492
+ for name in ("server", "database", "username", "password", "port", "encoding")
1330
1493
  }
1494
+ try:
1495
+ self._result = dict(connection_result(str(self.query_one("#db_type_select", Select).value), **values))
1496
+ except ValueError as exc:
1497
+ self.query_one("#connect_error", Static).update(str(exc))
1498
+ self.query_one("#port_input", Input).focus()
1499
+ return
1331
1500
  else:
1332
1501
  self._result = {"db_type": None}
1333
1502
  self.dismiss(self._result)
@@ -1382,7 +1551,30 @@ def _build_screen_map() -> dict:
1382
1551
  # ---------------------------------------------------------------------------
1383
1552
 
1384
1553
 
1385
- class _SingleDialogApp(App):
1554
+ class _DialogApp(App):
1555
+ """Return failures in the owned modal's message pump through its result."""
1556
+
1557
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
1558
+ super().__init__(*args, **kwargs)
1559
+ self._dialog_screen: ModalScreen | None = None
1560
+
1561
+ def _handle_exception(self, error: Exception) -> None:
1562
+ from textual._context import active_message_pump
1563
+
1564
+ dialog = self._dialog_screen
1565
+ pump = active_message_pump.get(None)
1566
+ if (
1567
+ dialog is not None
1568
+ and self.screen is dialog
1569
+ and (pump is dialog or dialog in getattr(pump, "ancestors", ()))
1570
+ ):
1571
+ self._dialog_screen = None
1572
+ dialog.dismiss({"error": str(error) or type(error).__name__, "button": None})
1573
+ return
1574
+ super()._handle_exception(error)
1575
+
1576
+
1577
+ class _SingleDialogApp(_DialogApp):
1386
1578
  """Runs a single ModalScreen dialog, returns its result, then exits.
1387
1579
 
1388
1580
  Used by ``_run_dialog_sync`` to show a dialog from the main thread without
@@ -1404,9 +1596,11 @@ class _SingleDialogApp(App):
1404
1596
  def on_mount(self) -> None:
1405
1597
  # push_screen with a callback avoids the worker requirement of
1406
1598
  # push_screen_wait; the callback fires when the screen is dismissed.
1407
- self.push_screen(self._screen_class(self._screen_args), self._on_result)
1599
+ self._dialog_screen = self._screen_class(self._screen_args)
1600
+ self.push_screen(self._dialog_screen, self._on_result)
1408
1601
 
1409
1602
  def _on_result(self, result: Any) -> None:
1603
+ self._dialog_screen = None
1410
1604
  self.exit(result)
1411
1605
 
1412
1606
 
@@ -1418,8 +1612,8 @@ class _SingleDialogApp(App):
1418
1612
  class _TextualSyncQueue:
1419
1613
  """Drop-in replacement for ``_state.gui_manager_queue`` on the Textual path.
1420
1614
 
1421
- gui_level >= 1 with Textual installed: instead of an async manager thread,
1422
- ``put()`` runs the dialog synchronously in the main thread by launching a
1615
+ ``put()`` runs an ordinary Textual dialog synchronously in the calling
1616
+ thread by launching a
1423
1617
  short-lived ``_SingleDialogApp``. After ``put()`` returns, the result is
1424
1618
  already on ``spec.return_queue`` so the calling metacommand's ``get()``
1425
1619
  unblocks immediately.
@@ -1448,8 +1642,6 @@ class _TextualSyncQueue:
1448
1642
  except Exception as exc:
1449
1643
  spec.return_queue.put({"error": str(exc), "button": None})
1450
1644
  return
1451
- if result is not None and result.get("cancelled"):
1452
- raise SystemExit(2)
1453
1645
  spec.return_queue.put(result if result is not None else {})
1454
1646
 
1455
1647
  def get_nowait(self) -> Any:
@@ -1474,11 +1666,40 @@ class _ConsoleDialogQueue:
1474
1666
 
1475
1667
  def __init__(self) -> None:
1476
1668
  self._q: _stdlib_queue.Queue = _stdlib_queue.Queue()
1669
+ self._pending: dict[int, Any] = {}
1670
+ self._lock = threading.Lock()
1671
+ self._closing = False
1477
1672
 
1478
1673
  def put(self, spec: Any, block: bool = True, timeout: Any = None) -> None:
1479
1674
  if spec is None:
1480
1675
  return
1481
- self._q.put(spec, block=block, timeout=timeout)
1676
+ with self._lock:
1677
+ if self._closing:
1678
+ spec.return_queue.put({"interrupted": True})
1679
+ return
1680
+ self._pending[id(spec)] = spec
1681
+ self._q.put(spec, block=block, timeout=timeout)
1682
+
1683
+ def reply(self, spec: Any, result: dict) -> None:
1684
+ """Reply once; shutdown may already have interrupted this request."""
1685
+ with self._lock:
1686
+ if self._pending.pop(id(spec), None) is not None:
1687
+ spec.return_queue.put(result)
1688
+
1689
+ def interrupt(self) -> bool:
1690
+ """Stop admitting dialogs and wake every pending response waiter."""
1691
+ with self._lock:
1692
+ self._closing = True
1693
+ pending = list(self._pending.values())
1694
+ self._pending.clear()
1695
+ while True:
1696
+ try:
1697
+ self._q.get_nowait()
1698
+ except _stdlib_queue.Empty:
1699
+ break
1700
+ for spec in pending:
1701
+ spec.return_queue.put({"interrupted": True})
1702
+ return bool(pending)
1482
1703
 
1483
1704
  def get_nowait(self) -> Any:
1484
1705
  return self._q.get_nowait()
@@ -1492,7 +1713,7 @@ class _ConsoleDialogQueue:
1492
1713
  # ---------------------------------------------------------------------------
1493
1714
 
1494
1715
 
1495
- class ConsoleApp(App):
1716
+ class ConsoleApp(_DialogApp):
1496
1717
  """Persistent Textual console for gui_level 3.
1497
1718
 
1498
1719
  The SQL script runs in a background worker thread. This app runs in the
@@ -1505,7 +1726,7 @@ class ConsoleApp(App):
1505
1726
  request as a ``ModalScreen`` overlay via ``push_screen_wait()``.
1506
1727
  """
1507
1728
 
1508
- BINDINGS = [Binding("ctrl+c", "request_quit", "Quit", show=True)]
1729
+ BINDINGS = [Binding("ctrl+c", "request_quit", "Quit", show=True, priority=True)]
1509
1730
 
1510
1731
  DEFAULT_CSS = """
1511
1732
  ConsoleApp {
@@ -1542,6 +1763,8 @@ class ConsoleApp(App):
1542
1763
  self._wait_on_exit = wait_on_exit
1543
1764
  self._script_thread: threading.Thread | None = None
1544
1765
  self._script_exception: BaseException | None = None
1766
+ self._quit_requested = False
1767
+ self._completion_reported = False
1545
1768
  self._screen_map: dict | None = None
1546
1769
  self._console_lines: list[str] = []
1547
1770
 
@@ -1561,17 +1784,36 @@ class ConsoleApp(App):
1561
1784
  )
1562
1785
  self._script_thread.start()
1563
1786
  self.set_interval(0.05, self._poll_dialog_queue)
1787
+ self.set_interval(0.05, self._poll_script_finished)
1564
1788
 
1565
1789
  def _run_script(self) -> None:
1566
1790
  try:
1567
1791
  self._script_runner()
1568
1792
  except BaseException as exc:
1569
1793
  self._script_exception = exc
1570
- finally:
1571
- self.call_from_thread(self._on_script_done)
1794
+
1795
+ def _poll_script_finished(self) -> None:
1796
+ if self._script_thread is not None and not self._script_thread.is_alive() and not self._completion_reported:
1797
+ self._completion_reported = True
1798
+ self._on_script_done()
1799
+
1800
+ def wait_for_script(self) -> None:
1801
+ """Join after app.run() returns, before the CLI tears down output/connections."""
1802
+ if self._script_thread is not None:
1803
+ self._script_thread.join()
1804
+
1805
+ async def on_unmount(self) -> None:
1806
+ # Unexpected app shutdown must also leave the loop available for worker
1807
+ # output callbacks until interruption and rollback have finished.
1808
+ import asyncio
1809
+
1810
+ if self._script_thread is not None and self._script_thread.is_alive():
1811
+ self.action_request_quit()
1812
+ while self._script_thread.is_alive():
1813
+ await asyncio.sleep(0.05)
1572
1814
 
1573
1815
  def _on_script_done(self) -> None:
1574
- if self._wait_on_exit:
1816
+ if self._wait_on_exit and not self._quit_requested:
1575
1817
  self.query_one("#status_bar", Label).update(
1576
1818
  "Script complete — press Ctrl+C or close window to exit.",
1577
1819
  )
@@ -1579,6 +1821,8 @@ class ConsoleApp(App):
1579
1821
  self.exit()
1580
1822
 
1581
1823
  def _poll_dialog_queue(self) -> None:
1824
+ if self._quit_requested:
1825
+ return
1582
1826
  try:
1583
1827
  spec = self._dialog_queue.get_nowait()
1584
1828
  except _stdlib_queue.Empty:
@@ -1586,29 +1830,26 @@ class ConsoleApp(App):
1586
1830
  from execsql.utils.gui import QUERY_CONSOLE
1587
1831
 
1588
1832
  if spec.gui_type == QUERY_CONSOLE:
1589
- spec.return_queue.put({"console_running": True})
1833
+ self._dialog_queue.reply(spec, {"console_running": True})
1590
1834
  return
1591
1835
  if self._screen_map is None:
1592
1836
  self._screen_map = _build_screen_map()
1593
1837
  screen_class = self._screen_map.get(spec.gui_type)
1594
1838
  if screen_class is None:
1595
- spec.return_queue.put({"error": f"Unknown GUI type: {spec.gui_type}", "button": None})
1839
+ self._dialog_queue.reply(spec, {"error": f"Unknown GUI type: {spec.gui_type}", "button": None})
1596
1840
  return
1597
1841
 
1598
1842
  async def _push() -> None:
1599
- result = await self.push_screen_wait(screen_class(spec.args))
1600
- if result is not None and result.get("cancelled"):
1601
- # Interrupt the worker thread
1602
- if self._script_thread and self._script_thread.is_alive():
1603
- tid = self._script_thread.ident
1604
- if tid is not None:
1605
- ctypes.pythonapi.PyThreadState_SetAsyncExc(
1606
- ctypes.c_ulong(tid),
1607
- ctypes.py_object(SystemExit),
1608
- )
1609
- spec.return_queue.put(result if result is not None else {})
1610
- else:
1611
- spec.return_queue.put(result if result is not None else {})
1843
+ if self._quit_requested:
1844
+ return
1845
+ try:
1846
+ self._dialog_screen = screen_class(spec.args)
1847
+ result = await self.push_screen_wait(self._dialog_screen)
1848
+ except Exception as exc:
1849
+ result = {"error": str(exc), "button": None}
1850
+ finally:
1851
+ self._dialog_screen = None
1852
+ self._dialog_queue.reply(spec, result if result is not None else {})
1612
1853
 
1613
1854
  self.run_worker(cast(Any, _push), exclusive=False)
1614
1855
 
@@ -1635,6 +1876,8 @@ class ConsoleApp(App):
1635
1876
  self.call_from_thread(self._update_status, msg)
1636
1877
 
1637
1878
  def _update_status(self, msg: str) -> None:
1879
+ if self._quit_requested:
1880
+ msg = "Stopping… waiting for script cleanup."
1638
1881
  try:
1639
1882
  self.query_one("#status_bar", Label).update(msg)
1640
1883
  except Exception:
@@ -1651,14 +1894,28 @@ class ConsoleApp(App):
1651
1894
  pass # Widget may not be mounted yet.
1652
1895
 
1653
1896
  def action_request_quit(self) -> None:
1654
- if self._script_thread and self._script_thread.is_alive():
1897
+ if self._script_thread is None or not self._script_thread.is_alive():
1898
+ self.exit()
1899
+ return
1900
+ if self._quit_requested:
1901
+ return
1902
+ self._quit_requested = True
1903
+ self._update_status("Stopping… waiting for script cleanup.")
1904
+ waiting_for_dialog = self._dialog_queue.interrupt()
1905
+ if waiting_for_dialog:
1906
+ # The checked response receiver raises on the worker thread. Do not
1907
+ # inject another exception while that worker may already be rolling back.
1908
+ if self.screen_stack and isinstance(self.screen, _BaseDialog) and self.screen.is_mounted:
1909
+ self.screen.dismiss({"interrupted": True})
1910
+ else:
1911
+ # A driver wait receives this plain interrupt when it next returns
1912
+ # to Python. Keep the UI alive until the worker has fully unwound.
1655
1913
  tid = self._script_thread.ident
1656
1914
  if tid is not None:
1657
- ctypes.pythonapi.PyThreadState_SetAsyncExc(
1658
- ctypes.c_ulong(tid),
1659
- ctypes.py_object(SystemExit),
1660
- )
1661
- self.exit()
1915
+ ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_ulong(tid), ctypes.py_object(SystemExit))
1916
+
1917
+ async def action_quit(self) -> None:
1918
+ self.action_request_quit()
1662
1919
 
1663
1920
 
1664
1921
  # ---------------------------------------------------------------------------
@@ -1667,15 +1924,13 @@ class ConsoleApp(App):
1667
1924
 
1668
1925
 
1669
1926
  class TextualBackend(GuiBackend):
1670
- """GUI backend for the Textual path (gui_level 1 or 2).
1671
-
1672
- Dialog dispatch goes through ``_TextualSyncQueue`` (set as
1673
- ``_state.gui_manager_queue`` by ``enable_gui()``), so the ``show_*``
1674
- methods below are the canonical implementations — called by
1675
- ``gui_manager_loop`` via ``dispatch()`` — but only used when the
1676
- thread-based manager path is taken (which it isn't for Textual; the sync
1677
- queue handles everything). They are implemented here to satisfy the ABC
1678
- and in case the backend is ever called directly.
1927
+ """Textual backend lifecycle hooks and directly callable dialog methods.
1928
+
1929
+ Ordinary requests use ``_TextualSyncQueue``, which launches a short-lived
1930
+ ``_SingleDialogApp`` through its screen map in the caller's thread. Direct
1931
+ ``show_*`` calls use the same app mechanism. Neither starts a manager thread.
1932
+ For the persistent CLI console, ``_console_app`` points to ``ConsoleApp``;
1933
+ its main-thread UI serves modal requests queued by the script worker.
1679
1934
  """
1680
1935
 
1681
1936
  def __init__(self) -> None: