execsql2 2.38.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 (47) 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 +20 -5
  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/system.py +0 -2
  24. execsql/parser.py +118 -8
  25. execsql/script/engine.py +1 -1
  26. execsql/script/executor.py +24 -3
  27. execsql/utils/auth.py +11 -6
  28. execsql/utils/gui.py +162 -53
  29. {execsql2-2.38.0.dist-info → execsql2-2.39.1.dist-info}/METADATA +2 -2
  30. {execsql2-2.38.0.dist-info → execsql2-2.39.1.dist-info}/RECORD +47 -47
  31. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/README.md +0 -0
  32. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/config_settings.sqlite +0 -0
  33. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/example_config_prompt.sql +0 -0
  34. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/make_config_db.sql +0 -0
  35. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/md_compare.sql +0 -0
  36. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/md_glossary.sql +0 -0
  37. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/md_upsert.sql +0 -0
  38. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/pg_compare.sql +0 -0
  39. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/pg_glossary.sql +0 -0
  40. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/script_template.sql +0 -0
  41. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/ss_compare.sql +0 -0
  42. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/ss_glossary.sql +0 -0
  43. {execsql2-2.38.0.data → execsql2-2.39.1.data}/data/execsql2_extras/ss_upsert.sql +0 -0
  44. {execsql2-2.38.0.dist-info → execsql2-2.39.1.dist-info}/WHEEL +0 -0
  45. {execsql2-2.38.0.dist-info → execsql2-2.39.1.dist-info}/entry_points.txt +0 -0
  46. {execsql2-2.38.0.dist-info → execsql2-2.39.1.dist-info}/licenses/LICENSE.txt +0 -0
  47. {execsql2-2.38.0.dist-info → execsql2-2.39.1.dist-info}/licenses/NOTICE +0 -0
execsql/gui/base.py CHANGED
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from abc import ABC, abstractmethod
6
6
  from dataclasses import dataclass, field
7
- from typing import TYPE_CHECKING, Any
7
+ from typing import TYPE_CHECKING, Any, TypedDict
8
8
 
9
9
  if TYPE_CHECKING:
10
10
  pass
@@ -14,6 +14,102 @@ __all__ = ["DiffResult", "GuiBackend", "compare_stats", "compute_row_diffs", "fo
14
14
  DIFF_MARKER = "● "
15
15
 
16
16
 
17
+ FILE_DATABASES = frozenset(("l", "k", "a"))
18
+ CONNECTION_ENCODINGS = ("UTF8", "LATIN1", "ASCII", "UTF16")
19
+
20
+
21
+ class ConnectResult(TypedDict):
22
+ """Confirmed connection inputs; a blank password never requests another prompt."""
23
+
24
+ db_type: str | None
25
+ server: str | None
26
+ database: str | None
27
+ db_file: str | None
28
+ username: str | None
29
+ password: str | None
30
+ port: int | None
31
+ encoding: str | None
32
+
33
+
34
+ def connection_result(
35
+ db_type: str,
36
+ server: str = "",
37
+ database: str = "",
38
+ username: str = "",
39
+ password: str = "",
40
+ port: str | int | None = None,
41
+ encoding: str = "",
42
+ ) -> ConnectResult:
43
+ """Normalize visible connection fields and reject invalid ports before connecting.
44
+
45
+ File databases ignore hidden network controls. DSNs use their configured host
46
+ and port. Password whitespace is significant and is never stripped.
47
+ """
48
+ if db_type not in "pslmkofad" or len(db_type) != 1:
49
+ raise ValueError("Select a database type.")
50
+ file_based = db_type in FILE_DATABASES
51
+ port_number = None
52
+ if isinstance(port, str):
53
+ port = port.strip()
54
+ if not file_based and db_type != "d" and port not in (None, ""):
55
+ try:
56
+ port_number = int(str(port).strip())
57
+ except ValueError as exc:
58
+ raise ValueError("Port must be an integer from 1 to 65535.") from exc
59
+ if not 1 <= port_number <= 65535:
60
+ raise ValueError("Port must be an integer from 1 to 65535.")
61
+ return ConnectResult(
62
+ db_type=db_type,
63
+ server=None if file_based or db_type == "d" else server.strip() or None,
64
+ database=None if file_based else database.strip() or None,
65
+ db_file=(database.strip() or None) if file_based else None,
66
+ username=None if file_based else username.strip() or None,
67
+ password=None if file_based else password or None,
68
+ port=port_number,
69
+ encoding=None if file_based else encoding.strip() or None,
70
+ )
71
+
72
+
73
+ def normalize_text_entry(value: str, entry_type: str | None = None, entry_case: str | None = None) -> str:
74
+ """Validate an ENTER_SUB value, expand BOOL prefixes, then apply requested case.
75
+
76
+ Empty values are allowed for every type. Numeric values remain textual,
77
+ preserving leading zeros and the entered decimal representation.
78
+ Validation errors do not include the value, which may be a password.
79
+ """
80
+ import re
81
+
82
+ kind = (entry_type or "text").lower()
83
+ if not isinstance(value, str):
84
+ raise ValueError("The entered value must be text.")
85
+ if value:
86
+ if kind == "int" and not re.fullmatch(r"-?[0-9]+", value):
87
+ raise ValueError("Enter digits with an optional leading minus sign.")
88
+ if kind == "float" and not re.fullmatch(r"-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)", value):
89
+ raise ValueError("Enter digits with at most one decimal point and an optional leading minus sign.")
90
+ if kind == "ident" and not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", value):
91
+ raise ValueError("Start with a letter and use only letters, digits and underscores.")
92
+ if kind == "bool":
93
+ if "true".startswith(value.lower()):
94
+ value = "True"
95
+ elif "false".startswith(value.lower()):
96
+ value = "False"
97
+ else:
98
+ raise ValueError("Enter True or False, or a nonempty prefix of either word.")
99
+ case = (entry_case or "any").lower()
100
+ if case == "lcase":
101
+ return value.lower()
102
+ if case == "ucase":
103
+ return value.upper()
104
+ return value
105
+
106
+
107
+ def selected_row_values(headers: list, row: list | tuple, destination_headers: list) -> list:
108
+ """Project a selected source row into the destination's display column order."""
109
+ values = dict(zip(headers, row))
110
+ return [values.get(header) for header in destination_headers]
111
+
112
+
17
113
  # ---------------------------------------------------------------------------
18
114
  # Plain-text table rendering (shared by the console backend and by
19
115
  # non-interactive metacommand fallbacks such as HALT ... DISPLAY)
@@ -130,6 +226,13 @@ class DiffResult:
130
226
  summary: str = ""
131
227
 
132
228
 
229
+ def _key_column_indices(headers: list[str], keylist: list) -> list[int]:
230
+ """Return every key column's index in declared order, or no indices if incomplete."""
231
+ if any(key not in headers for key in keylist):
232
+ return []
233
+ return [headers.index(key) for key in keylist]
234
+
235
+
133
236
  def compute_row_diffs(
134
237
  headers1: list,
135
238
  rows1: list,
@@ -158,8 +261,8 @@ def compute_row_diffs(
158
261
  return None
159
262
  headers1_str = [str(h) for h in headers1]
160
263
  headers2_str = [str(h) for h in headers2]
161
- key_idx1 = [i for i, h in enumerate(headers1_str) if h in keylist]
162
- key_idx2 = [i for i, h in enumerate(headers2_str) if h in keylist]
264
+ key_idx1 = _key_column_indices(headers1_str, keylist)
265
+ key_idx2 = _key_column_indices(headers2_str, keylist)
163
266
  if not key_idx1 or not key_idx2:
164
267
  return None
165
268
 
@@ -275,9 +378,17 @@ class GuiBackend(ABC):
275
378
  - ``show_display`` → ``{"button": int|None, "return_value": str|None}``
276
379
  - ``show_entry_form`` → ``{"button": int|None, "return_value": list[EntrySpec]}``
277
380
  - ``show_compare`` → ``{"button": int|None}``
278
- - ``show_select_rows``→ ``{"button": int|None}``
279
- - ``show_select_sub`` → ``{"button": int|None, "row": dict|None}``
280
- - ``show_action`` → ``{"button": int|None}``
381
+ - ``show_select_rows``→ ``{"button": int|None, "rows": list|None}``
382
+ ``rows`` contains new selections in source column order, with original
383
+ Python values and duplicates retained. ``[]`` means no selections;
384
+ ``None`` means cancelled or unavailable (console fallback).
385
+ - ``show_select_sub`` → ``{"button": int|None, "row": list|None}``
386
+ ``row`` contains the original Python values in source column order;
387
+ button 1 confirms it, 2 continues without selecting, None cancels.
388
+ - ``show_action`` → ``{"button": int|None, "row": list|None}``
389
+ Buttons 1..N identify the action in ``button_specs``; 0 continues
390
+ without an action, None cancels. Only data-required actions return
391
+ original source-row values, in source column order.
281
392
  - ``show_map`` → ``{"button": int|None}``
282
393
  - ``show_open_file`` → ``{"filename": str|None}``
283
394
  - ``show_save_file`` → ``{"filename": str|None}``
@@ -349,6 +460,9 @@ class GuiBackend(ABC):
349
460
  def console_show(self) -> None:
350
461
  """Show the console window (if applicable)."""
351
462
 
463
+ def console_resize(self, width: int, height: int) -> None:
464
+ """Resize a native console in characters/lines; terminal backends do nothing."""
465
+
352
466
  def console_progress(self, num: float, total: float | None = None) -> None:
353
467
  """Update the progress indicator."""
354
468
 
@@ -423,8 +537,17 @@ class GuiBackend(ABC):
423
537
 
424
538
  @abstractmethod
425
539
  def show_credentials(self, args: dict) -> dict:
426
- """Show a credentials (username + password) dialog."""
540
+ """Show a credentials dialog returning username and password strings.
541
+
542
+ GUI backends return button=1 for OK or button=None for cancellation;
543
+ confirming empty credentials is distinct from cancelling.
544
+ """
427
545
 
428
546
  @abstractmethod
429
547
  def show_connect(self, args: dict) -> dict:
430
- """Show a database connection selection dialog."""
548
+ """Collect connection inputs using the shared ConnectResult field names.
549
+
550
+ Confirmed inputs pass through connection_result; cancellation omits
551
+ db_type or returns None for it. Blank passwords do not request a
552
+ secondary password prompt. Password strings retain their whitespace.
553
+ """
execsql/gui/console.py CHANGED
@@ -16,6 +16,7 @@ from execsql.gui.base import (
16
16
  compare_stats as _compare_stats,
17
17
  compute_row_diffs,
18
18
  format_table,
19
+ normalize_text_entry,
19
20
  row_count_text as _row_count_text,
20
21
  )
21
22
 
@@ -143,17 +144,26 @@ class ConsoleBackend(GuiBackend):
143
144
  _print_table(headers, rows)
144
145
  print(f" {_row_count_text(len(rows))}", file=sys.stderr)
145
146
 
146
- return_value = None
147
- if textentry:
147
+ if not textentry:
148
+ return {"button": _prompt_buttons(button_list), "return_value": None}
149
+ while True:
148
150
  if hidetext:
149
151
  import getpass
150
152
 
151
- return_value = getpass.getpass("Enter value: ")
153
+ entered = getpass.getpass("Enter value: ")
152
154
  else:
153
- return_value = input(f"Enter value [{initial}]: ").strip() or initial
154
-
155
- btn = _prompt_buttons(button_list)
156
- return {"button": btn, "return_value": return_value}
155
+ entered = input(f"Enter value [{initial or ''}]: ")
156
+ if not entered:
157
+ entered = initial or ""
158
+ btn = _prompt_buttons(button_list)
159
+ if btn is None:
160
+ return {"button": None, "return_value": None}
161
+ try:
162
+ value = normalize_text_entry(entered, args.get("textentrytype"), args.get("textentrycase"))
163
+ except ValueError as exc:
164
+ print(f"Invalid entry: {exc}", file=sys.stderr)
165
+ continue
166
+ return {"button": btn, "return_value": value}
157
167
 
158
168
  def show_entry_form(self, args: dict) -> dict:
159
169
  title = args.get("title", "Entry")
@@ -306,7 +316,7 @@ class ConsoleBackend(GuiBackend):
306
316
  print("(Row selection requires a GUI backend; displaying source data only.)", file=sys.stderr)
307
317
 
308
318
  btn = _prompt_buttons(button_list)
309
- return {"button": btn}
319
+ return {"button": btn, "rows": None}
310
320
 
311
321
  def show_select_sub(self, args: dict) -> dict:
312
322
  title = args.get("title", "Select a row")
@@ -317,15 +327,27 @@ class ConsoleBackend(GuiBackend):
317
327
  print(f"\n=== {title} ===", file=sys.stderr)
318
328
  if message:
319
329
  print(message, file=sys.stderr)
330
+ _print_help_url(args)
331
+ can_continue = any(button[1] == 2 for button in args.get("button_list", []))
320
332
  if headers and rows:
321
333
  for i, row in enumerate(rows, 1):
322
334
  print(f" [{i}] " + ", ".join(f"{h}={v}" for h, v in zip(headers, row)), file=sys.stderr)
323
335
  while True:
324
- raw = input("Select row number (or blank to cancel): ").strip()
336
+ prompt = (
337
+ "Select row number, C to continue without selecting, or blank to cancel: "
338
+ if can_continue
339
+ else "Select row number (or blank to cancel): "
340
+ )
341
+ try:
342
+ raw = input(prompt).strip()
343
+ except EOFError:
344
+ raw = ""
325
345
  if not raw:
326
346
  return {"button": None, "row": None}
347
+ if can_continue and raw.lower() == "c":
348
+ return {"button": 2, "row": None}
327
349
  if raw.isdigit() and 1 <= int(raw) <= len(rows):
328
- row = dict(zip(headers, rows[int(raw) - 1]))
350
+ row = list(rows[int(raw) - 1])
329
351
  return {"button": 1, "row": row}
330
352
  print("Invalid selection.", file=sys.stderr)
331
353
  return {"button": None, "row": None}
@@ -342,27 +364,43 @@ class ConsoleBackend(GuiBackend):
342
364
  print(message, file=sys.stderr)
343
365
  _print_help_url(args)
344
366
  if headers and rows:
345
- _print_table(headers, rows)
367
+ _print_table(["#", *headers], [(i + 1, *row) for i, row in enumerate(rows)])
346
368
  print(f" {_row_count_text(len(rows))}", file=sys.stderr)
347
369
 
348
- if not button_specs:
349
- input("Press Enter to continue...")
350
- return {"button": 1}
351
-
352
370
  print("\nAvailable actions:", file=sys.stderr)
353
371
  for i, spec in enumerate(button_specs, 1):
354
- print(f" [{i}] {spec.label} — {spec.prompt}", file=sys.stderr)
372
+ required = " (select a data row first)" if spec.data_required else ""
373
+ print(f" [{i}] {spec.label} — {spec.prompt}{required}", file=sys.stderr)
374
+ if headers and rows:
375
+ print(" R <number>: select a data row", file=sys.stderr)
376
+ print(" Blank input: Cancel", file=sys.stderr)
355
377
 
356
378
  include_continue = args.get("include_continue_button")
357
379
  if include_continue:
358
380
  print(" [0] Continue", file=sys.stderr)
359
381
 
382
+ selected_row = None
360
383
  while True:
361
- raw = input("Select action: ").strip()
384
+ try:
385
+ raw = input("Select action or data row: ").strip()
386
+ except EOFError:
387
+ raw = ""
388
+ if not raw or raw == "\x1b":
389
+ return {"button": None, "row": None}
362
390
  if include_continue and raw == "0":
363
- return {"button": 1}
391
+ return {"button": 0, "row": None}
392
+ parts = raw.split()
393
+ if len(parts) == 2 and parts[0].lower() == "r" and parts[1].isdigit():
394
+ index = int(parts[1]) - 1
395
+ if rows and 0 <= index < len(rows):
396
+ selected_row = list(rows[index])
397
+ continue
364
398
  if raw.isdigit() and 1 <= int(raw) <= len(button_specs):
365
- return {"button": int(raw)}
399
+ index = int(raw) - 1
400
+ if button_specs[index].data_required and selected_row is None:
401
+ print("Select a data row before choosing this action.", file=sys.stderr)
402
+ continue
403
+ return {"button": index + 1, "row": selected_row if button_specs[index].data_required else None}
366
404
  print("Invalid choice.", file=sys.stderr)
367
405
 
368
406
  def show_map(self, args: dict) -> dict:
@@ -450,14 +488,23 @@ class ConsoleBackend(GuiBackend):
450
488
  for k, v in db_types.items():
451
489
  print(f" {k} — {v}", file=sys.stderr)
452
490
  db_type = input("Database type: ").strip().lower()
453
- server = input("Server (or blank): ").strip() or None
454
- database = input("Database (or blank): ").strip() or None
455
- db_file = input("File path (or blank): ").strip() or None
456
- username = input("Username (or blank): ").strip() or None
457
- return {
458
- "db_type": db_type,
459
- "server": server,
460
- "database": database,
461
- "db_file": db_file,
462
- "username": username,
463
- }
491
+ while db_type not in db_types:
492
+ print("Select one of the listed database types.", file=sys.stderr)
493
+ db_type = input("Database type: ").strip().lower()
494
+ import getpass
495
+
496
+ from execsql.gui.base import FILE_DATABASES, connection_result
497
+
498
+ if db_type in FILE_DATABASES:
499
+ return dict(connection_result(db_type, database=input("File path: ")))
500
+ server = input("Server (or blank): ") if db_type != "d" else ""
501
+ database = input("DSN: " if db_type == "d" else "Database (or blank): ")
502
+ username = input("Username (or blank): ")
503
+ password = getpass.getpass("Password (blank: no additional password prompt): ")
504
+ encoding = input("Encoding (blank: driver default): ")
505
+ while True:
506
+ port = input("Port (blank: DBMS default): ") if db_type != "d" else ""
507
+ try:
508
+ return dict(connection_result(db_type, server, database, username, password, port, encoding))
509
+ except ValueError as exc:
510
+ print(str(exc), file=sys.stderr)