execsql2 2.40.0__py3-none-any.whl → 2.41.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.
- execsql/__init__.py +4 -2
- execsql/api.py +40 -27
- execsql/cli/commands/__init__.py +1 -0
- execsql/cli/commands/inspect.py +292 -0
- execsql/cli/dispatch.py +3 -3
- execsql/cli/inspection.py +276 -0
- execsql/cli/lint.py +3 -4
- execsql/cli/options.py +15 -7
- execsql/config.py +15 -2
- execsql/db/access.py +6 -5
- execsql/db/base.py +14 -0
- execsql/db/dsn.py +3 -2
- execsql/db/duckdb.py +2 -1
- execsql/db/firebird.py +3 -2
- execsql/db/mysql.py +3 -2
- execsql/db/oracle.py +3 -2
- execsql/db/postgres.py +3 -2
- execsql/db/sqlite.py +2 -1
- execsql/db/sqlserver.py +3 -2
- execsql/ddl.py +310 -0
- execsql/exporters/xls.py +18 -4
- execsql/file_inspection.py +393 -0
- execsql/importers/base.py +19 -12
- execsql/importers/feather.py +16 -21
- execsql/importers/json.py +26 -32
- execsql/importers/xls.py +9 -4
- execsql/schema.py +816 -0
- execsql/script/executor.py +4 -0
- execsql/script/variables.py +14 -2
- execsql/utils/errors.py +21 -3
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/README.md +7 -0
- execsql2-2.41.0.data/data/execsql2_extras/inspect/README.md +116 -0
- execsql2-2.41.0.data/data/execsql2_extras/inspect/make_demo.py +106 -0
- {execsql2-2.40.0.dist-info → execsql2-2.41.0.dist-info}/METADATA +84 -19
- {execsql2-2.40.0.dist-info → execsql2-2.41.0.dist-info}/RECORD +51 -44
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/config_settings.sqlite +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/example_config_prompt.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/make_config_db.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/md_compare.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/md_glossary.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/md_upsert.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/pg_compare.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/pg_glossary.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/script_template.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/ss_compare.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/ss_glossary.sql +0 -0
- {execsql2-2.40.0.data → execsql2-2.41.0.data}/data/execsql2_extras/ss_upsert.sql +0 -0
- {execsql2-2.40.0.dist-info → execsql2-2.41.0.dist-info}/WHEEL +0 -0
- {execsql2-2.40.0.dist-info → execsql2-2.41.0.dist-info}/entry_points.txt +0 -0
- {execsql2-2.40.0.dist-info → execsql2-2.41.0.dist-info}/licenses/LICENSE.txt +0 -0
- {execsql2-2.40.0.dist-info → execsql2-2.41.0.dist-info}/licenses/NOTICE +0 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Human-readable rendering for database and file inspection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
import unicodedata
|
|
8
|
+
|
|
9
|
+
from rich import box
|
|
10
|
+
from rich.table import Table
|
|
11
|
+
from rich.text import Text
|
|
12
|
+
|
|
13
|
+
from execsql.cli.help import _console, _err_console
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _literal(value: object) -> Text:
|
|
17
|
+
"""Keep catalog names literal: no Rich markup or terminal control sequences."""
|
|
18
|
+
text = str(value)
|
|
19
|
+
return Text("".join(f"\\x{ord(c):02x}" if unicodedata.category(c) == "Cc" else c for c in text))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _name(item: dict[str, Any], *, referenced: bool = False) -> str:
|
|
23
|
+
prefix = "referenced_" if referenced else ""
|
|
24
|
+
parts = (
|
|
25
|
+
item.get(prefix + "catalog"),
|
|
26
|
+
item.get(prefix + "schema"),
|
|
27
|
+
item.get("referenced_table" if referenced else "name"),
|
|
28
|
+
)
|
|
29
|
+
return ".".join(str(p) for p in parts if p not in (None, ""))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _primary_key(item: dict[str, Any]) -> str:
|
|
33
|
+
keys = item["primary_key"]
|
|
34
|
+
return "unavailable" if keys is None else ", ".join(keys) if keys else "none"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def print_inspection(result: dict[str, Any], *, detailed: bool, database_overview: bool = False) -> None:
|
|
38
|
+
"""Show a catalog overview, or columns/relationships for selected tables."""
|
|
39
|
+
engine = result["dialect"] or f"{result['adapter']} (dialect unknown)"
|
|
40
|
+
database = result.get("database") if database_overview else None
|
|
41
|
+
if database is not None:
|
|
42
|
+
_console.print(_literal(f"Database: {database['name'] or 'unavailable'}"), style="bold")
|
|
43
|
+
_console.print(_literal(f"Engine: {database['engine'] or engine}"))
|
|
44
|
+
namespaces = result["schemas"]
|
|
45
|
+
if database["namespace_kind"] in ("schema", "attached_database") and namespaces is not None:
|
|
46
|
+
overview = Table(box=box.SIMPLE, show_edge=False)
|
|
47
|
+
for title in (
|
|
48
|
+
"Namespace" if database["namespace_kind"] == "attached_database" else "Schema",
|
|
49
|
+
"Visible tables",
|
|
50
|
+
"Visible views",
|
|
51
|
+
):
|
|
52
|
+
overview.add_column(title, overflow="fold")
|
|
53
|
+
for namespace in namespaces:
|
|
54
|
+
overview.add_row(
|
|
55
|
+
_literal(namespace["name"] if namespace["name"] is not None else "(no schema)"),
|
|
56
|
+
str(namespace["table_count"]),
|
|
57
|
+
str(namespace["view_count"]),
|
|
58
|
+
)
|
|
59
|
+
_console.print(overview)
|
|
60
|
+
if not namespaces:
|
|
61
|
+
_console.print("No visible schemas or namespaces.")
|
|
62
|
+
return
|
|
63
|
+
if namespaces is None:
|
|
64
|
+
_console.print("Schema enumeration unavailable; showing visible objects.")
|
|
65
|
+
else:
|
|
66
|
+
_console.print(_literal(engine), style="bold")
|
|
67
|
+
tables = result["tables"]
|
|
68
|
+
if not tables:
|
|
69
|
+
_console.print("No matching tables or views.")
|
|
70
|
+
return
|
|
71
|
+
if detailed:
|
|
72
|
+
for item in tables:
|
|
73
|
+
_print_table(item)
|
|
74
|
+
return
|
|
75
|
+
overview = Table(box=box.SIMPLE, show_edge=False)
|
|
76
|
+
titles = ("Object", "Kind") if database_overview else ("Object", "Kind", "Columns", "Primary key", "Foreign keys")
|
|
77
|
+
for title in titles:
|
|
78
|
+
overview.add_column(title, overflow="fold")
|
|
79
|
+
for item in tables:
|
|
80
|
+
if database_overview:
|
|
81
|
+
overview.add_row(_literal(_name(item)), _literal(item["kind"]))
|
|
82
|
+
continue
|
|
83
|
+
foreign = item["foreign_keys"]
|
|
84
|
+
overview.add_row(
|
|
85
|
+
_literal(_name(item)),
|
|
86
|
+
_literal(item["kind"]),
|
|
87
|
+
_literal(len(item["columns"])),
|
|
88
|
+
_literal(_primary_key(item)),
|
|
89
|
+
_literal("unavailable" if foreign is None else len(foreign)),
|
|
90
|
+
)
|
|
91
|
+
_console.print(overview)
|
|
92
|
+
_console.print(f"{len(tables)} object(s).")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _print_table(item: dict[str, Any]) -> None:
|
|
96
|
+
_console.print()
|
|
97
|
+
_console.print(_literal(f"{_name(item)} ({item['kind']})"), style="bold")
|
|
98
|
+
columns = Table(box=box.SIMPLE, show_edge=False)
|
|
99
|
+
for title in ("Column", "Type", "Nullable", "Key"):
|
|
100
|
+
columns.add_column(title, overflow="fold")
|
|
101
|
+
primary = item["primary_key"] or []
|
|
102
|
+
foreign = item["foreign_keys"]
|
|
103
|
+
for column in item["columns"]:
|
|
104
|
+
name = column["name"]
|
|
105
|
+
flags = []
|
|
106
|
+
if name in primary:
|
|
107
|
+
flags.append("PK")
|
|
108
|
+
if foreign and any(name in key["columns"] for key in foreign):
|
|
109
|
+
flags.append("FK")
|
|
110
|
+
data_type = column["data_type"]
|
|
111
|
+
type_text = "unavailable" if data_type is None else data_type or "(undeclared)"
|
|
112
|
+
nullable = "unknown" if column["nullable"] is None else "yes" if column["nullable"] else "no"
|
|
113
|
+
columns.add_row(_literal(name), _literal(type_text), _literal(nullable), _literal(", ".join(flags)))
|
|
114
|
+
_console.print(columns)
|
|
115
|
+
_console.print(_literal(f"Primary key: {_primary_key(item)}"))
|
|
116
|
+
if not foreign:
|
|
117
|
+
_console.print("Foreign keys: unavailable" if foreign is None else "Foreign keys: none")
|
|
118
|
+
else:
|
|
119
|
+
_console.print("Foreign keys:")
|
|
120
|
+
for key in foreign:
|
|
121
|
+
source = ", ".join(key["columns"])
|
|
122
|
+
target = ", ".join(c if c is not None else "?" for c in key["referenced_columns"])
|
|
123
|
+
constraint = f" [{key['name']}]" if key["name"] is not None else ""
|
|
124
|
+
_console.print(_literal(f" ({source}) -> {_name(key, referenced=True)} ({target}){constraint}"))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def print_inspection_error(result: dict[str, Any], dsn: str | None) -> None:
|
|
128
|
+
"""Explain failures without printing credential-bearing URLs or driver text."""
|
|
129
|
+
error = result["error"]
|
|
130
|
+
_err_console.print(_literal(f"Error: {error['message']}"), style="bold red")
|
|
131
|
+
if error["code"] == "dependency_error":
|
|
132
|
+
return
|
|
133
|
+
hints = {
|
|
134
|
+
"configuration_error": "Check execsql.conf [connect] or pass --dsn URL; --config FILE selects an additional configuration file.",
|
|
135
|
+
"metadata_error": "Check catalog permissions and the adapter's schema-discovery support.",
|
|
136
|
+
"unsupported_adapter": "Use a supported database adapter; see the schema-discovery reference.",
|
|
137
|
+
"close_error": "The connection could not be closed. Check the database server and driver.",
|
|
138
|
+
}
|
|
139
|
+
hint = hints.get(error["code"])
|
|
140
|
+
if hint is None:
|
|
141
|
+
hint = (
|
|
142
|
+
_connection_hint(dsn)
|
|
143
|
+
if dsn is not None
|
|
144
|
+
else "Check the configured database target, driver and credentials; inspection never creates a database."
|
|
145
|
+
)
|
|
146
|
+
_err_console.print(_literal(hint))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _connection_hint(dsn: str) -> str:
|
|
150
|
+
from execsql.cli.dsn import _parse_connection_string
|
|
151
|
+
|
|
152
|
+
try:
|
|
153
|
+
params = _parse_connection_string(dsn)
|
|
154
|
+
except Exception:
|
|
155
|
+
return "Check the URL scheme, host, port and database name. Run execsql inspect database --help for examples."
|
|
156
|
+
file = params["db_file"]
|
|
157
|
+
if file and file != ":memory:":
|
|
158
|
+
try:
|
|
159
|
+
exists = Path(file).is_file()
|
|
160
|
+
except (OSError, ValueError):
|
|
161
|
+
return "Check the database file path and read permissions."
|
|
162
|
+
if not exists:
|
|
163
|
+
return "Check the file path; inspection never creates a database."
|
|
164
|
+
return "Check that the database file is readable and its adapter driver is installed."
|
|
165
|
+
if params["db_type"] in ("l", "k"):
|
|
166
|
+
return "Check that the in-process database driver is installed and the database can be opened."
|
|
167
|
+
return (
|
|
168
|
+
"Check the server, port, database name, installed driver and credentials. "
|
|
169
|
+
"Include the user in the URL and use --prompt-password on a terminal for password authentication, "
|
|
170
|
+
"or --no-passwd for driver/OS authentication."
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def print_file_inspection(
|
|
175
|
+
result: dict[str, Any],
|
|
176
|
+
*,
|
|
177
|
+
show_settings: bool = False,
|
|
178
|
+
show_config: bool = False,
|
|
179
|
+
) -> None:
|
|
180
|
+
"""Render the file contract as literal metadata, never source row values."""
|
|
181
|
+
_console.print(_literal(f"File: {result['file']}"), style="bold")
|
|
182
|
+
_console.print(_literal(f"Format: {result['format']} ({result['format_source']})"))
|
|
183
|
+
if result["encoding"] is not None:
|
|
184
|
+
encoding = result["encoding"]
|
|
185
|
+
_console.print(_literal(f"Encoding: {encoding['name']} ({encoding['source']})"))
|
|
186
|
+
if result["format"] == "delimited":
|
|
187
|
+
_console.print(
|
|
188
|
+
_literal(f"Delimiter: {result['delimiter']!r}; quote: {result['quote']!r} ({result['dialect_source']})"),
|
|
189
|
+
)
|
|
190
|
+
if result["skip_rows"]:
|
|
191
|
+
_console.print(f"Skipped before header: {result['skip_rows']} line(s)/worksheet row(s).")
|
|
192
|
+
if result["worksheets"] is not None and result["sheet"] is None:
|
|
193
|
+
_console.print("Worksheets:")
|
|
194
|
+
for index, name in enumerate(result["worksheets"], 1):
|
|
195
|
+
_console.print(_literal(f" {index}. {name}"))
|
|
196
|
+
_console.print("Use --sheet NAME to inspect columns.")
|
|
197
|
+
else:
|
|
198
|
+
if result["sheet"] is not None:
|
|
199
|
+
_console.print(_literal(f"Worksheet: {result['sheet']}"))
|
|
200
|
+
scan = result["scan"]
|
|
201
|
+
complete = "complete" if scan["complete"] else "incomplete; inferred types are provisional"
|
|
202
|
+
_console.print(f"Scan: {scan['mode']}, {scan['rows_examined']} data rows examined ({complete}).")
|
|
203
|
+
if not scan["complete"]:
|
|
204
|
+
_console.print(f"Total data rows: {scan['total_rows'] if scan['total_rows'] is not None else 'unknown'}")
|
|
205
|
+
if scan["mode"] == "sample" and scan["source_materialized"]:
|
|
206
|
+
_console.print(
|
|
207
|
+
"This reader materialized the full source; sampling limited inference, not file reads or memory.",
|
|
208
|
+
)
|
|
209
|
+
columns = Table(box=box.SIMPLE, show_edge=False)
|
|
210
|
+
stored = any(column["source_type"] is not None for column in result["columns"])
|
|
211
|
+
for heading in ("Column", "Inferred type", "Nulls"):
|
|
212
|
+
columns.add_column(heading, overflow="fold")
|
|
213
|
+
if stored:
|
|
214
|
+
columns.add_column("Stored type", overflow="fold")
|
|
215
|
+
for column in result["columns"]:
|
|
216
|
+
values: list[Text | str] = [
|
|
217
|
+
_literal(column["name"]),
|
|
218
|
+
_literal(column["inferred_type"]),
|
|
219
|
+
str(column["null_count"]),
|
|
220
|
+
]
|
|
221
|
+
if stored:
|
|
222
|
+
values.append(_literal(column["source_type"] or "unavailable"))
|
|
223
|
+
columns.add_row(*values)
|
|
224
|
+
_console.print(columns)
|
|
225
|
+
print_inspection_context(
|
|
226
|
+
result,
|
|
227
|
+
show_settings=show_settings,
|
|
228
|
+
show_config=show_config,
|
|
229
|
+
settings_label="Import settings",
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _catalog_settings(result: dict[str, Any]) -> dict[str, str]:
|
|
234
|
+
"""Present applicable connection policies without claiming they were exercised."""
|
|
235
|
+
settings = result["settings"]
|
|
236
|
+
if not settings:
|
|
237
|
+
return {}
|
|
238
|
+
adapter = result["adapter"]
|
|
239
|
+
shown = {"Database type": {"Access": "MS Access", "DSN": "ODBC DSN"}.get(adapter, adapter)}
|
|
240
|
+
if adapter not in ("SQLite", "DuckDB"):
|
|
241
|
+
prompt = settings["password_prompt"]
|
|
242
|
+
shown["Password prompting allowed"] = "Yes" if prompt else "No"
|
|
243
|
+
if prompt:
|
|
244
|
+
shown["Keyring allowed"] = "Yes" if settings["use_keyring"] else "No"
|
|
245
|
+
# Only these adapters use the configured encoding when opening a connection.
|
|
246
|
+
if adapter in ("MySQL", "Firebird") and settings.get("database_encoding") is not None:
|
|
247
|
+
shown["Connection encoding"] = settings["database_encoding"]
|
|
248
|
+
if adapter == "SQL Server":
|
|
249
|
+
shown["Trust server certificate"] = "Yes" if settings["trust_server_certificate"] else "No"
|
|
250
|
+
return shown
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def print_inspection_context(
|
|
254
|
+
result: dict[str, Any],
|
|
255
|
+
*,
|
|
256
|
+
show_settings: bool,
|
|
257
|
+
show_config: bool,
|
|
258
|
+
settings_label: str = "Inspection settings",
|
|
259
|
+
) -> None:
|
|
260
|
+
"""Render opt-in configuration provenance for any inspection scope."""
|
|
261
|
+
if show_config:
|
|
262
|
+
_console.print(
|
|
263
|
+
_literal("Configuration files: " + (", ".join(result["config_files"]) or "none (built-in defaults)")),
|
|
264
|
+
)
|
|
265
|
+
if show_settings:
|
|
266
|
+
if "adapter" in result:
|
|
267
|
+
settings = _catalog_settings(result)
|
|
268
|
+
_console.print(_literal(settings_label + (":" if settings else ": none")))
|
|
269
|
+
for name, value in settings.items():
|
|
270
|
+
_console.print(_literal(f" {name}: {value}"))
|
|
271
|
+
return
|
|
272
|
+
_console.print(
|
|
273
|
+
_literal(
|
|
274
|
+
settings_label + ": " + ", ".join(f"{name}={value}" for name, value in result["settings"].items()),
|
|
275
|
+
),
|
|
276
|
+
)
|
execsql/cli/lint.py
CHANGED
|
@@ -1074,13 +1074,12 @@ def _lint_nodes(
|
|
|
1074
1074
|
visited_scripts=visited_scripts,
|
|
1075
1075
|
guarded=guarded,
|
|
1076
1076
|
)
|
|
1077
|
-
elif isinstance(node, ScriptBlock):
|
|
1077
|
+
elif isinstance(node, ScriptBlock) and node.name not in visited_scripts:
|
|
1078
1078
|
# Lint the block body once (structural errors are caught by the
|
|
1079
1079
|
# parser). Issues carry their own line, which already places them
|
|
1080
1080
|
# inside the block, so the message does not repeat the block name.
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
_lint_nodes(node.body, script_dir, defined_vars, script_blocks, issues, visited_scripts=visited_scripts)
|
|
1081
|
+
visited_scripts.add(node.name)
|
|
1082
|
+
_lint_nodes(node.body, script_dir, defined_vars, script_blocks, issues, visited_scripts=visited_scripts)
|
|
1084
1083
|
|
|
1085
1084
|
|
|
1086
1085
|
# ---------------------------------------------------------------------------
|
execsql/cli/options.py
CHANGED
|
@@ -21,6 +21,7 @@ __all__ = [
|
|
|
21
21
|
"OutputFormat",
|
|
22
22
|
"OutputFormatOpt",
|
|
23
23
|
"PortOpt",
|
|
24
|
+
"RequiredDsnOpt",
|
|
24
25
|
"ScriptEncodingOpt",
|
|
25
26
|
"UserOpt",
|
|
26
27
|
]
|
|
@@ -42,20 +43,27 @@ DbTypeOpt = Annotated[
|
|
|
42
43
|
),
|
|
43
44
|
]
|
|
44
45
|
|
|
46
|
+
_CONNECTION_URL_FLAGS = ("--dsn", "--connection-string")
|
|
47
|
+
_CONNECTION_URL_HELP = (
|
|
48
|
+
"Database connection URL, e.g. postgresql://user@host:5432/db. "
|
|
49
|
+
"Supported schemes: postgresql (postgres), mysql (mariadb), mssql (sqlserver), oracle, firebird, sqlite, duckdb."
|
|
50
|
+
)
|
|
51
|
+
|
|
45
52
|
DsnOpt = Annotated[
|
|
46
53
|
str | None,
|
|
47
54
|
typer.Option(
|
|
48
|
-
|
|
49
|
-
"--connection-string",
|
|
55
|
+
*_CONNECTION_URL_FLAGS,
|
|
50
56
|
metavar="URL",
|
|
51
|
-
help=
|
|
52
|
-
"Database connection URL, e.g. postgresql://user:pass@host:5432/db. "
|
|
53
|
-
"Supported schemes: postgresql (postgres), mysql (mariadb), mssql (sqlserver), oracle, firebird, sqlite, duckdb. "
|
|
54
|
-
"Overrides -t/-u/-p and positional server/db args."
|
|
55
|
-
),
|
|
57
|
+
help=_CONNECTION_URL_HELP + " Overrides -t/-u/-p and positional server/db args.",
|
|
56
58
|
),
|
|
57
59
|
]
|
|
58
60
|
|
|
61
|
+
RequiredDsnOpt = Annotated[
|
|
62
|
+
str,
|
|
63
|
+
typer.Option(*_CONNECTION_URL_FLAGS, metavar="URL", help=_CONNECTION_URL_HELP),
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
|
|
59
67
|
UserOpt = Annotated[str | None, typer.Option("-u", "--user", help="Database user name.")]
|
|
60
68
|
|
|
61
69
|
PortOpt = Annotated[int | None, typer.Option("-p", "--port", help="Database server port.")]
|
execsql/config.py
CHANGED
|
@@ -35,6 +35,17 @@ __all__ = [
|
|
|
35
35
|
]
|
|
36
36
|
|
|
37
37
|
|
|
38
|
+
def check_explicit_config_file(config_file: str | Path | None) -> None:
|
|
39
|
+
"""Refuse an explicitly requested inspection config that cannot be read."""
|
|
40
|
+
if config_file is None:
|
|
41
|
+
return
|
|
42
|
+
path = Path(config_file)
|
|
43
|
+
if not path.is_file():
|
|
44
|
+
raise ConfigError("Explicit configuration must be an existing readable regular file.")
|
|
45
|
+
with path.open("rb"):
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
38
49
|
class _VariablePool(Protocol):
|
|
39
50
|
def substitute(self, strval: str) -> tuple[str, int]: ...
|
|
40
51
|
def var_name_ok(self, varname: str) -> bool: ...
|
|
@@ -59,9 +70,11 @@ class StatObj:
|
|
|
59
70
|
self.metacommand_error = False
|
|
60
71
|
self.cancel_halt = True
|
|
61
72
|
self.dialog_canceled = False
|
|
62
|
-
# Cumulative record of
|
|
73
|
+
# Cumulative record of execution errors: (source, line_no, command, message).
|
|
63
74
|
# Unlike sql_error/metacommand_error, this is never reset between statements.
|
|
64
|
-
self.error_history: list[tuple[str, int | None, str, str]] = []
|
|
75
|
+
self.error_history: list[tuple[str, int | None, str | None, str]] = []
|
|
76
|
+
# The final ScriptExit must not add its already recorded error twice.
|
|
77
|
+
self.last_halting_error_id: int | None = None
|
|
65
78
|
# BatchLevels is defined in the main module; defer import to avoid circular deps
|
|
66
79
|
from execsql.script import BatchLevels
|
|
67
80
|
|
execsql/db/access.py
CHANGED
|
@@ -94,11 +94,12 @@ class AccessDatabase(Database):
|
|
|
94
94
|
self.last_dao_time = 0.0
|
|
95
95
|
self.temp_query_names: list[str] = []
|
|
96
96
|
self.autocommit = True
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
97
|
+
with self._initial_connection():
|
|
98
|
+
# Create the DAO connection
|
|
99
|
+
self.open_dao()
|
|
100
|
+
# Create the ODBC connection
|
|
101
|
+
self.open_db()
|
|
102
|
+
self.password = None # Clear cleartext password after successful connection
|
|
102
103
|
|
|
103
104
|
def __repr__(self) -> str:
|
|
104
105
|
return f"AccessDatabase({self.db_name}, {self.encoding})"
|
execsql/db/base.py
CHANGED
|
@@ -168,6 +168,20 @@ class Database(ABC):
|
|
|
168
168
|
"""Open the underlying database connection."""
|
|
169
169
|
...
|
|
170
170
|
|
|
171
|
+
@contextlib.contextmanager
|
|
172
|
+
def _initial_connection(self) -> Iterator[None]:
|
|
173
|
+
"""Release acquired resources if initial connection setup cannot finish."""
|
|
174
|
+
try:
|
|
175
|
+
yield
|
|
176
|
+
except BaseException:
|
|
177
|
+
try:
|
|
178
|
+
self.close()
|
|
179
|
+
except BaseException:
|
|
180
|
+
pass # Preserve the setup failure or interruption.
|
|
181
|
+
finally:
|
|
182
|
+
self.conn = None
|
|
183
|
+
raise
|
|
184
|
+
|
|
171
185
|
def cursor(self):
|
|
172
186
|
"""Return a new cursor, opening the connection first if it has not been opened yet."""
|
|
173
187
|
if self.conn is None:
|
execsql/db/dsn.py
CHANGED
|
@@ -65,8 +65,9 @@ class DsnDatabase(Database):
|
|
|
65
65
|
self.password = password
|
|
66
66
|
self.encoding = encoding
|
|
67
67
|
self.paramstr = "?"
|
|
68
|
-
self.
|
|
69
|
-
|
|
68
|
+
with self._initial_connection():
|
|
69
|
+
self.open_db()
|
|
70
|
+
self.password = None # Clear cleartext password after successful connection
|
|
70
71
|
|
|
71
72
|
def __repr__(self) -> str:
|
|
72
73
|
return f"DsnDatabase({self.db_name!r}, {self.user!r}, {self.need_passwd!r}, {self.port!r}, {self.encoding!r})"
|
execsql/db/duckdb.py
CHANGED
|
@@ -197,7 +197,8 @@ class DuckDBDatabase(Database):
|
|
|
197
197
|
)
|
|
198
198
|
self.type = dbt_duckdb
|
|
199
199
|
self.catalog_name = Path(DuckDB_fn).stem
|
|
200
|
-
self.
|
|
200
|
+
with self._initial_connection():
|
|
201
|
+
self.open_db()
|
|
201
202
|
|
|
202
203
|
def current_schema(self) -> str | None:
|
|
203
204
|
return self._query_current_schema("select current_schema()")
|
execsql/db/firebird.py
CHANGED
|
@@ -74,8 +74,9 @@ class FirebirdDatabase(Database):
|
|
|
74
74
|
self.password = password
|
|
75
75
|
self.encoding = encoding or "latin1"
|
|
76
76
|
self.paramstr = "?"
|
|
77
|
-
self.
|
|
78
|
-
|
|
77
|
+
with self._initial_connection():
|
|
78
|
+
self.open_db()
|
|
79
|
+
self.password = None # Clear cleartext password after successful connection
|
|
79
80
|
|
|
80
81
|
def __repr__(self) -> str:
|
|
81
82
|
return (
|
execsql/db/mysql.py
CHANGED
|
@@ -171,8 +171,9 @@ class MySQLDatabase(Database):
|
|
|
171
171
|
# server is reached — so it silently capped what execsql could move.
|
|
172
172
|
self.encoding = encoding or "utf8mb4"
|
|
173
173
|
self.paramstr = "%s"
|
|
174
|
-
self.
|
|
175
|
-
|
|
174
|
+
with self._initial_connection():
|
|
175
|
+
self.open_db()
|
|
176
|
+
self.password = None # Clear cleartext password after successful connection
|
|
176
177
|
|
|
177
178
|
def __repr__(self) -> str:
|
|
178
179
|
return (
|
execsql/db/oracle.py
CHANGED
|
@@ -116,8 +116,9 @@ class OracleDatabase(Database):
|
|
|
116
116
|
self.password = password
|
|
117
117
|
self.encoding = encoding or "UTF8"
|
|
118
118
|
self.paramstr = ":1"
|
|
119
|
-
self.
|
|
120
|
-
|
|
119
|
+
with self._initial_connection():
|
|
120
|
+
self.open_db()
|
|
121
|
+
self.password = None # Clear cleartext password after successful connection
|
|
121
122
|
|
|
122
123
|
def __repr__(self) -> str:
|
|
123
124
|
return (
|
execsql/db/postgres.py
CHANGED
|
@@ -69,8 +69,9 @@ class PostgresDatabase(Database):
|
|
|
69
69
|
self.new_db = new_db
|
|
70
70
|
self.paramstr = "%s"
|
|
71
71
|
self.connect_timeout = connect_timeout
|
|
72
|
-
self.
|
|
73
|
-
|
|
72
|
+
with self._initial_connection():
|
|
73
|
+
self.open_db()
|
|
74
|
+
self.password = None # Clear cleartext password after successful connection
|
|
74
75
|
|
|
75
76
|
def __repr__(self) -> str:
|
|
76
77
|
return (
|
execsql/db/sqlite.py
CHANGED
execsql/db/sqlserver.py
CHANGED
|
@@ -65,8 +65,9 @@ class SqlServerDatabase(Database):
|
|
|
65
65
|
self.password = password
|
|
66
66
|
self.encoding = encoding or "latin1" # Default on installation of SQL Server
|
|
67
67
|
self.paramstr = "?"
|
|
68
|
-
self.
|
|
69
|
-
|
|
68
|
+
with self._initial_connection():
|
|
69
|
+
self.open_db()
|
|
70
|
+
self.password = None # Clear cleartext password after successful connection
|
|
70
71
|
|
|
71
72
|
def current_schema(self) -> str | None:
|
|
72
73
|
return self._query_current_schema("select schema_name()")
|