execsql2 2.38.0__py3-none-any.whl → 2.40.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. execsql/cli/lint.py +40 -8
  2. execsql/cli/run.py +123 -56
  3. execsql/data/execsql.conf.template +5 -2
  4. execsql/db/base.py +9 -0
  5. execsql/db/dsn.py +2 -3
  6. execsql/db/firebird.py +31 -22
  7. execsql/db/mysql.py +14 -20
  8. execsql/db/oracle.py +6 -4
  9. execsql/db/postgres.py +13 -18
  10. execsql/exceptions.py +5 -0
  11. execsql/gui/__init__.py +13 -10
  12. execsql/gui/base.py +131 -8
  13. execsql/gui/console.py +77 -30
  14. execsql/gui/desktop.py +290 -120
  15. execsql/gui/tui.py +384 -132
  16. execsql/importers/base.py +6 -12
  17. execsql/importers/csv.py +3 -5
  18. execsql/metacommands/control.py +40 -27
  19. execsql/metacommands/data.py +11 -9
  20. execsql/metacommands/io_fileops.py +1 -1
  21. execsql/metacommands/io_write.py +0 -9
  22. execsql/metacommands/prompt.py +94 -42
  23. execsql/metacommands/script_ext.py +6 -2
  24. execsql/metacommands/system.py +0 -2
  25. execsql/parser.py +118 -8
  26. execsql/script/engine.py +1 -1
  27. execsql/script/executor.py +31 -3
  28. execsql/script/parser.py +31 -0
  29. execsql/utils/auth.py +11 -6
  30. execsql/utils/gui.py +162 -53
  31. {execsql2-2.38.0.dist-info → execsql2-2.40.0.dist-info}/METADATA +2 -2
  32. {execsql2-2.38.0.dist-info → execsql2-2.40.0.dist-info}/RECORD +49 -49
  33. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/README.md +0 -0
  34. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/config_settings.sqlite +0 -0
  35. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/example_config_prompt.sql +0 -0
  36. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/make_config_db.sql +0 -0
  37. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/md_compare.sql +0 -0
  38. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/md_glossary.sql +0 -0
  39. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/md_upsert.sql +0 -0
  40. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/pg_compare.sql +0 -0
  41. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/pg_glossary.sql +0 -0
  42. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/script_template.sql +0 -0
  43. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/ss_compare.sql +0 -0
  44. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/ss_glossary.sql +0 -0
  45. {execsql2-2.38.0.data → execsql2-2.40.0.data}/data/execsql2_extras/ss_upsert.sql +0 -0
  46. {execsql2-2.38.0.dist-info → execsql2-2.40.0.dist-info}/WHEEL +0 -0
  47. {execsql2-2.38.0.dist-info → execsql2-2.40.0.dist-info}/entry_points.txt +0 -0
  48. {execsql2-2.38.0.dist-info → execsql2-2.40.0.dist-info}/licenses/LICENSE.txt +0 -0
  49. {execsql2-2.38.0.dist-info → execsql2-2.40.0.dist-info}/licenses/NOTICE +0 -0
execsql/gui/tui.py CHANGED
@@ -23,8 +23,7 @@ import queue as _stdlib_queue
23
23
  import threading
24
24
  from typing import Any, Literal, cast
25
25
 
26
- from execsql.exceptions import ScriptExit
27
- from execsql.gui.base import GuiBackend
26
+ from execsql.gui.base import GuiBackend, selected_row_values
28
27
 
29
28
  # ---------------------------------------------------------------------------
30
29
  # Textual import guard — raises ImportError if not installed so that the
@@ -37,10 +36,11 @@ except ImportError as _e:
37
36
  "Textual is not installed. It is a dependency of execsql2; reinstall execsql2 to restore it.",
38
37
  ) from _e
39
38
 
40
- from textual import on
39
+ from textual import events, on
41
40
  from textual.app import App, ComposeResult
42
41
  from textual.binding import Binding
43
42
  from textual.containers import Container, Horizontal, ScrollableContainer, Vertical
43
+ from textual.message import Message
44
44
  from textual.screen import ModalScreen
45
45
  from textual.widgets import (
46
46
  Button,
@@ -62,7 +62,14 @@ from textual.widgets import (
62
62
 
63
63
  __all__ = ["TextualBackend"]
64
64
 
65
- 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
+ )
66
73
 
67
74
  # ---------------------------------------------------------------------------
68
75
  # Helpers
@@ -74,9 +81,15 @@ def _row_count_text(n: int) -> str:
74
81
  return f"{n:,} row{'s' if n != 1 else ''}"
75
82
 
76
83
 
77
- 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:
78
91
  """Build a DataTable widget populated with data."""
79
- 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")
80
93
  dt.add_columns(*[str(h) for h in headers])
81
94
  for row in rows:
82
95
  dt.add_row(*[str(c) if c is not None else "" for c in row])
@@ -95,9 +108,9 @@ def _button_row(button_list: list, no_cancel: bool = False) -> list[Button]:
95
108
 
96
109
  A Cancel button (id ``btn_cancel_exit``) is prepended so it appears on the
97
110
  left while the primary action button sits on the far right. Entries in
98
- *button_list* with a falsy value (0 or None) are treated as the cancel
99
- label source and are otherwise excluded from the numbered buttons so that
100
- ``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.
101
114
 
102
115
  When *no_cancel* is set, the Cancel button is omitted — dialogs such as
103
116
  HALT have no meaningful cancel action, and cancelling one would exit with
@@ -107,7 +120,7 @@ def _button_row(button_list: list, no_cancel: bool = False) -> list[Button]:
107
120
  primary_buttons = []
108
121
  for i, btn in enumerate(button_list):
109
122
  label, value = btn[0], btn[1]
110
- if not value and value != 1: # falsy but not accidentally 1
123
+ if value is None:
111
124
  cancel_label = label
112
125
  else:
113
126
  variant: Literal["primary", "default"] = "primary" if i == 0 else "default"
@@ -202,7 +215,7 @@ class _BaseDialog(ModalScreen):
202
215
 
203
216
  @on(Button.Pressed, "#btn_cancel_exit")
204
217
  def _on_cancel_exit(self, event: Button.Pressed) -> None:
205
- """Universal Cancel handler — dismisses with cancelled=True so the sync queue can exit."""
218
+ """Return cancellation to the script's prompt handler."""
206
219
  event.stop()
207
220
  self._result = {"button": None, "cancelled": True}
208
221
  self.dismiss(self._result)
@@ -425,8 +438,26 @@ class DisplayScreen(_BaseDialog):
425
438
  break
426
439
  if value is None:
427
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:
428
449
  text_input = self.query_one("#text_input", Input) if self.args.get("textentry") else None
429
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
430
461
  self._result = {"button": value, "return_value": return_value}
431
462
  self.dismiss(self._result)
432
463
 
@@ -436,10 +467,7 @@ class DisplayScreen(_BaseDialog):
436
467
  idx = int(btn_id.split("_")[1])
437
468
  button_list = self.args.get("button_list", [("Continue", 1)])
438
469
  value = button_list[idx][1]
439
- text_input = self.query_one("#text_input", Input) if self.args.get("textentry") else None
440
- return_value = text_input.value if text_input else None
441
- self._result = {"button": value, "return_value": return_value}
442
- self.dismiss(self._result)
470
+ self._submit(value)
443
471
 
444
472
 
445
473
  # ---------------------------------------------------------------------------
@@ -477,6 +505,7 @@ class EntryFormScreen(_BaseDialog):
477
505
  def __init__(self, args: dict) -> None:
478
506
  super().__init__(args)
479
507
  self._inputs: dict[str, Any] = {}
508
+ self._browse_fields: dict[str, str] = {}
480
509
 
481
510
  def compose(self) -> ComposeResult:
482
511
  title = self.args.get("title", "Entry")
@@ -498,9 +527,9 @@ class EntryFormScreen(_BaseDialog):
498
527
  yield _make_table_widget("form_table", headers, rows)
499
528
  yield Static(_row_count_text(len(rows)), classes="row-count")
500
529
  with ScrollableContainer(id="fields"):
501
- for spec in specs:
530
+ for index, spec in enumerate(specs):
502
531
  etype = (spec.entry_type or "text").lower()
503
- field_id = f"field_{spec.varname}"
532
+ field_id = f"field_{index}"
504
533
  # Compute the display label (radiobuttons uses semicolon-delimited)
505
534
  if etype == "radiobuttons":
506
535
  parts = (spec.label or "").split(";")
@@ -512,8 +541,8 @@ class EntryFormScreen(_BaseDialog):
512
541
  # Multi-row widget — render label + SelectionList vertically
513
542
  yield Static(field_label, classes="row-count")
514
543
  height = spec.default_height or 4
515
- sl = SelectionList[str](
516
- *[(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],
517
546
  id=field_id,
518
547
  )
519
548
  sl.styles.height = height + 2
@@ -566,9 +595,11 @@ class EntryFormScreen(_BaseDialog):
566
595
  placeholder="Enter file path or click Browse",
567
596
  )
568
597
  yield inp
598
+ browse_id = f"browse_{index}"
599
+ self._browse_fields[browse_id] = spec.varname
569
600
  yield Button(
570
601
  "Browse…",
571
- id=f"browse_{spec.varname}",
602
+ id=browse_id,
572
603
  variant="default",
573
604
  )
574
605
  self._inputs[spec.varname] = inp
@@ -599,7 +630,7 @@ class EntryFormScreen(_BaseDialog):
599
630
  if not btn_id.startswith("browse_"):
600
631
  return
601
632
  event.stop()
602
- varname = btn_id[len("browse_") :]
633
+ varname = self._browse_fields[btn_id]
603
634
  tree = self.query_one("#file_tree", DirectoryTree)
604
635
  if tree.styles.display == "none":
605
636
  self._browse_target = varname
@@ -628,8 +659,7 @@ class EntryFormScreen(_BaseDialog):
628
659
  if etype == "checkbox":
629
660
  spec.value = "1" if widget.value else "0"
630
661
  elif etype == "listbox" and isinstance(widget, SelectionList):
631
- selected = widget.selected
632
- items = [str(widget.get_option_at_index(i).value) for i in selected]
662
+ items = [value for _, value in widget.selected]
633
663
  spec.value = ",".join(f"'{v.replace(chr(39), chr(39) + chr(39))}'" for v in items)
634
664
  elif etype == "radiobuttons" and isinstance(widget, RadioSet):
635
665
  spec.value = str(widget.pressed_index + 1) if widget.pressed_index >= 0 else "1"
@@ -646,6 +676,10 @@ class EntryFormScreen(_BaseDialog):
646
676
  etype = (spec.entry_type or "text").lower()
647
677
  if spec.required and not val and etype != "checkbox":
648
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")
649
683
  if spec.validation_regex and val and not _re.fullmatch(spec.validation_regex, val):
650
684
  errors.append(f"{spec.label or spec.varname}: does not match pattern")
651
685
  return errors
@@ -786,8 +820,12 @@ class CompareScreen(_BaseDialog):
786
820
  rows1 = self.args.get("rows1", [])
787
821
  rows2 = self.args.get("rows2", [])
788
822
 
789
- self._key_idx1 = [i for i, h in enumerate(headers1) if h in keylist]
790
- 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
791
829
 
792
830
  # Syncing uses display-consistent string normalization (DataTable
793
831
  # cells are strings). The diff engine in base.py has its own
@@ -937,6 +975,23 @@ class CompareScreen(_BaseDialog):
937
975
  # ---------------------------------------------------------------------------
938
976
 
939
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
+
940
995
  class SelectRowsScreen(_BaseDialog):
941
996
  """Row selection dialog: pick rows from source table and add to target."""
942
997
 
@@ -959,6 +1014,12 @@ class SelectRowsScreen(_BaseDialog):
959
1014
  """
960
1015
  )
961
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
+
962
1023
  def compose(self) -> ComposeResult:
963
1024
  title = self.args.get("title", "Select rows")
964
1025
  message = self.args.get("message", "")
@@ -976,33 +1037,47 @@ class SelectRowsScreen(_BaseDialog):
976
1037
  yield help_btn
977
1038
  if message:
978
1039
  yield Static(message, id="message")
979
- 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
+ )
980
1044
  with Horizontal(id="tables"):
981
1045
  with Vertical(classes="sel-table"):
982
1046
  yield Label("Source (select rows)")
983
- 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
984
1050
  yield Static(_row_count_text(len(rows1)), classes="row-count")
985
1051
  with Vertical(classes="sel-table"):
986
1052
  yield Label("Destination")
987
- yield _make_table_widget("dest_table", headers2, rows2)
988
- 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")
989
1055
  with Horizontal(id="buttons"):
990
1056
  yield from _button_row(button_list)
991
1057
 
992
1058
  def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
1059
+ dest = self.query_one("#dest_table", DataTable)
993
1060
  if event.data_table.id == "source_table":
994
- dest: DataTable = self.query_one("#dest_table", DataTable)
995
1061
  row_key = event.row_key
996
- src: DataTable = self.query_one("#source_table", DataTable)
997
- values = [src.get_cell(row_key, col) for col in src.columns]
998
- 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))
999
1074
 
1000
1075
  def action_submit(self) -> None:
1001
1076
  """Submit the first primary button value (triggered by Enter key)."""
1002
1077
  button_list = self.args.get("button_list", [("Continue", 1)])
1003
1078
  for btn in button_list:
1004
1079
  if btn[1]:
1005
- self._result = {"button": btn[1]}
1080
+ self._result = {"button": btn[1], "rows": self._selected_rows}
1006
1081
  self.dismiss(self._result)
1007
1082
  return
1008
1083
 
@@ -1011,7 +1086,7 @@ class SelectRowsScreen(_BaseDialog):
1011
1086
  if btn_id and btn_id.startswith("btn_") and btn_id[4:].isdigit():
1012
1087
  idx = int(btn_id.split("_")[1])
1013
1088
  value = self.args.get("button_list", [("Continue", 1)])[idx][1]
1014
- self._result = {"button": value}
1089
+ self._result = {"button": value, "rows": self._selected_rows if value is not None else None}
1015
1090
  self.dismiss(self._result)
1016
1091
 
1017
1092
 
@@ -1020,20 +1095,36 @@ class SelectRowsScreen(_BaseDialog):
1020
1095
  # ---------------------------------------------------------------------------
1021
1096
 
1022
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
+
1023
1112
  class SelectSubScreen(_BaseDialog):
1024
1113
  """Single-row selection dialog: pick one row and assign column values to vars."""
1025
1114
 
1115
+ BINDINGS = [*_BaseDialog.BINDINGS, Binding("enter", "submit", "Submit", priority=True)]
1116
+
1026
1117
  def __init__(self, args: dict) -> None:
1027
1118
  super().__init__(args)
1028
- self._selected_row: dict | None = None
1029
- self._headers: list = args.get("headers", [])
1119
+ self._selected_row: list | None = None
1120
+ self._source_rows: dict[Any, list] = {}
1030
1121
 
1031
1122
  def compose(self) -> ComposeResult:
1032
1123
  title = self.args.get("title", "Select a row")
1033
1124
  message = self.args.get("message", "")
1034
1125
  headers = self.args.get("headers", [])
1035
1126
  rows = self.args.get("rows", [])
1036
- button_list = self.args.get("button_list", [("OK", 1), ("Cancel", 0)])
1127
+ button_list = self.args.get("button_list", [("OK", 1)])
1037
1128
 
1038
1129
  with Container(id="dialog"):
1039
1130
  if title:
@@ -1045,24 +1136,38 @@ class SelectSubScreen(_BaseDialog):
1045
1136
  yield Static(message, id="message")
1046
1137
  yield Static("Click a row to select it.", id="hint")
1047
1138
  with ScrollableContainer():
1048
- 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
1049
1142
  yield Static(_row_count_text(len(rows)), classes="row-count")
1050
1143
  with Horizontal(id="buttons"):
1051
1144
  yield from _button_row(button_list)
1052
1145
 
1053
1146
  def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
1054
- row_key = event.row_key
1055
- tbl: DataTable = self.query_one("#sel_table", DataTable)
1056
- values = [tbl.get_cell(row_key, col) for col in tbl.columns]
1057
- 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)
1058
1164
 
1059
1165
  def on_button_pressed(self, event: Button.Pressed) -> None:
1060
1166
  btn_id = event.button.id
1061
1167
  if btn_id and btn_id.startswith("btn_") and btn_id[4:].isdigit():
1062
1168
  idx = int(btn_id.split("_")[1])
1063
- value = self.args.get("button_list", [("OK", 1), ("Cancel", 0)])[idx][1]
1064
- self._result = {"button": value, "row": self._selected_row}
1065
- self.dismiss(self._result)
1169
+ value = self.args.get("button_list", [("OK", 1)])[idx][1]
1170
+ self._submit(value)
1066
1171
 
1067
1172
 
1068
1173
  # ---------------------------------------------------------------------------
@@ -1076,6 +1181,20 @@ class ActionScreen(_BaseDialog):
1076
1181
  BINDINGS = [
1077
1182
  *_BaseDialog.BINDINGS,
1078
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
1079
1198
 
1080
1199
  def compose(self) -> ComposeResult:
1081
1200
  title = self.args.get("title", "Actions")
@@ -1094,24 +1213,47 @@ class ActionScreen(_BaseDialog):
1094
1213
  if message:
1095
1214
  yield Static(message, id="message")
1096
1215
  if headers and rows:
1097
- with ScrollableContainer():
1098
- 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
1099
1220
  yield Static(_row_count_text(len(rows)), classes="row-count")
1100
1221
  with Vertical(id="action_buttons"):
1101
1222
  for i, spec in enumerate(button_specs):
1102
- 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
+ )
1103
1229
  if include_continue:
1104
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)
1105
1241
 
1106
- self._button_specs = button_specs
1242
+ def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
1243
+ self._select_row(event.row_key)
1107
1244
 
1108
1245
  def on_button_pressed(self, event: Button.Pressed) -> None:
1109
1246
  btn_id = event.button.id
1110
1247
  if btn_id == "action_continue":
1111
- self._result = {"button": 1}
1112
- 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():
1113
1250
  idx = int(btn_id.split("_")[1])
1114
- 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
1115
1257
  self.dismiss(self._result)
1116
1258
 
1117
1259
 
@@ -1245,9 +1387,9 @@ class CredentialsScreen(_BaseDialog):
1245
1387
  if event.button.id == "btn_ok":
1246
1388
  username = self.query_one("#username_input", Input).value
1247
1389
  password = self.query_one("#password_input", Input).value
1248
- self._result = {"username": username, "password": password}
1390
+ self._result = {"button": 1, "username": username, "password": password}
1249
1391
  else:
1250
- self._result = {"username": "", "password": ""}
1392
+ self._result = {"button": None, "username": "", "password": ""}
1251
1393
  self.dismiss(self._result)
1252
1394
 
1253
1395
 
@@ -1275,12 +1417,15 @@ class ConnectScreen(_BaseDialog):
1275
1417
  DEFAULT_CSS = (
1276
1418
  _BaseDialog.DEFAULT_CSS
1277
1419
  + """
1278
- .field-row {
1420
+ ConnectScreen #connect_fields {
1421
+ height: auto;
1422
+ }
1423
+ ConnectScreen .field-row {
1279
1424
  height: 3;
1280
- margin-bottom: 1;
1425
+ margin-bottom: 0;
1281
1426
  }
1282
- .field-label {
1283
- width: 14;
1427
+ ConnectScreen .field-label {
1428
+ width: 16;
1284
1429
  content-align: right middle;
1285
1430
  padding-right: 1;
1286
1431
  }
@@ -1288,47 +1433,70 @@ class ConnectScreen(_BaseDialog):
1288
1433
  )
1289
1434
 
1290
1435
  def compose(self) -> ComposeResult:
1291
- message = self.args.get("message", "")
1436
+ from execsql.gui.base import CONNECTION_ENCODINGS
1437
+
1292
1438
  with Container(id="dialog"):
1293
1439
  yield Label("Connect to Database", id="title")
1294
1440
  help_btn = _help_button(self.args.get("help_url"))
1295
1441
  if help_btn:
1296
1442
  yield help_btn
1297
- if message:
1298
- yield Static(message, id="message")
1299
- with Horizontal(classes="field-row"):
1300
- yield Label("Database type:", classes="field-label")
1301
- yield Select(
1302
- options=[(v, k) for k, v in _DB_TYPES],
1303
- id="db_type_select",
1304
- )
1305
- with Horizontal(classes="field-row"):
1306
- yield Label("Server:", classes="field-label")
1307
- yield Input(id="server_input", placeholder="Hostname or IP")
1308
- with Horizontal(classes="field-row"):
1309
- yield Label("Database:", classes="field-label")
1310
- yield Input(id="database_input", placeholder="Database name or file path")
1311
- with Horizontal(classes="field-row"):
1312
- yield Label("Username:", classes="field-label")
1313
- 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")
1314
1466
  with Horizontal(id="buttons"):
1315
1467
  yield Button("Connect", id="btn_ok", variant="primary")
1316
1468
  yield Button("Cancel", id="btn_cancel", variant="default")
1317
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
+
1318
1486
  def on_button_pressed(self, event: Button.Pressed) -> None:
1487
+ from execsql.gui.base import connection_result
1488
+
1319
1489
  if event.button.id == "btn_ok":
1320
- db_type_sel = self.query_one("#db_type_select", Select)
1321
- db_type = str(db_type_sel.value) if db_type_sel.value else "l"
1322
- server = self.query_one("#server_input", Input).value.strip() or None
1323
- database = self.query_one("#database_input", Input).value.strip() or None
1324
- username = self.query_one("#username_input", Input).value.strip() or None
1325
- self._result = {
1326
- "db_type": db_type,
1327
- "server": server,
1328
- "database": database,
1329
- "db_file": database if db_type in ("l", "k", "a") else None,
1330
- "username": username,
1490
+ values = {
1491
+ name: self.query_one(f"#{name}_input", Input).value
1492
+ for name in ("server", "database", "username", "password", "port", "encoding")
1331
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
1332
1500
  else:
1333
1501
  self._result = {"db_type": None}
1334
1502
  self.dismiss(self._result)
@@ -1383,7 +1551,30 @@ def _build_screen_map() -> dict:
1383
1551
  # ---------------------------------------------------------------------------
1384
1552
 
1385
1553
 
1386
- 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):
1387
1578
  """Runs a single ModalScreen dialog, returns its result, then exits.
1388
1579
 
1389
1580
  Used by ``_run_dialog_sync`` to show a dialog from the main thread without
@@ -1405,9 +1596,11 @@ class _SingleDialogApp(App):
1405
1596
  def on_mount(self) -> None:
1406
1597
  # push_screen with a callback avoids the worker requirement of
1407
1598
  # push_screen_wait; the callback fires when the screen is dismissed.
1408
- 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)
1409
1601
 
1410
1602
  def _on_result(self, result: Any) -> None:
1603
+ self._dialog_screen = None
1411
1604
  self.exit(result)
1412
1605
 
1413
1606
 
@@ -1419,8 +1612,8 @@ class _SingleDialogApp(App):
1419
1612
  class _TextualSyncQueue:
1420
1613
  """Drop-in replacement for ``_state.gui_manager_queue`` on the Textual path.
1421
1614
 
1422
- gui_level >= 1 with Textual installed: instead of an async manager thread,
1423
- ``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
1424
1617
  short-lived ``_SingleDialogApp``. After ``put()`` returns, the result is
1425
1618
  already on ``spec.return_queue`` so the calling metacommand's ``get()``
1426
1619
  unblocks immediately.
@@ -1449,8 +1642,6 @@ class _TextualSyncQueue:
1449
1642
  except Exception as exc:
1450
1643
  spec.return_queue.put({"error": str(exc), "button": None})
1451
1644
  return
1452
- if result is not None and result.get("cancelled"):
1453
- raise ScriptExit(2)
1454
1645
  spec.return_queue.put(result if result is not None else {})
1455
1646
 
1456
1647
  def get_nowait(self) -> Any:
@@ -1475,11 +1666,40 @@ class _ConsoleDialogQueue:
1475
1666
 
1476
1667
  def __init__(self) -> None:
1477
1668
  self._q: _stdlib_queue.Queue = _stdlib_queue.Queue()
1669
+ self._pending: dict[int, Any] = {}
1670
+ self._lock = threading.Lock()
1671
+ self._closing = False
1478
1672
 
1479
1673
  def put(self, spec: Any, block: bool = True, timeout: Any = None) -> None:
1480
1674
  if spec is None:
1481
1675
  return
1482
- 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)
1483
1703
 
1484
1704
  def get_nowait(self) -> Any:
1485
1705
  return self._q.get_nowait()
@@ -1493,7 +1713,7 @@ class _ConsoleDialogQueue:
1493
1713
  # ---------------------------------------------------------------------------
1494
1714
 
1495
1715
 
1496
- class ConsoleApp(App):
1716
+ class ConsoleApp(_DialogApp):
1497
1717
  """Persistent Textual console for gui_level 3.
1498
1718
 
1499
1719
  The SQL script runs in a background worker thread. This app runs in the
@@ -1506,7 +1726,7 @@ class ConsoleApp(App):
1506
1726
  request as a ``ModalScreen`` overlay via ``push_screen_wait()``.
1507
1727
  """
1508
1728
 
1509
- BINDINGS = [Binding("ctrl+c", "request_quit", "Quit", show=True)]
1729
+ BINDINGS = [Binding("ctrl+c", "request_quit", "Quit", show=True, priority=True)]
1510
1730
 
1511
1731
  DEFAULT_CSS = """
1512
1732
  ConsoleApp {
@@ -1543,6 +1763,8 @@ class ConsoleApp(App):
1543
1763
  self._wait_on_exit = wait_on_exit
1544
1764
  self._script_thread: threading.Thread | None = None
1545
1765
  self._script_exception: BaseException | None = None
1766
+ self._quit_requested = False
1767
+ self._completion_reported = False
1546
1768
  self._screen_map: dict | None = None
1547
1769
  self._console_lines: list[str] = []
1548
1770
 
@@ -1562,17 +1784,36 @@ class ConsoleApp(App):
1562
1784
  )
1563
1785
  self._script_thread.start()
1564
1786
  self.set_interval(0.05, self._poll_dialog_queue)
1787
+ self.set_interval(0.05, self._poll_script_finished)
1565
1788
 
1566
1789
  def _run_script(self) -> None:
1567
1790
  try:
1568
1791
  self._script_runner()
1569
1792
  except BaseException as exc:
1570
1793
  self._script_exception = exc
1571
- finally:
1572
- 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)
1573
1814
 
1574
1815
  def _on_script_done(self) -> None:
1575
- if self._wait_on_exit:
1816
+ if self._wait_on_exit and not self._quit_requested:
1576
1817
  self.query_one("#status_bar", Label).update(
1577
1818
  "Script complete — press Ctrl+C or close window to exit.",
1578
1819
  )
@@ -1580,6 +1821,8 @@ class ConsoleApp(App):
1580
1821
  self.exit()
1581
1822
 
1582
1823
  def _poll_dialog_queue(self) -> None:
1824
+ if self._quit_requested:
1825
+ return
1583
1826
  try:
1584
1827
  spec = self._dialog_queue.get_nowait()
1585
1828
  except _stdlib_queue.Empty:
@@ -1587,29 +1830,26 @@ class ConsoleApp(App):
1587
1830
  from execsql.utils.gui import QUERY_CONSOLE
1588
1831
 
1589
1832
  if spec.gui_type == QUERY_CONSOLE:
1590
- spec.return_queue.put({"console_running": True})
1833
+ self._dialog_queue.reply(spec, {"console_running": True})
1591
1834
  return
1592
1835
  if self._screen_map is None:
1593
1836
  self._screen_map = _build_screen_map()
1594
1837
  screen_class = self._screen_map.get(spec.gui_type)
1595
1838
  if screen_class is None:
1596
- 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})
1597
1840
  return
1598
1841
 
1599
1842
  async def _push() -> None:
1600
- result = await self.push_screen_wait(screen_class(spec.args))
1601
- if result is not None and result.get("cancelled"):
1602
- # Interrupt the worker thread
1603
- if self._script_thread and self._script_thread.is_alive():
1604
- tid = self._script_thread.ident
1605
- if tid is not None:
1606
- ctypes.pythonapi.PyThreadState_SetAsyncExc(
1607
- ctypes.c_ulong(tid),
1608
- ctypes.py_object(ScriptExit),
1609
- )
1610
- spec.return_queue.put(result if result is not None else {})
1611
- else:
1612
- 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 {})
1613
1853
 
1614
1854
  self.run_worker(cast(Any, _push), exclusive=False)
1615
1855
 
@@ -1636,6 +1876,8 @@ class ConsoleApp(App):
1636
1876
  self.call_from_thread(self._update_status, msg)
1637
1877
 
1638
1878
  def _update_status(self, msg: str) -> None:
1879
+ if self._quit_requested:
1880
+ msg = "Stopping… waiting for script cleanup."
1639
1881
  try:
1640
1882
  self.query_one("#status_bar", Label).update(msg)
1641
1883
  except Exception:
@@ -1652,16 +1894,28 @@ class ConsoleApp(App):
1652
1894
  pass # Widget may not be mounted yet.
1653
1895
 
1654
1896
  def action_request_quit(self) -> None:
1655
- # A plain SystemExit, not ScriptExit: quitting while a statement runs
1656
- # interrupts it, and it is rolled back like a failed one.
1657
- 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.
1658
1913
  tid = self._script_thread.ident
1659
1914
  if tid is not None:
1660
- ctypes.pythonapi.PyThreadState_SetAsyncExc(
1661
- ctypes.c_ulong(tid),
1662
- ctypes.py_object(SystemExit),
1663
- )
1664
- 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()
1665
1919
 
1666
1920
 
1667
1921
  # ---------------------------------------------------------------------------
@@ -1670,15 +1924,13 @@ class ConsoleApp(App):
1670
1924
 
1671
1925
 
1672
1926
  class TextualBackend(GuiBackend):
1673
- """GUI backend for the Textual path (gui_level 1 or 2).
1674
-
1675
- Dialog dispatch goes through ``_TextualSyncQueue`` (set as
1676
- ``_state.gui_manager_queue`` by ``enable_gui()``), so the ``show_*``
1677
- methods below are the canonical implementations — called by
1678
- ``gui_manager_loop`` via ``dispatch()`` — but only used when the
1679
- thread-based manager path is taken (which it isn't for Textual; the sync
1680
- queue handles everything). They are implemented here to satisfy the ABC
1681
- 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.
1682
1934
  """
1683
1935
 
1684
1936
  def __init__(self) -> None: