execsql2 2.5.0__py3-none-any.whl → 2.7.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 (32) hide show
  1. execsql/exporters/__init__.py +3 -3
  2. execsql/exporters/delimited.py +2 -2
  3. execsql/exporters/markdown.py +126 -0
  4. execsql/exporters/xlsx.py +317 -0
  5. execsql/exporters/yaml.py +87 -0
  6. execsql/gui/tui.py +132 -0
  7. execsql/metacommands/__init__.py +203 -182
  8. execsql/metacommands/dispatch.py +11 -0
  9. execsql/metacommands/io.py +2 -0
  10. execsql/metacommands/io_export.py +75 -0
  11. execsql/state.py +261 -200
  12. {execsql2-2.5.0.dist-info → execsql2-2.7.1.dist-info}/METADATA +5 -2
  13. {execsql2-2.5.0.dist-info → execsql2-2.7.1.dist-info}/RECORD +32 -29
  14. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/README.md +0 -0
  15. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/config_settings.sqlite +0 -0
  16. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/example_config_prompt.sql +0 -0
  17. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/execsql.conf +0 -0
  18. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/make_config_db.sql +0 -0
  19. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/md_compare.sql +0 -0
  20. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/md_glossary.sql +0 -0
  21. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/md_upsert.sql +0 -0
  22. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/pg_compare.sql +0 -0
  23. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/pg_glossary.sql +0 -0
  24. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/pg_upsert.sql +0 -0
  25. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/script_template.sql +0 -0
  26. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/ss_compare.sql +0 -0
  27. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/ss_glossary.sql +0 -0
  28. {execsql2-2.5.0.data → execsql2-2.7.1.data}/data/execsql2_extras/ss_upsert.sql +0 -0
  29. {execsql2-2.5.0.dist-info → execsql2-2.7.1.dist-info}/WHEEL +0 -0
  30. {execsql2-2.5.0.dist-info → execsql2-2.7.1.dist-info}/entry_points.txt +0 -0
  31. {execsql2-2.5.0.dist-info → execsql2-2.7.1.dist-info}/licenses/LICENSE.txt +0 -0
  32. {execsql2-2.5.0.dist-info → execsql2-2.7.1.dist-info}/licenses/NOTICE +0 -0
@@ -9,9 +9,9 @@ handlers can access them via ``_state.write_query_to_csv`` etc. without
9
9
  importing directly from here.
10
10
 
11
11
  Sub-modules: ``base``, ``delimited``, ``json``, ``xml``, ``html``,
12
- ``latex``, ``ods``, ``xls``, ``zip``, ``raw``, ``pretty``, ``values``,
13
- ``templates``, ``feather``, ``parquet``, ``duckdb``, ``sqlite``,
14
- ``protocol``.
12
+ ``latex``, ``markdown``, ``ods``, ``xls``, ``zip``, ``raw``, ``pretty``,
13
+ ``values``, ``templates``, ``feather``, ``parquet``, ``duckdb``,
14
+ ``sqlite``, ``protocol``.
15
15
  """
16
16
 
17
17
  from execsql.exporters.protocol import QueryExporter, RowsetExporter
@@ -27,7 +27,7 @@ from execsql.exceptions import ErrInfo
27
27
  from execsql.models import DataTable
28
28
  from execsql.utils.errors import exception_desc
29
29
  from execsql.utils.fileio import filewriter_close
30
- from execsql.utils.strings import clean_words, fold_words
30
+ from execsql.utils.strings import clean_words, dedup_words, fold_words
31
31
 
32
32
  __all__ = ["LineDelimiter", "CsvFile", "CsvWriter", "DelimitedWriter", "write_delimited_file"]
33
33
 
@@ -677,7 +677,7 @@ class CsvFile(EncodedFile):
677
677
  if conf.fold_col_hdrs != "no":
678
678
  colnames = fold_words(colnames, conf.fold_col_hdrs)
679
679
  if conf.dedup_col_hdrs:
680
- colnames = _state.dedup_words(colnames)
680
+ colnames = dedup_words(colnames)
681
681
  return colnames
682
682
 
683
683
  def column_headers(self) -> list[str]:
@@ -0,0 +1,126 @@
1
+ from __future__ import annotations
2
+
3
+ """
4
+ GitHub-Flavored Markdown (GFM) pipe table export for execsql.
5
+
6
+ Provides :func:`write_query_to_markdown`, which serializes a query result
7
+ set as a GFM pipe table suitable for inclusion in GitHub README files,
8
+ wikis, and any Markdown renderer that supports the pipe-table extension.
9
+
10
+ Example output::
11
+
12
+ | id | name | score |
13
+ |----|--------|-------|
14
+ | 1 | Alice | 95.2 |
15
+ | 2 | Bob | 87.0 |
16
+
17
+ No optional dependencies — pure Python.
18
+ """
19
+
20
+ from typing import Any
21
+
22
+ import execsql.state as _state
23
+ from execsql.exceptions import ErrInfo
24
+ from execsql.exporters.zip import ZipWriter
25
+ from execsql.utils.errors import exception_desc
26
+ from execsql.utils.fileio import filewriter_close
27
+
28
+ __all__ = ["write_query_to_markdown"]
29
+
30
+ _PIPE_ESCAPE = str.maketrans({"|": r"\|", "\\": "\\\\"})
31
+
32
+
33
+ def _cell(value: Any) -> str:
34
+ """Render a single cell value as a Markdown-safe string.
35
+
36
+ Args:
37
+ value: The cell value from the result set. ``None`` is rendered as
38
+ an empty string. Pipe characters are escaped so they do not
39
+ break the table structure.
40
+
41
+ Returns:
42
+ A string safe to embed between pipe characters in a GFM table row.
43
+ """
44
+ if value is None:
45
+ return ""
46
+ return str(value).translate(_PIPE_ESCAPE)
47
+
48
+
49
+ def write_query_to_markdown(
50
+ select_stmt: str,
51
+ db: Any,
52
+ outfile: str,
53
+ append: bool = False,
54
+ desc: str | None = None,
55
+ zipfile: str | None = None,
56
+ ) -> None:
57
+ """Execute *select_stmt* and write the result set as a GFM pipe table.
58
+
59
+ Writes a GitHub-Flavored Markdown pipe table to *outfile* (or into
60
+ *zipfile* when provided). Column widths are derived from the widest
61
+ value in each column (including the header), so the table renders
62
+ legibly in plain-text editors as well as in Markdown renderers.
63
+
64
+ Args:
65
+ select_stmt: SQL SELECT statement to execute.
66
+ db: Database connection object exposing ``select_rowsource()``.
67
+ outfile: Destination file path, or ``"stdout"`` for console output.
68
+ append: When ``True`` open the file in append mode. A blank line
69
+ is written before the table so consecutive appended tables are
70
+ visually separated.
71
+ desc: Optional human-readable description. When provided it is
72
+ written as an HTML comment (``<!-- desc -->``), which is valid
73
+ Markdown and invisible in rendered output.
74
+ zipfile: When set, write into this ZIP archive instead of a plain
75
+ file. *outfile* becomes the entry name inside the archive.
76
+ """
77
+ conf = _state.conf
78
+ try:
79
+ hdrs, rows = db.select_rowsource(select_stmt)
80
+ except ErrInfo:
81
+ raise
82
+ except Exception as e:
83
+ raise ErrInfo("db", select_stmt, exception_msg=exception_desc()) from e
84
+
85
+ # Materialise the full result set so we can compute column widths in one
86
+ # pass before writing. GFM tables require consistent column widths for
87
+ # readability; width computation requires seeing all rows first.
88
+ str_hdrs: list[str] = [_cell(h) for h in hdrs]
89
+ str_rows: list[list[str]] = [[_cell(v) for v in row] for row in rows]
90
+
91
+ # Minimum separator width is 3 dashes (GFM spec minimum for alignment row).
92
+ col_widths: list[int] = [max(3, len(h)) for h in str_hdrs]
93
+ for row in str_rows:
94
+ for i, cell in enumerate(row):
95
+ if len(cell) > col_widths[i]:
96
+ col_widths[i] = len(cell)
97
+
98
+ def _format_row(cells: list[str]) -> str:
99
+ padded = (f" {c:<{col_widths[i]}} " for i, c in enumerate(cells))
100
+ return "|" + "|".join(padded) + "|\n"
101
+
102
+ def _format_separator() -> str:
103
+ dashes = (f" {'-' * col_widths[i]} " for i in range(len(str_hdrs)))
104
+ return "|" + "|".join(dashes) + "|\n"
105
+
106
+ if zipfile is None:
107
+ filewriter_close(outfile)
108
+ from execsql.utils.fileio import EncodedFile
109
+
110
+ ef = EncodedFile(outfile, conf.output_encoding)
111
+ f = ef.open("at" if append else "wt")
112
+ else:
113
+ f = ZipWriter(zipfile, outfile, append)
114
+
115
+ try:
116
+ if append:
117
+ # Blank line separates consecutive tables when appending.
118
+ f.write("\n")
119
+ if desc is not None:
120
+ f.write(f"<!-- {desc} -->\n\n")
121
+ f.write(_format_row(str_hdrs))
122
+ f.write(_format_separator())
123
+ for row in str_rows:
124
+ f.write(_format_row(row))
125
+ finally:
126
+ f.close()
@@ -0,0 +1,317 @@
1
+ from __future__ import annotations
2
+
3
+ """
4
+ XLSX (Excel Open XML) export for execsql.
5
+
6
+ Provides :func:`write_query_to_xlsx` (single-sheet export) and
7
+ :func:`write_queries_to_xlsx` (multi-sheet export). Requires the
8
+ ``openpyxl`` package (``execsql2[excel]``).
9
+ """
10
+
11
+ import datetime
12
+ import getpass
13
+ import os
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import execsql.state as _state
18
+ from execsql.exceptions import ErrInfo
19
+ from execsql.exporters.base import ExportRecord
20
+ from execsql.exporters.pretty import prettyprint_query
21
+ from execsql.script import current_script_line
22
+ from execsql.utils.errors import exception_desc, fatal_error
23
+ from execsql.utils.fileio import filewriter_close
24
+ from execsql.utils.strings import unquoted
25
+
26
+ __all__ = ["write_query_to_xlsx", "write_queries_to_xlsx"]
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Internal helpers
30
+ # ---------------------------------------------------------------------------
31
+
32
+
33
+ def _require_openpyxl() -> Any:
34
+ """Import and return the openpyxl module, raising a fatal error if absent."""
35
+ try:
36
+ import openpyxl
37
+
38
+ return openpyxl
39
+ except ImportError:
40
+ fatal_error("The openpyxl library is needed to write Excel (.xlsx) spreadsheets (install execsql2[excel]).")
41
+
42
+
43
+ def _cell_value(item: Any) -> Any:
44
+ """Return a value suitable for writing directly to an openpyxl cell.
45
+
46
+ openpyxl natively handles int, float, bool, str, datetime.datetime,
47
+ datetime.date, and None. datetime.time is converted to a string because
48
+ openpyxl does not have a native time-only cell type.
49
+ """
50
+ if item is None:
51
+ return None
52
+ if isinstance(item, bool):
53
+ # bool must be checked before int — bool is a subclass of int.
54
+ return item
55
+ if isinstance(item, int | float):
56
+ return item
57
+ if isinstance(item, datetime.datetime):
58
+ return item
59
+ if isinstance(item, datetime.date):
60
+ return item
61
+ if isinstance(item, datetime.time):
62
+ # openpyxl has no native time-only type; store as HH:MM:SS string.
63
+ return item.strftime("%H:%M:%S")
64
+ return str(item)
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Public API
69
+ # ---------------------------------------------------------------------------
70
+
71
+
72
+ def write_query_to_xlsx(
73
+ select_stmt: str,
74
+ db: Any,
75
+ outfile: str,
76
+ append: bool = False,
77
+ desc: str | None = None,
78
+ sheetname: str | None = None,
79
+ ) -> None:
80
+ """Execute *select_stmt* and write the result to a single worksheet in an XLSX file.
81
+
82
+ Args:
83
+ select_stmt: SQL SELECT statement to execute.
84
+ db: An execsql database adapter with a ``select_rowsource()`` method.
85
+ outfile: Destination ``.xlsx`` file path.
86
+ append: If ``True`` and *outfile* exists, add a new sheet to the
87
+ existing workbook. If ``False``, overwrite any existing file.
88
+ desc: Optional human-readable description stored in the inventory sheet.
89
+ sheetname: Name for the new worksheet. Defaults to ``"Sheet1"``
90
+ (or ``"Sheet2"``, ``"Sheet3"``, etc. when appending to avoid
91
+ name collisions).
92
+ """
93
+ openpyxl = _require_openpyxl()
94
+
95
+ try:
96
+ hdrs, rows = db.select_rowsource(select_stmt)
97
+ except ErrInfo:
98
+ raise
99
+ except Exception as e:
100
+ raise ErrInfo("db", select_stmt, exception_msg=exception_desc()) from e
101
+
102
+ # ------------------------------------------------------------------
103
+ # Determine sheet name and open/create workbook
104
+ # ------------------------------------------------------------------
105
+ if append and Path(outfile).is_file():
106
+ wb = openpyxl.load_workbook(outfile)
107
+ existing_names = wb.sheetnames
108
+ base = sheetname or "Sheet"
109
+ sheet_name = base
110
+ sheet_no = 1
111
+ while sheet_name in existing_names:
112
+ sheet_no += 1
113
+ sheet_name = f"{base}{sheet_no}"
114
+ else:
115
+ sheet_name = sheetname or "Sheet1"
116
+ if Path(outfile).is_file():
117
+ filewriter_close(outfile)
118
+ os.unlink(outfile)
119
+ wb = openpyxl.Workbook()
120
+ # openpyxl creates a default sheet named "Sheet"; remove it so we
121
+ # start with a clean workbook.
122
+ if wb.sheetnames:
123
+ del wb[wb.sheetnames[0]]
124
+
125
+ # ------------------------------------------------------------------
126
+ # Ensure the inventory sheet exists
127
+ # ------------------------------------------------------------------
128
+ inventory_name = "Datasheets"
129
+ if inventory_name not in wb.sheetnames:
130
+ inv_ws = wb.create_sheet(inventory_name)
131
+ bold_font = openpyxl.styles.Font(bold=True)
132
+ for col_idx, hdr in enumerate(
133
+ ("datasheet_name", "created_on", "created_by", "description", "source"),
134
+ start=1,
135
+ ):
136
+ cell = inv_ws.cell(row=1, column=col_idx, value=hdr)
137
+ cell.font = bold_font
138
+ else:
139
+ inv_ws = wb[inventory_name]
140
+
141
+ # ------------------------------------------------------------------
142
+ # Write data to a new sheet
143
+ # ------------------------------------------------------------------
144
+ ws = wb.create_sheet(sheet_name)
145
+ bold_font = openpyxl.styles.Font(bold=True)
146
+
147
+ # Header row
148
+ for col_idx, hdr in enumerate(hdrs, start=1):
149
+ cell = ws.cell(row=1, column=col_idx, value=str(hdr))
150
+ cell.font = bold_font
151
+
152
+ # Data rows
153
+ for row_idx, row in enumerate(rows, start=2):
154
+ for col_idx, item in enumerate(row, start=1):
155
+ ws.cell(row=row_idx, column=col_idx, value=_cell_value(item))
156
+
157
+ # ------------------------------------------------------------------
158
+ # Update inventory sheet
159
+ # ------------------------------------------------------------------
160
+ script, lno = current_script_line()
161
+ src = (
162
+ f"{select_stmt} with database {_state.dbs.current().name()}, "
163
+ f"with script {str(Path(script).resolve())}, line {lno}"
164
+ )
165
+ next_row = inv_ws.max_row + 1
166
+ for col_idx, value in enumerate(
167
+ (
168
+ sheet_name,
169
+ datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
170
+ getpass.getuser(),
171
+ desc,
172
+ src,
173
+ ),
174
+ start=1,
175
+ ):
176
+ inv_ws.cell(row=next_row, column=col_idx, value=value)
177
+
178
+ wb.save(outfile)
179
+ wb.close()
180
+
181
+
182
+ def write_queries_to_xlsx(
183
+ table_list: str,
184
+ db: Any,
185
+ outfile: str,
186
+ append: bool = False,
187
+ tee: bool = False,
188
+ desc: str | None = None,
189
+ ) -> None:
190
+ """Write multiple tables/queries to separate worksheets in a single XLSX workbook.
191
+
192
+ Args:
193
+ table_list: Comma-separated list of table names (optionally schema-qualified).
194
+ db: An execsql database adapter with a ``select_rowsource()`` method.
195
+ outfile: Destination ``.xlsx`` file path.
196
+ append: If ``True`` and *outfile* exists, add new sheets to the existing
197
+ workbook rather than replacing it.
198
+ tee: If ``True``, also pretty-print each query result to stdout.
199
+ desc: Optional description(s). A single string is applied to every
200
+ sheet; a comma-separated string with the same count as *table_list*
201
+ assigns individual descriptions per sheet.
202
+ """
203
+ openpyxl = _require_openpyxl()
204
+
205
+ tables = [t.strip() for t in table_list.split(",")]
206
+ if desc is not None:
207
+ descriptions = [d.strip() for d in desc.split(",")]
208
+ one_desc = len(descriptions) != len(tables)
209
+ else:
210
+ descriptions = []
211
+ one_desc = False
212
+
213
+ # ------------------------------------------------------------------
214
+ # Open or create workbook
215
+ # ------------------------------------------------------------------
216
+ if Path(outfile).is_file() and not append:
217
+ filewriter_close(outfile)
218
+ os.unlink(outfile)
219
+
220
+ if Path(outfile).is_file():
221
+ wb = openpyxl.load_workbook(outfile)
222
+ else:
223
+ wb = openpyxl.Workbook()
224
+ # Remove the default empty sheet created by openpyxl.
225
+ if wb.sheetnames:
226
+ del wb[wb.sheetnames[0]]
227
+
228
+ # ------------------------------------------------------------------
229
+ # Ensure the inventory sheet exists
230
+ # ------------------------------------------------------------------
231
+ inventory_name = "Datasheets"
232
+ if inventory_name not in wb.sheetnames:
233
+ inv_ws = wb.create_sheet(inventory_name)
234
+ bold_font = openpyxl.styles.Font(bold=True)
235
+ for col_idx, hdr in enumerate(
236
+ ("datasheet_name", "created_on", "created_by", "description", "source"),
237
+ start=1,
238
+ ):
239
+ cell = inv_ws.cell(row=1, column=col_idx, value=hdr)
240
+ cell.font = bold_font
241
+ else:
242
+ inv_ws = wb[inventory_name]
243
+
244
+ # ------------------------------------------------------------------
245
+ # Write each table to its own sheet
246
+ # ------------------------------------------------------------------
247
+ bold_font = openpyxl.styles.Font(bold=True)
248
+
249
+ for i, t in enumerate(tables):
250
+ # Determine the table name used for the sheet label.
251
+ if "." in t:
252
+ st = t.split(".")
253
+ if len(st) != 2:
254
+ raise ErrInfo("cmd", other_msg=f"Unrecognized table specification in <{t}>")
255
+ tblname = unquoted(st[1])
256
+ else:
257
+ tblname = unquoted(t)
258
+
259
+ # Avoid duplicate sheet names.
260
+ existing_names = wb.sheetnames
261
+ sheet_name = tblname
262
+ sheet_no = 1
263
+ while sheet_name in existing_names:
264
+ sheet_name = f"{tblname}_{sheet_no}"
265
+ sheet_no += 1
266
+
267
+ # Fetch data.
268
+ select_stmt = f"select * from {t};"
269
+ try:
270
+ hdrs, rows = db.select_rowsource(select_stmt)
271
+ except ErrInfo:
272
+ raise
273
+ except Exception as e:
274
+ raise ErrInfo("db", select_stmt, exception_msg=exception_desc()) from e
275
+
276
+ # Write data sheet.
277
+ ws = wb.create_sheet(sheet_name)
278
+
279
+ for col_idx, hdr in enumerate(hdrs, start=1):
280
+ cell = ws.cell(row=1, column=col_idx, value=str(hdr))
281
+ cell.font = bold_font
282
+
283
+ for row_idx, row in enumerate(rows, start=2):
284
+ for col_idx, item in enumerate(row, start=1):
285
+ ws.cell(row=row_idx, column=col_idx, value=_cell_value(item))
286
+
287
+ # Determine per-sheet description.
288
+ if desc is None:
289
+ d = None
290
+ elif one_desc:
291
+ d = desc
292
+ else:
293
+ d = descriptions[i]
294
+
295
+ # Update inventory sheet.
296
+ script, lno = current_script_line()
297
+ src = f"From database {_state.dbs.current().name()}, with script {str(Path(script).resolve())}, line {lno}"
298
+ next_row = inv_ws.max_row + 1
299
+ for col_idx, value in enumerate(
300
+ (
301
+ sheet_name,
302
+ datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
303
+ getpass.getuser(),
304
+ d,
305
+ src,
306
+ ),
307
+ start=1,
308
+ ):
309
+ inv_ws.cell(row=next_row, column=col_idx, value=value)
310
+
311
+ if tee and outfile.lower() != "stdout":
312
+ prettyprint_query(select_stmt, db, "stdout", False, desc=d)
313
+
314
+ _state.export_metadata.add(ExportRecord(queryname=select_stmt, outfile=outfile, zipfile=None, description=d))
315
+
316
+ wb.save(outfile)
317
+ wb.close()
@@ -0,0 +1,87 @@
1
+ from __future__ import annotations
2
+
3
+ """
4
+ YAML export for execsql.
5
+
6
+ Provides :func:`write_query_to_yaml` which serialises a query result set as a
7
+ YAML sequence of mappings (one mapping per row).
8
+
9
+ Requires the ``PyYAML`` package (``pip install PyYAML`` or
10
+ ``pip install 'execsql2[formats]'``).
11
+ """
12
+
13
+ from typing import Any
14
+
15
+ import execsql.state as _state
16
+ from execsql.exceptions import ErrInfo
17
+ from execsql.exporters.zip import ZipWriter
18
+ from execsql.utils.errors import exception_desc
19
+ from execsql.utils.fileio import filewriter_close
20
+
21
+ __all__ = ["write_query_to_yaml"]
22
+
23
+
24
+ def write_query_to_yaml(
25
+ select_stmt: str,
26
+ db: Any,
27
+ outfile: str,
28
+ append: bool = False,
29
+ desc: str | None = None,
30
+ zipfile: str | None = None,
31
+ ) -> None:
32
+ """Execute *select_stmt* and write the result set to *outfile* as YAML.
33
+
34
+ The output is a YAML sequence of mappings — one mapping per row with
35
+ column headers as keys. Python types are preserved: integers stay
36
+ integers, floats stay floats, ``None`` becomes ``null``.
37
+
38
+ Args:
39
+ select_stmt: SQL SELECT statement to execute.
40
+ db: Database connection object exposing ``select_rowsource()``.
41
+ outfile: Destination file path, or ``"stdout"``.
42
+ append: When ``True`` the YAML sequence is appended to an existing
43
+ file. Note that concatenating two bare YAML sequences in one
44
+ file produces a multi-document stream; callers are responsible
45
+ for ensuring the resulting file is valid for their use-case.
46
+ desc: Optional description string. Ignored in plain YAML output
47
+ (YAML does not have a standard metadata header), but accepted
48
+ for API consistency with other exporters.
49
+ zipfile: When provided, write *outfile* as a member of this zip
50
+ archive instead of writing to the filesystem directly.
51
+ """
52
+ try:
53
+ import yaml # type: ignore[import-untyped]
54
+ except ImportError as exc:
55
+ raise ErrInfo(
56
+ "error",
57
+ other_msg=("PyYAML is required for FORMAT YAML export. Install it with: pip install PyYAML"),
58
+ ) from exc
59
+
60
+ conf = _state.conf
61
+ try:
62
+ hdrs, rows = db.select_rowsource(select_stmt)
63
+ except ErrInfo:
64
+ raise
65
+ except Exception as e:
66
+ raise ErrInfo("db", select_stmt, exception_msg=exception_desc()) from e
67
+
68
+ # Build the list of dicts in memory. YAML output is human-readable and
69
+ # typically used for small-to-medium result sets; loading into memory is
70
+ # acceptable and required by yaml.dump().
71
+ uhdrs = [str(h) for h in hdrs]
72
+ data = [dict(zip(uhdrs, row)) for row in rows]
73
+ yaml_text = yaml.dump(data, default_flow_style=False, allow_unicode=True)
74
+
75
+ if zipfile is None:
76
+ filewriter_close(outfile)
77
+ from execsql.utils.fileio import EncodedFile
78
+
79
+ ef = EncodedFile(outfile, conf.output_encoding)
80
+ f = ef.open("at" if append else "wt")
81
+ else:
82
+ f = ZipWriter(zipfile, outfile, append)
83
+
84
+ try:
85
+ f.write(yaml_text)
86
+ finally:
87
+ f.close()