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/db/sqlite.py CHANGED
@@ -9,20 +9,70 @@ files via the Python standard library ``sqlite3`` module. Corresponds to
9
9
  """
10
10
 
11
11
  import datetime
12
+ import math
12
13
  import re
13
- from decimal import Decimal
14
+ from collections.abc import Callable
15
+ from decimal import Decimal, InvalidOperation
14
16
  from typing import Any
15
17
 
16
18
  from execsql.db.base import Database
19
+ from execsql.db.target_types import ColumnKinds, _NUMBER_TEXT, _whole_number_converter, kind_for_type_name
20
+ from execsql.types import DT_Long
17
21
  from execsql.exceptions import ErrInfo
18
22
  from execsql.utils.errors import exception_desc, fatal_error
19
23
  import execsql.state as _state
20
24
 
21
- __all__ = ["SQLiteDatabase"]
25
+ __all__ = ["SQLiteDatabase", "sqlite_affinity"]
22
26
 
23
27
  DEFAULT_CONNECT_TIMEOUT = 30 # seconds
24
28
 
25
29
 
30
+ def sqlite_affinity(declaration: str) -> str:
31
+ """Return SQLite's affinity, observing its ordered type-name rules."""
32
+ name = declaration.upper()
33
+ if "INT" in name:
34
+ return "INTEGER"
35
+ if any(part in name for part in ("CHAR", "CLOB", "TEXT")):
36
+ return "TEXT"
37
+ if not name or "BLOB" in name:
38
+ return "BLOB"
39
+ if any(part in name for part in ("REAL", "FLOA", "DOUB")):
40
+ return "REAL"
41
+ return "NUMERIC"
42
+
43
+
44
+ def _integer_converter(column: str, table: str) -> Callable[[Any], Any]:
45
+ """Use the shared whole-number rule with SQLite's signed int64 bounds."""
46
+ whole_number = _whole_number_converter(column, table, lambda value: value)
47
+
48
+ def range_error(value: Any) -> ErrInfo:
49
+ return ErrInfo(
50
+ type="error",
51
+ other_msg=(
52
+ f"Can't load {value!r} into column {column} of {table}: the column holds whole numbers "
53
+ "in SQLite's signed 64-bit integer range."
54
+ ),
55
+ )
56
+
57
+ def convert(value: Any) -> Any:
58
+ number = None
59
+ try:
60
+ if (
61
+ isinstance(value, (int, float, Decimal))
62
+ and not isinstance(value, bool)
63
+ or isinstance(value, str)
64
+ and _NUMBER_TEXT.fullmatch(value)
65
+ ):
66
+ number = Decimal(value)
67
+ except InvalidOperation as exc:
68
+ raise range_error(value) from exc
69
+ if number is not None and number.is_finite() and not -(2**63) <= number <= 2**63 - 1:
70
+ raise range_error(value)
71
+ return whole_number(value)
72
+
73
+ return convert
74
+
75
+
26
76
  class SQLiteDatabase(Database):
27
77
  """SQLite adapter using the Python standard-library sqlite3 module."""
28
78
 
@@ -98,11 +148,12 @@ class SQLiteDatabase(Database):
98
148
  unqualified_lookup_is_scoped = True
99
149
 
100
150
  def table_exists(self, table_name: str, schema_name: str | None = None) -> bool:
101
- """Return True if the named table exists in the SQLite database."""
151
+ """Look up a table in *schema_name* (an attached database), or main."""
102
152
  # SQLite stores names as-created; match case-insensitively so a lookup
103
153
  # of "mytable" finds the catalog entry for MyTable.
104
154
  with self._cursor() as curs:
105
- sql = "select name from sqlite_master where type='table' and lower(name)=lower(?);"
155
+ catalog = self.schema_qualified_table_name(schema_name or "main", "sqlite_master")
156
+ sql = f"select name from {catalog} where type='table' and lower(name)=lower(?);"
106
157
  try:
107
158
  curs.execute(sql, (table_name,))
108
159
  except ErrInfo:
@@ -129,9 +180,9 @@ class SQLiteDatabase(Database):
129
180
  return column_name in cols
130
181
 
131
182
  def table_columns(self, table_name: str, schema_name: str | None = None) -> list[str]:
132
- """Return a list of column names for the given SQLite table."""
183
+ """Return column names from the optionally database-qualified table."""
133
184
  with self._cursor() as curs:
134
- quoted_tbl = self.quote_identifier(table_name)
185
+ quoted_tbl = self.schema_qualified_table_name(schema_name, table_name)
135
186
  sql = f"select * from {quoted_tbl} where 1=0;"
136
187
  try:
137
188
  curs.execute(sql)
@@ -147,6 +198,28 @@ class SQLiteDatabase(Database):
147
198
  ) from e
148
199
  return [d[0] for d in curs.description]
149
200
 
201
+ def column_kinds(self, sq_name: str) -> ColumnKinds:
202
+ """Read declared types from the database INSERT resolves for *sq_name*.
203
+
204
+ Use execsql's type names, including scale-zero DECIMAL, rather than
205
+ SQLite's broader INTEGER-affinity substring rule. An unqualified name
206
+ keeps SQLite's normal temporary/main/attached lookup order.
207
+ """
208
+ return {
209
+ name: kind_for_type_name(declaration) for name, declaration in self._column_declarations(sq_name).items()
210
+ }
211
+
212
+ def _column_declarations(self, sq_name: str) -> dict[str, str]:
213
+ """Read declared column types from the same qualified table INSERT uses."""
214
+ identifier = r'(?:"(?:[^"]|"")*"|\w+)'
215
+ name = re.fullmatch(rf"(?:(?P<schema>{identifier})\.)?(?P<table>{identifier})", sq_name)
216
+ if name is None:
217
+ raise ErrInfo(type="error", other_msg=f"Invalid SQLite table name: {sq_name}")
218
+ prefix = f"{name['schema']}." if name["schema"] else ""
219
+ sql = f"PRAGMA {prefix}table_xinfo({name['table']})"
220
+ _description, rows = self._column_type_query(sq_name, sql)
221
+ return {row[1].lower(): row[2] for row in rows}
222
+
150
223
  def view_exists(self, view_name: str, schema_name: str | None = None) -> bool:
151
224
  """Return True if the named view exists in the SQLite database."""
152
225
  # Match case-insensitively — see table_exists().
@@ -187,12 +260,14 @@ class SQLiteDatabase(Database):
187
260
  ) -> None:
188
261
  """Populate a SQLite table from a row source generator.
189
262
 
190
- Values are inserted as the source gives them (dates, times and
191
- decimals as text), so *existing_table* changes nothing here.
263
+ Existing integer-kind columns reject fractions and values outside the
264
+ signed 64-bit range. Other columns retain their pass-through behavior
265
+ (dates, times and decimals as text). Finite decimals cannot overflow
266
+ a numeric-affinity column to infinity. A failed load is rolled back.
192
267
  """
193
268
  # The rowsource argument must be a generator yielding a list of values for the columns of the table.
194
269
  # The column_list argument must an iterable containing column names in the same order as produced by the rowsource.
195
- sq_name = self.schema_qualified_table_name(None, table_name)
270
+ sq_name = self.schema_qualified_table_name(schema_name, table_name)
196
271
  # Check specified column names.
197
272
  tablespec = tablespec_src()
198
273
  ts_colnames = [col.name for col in tablespec.cols]
@@ -205,6 +280,22 @@ class SQLiteDatabase(Database):
205
280
  # Get column indexes for selected column names.
206
281
  columns = column_list
207
282
  data_indexes = [ts_colnames.index(col) for col in columns]
283
+ declarations = self._column_declarations(sq_name)
284
+ kinds = (
285
+ {name: kind_for_type_name(declaration) for name, declaration in declarations.items()}
286
+ if existing_table
287
+ else {}
288
+ )
289
+ numeric_columns = {
290
+ i
291
+ for i, column in enumerate(columns)
292
+ if sqlite_affinity(declarations.get(column.lower(), "")) in ("NUMERIC", "REAL", "INTEGER")
293
+ }
294
+ converters = {
295
+ i: _integer_converter(column, sq_name)
296
+ for i, column in enumerate(columns)
297
+ if kinds.get(column.lower()) is DT_Long
298
+ }
208
299
  # Construct prepared SQL statement
209
300
  colspec = ",".join([self.type.quoted(c) for c in columns])
210
301
  paramspec = ",".join(["?" for c in columns])
@@ -227,7 +318,6 @@ class SQLiteDatabase(Database):
227
318
  except ErrInfo:
228
319
  raise
229
320
  except Exception as e:
230
- self.rollback()
231
321
  raise ErrInfo(
232
322
  type="db",
233
323
  command_text=sql,
@@ -244,6 +334,8 @@ class SQLiteDatabase(Database):
244
334
 
245
335
  last_line: list[Any] = []
246
336
  try:
337
+ if converters or numeric_columns:
338
+ self.begin_transaction()
247
339
  for line in rowsource:
248
340
  # Skip empty rows.
249
341
  if not (len(line) == 1 and line[0] is None):
@@ -259,6 +351,18 @@ class SQLiteDatabase(Database):
259
351
  if not _state.conf.empty_strings and line[i].strip() == "":
260
352
  line[i] = None
261
353
  linedata = [line[ix] for ix in data_indexes]
354
+ for i, convert in converters.items():
355
+ linedata[i] = convert(linedata[i])
356
+ for i in numeric_columns:
357
+ value = linedata[i]
358
+ if isinstance(value, Decimal) and value.is_finite() and math.isinf(float(value)):
359
+ raise ErrInfo(
360
+ type="error",
361
+ other_msg=(
362
+ f"Can't load {value!r} into column {columns[i]} of {sq_name}: "
363
+ "SQLite would store infinity instead of this finite value."
364
+ ),
365
+ )
262
366
  # Convert datetime, time, and Decimal values to strings.
263
367
  for i in range(len(linedata)):
264
368
  if type(linedata[i]) in (datetime.datetime, datetime.time, Decimal):
@@ -272,6 +376,9 @@ class SQLiteDatabase(Database):
272
376
  if len(batch) >= batch_size:
273
377
  _flush(last_line)
274
378
  _flush(last_line)
379
+ except Exception:
380
+ self.rollback()
381
+ raise
275
382
  finally:
276
383
  curs.close()
277
384
  if _state.exec_log:
execsql/db/sqlserver.py CHANGED
@@ -8,7 +8,7 @@ Server via ``pyodbc``. Corresponds to ``-t s`` on the CLI.
8
8
  """
9
9
 
10
10
  from execsql.db.base import Database
11
- from execsql.db.target_types import ColumnKinds, kind_for_type_name
11
+ from execsql.db.target_types import ColumnKinds, ColumnMetadata, kind_and_scale_for_type_name
12
12
  from execsql.db.odbc import connection_string, fresh_sessions, loggable
13
13
  from execsql.exceptions import ErrInfo
14
14
  from execsql.utils.errors import fatal_error, install_hint
@@ -245,12 +245,16 @@ class SqlServerDatabase(Database):
245
245
  )
246
246
  if not rows:
247
247
  return super().column_kinds(sq_name)
248
- return {
249
- name.lower(): kind_for_type_name(
250
- f"{type_name}({precision},{scale})" if type_name in ("decimal", "numeric") else type_name,
251
- )
252
- for name, type_name, precision, scale in rows
253
- }
248
+ return ColumnMetadata(
249
+ {
250
+ name.lower(): kind_and_scale_for_type_name(
251
+ f"{type_name}({precision},{scale})"
252
+ if type_name in ("decimal", "numeric", "money", "smallmoney")
253
+ else type_name,
254
+ )
255
+ for name, type_name, precision, scale in rows
256
+ },
257
+ )
254
258
 
255
259
  def drop_table(self, tablename: str) -> None:
256
260
  """Drop *tablename*, schema-qualified and quoted by the caller."""
@@ -21,7 +21,7 @@ import datetime
21
21
  import math
22
22
  import re
23
23
  from collections.abc import Callable
24
- from decimal import Decimal
24
+ from decimal import Decimal, InvalidOperation
25
25
  from typing import Any, TypeAlias
26
26
 
27
27
  from execsql.exceptions import ErrInfo
@@ -39,7 +39,15 @@ from execsql.types import (
39
39
  DT_TimestampTZ,
40
40
  )
41
41
 
42
- __all__ = ["ColumnKinds", "existing_table_converter", "kind_for_python_type", "kind_for_type_name"]
42
+ __all__ = [
43
+ "decimal_parameter",
44
+ "ColumnKinds",
45
+ "ColumnMetadata",
46
+ "existing_table_converter",
47
+ "kind_for_python_type",
48
+ "kind_for_type_name",
49
+ "kind_and_scale_for_type_name",
50
+ ]
43
51
 
44
52
  #: Lower-cased column name -> the execsql type values for it convert to, or None.
45
53
  #: A string, not ``dict[...]``: on Python 3.10 that object passes
@@ -47,6 +55,17 @@ __all__ = ["ColumnKinds", "existing_table_converter", "kind_for_python_type", "k
47
55
  #: would take it for one.
48
56
  ColumnKinds: TypeAlias = "dict[str, type[DataType] | None]"
49
57
 
58
+
59
+ class ColumnMetadata(dict[str, type[DataType] | None]):
60
+ """A compatible column-kind dictionary carrying known decimal scales."""
61
+
62
+ def __init__(self, columns: dict[str, tuple[type[DataType] | None, int | None]]) -> None:
63
+ super().__init__((name, kind) for name, (kind, _scale) in columns.items())
64
+ self.decimal_scales = {
65
+ name: scale for name, (kind, scale) in columns.items() if kind is DT_Decimal and scale is not None
66
+ }
67
+
68
+
50
69
  _TEXT = {
51
70
  "char",
52
71
  "character",
@@ -162,6 +181,28 @@ def kind_for_type_name(type_name: str, *, oracle: bool = False) -> type[DataType
162
181
  return None
163
182
 
164
183
 
184
+ def kind_and_scale_for_type_name(type_name: str, *, oracle: bool = False) -> tuple[type[DataType] | None, int | None]:
185
+ """Return the existing kind and a declared decimal scale, if known."""
186
+ kind = kind_for_type_name(type_name, oracle=oracle)
187
+ if kind not in (DT_Decimal, DT_Long):
188
+ return kind, None
189
+ name = type_name.strip().lower()
190
+ base = " ".join(_PARAMS.sub(" ", name).replace(" unsigned", " ").replace(" zerofill", " ").split())
191
+ params = _PARAMS.search(name)
192
+ if base not in _DECIMAL or params is None:
193
+ return kind, None
194
+ args = [arg.strip() for arg in params.group(1).split(",")]
195
+ if len(args) == 1:
196
+ return kind, 0
197
+ if len(args) != 2:
198
+ return kind, None
199
+ try:
200
+ scale = int(args[1])
201
+ except ValueError:
202
+ scale = None
203
+ return kind, scale
204
+
205
+
165
206
  def kind_for_python_type(type_code: object, scale: object = None) -> type[DataType] | None:
166
207
  """The execsql type for a column a driver describes by the Python type it returns (pyodbc, firebird-driver).
167
208
 
@@ -201,7 +242,8 @@ Converter = Callable[[Any], Any]
201
242
 
202
243
 
203
244
  def _as_given(value: Any) -> Any:
204
- return value
245
+ # Bind decimal text ourselves before a driver can cast it through DOUBLE.
246
+ return str(value) if isinstance(value, Decimal) and value.is_finite() else value
205
247
 
206
248
 
207
249
  def _whole_number_converter(column: str, table: str, default: Converter) -> Converter:
@@ -255,23 +297,128 @@ def _true_false_as_number(default: Converter) -> Converter:
255
297
  return convert
256
298
 
257
299
 
300
+ def _check_decimal_scale(number: Decimal, value: Any, scale: int | None, column: str, table: str) -> None:
301
+ """Check coefficient digits without quantizing, expanding or using context precision."""
302
+ if scale is None or not number.is_finite() or number.is_zero():
303
+ return
304
+ parts = number.as_tuple()
305
+ exponent = parts.exponent
306
+ assert isinstance(exponent, int)
307
+ discarded = -scale - exponent
308
+ if discarded <= 0:
309
+ return
310
+ if discarded >= len(parts.digits) or any(parts.digits[-discarded:]):
311
+ raise ErrInfo(
312
+ type="error",
313
+ other_msg=(
314
+ f"Can't load {value!r} into column {column} of {table}: the column's scale is {scale}, "
315
+ "and the database would round the value."
316
+ ),
317
+ )
318
+
319
+
320
+ def decimal_parameter(number: Decimal, binding_precision: int | None, column: str, table: str) -> Decimal | str:
321
+ """Bind a finite Decimal exactly within an adapter's native parameter capacity."""
322
+ if binding_precision is None:
323
+ return number
324
+ if number.is_zero():
325
+ return Decimal(0).copy_sign(number)
326
+ parts = number.as_tuple()
327
+ exponent = parts.exponent
328
+ assert isinstance(exponent, int) # Only finite values reach this helper.
329
+ if exponent > 0:
330
+ if number.adjusted() >= binding_precision:
331
+ raise ErrInfo(
332
+ type="error",
333
+ other_msg=(
334
+ f"Can't load {number!r} into column {column} of {table}: "
335
+ f"the database supports at most {binding_precision} decimal digits."
336
+ ),
337
+ )
338
+ # Expansion is bounded by the adapter, never by the input exponent.
339
+ return Decimal(format(number, "f"))
340
+ native_width = len(parts.digits)
341
+ if -exponent > native_width:
342
+ native_width = -exponent + 1
343
+ if native_width > binding_precision:
344
+ # Avoid a driver's silent Decimal-to-double fallback. Fixed text
345
+ # also avoids exponent parsing at the maximum supported scale.
346
+ if exponent >= -binding_precision:
347
+ return format(number, "f")
348
+ return str(number)
349
+ return number
350
+
351
+
352
+ def _exact_decimal_converter(
353
+ default: Converter,
354
+ column: str,
355
+ table: str,
356
+ binding_precision: int | None,
357
+ scale: int | None,
358
+ ) -> Converter:
359
+ """Retain finite exact source numbers for an existing decimal column.
360
+
361
+ Floats and non-numeric values keep the scanned conversion; converting a
362
+ float here cannot recover source digits already lost by its reader.
363
+ """
364
+
365
+ def convert(value: Any) -> Any:
366
+ if isinstance(value, bool):
367
+ return default(value)
368
+ if isinstance(value, int):
369
+ _check_decimal_scale(Decimal(value), value, scale, column, table)
370
+ return value
371
+ if isinstance(value, Decimal) and value.is_finite():
372
+ _check_decimal_scale(value, value, scale, column, table)
373
+ return decimal_parameter(value, binding_precision, column, table)
374
+ if isinstance(value, str) and _NUMBER_TEXT.fullmatch(value):
375
+ try:
376
+ number = Decimal(value)
377
+ except InvalidOperation:
378
+ return default(value)
379
+ if number.is_finite():
380
+ _check_decimal_scale(number, value, scale, column, table)
381
+ return decimal_parameter(number, binding_precision, column, table)
382
+ return default(value)
383
+
384
+ return convert
385
+
386
+
258
387
  def existing_table_converter(
259
388
  kind: type[DataType] | None,
260
389
  scanned: type[DataType],
261
390
  default: Converter,
262
391
  column: str,
263
392
  table: str,
393
+ *,
394
+ decimal_binding_precision: int | None = None,
395
+ decimal_scale: int | None = None,
264
396
  ) -> Converter:
265
397
  """How a value for *column* of existing table *table* is converted.
266
398
 
267
399
  *kind* is the column's type (``None`` if execsql has none that fits),
268
400
  *scanned* the type the source column scanned as, and *default* the
269
401
  conversion to that scanned type, which a new table's values get.
402
+ *decimal_binding_precision* bounds native Decimal parameter conversion
403
+ for drivers that need it. *decimal_scale* rejects exact source values that
404
+ need rounding; None leaves the destination scale to the database.
270
405
  """
271
406
  if kind is DT_Text:
272
407
  return _as_given
273
408
  if kind in (DT_Long, DT_Decimal, DT_Float) and scanned is DT_Boolean:
274
- return _true_false_as_number(default)
409
+ boolean_converter = _true_false_as_number(default)
410
+ if kind is DT_Decimal and decimal_scale is not None:
411
+
412
+ def checked_boolean(value: Any) -> Any:
413
+ result = boolean_converter(value)
414
+ if isinstance(result, (int, Decimal)):
415
+ _check_decimal_scale(Decimal(result), value, decimal_scale, column, table)
416
+ return result
417
+
418
+ return checked_boolean
419
+ return boolean_converter
275
420
  if kind is DT_Long:
276
421
  return _whole_number_converter(column, table, default)
422
+ if kind is DT_Decimal:
423
+ return _exact_decimal_converter(default, column, table, decimal_binding_precision, decimal_scale)
277
424
  return default
execsql/debug/repl.py CHANGED
@@ -27,6 +27,7 @@ from pathlib import Path
27
27
  from typing import Any
28
28
 
29
29
  import execsql.state as _state
30
+ from execsql.exceptions import ScriptExit
30
31
  from execsql.interactive import Prompt, common_dot_command, read_eval_loop, unknown_dot_command
31
32
  from execsql.utils.color import color_disabled_by_env
32
33
 
@@ -237,7 +238,7 @@ def _handle_dot_command(line: str) -> bool:
237
238
  if command in ("continue", "c"):
238
239
  return False
239
240
  if command in ("abort", "q", "quit"):
240
- raise SystemExit(1)
241
+ raise ScriptExit(1)
241
242
  if command in ("next", "n"):
242
243
  _enable_step_mode()
243
244
  return False
execsql/exceptions.py CHANGED
@@ -21,6 +21,7 @@ can import from a single location. Notable exceptions:
21
21
  — spreadsheet I/O failures.
22
22
  - :class:`ConsoleUIError` — GUI console errors.
23
23
  - :class:`CondParserError` / :class:`NumericParserError` — parser failures.
24
+ - :class:`ScriptExit` — execsql ending the run on purpose (a ``SystemExit``).
24
25
 
25
26
  Note:
26
27
  The ``execsql`` top-level package re-exports a *separate*
@@ -49,6 +50,7 @@ __all__ = [
49
50
  "ConsoleUIError",
50
51
  "CondParserError",
51
52
  "NumericParserError",
53
+ "ScriptExit",
52
54
  ]
53
55
 
54
56
 
@@ -106,6 +108,8 @@ class ErrInfo(ExecSqlError):
106
108
 
107
109
  ``eval_err()`` / ``write()`` remain available for the full formatted
108
110
  message including script location, timestamp, and command context.
111
+ ``always_halt`` makes a metacommand failure stop execution regardless
112
+ of the metacommand-error setting, such as an unevaluable condition.
109
113
  """
110
114
 
111
115
  def __repr__(self) -> str:
@@ -120,6 +124,8 @@ class ErrInfo(ExecSqlError):
120
124
  command_text: str | None = None,
121
125
  exception_msg: str | None = None,
122
126
  other_msg: str | None = None,
127
+ *,
128
+ always_halt: bool = False,
123
129
  ) -> None:
124
130
  self.type: str = type
125
131
  self.command: str | None = command_text
@@ -130,6 +136,7 @@ class ErrInfo(ExecSqlError):
130
136
  self.cmd: str | None = None
131
137
  self.cmdtype: str | None = None
132
138
  self.error_message: str | None = None
139
+ self.always_halt = always_halt
133
140
  # Pass a concise message to Exception so str(e), e.args, and
134
141
  # standard loggers produce useful output.
135
142
  super().__init__(self.other or self.exception or self.type)
@@ -272,3 +279,15 @@ class CondParserError(ExecSqlError):
272
279
 
273
280
  class NumericParserError(ExecSqlError):
274
281
  """Raised for numeric-expression parse errors."""
282
+
283
+
284
+ class ScriptExit(SystemExit):
285
+ """execsql ending the run on purpose.
286
+
287
+ Raised by ``exit_now()`` (``HALT``, an error that halts the run, a
288
+ cancelled ``PROMPT``), by a cancelled dialog, and by ``.quit`` / ``.abort``
289
+ at a ``BREAKPOINT`` prompt. A ``SystemExit``, so everything that catches
290
+ one still does. A plain ``SystemExit`` -- from a signal handler, execsql's
291
+ own SIGTERM handler, or quitting the Textual console -- is an interrupt:
292
+ the statement it stops is rolled back like a failed one.
293
+ """
execsql/exporters/html.py CHANGED
@@ -28,6 +28,26 @@ from execsql.utils.fileio import filewriter_close
28
28
  __all__ = ["export_html", "export_cgi_html", "write_query_to_html", "write_query_to_cgi_html"]
29
29
 
30
30
 
31
+ def _write_table(f: Any, hdrs: list[str], rows: Any, desc: str | None) -> None:
32
+ """Write the table fragment shared by standalone and CGI HTML exports."""
33
+ f.write("<table>\n")
34
+ if desc is not None:
35
+ f.write(f"<caption>{desc}</caption>\n")
36
+ f.write("<thead><tr>")
37
+ for h in hdrs:
38
+ f.write(f"<th>{html_mod.escape(str(h))}</th>")
39
+ f.write("</tr></thead>\n<tbody>\n")
40
+ for r in rows:
41
+ f.write("<tr>")
42
+ for v in r:
43
+ # `if v is not None`, not `if v`: 0, False, and an empty
44
+ # string are all falsy, and a zero measurement silently became
45
+ # an empty cell.
46
+ f.write(f"<td>{html_mod.escape(str(v)) if v is not None else ''}</td>")
47
+ f.write("</tr>\n")
48
+ f.write("</tbody>\n</table>\n")
49
+
50
+
31
51
  def export_html(
32
52
  outfile: str,
33
53
  hdrs: list[str],
@@ -40,24 +60,6 @@ def export_html(
40
60
  """Write a complete HTML document containing a data table to a file or ZIP archive."""
41
61
  conf = _state.conf
42
62
 
43
- def write_table(f):
44
- f.write("<table>\n")
45
- if desc is not None:
46
- f.write(f"<caption>{desc}</caption>\n")
47
- f.write("<thead><tr>")
48
- for h in hdrs:
49
- f.write(f"<th>{html_mod.escape(str(h))}</th>")
50
- f.write("</tr></thead>\n<tbody>\n")
51
- for r in rows:
52
- f.write("<tr>")
53
- for v in r:
54
- # `if v is not None`, not `if v`: 0, False, and an empty
55
- # string are all falsy, and a zero measurement silently became
56
- # an empty cell.
57
- f.write(f"<td>{html_mod.escape(str(v)) if v is not None else ''}</td>")
58
- f.write("</tr>\n")
59
- f.write("</tbody>\n</table>\n")
60
-
61
63
  script, lno = current_script_line()
62
64
  # If not append, write a complete HTML document with header and table.
63
65
  # If append and the file does not exist, write just the table.
@@ -112,7 +114,7 @@ def export_html(
112
114
  f.write("tbody tr { border-bottom: 1px dotted #814324; }\n")
113
115
  f.write("</style>")
114
116
  f.write("\n</head>\n<body>\n")
115
- write_table(f)
117
+ _write_table(f, hdrs, rows, desc)
116
118
  f.write("</body>\n</html>\n")
117
119
  finally:
118
120
  if outfile.lower() != "stdout":
@@ -120,14 +122,14 @@ def export_html(
120
122
  elif not zipfile and append:
121
123
  if outfile.lower() == "stdout":
122
124
  f = sys.stdout
123
- write_table(f)
125
+ _write_table(f, hdrs, rows, desc)
124
126
  elif not Path(outfile).is_file():
125
127
  from execsql.utils.fileio import EncodedFile
126
128
 
127
129
  ef = EncodedFile(outfile, conf.output_encoding)
128
130
  f = ef.open("wt")
129
131
  try:
130
- write_table(f)
132
+ _write_table(f, hdrs, rows, desc)
131
133
  finally:
132
134
  f.close()
133
135
  else:
@@ -152,7 +154,7 @@ def export_html(
152
154
  else:
153
155
  t.write(line)
154
156
  t.write("\n")
155
- write_table(t)
157
+ _write_table(t, hdrs, rows, desc)
156
158
  t.write(remainder)
157
159
  for line in f:
158
160
  t.write(line)
@@ -183,24 +185,6 @@ def export_cgi_html(
183
185
  """Write a CGI-style HTML fragment (Content-Type header + table) to a file or ZIP archive."""
184
186
  conf = _state.conf
185
187
 
186
- def write_table(f):
187
- f.write("<table>\n")
188
- if desc is not None:
189
- f.write(f"<caption>{desc}</caption>\n")
190
- f.write("<thead><tr>")
191
- for h in hdrs:
192
- f.write(f"<th>{html_mod.escape(str(h))}</th>")
193
- f.write("</tr></thead>\n<tbody>\n")
194
- for r in rows:
195
- f.write("<tr>")
196
- for v in r:
197
- # `if v is not None`, not `if v`: 0, False, and an empty
198
- # string are all falsy, and a zero measurement silently became
199
- # an empty cell.
200
- f.write(f"<td>{html_mod.escape(str(v)) if v is not None else ''}</td>")
201
- f.write("</tr>\n")
202
- f.write("</tbody>\n</table>\n")
203
-
204
188
  script, lno = current_script_line()
205
189
  if zipfile or not append or (append and not Path(outfile).is_file()):
206
190
  if zipfile is None:
@@ -216,7 +200,7 @@ def export_cgi_html(
216
200
  f = ZipWriter(zipfile, outfile, append)
217
201
  try:
218
202
  f.write("Content-Type: text/html\n\n")
219
- write_table(f)
203
+ _write_table(f, hdrs, rows, desc)
220
204
  finally:
221
205
  if outfile.lower() != "stdout":
222
206
  f.close()
@@ -229,7 +213,7 @@ def export_cgi_html(
229
213
  ef = EncodedFile(outfile, conf.output_encoding)
230
214
  f = ef.open("a")
231
215
  try:
232
- write_table(f)
216
+ _write_table(f, hdrs, rows, desc)
233
217
  finally:
234
218
  if outfile.lower() != "stdout":
235
219
  f.close()