execsql2 2.19.2__py3-none-any.whl → 2.21.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 (32) hide show
  1. execsql/cli/run.py +28 -11
  2. execsql/db/access.py +5 -1
  3. execsql/db/base.py +8 -2
  4. execsql/db/dsn.py +3 -1
  5. execsql/db/factory.py +1 -1
  6. execsql/db/firebird.py +10 -4
  7. execsql/db/mysql.py +6 -0
  8. execsql/db/postgres.py +20 -18
  9. execsql/db/sqlserver.py +4 -1
  10. execsql/format.py +172 -16
  11. execsql/utils/mail.py +7 -4
  12. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/README.md +1 -1
  13. {execsql2-2.19.2.dist-info → execsql2-2.21.0.dist-info}/METADATA +56 -58
  14. {execsql2-2.19.2.dist-info → execsql2-2.21.0.dist-info}/RECORD +31 -32
  15. execsql2-2.19.2.data/data/execsql2_extras/execsql.conf +0 -359
  16. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/config_settings.sqlite +0 -0
  17. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/example_config_prompt.sql +0 -0
  18. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/make_config_db.sql +0 -0
  19. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/md_compare.sql +0 -0
  20. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/md_glossary.sql +0 -0
  21. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/md_upsert.sql +0 -0
  22. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/pg_compare.sql +0 -0
  23. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/pg_glossary.sql +0 -0
  24. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/pg_upsert.sql +0 -0
  25. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/script_template.sql +0 -0
  26. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/ss_compare.sql +0 -0
  27. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/ss_glossary.sql +0 -0
  28. {execsql2-2.19.2.data → execsql2-2.21.0.data}/data/execsql2_extras/ss_upsert.sql +0 -0
  29. {execsql2-2.19.2.dist-info → execsql2-2.21.0.dist-info}/WHEEL +0 -0
  30. {execsql2-2.19.2.dist-info → execsql2-2.21.0.dist-info}/entry_points.txt +0 -0
  31. {execsql2-2.19.2.dist-info → execsql2-2.21.0.dist-info}/licenses/LICENSE.txt +0 -0
  32. {execsql2-2.19.2.dist-info → execsql2-2.21.0.dist-info}/licenses/NOTICE +0 -0
execsql/cli/run.py CHANGED
@@ -206,9 +206,29 @@ def _ping_db(db: Any) -> None:
206
206
  # ---------------------------------------------------------------------------
207
207
 
208
208
 
209
- # B12/F014: shared sensitive-name filter used by env-var seeding, -a
210
- # value logging, and any future credential-redaction sites.
211
- _SENSITIVE_SUBSTRINGS = ("SECRET", "TOKEN", "PASSWORD", "PASSWD", "PRIVATE_KEY", "CREDENTIAL")
209
+ # B12/F014: shared sensitive-name filter for env-var seeding and any
210
+ # other name-based credential-redaction sites. Case-insensitive substring
211
+ # matches: an env var whose name (uppercased) contains any of these is
212
+ # not seeded into the substitution pool. "_KEY" uses a leading underscore
213
+ # so it catches AWS_ACCESS_KEY_ID / SECRET_KEY without also blocking
214
+ # KEYBOARD-style names. Substring matching catches the common service-
215
+ # prefixed forms (STRIPE_KEY, OPENAI_API_KEY, SENTRY_DSN, SLACK_WEBHOOK);
216
+ # GitHub PAT-suffixed names (GITHUB_PAT) and URL-encoded DSNs
217
+ # (DATABASE_URL) are documented gaps — use a TOKEN- or SECRET-prefixed
218
+ # name when storing those.
219
+ _SENSITIVE_SUBSTRINGS = (
220
+ "SECRET",
221
+ "TOKEN",
222
+ "PASSWORD",
223
+ "PASSWD",
224
+ "PRIVATE_KEY",
225
+ "CREDENTIAL",
226
+ "_KEY",
227
+ "APIKEY",
228
+ "API_KEY",
229
+ "DSN",
230
+ "WEBHOOK",
231
+ )
212
232
 
213
233
 
214
234
  def _seed_early_subvars() -> SubVarSet:
@@ -517,15 +537,12 @@ def _setup_logging(
517
537
  for n, repl in enumerate(sub_vars):
518
538
  var = f"$ARG_{n + 1}"
519
539
  subvars.add_substitution(var, repl)
520
- # B12/F014: -a values are user input that may contain
521
- # secrets. Redact the value in the log line when the
522
- # surrounding -a payload looks sensitive (matches the
523
- # existing env-var filter at _seed_early_subvars).
524
- display_repl = repl
525
- if any(s in str(repl).upper() for s in _SENSITIVE_SUBSTRINGS):
526
- display_repl = "***"
540
+ # `-a` values are positional and opaque (no name to denylist
541
+ # against). High-entropy secrets (sk-live-*, AKIA*, ghp_*,
542
+ # JWTs) pass any substring/value heuristic, so log the
543
+ # assignment confirmation without the value.
527
544
  logger.log_status_info(
528
- f"Command-line substitution variable assignment: {var} set to {{{display_repl}}}",
545
+ f"Command-line substitution variable assignment: {var} set to {{***}}",
529
546
  )
530
547
 
531
548
  return logger
execsql/db/access.py CHANGED
@@ -107,7 +107,11 @@ class AccessDatabase(Database):
107
107
  else:
108
108
  connstr = cs % db_name
109
109
  try:
110
- self.conn = pyodbc.connect(connstr)
110
+ # Access is file-based but a UNC path on an
111
+ # unreachable share can still block forever; cap
112
+ # the connect attempt at 30 s to match the other
113
+ # adapters.
114
+ self.conn = pyodbc.connect(connstr, timeout=30)
111
115
  except Exception:
112
116
  if _state.exec_log is not None:
113
117
  _state.exec_log.log_status_info(
execsql/db/base.py CHANGED
@@ -239,8 +239,14 @@ class Database(ABC):
239
239
  if self.conn:
240
240
  try:
241
241
  self.conn.rollback()
242
- except Exception:
243
- pass # Best-effort; connection may already be closed.
242
+ except Exception as e:
243
+ # Best-effort; connection may already be closed. Still
244
+ # log so a cascading rollback failure isn't invisible
245
+ # in a CI / cron log.
246
+ if _state.exec_log is not None:
247
+ _state.exec_log.log_status_info(
248
+ f"Rollback failed on {self.__class__.__name__}: {e!r}",
249
+ )
244
250
 
245
251
  def needs_explicit_commit_after_ddl(self) -> bool:
246
252
  """Return True if this adapter's driver does NOT auto-commit DDL.
execsql/db/dsn.py CHANGED
@@ -90,7 +90,9 @@ class DsnDatabase(Database):
90
90
  parts.append(f"PWD={_odbc_quote(self.password)}")
91
91
  connstr = ";".join(parts) + ";"
92
92
  kwargs = {"autocommit": autocommit} if autocommit else {}
93
- self.conn = pyodbc.connect(connstr, **kwargs)
93
+ # 30 s connect timeout matches the Postgres adapter default
94
+ # so a wedged DSN peer cannot hang a script indefinitely.
95
+ self.conn = pyodbc.connect(connstr, timeout=30, **kwargs)
94
96
 
95
97
  def _try_connect():
96
98
  try:
execsql/db/factory.py CHANGED
@@ -63,7 +63,7 @@ def db_Postgres(
63
63
  new_db: bool = False,
64
64
  password: str | None = None,
65
65
  ) -> PostgresDatabase:
66
- """Open a new PostgreSQL connection via psycopg2."""
66
+ """Open a new PostgreSQL connection via psycopg (psycopg3)."""
67
67
  return PostgresDatabase(server_name, database_name, user, pw_needed, port, new_db=new_db, password=password)
68
68
 
69
69
 
execsql/db/firebird.py CHANGED
@@ -18,7 +18,7 @@ __all__ = ["FirebirdDatabase"]
18
18
 
19
19
 
20
20
  class FirebirdDatabase(Database):
21
- """Firebird adapter using the firebird-driver (fdb) package."""
21
+ """Firebird adapter using the firebird-driver package."""
22
22
 
23
23
  def __init__(
24
24
  self,
@@ -31,10 +31,11 @@ class FirebirdDatabase(Database):
31
31
  password: str | None = None,
32
32
  ) -> None:
33
33
  try:
34
- import fdb as firebird_lib # noqa: F401
34
+ from firebird import driver as firebird_lib # noqa: F401
35
35
  except Exception:
36
36
  fatal_error(
37
- "The fdb module is required to connect to Firebird. See https://pypi.python.org/pypi/fdb/",
37
+ "The firebird-driver module is required to connect to Firebird. "
38
+ "See https://pypi.org/project/firebird-driver/",
38
39
  )
39
40
  from execsql.types import dbt_firebird
40
41
 
@@ -67,7 +68,10 @@ class FirebirdDatabase(Database):
67
68
 
68
69
  def open_db(self) -> None:
69
70
  """Open a connection to the Firebird database."""
70
- import fdb as firebird_lib
71
+ from firebird import driver as firebird_lib
72
+
73
+ # 30 s connect timeout matches the Postgres adapter default.
74
+ connect_timeout = 30
71
75
 
72
76
  def db_conn():
73
77
  if self.user and self.password:
@@ -78,6 +82,7 @@ class FirebirdDatabase(Database):
78
82
  user=self.user,
79
83
  password=self.password,
80
84
  charset=self.encoding,
85
+ timeout=connect_timeout,
81
86
  )
82
87
  else:
83
88
  return firebird_lib.connect(
@@ -85,6 +90,7 @@ class FirebirdDatabase(Database):
85
90
  database=self.db_name,
86
91
  port=self.port,
87
92
  charset=self.encoding,
93
+ timeout=connect_timeout,
88
94
  )
89
95
 
90
96
  if self.conn is None:
execsql/db/mysql.py CHANGED
@@ -152,6 +152,10 @@ class MySQLDatabase(Database):
152
152
  """Open a connection to the MySQL or MariaDB server."""
153
153
  import pymysql as mysql_lib
154
154
 
155
+ # 30 s default matches the Postgres adapter so a wedged peer
156
+ # can't hang a script indefinitely.
157
+ connect_timeout = 30
158
+
155
159
  def db_conn():
156
160
  if self.user and self.password:
157
161
  return mysql_lib.connect(
@@ -162,6 +166,7 @@ class MySQLDatabase(Database):
162
166
  password=self.password,
163
167
  charset=self.encoding,
164
168
  local_infile=True,
169
+ connect_timeout=connect_timeout,
165
170
  )
166
171
  else:
167
172
  return mysql_lib.connect(
@@ -170,6 +175,7 @@ class MySQLDatabase(Database):
170
175
  port=self.port,
171
176
  charset=self.encoding,
172
177
  local_infile=True,
178
+ connect_timeout=connect_timeout,
173
179
  )
174
180
 
175
181
  if self.conn is None:
execsql/db/postgres.py CHANGED
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  """
4
4
  PostgreSQL database adapter for execsql.
5
5
 
6
- Implements :class:`PostgresDatabase`. Uses ``psycopg2`` for the
6
+ Implements :class:`PostgresDatabase`. Uses ``psycopg`` (psycopg3) for the
7
7
  connection, supports schema-qualified tables, server-side ``COPY`` for
8
8
  fast IMPORT, ``CREATE DATABASE`` when ``new_db=True``, ``ROLE_EXISTS``,
9
9
  and the ``PG_VACUUM`` metacommand (``vacuum()`` method). Corresponds to
@@ -26,7 +26,7 @@ DEFAULT_CONNECT_TIMEOUT = 30 # seconds
26
26
 
27
27
 
28
28
  class PostgresDatabase(Database):
29
- """PostgreSQL adapter using psycopg2, with schema support, server-side COPY, and keyring auth."""
29
+ """PostgreSQL adapter using psycopg (psycopg3), with schema support, server-side COPY, and keyring auth."""
30
30
 
31
31
  def __init__(
32
32
  self,
@@ -41,10 +41,11 @@ class PostgresDatabase(Database):
41
41
  connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,
42
42
  ) -> None:
43
43
  try:
44
- import psycopg2 # noqa: F401
44
+ import psycopg # noqa: F401
45
45
  except Exception:
46
46
  fatal_error(
47
- "The psycopg2 module is required to connect to PostgreSQL. See http://initd.org/psycopg/",
47
+ "The psycopg module (psycopg3) is required to connect to PostgreSQL. "
48
+ "See https://www.psycopg.org/psycopg3/",
48
49
  )
49
50
  from execsql.types import dbt_postgres
50
51
 
@@ -73,23 +74,23 @@ class PostgresDatabase(Database):
73
74
 
74
75
  def open_db(self) -> None:
75
76
  """Open a connection to the PostgreSQL database."""
76
- import psycopg2
77
+ import psycopg
77
78
 
78
79
  def db_conn(db: PostgresDatabase, db_name: str):
79
80
  try:
80
81
  if db.user and db.password:
81
- return psycopg2.connect(
82
+ return psycopg.connect(
82
83
  host=str(db.server_name),
83
- database=str(db_name),
84
+ dbname=str(db_name),
84
85
  port=db.port,
85
86
  user=db.user,
86
87
  password=db.password,
87
88
  connect_timeout=db.connect_timeout,
88
89
  )
89
90
  else:
90
- return psycopg2.connect(
91
+ return psycopg.connect(
91
92
  host=str(db.server_name),
92
- database=db_name,
93
+ dbname=db_name,
93
94
  port=db.port,
94
95
  connect_timeout=db.connect_timeout,
95
96
  )
@@ -148,7 +149,7 @@ class PostgresDatabase(Database):
148
149
  msg = f"Failed to open PostgreSQL database {self.db_name} on {self.server_name}"
149
150
  raise ErrInfo(type="exception", exception_msg=exception_desc(), other_msg=msg) from e
150
151
  # (Re)set the encoding to match the database.
151
- self.encoding = self.conn.encoding
152
+ self.encoding = self.conn.info.encoding
152
153
 
153
154
  def exec_cmd(self, querycommand: str) -> None:
154
155
  """Execute a stored function by name."""
@@ -242,13 +243,13 @@ class PostgresDatabase(Database):
242
243
  but should not be exposed to untrusted input.
243
244
  """
244
245
  self.commit()
245
- self.conn.set_session(autocommit=True)
246
+ self.conn.autocommit = True
246
247
  curs = self.conn.cursor()
247
248
  try:
248
249
  curs.execute(f"VACUUM {argstring};")
249
250
  finally:
250
251
  curs.close()
251
- self.conn.set_session(autocommit=False)
252
+ self.conn.autocommit = False
252
253
 
253
254
  def import_tabular_file(
254
255
  self,
@@ -290,7 +291,7 @@ class PostgresDatabase(Database):
290
291
  import_cols = [self.type.quoted(col) for col in import_cols]
291
292
  csv_file_cols_q = [self.type.quoted(col) for col in csv_file_cols]
292
293
  input_col_list = ",".join(import_cols)
293
- # If encodings match, use copy_expert.
294
+ # If encodings match, use server-side COPY.
294
295
  # If encodings don't match, and the file encoding isn't recognized by CSV, read as CSV.
295
296
  enc_xlates = {
296
297
  "cp1252": "win1252",
@@ -319,7 +320,7 @@ class PostgresDatabase(Database):
319
320
  and not _state.conf.trim_strings
320
321
  and not _state.conf.replace_newlines
321
322
  ):
322
- # Use Postgres' COPY FROM method via psycopg2's copy_expert() method.
323
+ # Use Postgres' COPY FROM method via psycopg3's cursor.copy() context manager.
323
324
  rf = csv_file_obj.open("rt")
324
325
  if skipheader:
325
326
  next(rf)
@@ -346,7 +347,9 @@ class PostgresDatabase(Database):
346
347
  )
347
348
  with self._cursor() as curs:
348
349
  try:
349
- curs.copy_expert(copy_cmd, rf, _state.conf.import_buffer)
350
+ with curs.copy(copy_cmd) as copy:
351
+ while chunk := rf.read(_state.conf.import_buffer):
352
+ copy.write(chunk)
350
353
  except ErrInfo:
351
354
  raise
352
355
  except Exception as e:
@@ -461,12 +464,11 @@ class PostgresDatabase(Database):
461
464
  file_name: str,
462
465
  ) -> None:
463
466
  """Import an entire binary file into a single column of a table."""
464
- import psycopg2
465
-
466
467
  with open(file_name, "rb") as f:
467
468
  filedata = f.read()
468
469
  sq_name = self.schema_qualified_table_name(schema_name, table_name)
469
470
  quoted_col = self.quote_identifier(column_name)
470
471
  sql = f"insert into {sq_name} ({quoted_col}) values ({self.paramsubs(1)});"
471
472
  with self._cursor() as curs:
472
- curs.execute(sql, (psycopg2.Binary(filedata),))
473
+ # psycopg3 sends ``bytes`` to a ``bytea`` column directly; no Binary() wrapper.
474
+ curs.execute(sql, (filedata,))
execsql/db/sqlserver.py CHANGED
@@ -113,7 +113,10 @@ class SqlServerDatabase(Database):
113
113
  f"DATABASE={self.db_name};Trusted_Connection=yes"
114
114
  )
115
115
  try:
116
- self.conn = pyodbc.connect(connstr)
116
+ # 30 s connect timeout matches the Postgres adapter
117
+ # default; pyodbc treats `timeout` as the login-and-
118
+ # query timeout on the connection.
119
+ self.conn = pyodbc.connect(connstr, timeout=30)
117
120
  except Exception:
118
121
  if _state.exec_log is not None:
119
122
  _state.exec_log.log_status_info(
execsql/format.py CHANGED
@@ -45,6 +45,13 @@ METACOMMAND_RE = re.compile(r"^\s*--\s*!x!\s*(.*)", re.IGNORECASE)
45
45
 
46
46
  # Multi-word keywords — checked longest-first before single-word fallback.
47
47
  # Order matters: more-specific variants must precede their prefixes.
48
+ # Only entries that appear at the *start* of a `-- !x!` payload belong
49
+ # here — `parse_keyword()` matches against the beginning of the payload,
50
+ # not embedded sub-clauses. `IN ZIPFILE` / `WITH TEMPLATE` are EXPORT
51
+ # sub-clauses and never appear at the start, so they don't go here.
52
+ # When adding a new dispatch keyword, mirror it here (or fix the missing
53
+ # entry via the `tests/test_format.py` drift check that pulls names from
54
+ # the dispatch table).
48
55
  MULTIWORD_KEYWORDS = [
49
56
  "METACOMMAND_ERROR_HALT",
50
57
  "ON ERROR_HALT",
@@ -77,18 +84,31 @@ MULTIWORD_KEYWORDS = [
77
84
  "SUB_INI",
78
85
  "PROMPT ENTRY_FORM",
79
86
  "PROMPT SELECT_SUB",
87
+ "PROMPT SELECT_ROWS",
80
88
  "PROMPT ENTER_SUB",
81
89
  "PROMPT DIRECTORY",
90
+ "PROMPT CREDENTIALS",
82
91
  "PROMPT CONNECT",
83
92
  "PROMPT COMPARE",
84
93
  "PROMPT MESSAGE",
85
94
  "PROMPT DISPLAY",
86
95
  "PROMPT ACTION",
96
+ "PROMPT OPENFILE",
97
+ "PROMPT SAVEFILE",
87
98
  "PROMPT PAUSE",
88
- "PROMPT FILE",
99
+ # PROMPT ASK COMPARE must precede PROMPT ASK so longest-match wins;
100
+ # parse_keyword iterates in list order, not by length.
101
+ "PROMPT ASK COMPARE",
89
102
  "PROMPT ASK",
90
- "WITH TEMPLATE",
91
- "IN ZIPFILE",
103
+ "PROMPT MAP",
104
+ "APPEND SCRIPT",
105
+ "PG_UPSERT CHECK",
106
+ "PG_UPSERT QA",
107
+ "RESET COUNTER",
108
+ "RESET DIALOG_CANCELED",
109
+ "SET COUNTER",
110
+ "WRITE CREATE_TABLE",
111
+ "WRITE SCRIPT",
92
112
  "SHOW SCRIPTS",
93
113
  ]
94
114
 
@@ -98,9 +118,18 @@ BLOCK_CLOSE = frozenset({"ENDIF", "END LOOP", "ENDLOOP", "END SCRIPT", "END BATC
98
118
  PIVOT = frozenset({"ELSE", "ELSEIF"}) # decrease depth before emit, increase after
99
119
  CONTINUATION = frozenset({"ANDIF", "ORIF"}) # emit at depth-1, no depth change
100
120
 
101
- # Inline IF: "IF (cond) { command }" — self-contained, no ENDIF, no depth change.
102
- # Mirrors src/execsql/cli/lint.py:_RX_IF_INLINE so formatter and linter agree.
121
+ # Inline IF: "IF (cond) { command }" — self-contained, no ENDIF, no depth
122
+ # change. Pattern must accept the same payloads as
123
+ # src/execsql/script/parser.py:_IF_INLINE_RX. Kept as a separate compiled
124
+ # pattern (not an import) so execsql-format doesn't pull in the AST parser
125
+ # module graph at startup; tests/test_format.py has a drift check that
126
+ # asserts both regexes recognise the same inputs.
103
127
  _IF_INLINE_RE = re.compile(r"^\s*IF\s*\(\s*.+\s*\)\s*\{.+\}\s*$", re.I)
128
+
129
+ # Matches both untagged `$$` and tagged `$tag$` dollar-quote markers
130
+ # (PostgreSQL PL/pgSQL / DO-block syntax). Tags are letter-or-underscore
131
+ # followed by word characters; the empty tag (just `$$`) is also valid.
132
+ _DOLLAR_QUOTE_RE = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)?\$")
104
133
  # BLOCK_OPEN keywords whose bodies are guaranteed-SQL (not metacommand-driven).
105
134
  # Blank lines inside these belong to the SQL accumulator, not the output stream.
106
135
  _SQL_BODY_BLOCKS = frozenset({"BEGIN SQL", "BEGIN BATCH"})
@@ -180,9 +209,16 @@ def _is_comment_line(line: str, in_block: bool) -> tuple[bool, bool]:
180
209
  def _sqlglot_format(
181
210
  sql_lines: list[str],
182
211
  sql_indent: int = 4,
183
- leading_comma: bool = False,
212
+ leading_comma: bool = False, # noqa: ARG001 — leading-comma layout is applied as a textual post-pass on the assembled output; sqlglot's own `leading_comma=True` is non-idempotent under inline comments.
184
213
  ) -> list[str]:
185
- """Format a list of SQL-only lines (no comment-only lines) via sqlglot."""
214
+ """Format a list of SQL-only lines (no comment-only lines) via sqlglot.
215
+
216
+ Always emits trailing-comma style; if the caller wants leading commas
217
+ they are produced by ``_apply_leading_comma`` at the end of
218
+ ``format_file``. sqlglot's own ``leading_comma=True`` reshuffles inline
219
+ comments and is therefore non-idempotent on SQL with mid-statement
220
+ comments, which is the dominant real-world case.
221
+ """
186
222
  sqlglot = _require_sqlglot()
187
223
  import sqlglot.errors as sqlglot_errors
188
224
 
@@ -211,7 +247,6 @@ def _sqlglot_format(
211
247
  pad=sql_indent,
212
248
  indent=sql_indent,
213
249
  max_text_width=120,
214
- leading_comma=leading_comma,
215
250
  ),
216
251
  )
217
252
  stmts = [s for s in statements if s]
@@ -508,13 +543,105 @@ def format_metacommand(payload: str, depth: int, indent: int) -> str:
508
543
  return f"{prefix}-- !x! {keyword}"
509
544
 
510
545
 
546
+ def _is_comment_only(s: str) -> bool:
547
+ """Strict comment classifier for the leading-comma post/pre passes."""
548
+ st = s.strip()
549
+ return st.startswith("--") or st.startswith("/*") or st.startswith("*/")
550
+
551
+
552
+ def _normalize_to_trailing_comma(text: str) -> str:
553
+ """Rewrite leading-comma SQL (`, foo`) back to trailing-comma style.
554
+
555
+ Symmetric inverse of ``_apply_leading_comma``. Used as a pre-pass so
556
+ that sqlglot — which migrates inline ``/* marker */`` comments under
557
+ leading-comma input — sees a consistent trailing-comma shape on
558
+ every invocation. Comments between the two SQL lines stay in place.
559
+ """
560
+ lines = text.split("\n")
561
+
562
+ def find_prev_sql_line(idx: int) -> int:
563
+ k = idx - 1
564
+ while k >= 0 and (not lines[k].strip() or _is_comment_only(lines[k])):
565
+ k -= 1
566
+ return k
567
+
568
+ for i, line in enumerate(lines):
569
+ stripped = line.lstrip()
570
+ if not stripped.startswith(",") or _is_comment_only(line):
571
+ continue
572
+ # Don't try to rewrite leading-comma inside a comment-only line.
573
+ # Move the comma onto the previous SQL line as a trailing `,`.
574
+ prev = find_prev_sql_line(i)
575
+ if prev < 0:
576
+ continue
577
+ # Drop the `, ` (or `,`) at the start of this line.
578
+ indent_len = len(line) - len(stripped)
579
+ rest = stripped[1:].lstrip()
580
+ lines[i] = line[:indent_len] + rest
581
+ # Append `,` to the prev SQL line (preserving any existing right-side
582
+ # trailing whitespace — there shouldn't be any after format_file).
583
+ prev_rstripped = lines[prev].rstrip()
584
+ if not prev_rstripped.endswith(","):
585
+ lines[prev] = prev_rstripped + ","
586
+ return "\n".join(lines)
587
+
588
+
589
+ def _apply_leading_comma(text: str) -> str:
590
+ """Rewrite trailing-comma SQL to leading-comma style as a textual pass.
591
+
592
+ Walks the assembled output line-by-line. For every line that ends with
593
+ ``,`` (and is not a comment), strip the comma and prepend ``, `` to the
594
+ next non-blank, non-comment line — preserving that target line's
595
+ indent. Comments between the two SQL lines stay in place. The
596
+ transformation is idempotent: rerunning it on its own output is a
597
+ no-op (the source line no longer ends with ``,``).
598
+
599
+ This decouples our user-facing ``--leading-comma`` flag from
600
+ sqlglot's own ``leading_comma=True`` mode, which is non-idempotent
601
+ when inline ``/* marker */`` comments are present — sqlglot moves
602
+ the markers around between passes (verified in tests/test_format.py
603
+ TestIdempotency).
604
+ """
605
+ lines = text.split("\n")
606
+ i = 0
607
+ n = len(lines)
608
+ while i < n:
609
+ rstripped = lines[i].rstrip()
610
+ if rstripped.endswith(",") and not _is_comment_only(lines[i]):
611
+ j = i + 1
612
+ while j < n and (not lines[j].strip() or _is_comment_only(lines[j])):
613
+ j += 1
614
+ if j < n:
615
+ stripped = lines[i].rstrip()
616
+ comma_idx = stripped.rfind(",")
617
+ lines[i] = stripped[:comma_idx] + stripped[comma_idx + 1 :]
618
+ target = lines[j]
619
+ indent_len = len(target) - len(target.lstrip())
620
+ lines[j] = target[:indent_len] + ", " + target[indent_len:]
621
+ i += 1
622
+ return "\n".join(lines)
623
+
624
+
511
625
  def format_file(source: str, indent: int = 4, use_sql: bool = True, leading_comma: bool = False) -> str:
512
626
  """Format the source text of an execsql script and return the result."""
627
+ # Normalize any leading-comma SQL in the source to trailing commas so
628
+ # that sqlglot always sees the same comma shape regardless of how
629
+ # the user saved the file. The post-pass at the bottom of this
630
+ # function re-applies leading commas when the caller asked for them.
631
+ # This is what makes leading_comma=True idempotent under inline
632
+ # comments — sqlglot itself migrates `/* marker */` comments when
633
+ # parsing leading-comma input.
634
+ source = _normalize_to_trailing_comma(source)
635
+
513
636
  depth = 0
514
637
  sql_acc: list[str] = []
515
638
  output: list[str] = []
516
639
 
517
640
  in_dollar_quote = False
641
+ # When in_dollar_quote, the tag string we are inside ("" for `$$`,
642
+ # "body" for `$body$`, etc.). Nested markers with a different tag
643
+ # are ignored — only a matching close marker re-opens us.
644
+ current_dq_tag: str | None = None
518
645
  in_block_comment = False
519
646
  # Track whether we are inside an open SQL statement (last SQL line
520
647
  # did not end with ';'). Blank lines mid-statement should NOT flush
@@ -527,7 +654,7 @@ def format_file(source: str, indent: int = 4, use_sql: bool = True, leading_comm
527
654
  in_explicit_sql_block = False
528
655
 
529
656
  def flush_sql() -> None:
530
- nonlocal in_dollar_quote, in_sql_statement
657
+ nonlocal in_dollar_quote, current_dq_tag, in_sql_statement
531
658
  if sql_acc:
532
659
  # If any line in the accumulated block is inside a $$-delimited
533
660
  # region, skip sqlglot formatting entirely. PL/pgSQL function
@@ -596,9 +723,19 @@ def format_file(source: str, indent: int = 4, use_sql: bool = True, leading_comm
596
723
  output.append(format_metacommand(payload, depth, indent))
597
724
 
598
725
  else:
599
- # Track $$ boundaries to prevent sqlglot from mangling PL/pgSQL
600
- if "$$" in raw_line and raw_line.count("$$") % 2 == 1:
601
- in_dollar_quote = not in_dollar_quote
726
+ # Track $$ and $tag$ boundaries to prevent sqlglot from mangling
727
+ # PL/pgSQL. Walk every dollar-quote marker on the line; toggle
728
+ # state only when we hit the matching open or close.
729
+ for m in _DOLLAR_QUOTE_RE.finditer(raw_line):
730
+ tag = m.group(1) or ""
731
+ if not in_dollar_quote:
732
+ in_dollar_quote = True
733
+ current_dq_tag = tag
734
+ elif tag == current_dq_tag:
735
+ in_dollar_quote = False
736
+ current_dq_tag = None
737
+ # else: tag mismatch — a foreign-tagged marker inside our
738
+ # quoted region; ignore (PG would treat it as literal text).
602
739
  sql_acc.append(raw_line)
603
740
  # Update statement tracking: if this SQL line ends with ';'
604
741
  # (and isn't a comment), the statement is complete.
@@ -610,6 +747,8 @@ def format_file(source: str, indent: int = 4, use_sql: bool = True, leading_comm
610
747
  flush_sql()
611
748
 
612
749
  result = "\n".join(output)
750
+ if leading_comma:
751
+ result = _apply_leading_comma(result)
613
752
  if not result.endswith("\n"):
614
753
  result += "\n"
615
754
  return result
@@ -665,6 +804,12 @@ def main() -> None:
665
804
  "--leading-comma",
666
805
  help="Place commas at the start of lines instead of the end.",
667
806
  ),
807
+ encoding: str = typer.Option(
808
+ "utf-8",
809
+ "--encoding",
810
+ metavar="NAME",
811
+ help="Text encoding used to read and write SQL files (default utf-8).",
812
+ ),
668
813
  ) -> None:
669
814
  use_sql = not no_sql
670
815
  paths = collect_paths(targets)
@@ -673,12 +818,23 @@ def main() -> None:
673
818
  raise typer.Exit(code=1)
674
819
 
675
820
  any_changed = False
821
+ any_errors = False
676
822
  for path in paths:
677
823
  try:
678
- source = path.read_text(encoding="utf-8")
824
+ source = path.read_text(encoding=encoding)
679
825
  except OSError as exc:
680
826
  _err_console.print(f"[bold red]Error:[/bold red] reading {path}: {exc}")
681
- raise typer.Exit(code=1) from None
827
+ any_errors = True
828
+ # Collect read errors instead of short-circuiting so a single
829
+ # unreadable file doesn't hide the rest of the report.
830
+ continue
831
+ except UnicodeDecodeError as exc:
832
+ _err_console.print(
833
+ f"[bold red]Error:[/bold red] decoding {path} as {encoding}: {exc}. "
834
+ f"Try [bold]--encoding cp1252[/bold] or another text encoding.",
835
+ )
836
+ any_errors = True
837
+ continue
682
838
 
683
839
  formatted = format_file(source, indent=indent, use_sql=use_sql, leading_comma=leading_comma)
684
840
 
@@ -688,12 +844,12 @@ def main() -> None:
688
844
  any_changed = True
689
845
  elif in_place:
690
846
  if formatted != source:
691
- path.write_text(formatted, encoding="utf-8")
847
+ path.write_text(formatted, encoding=encoding)
692
848
  _console.print(f"reformatted {path}")
693
849
  else:
694
850
  sys.stdout.write(formatted)
695
851
 
696
- if check and any_changed:
852
+ if any_errors or (check and any_changed):
697
853
  raise typer.Exit(code=1)
698
854
 
699
855
  app()
execsql/utils/mail.py CHANGED
@@ -51,16 +51,19 @@ class Mailer:
51
51
  conf = _state.conf
52
52
  if conf.smtp_host is None:
53
53
  raise ErrInfo(type="error", other_msg="Can't send email; the email host is not configured.")
54
+ # 30 s connect/read timeout matches the DB-adapter default so a
55
+ # silently-dropped SMTP peer can't hang a script (or a CI run).
56
+ smtp_timeout = 30
54
57
  if conf.smtp_port is None:
55
58
  if conf.smtp_ssl:
56
- self.smtpconn = smtplib.SMTP_SSL(conf.smtp_host)
59
+ self.smtpconn = smtplib.SMTP_SSL(conf.smtp_host, timeout=smtp_timeout)
57
60
  else:
58
- self.smtpconn = smtplib.SMTP(conf.smtp_host)
61
+ self.smtpconn = smtplib.SMTP(conf.smtp_host, timeout=smtp_timeout)
59
62
  else:
60
63
  if conf.smtp_ssl:
61
- self.smtpconn = smtplib.SMTP_SSL(conf.smtp_host, conf.smtp_port)
64
+ self.smtpconn = smtplib.SMTP_SSL(conf.smtp_host, conf.smtp_port, timeout=smtp_timeout)
62
65
  else:
63
- self.smtpconn = smtplib.SMTP(conf.smtp_host, conf.smtp_port)
66
+ self.smtpconn = smtplib.SMTP(conf.smtp_host, conf.smtp_port, timeout=smtp_timeout)
64
67
  self.smtpconn.ehlo_or_hello_if_needed()
65
68
  if conf.smtp_tls:
66
69
  self.smtpconn.starttls()
@@ -2,7 +2,7 @@
2
2
 
3
3
  Several types of templates are provided that may be useful in conjunction with execsql. These are:
4
4
 
5
- - **execsql.conf** — An annotated version of the configuration file that includes all configuration settings and notes on their usage.
5
+ - **execsql.conf** — An annotated reference of every configuration setting with notes on its usage. Generate a fresh copy in any directory with `execsql --init-config > execsql.conf`; the canonical content ships inside the installed package and is loaded via `importlib.resources` (no need to find or copy a source file).
6
6
 
7
7
  - **script_template.sql** — A framework for SQL scripts that make use of several execsql features. It includes sections for custom configuration settings, custom logfile creation, and reporting of unexpected script exits (through user cancellation or errors).
8
8