interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / qrf / README.md

800 lines · 38026 bytes Raw Blame History Rendered
1# SQLite Query Result Formatting Subsystem
2
3The "Query Result Formatter" or "QRF" subsystem is a C-language
4subroutine that formats the output from an SQLite query for display using
5a fix-width font, for example on a terminal window over an SSH connection.
6The output format is configurable. The application can request various
7table formats, with flexible column widths and alignments, row-oriented
8formats, such as CSV and similar, as well as various special purpose formats
9like JSON.
10
11For the first 25 years of SQLite's existance, the
12[command-line interface](https://sqlite.org/cli.html) (CLI)
13formatted query results using a hodge-podge of routines
14that had grown slowly by accretion. The QRF was created
15in fall of 2025 to refactor and reorganize this code into
16a more usable form. The idea behind QRF is to implement all the
17query result formatting capabilities of the CLI in a subroutine
18that can be incorporated and reused by other applications.
19
20## 1.0 Overview Of Operation
21
22Suppose variable `sqlite3_stmt *pStmt` is a pointer to an SQLite
23prepared statement that has been reset and bound and is ready to run.
24Then to format the output from this prepared statement, use code
25similar to the following:
26
27> ~~~
28sqlite3_qrf_spec spec; /* Format specification */
29char *zErrMsg; /* Text error message (optional) */
30char *zResult = 0; /* Formatted output written here */
31int rc; /* Result code */
32
33memset(&spec, 0, sizeof(spec)); /* Initialize the spec */
34spec.iVersion = 2; /* Latest version number */
35spec.pzOutput = &zResult; /* Write results in variable zResult */
36/* Optionally fill in other settings in spec here, as needed */
37zErrMsg = 0; /* Not required; just being pedantic */
38rc = sqlite3_format_query_result(pStmt, &spec, &zErrMsg); /* Format results */
39if( rc ){
40 printf("Error (%d): %s\n", rc, zErrMsg); /* Report an error */
41 sqlite3_free(zErrMsg); /* Free the error message text */
42}else{
43 printf("%s", zResult); /* Report the results */
44}
45sqlite3_free(zResult); /* Free memory used to hold results */
46~~~
47
48The `sqlite3_qrf_spec` object describes the desired output format
49and where to send the generated output. Most of the work in using
50the QRF involves filling out the sqlite3_qrf_spec.
51
52### 1.1 Using QRF with SQL text
53
54If you start with SQL text instead of an sqlite3_stmt pointer, and
55especially if the SQL text might comprise two or more statements, then
56the SQL text needs to be converted into sqlite3_stmt objects separately.
57If the original SQL text is in a variable `const char *zSql` and the
58database connection is in variable `sqlite3 *db`, then code
59similar to the following should work:
60
61> ~~~
62sqlite3_qrf_spec spec; /* Format specification */
63char *zErrMsg; /* Text error message (optional) */
64char *zResult = 0; /* Formatted output written here */
65sqlite3_stmt *pStmt; /* Next prepared statement */
66int rc; /* Result code */
67
68memset(&spec, 0, sizeof(spec)); /* Initialize the spec */
69spec.iVersion = 2; /* Latest version number */
70spec.pzOutput = &zResult; /* Write results in variable zResult */
71/* Optionally fill in other settings in spec here, as needed */
72zErrMsg = 0; /* Not required; just being pedantic */
73while( zSql && zSql[0] ){
74 pStmt = 0; /* Not required; just being pedantic */
75 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
76 if( rc!=SQLITE_OK ){
77 printf("Error: %s\n", sqlite3_errmsg(db));
78 }else{
79 rc = sqlite3_format_query_result(pStmt, &spec, &zErrMsg); /* Get results */
80 if( rc ){
81 printf("Error (%d): %s\n", rc, zErrMsg); /* Report an error */
82 sqlite3_free(zErrMsg); /* Free the error message text */
83 }else{
84 printf("%s", zResult); /* Report the results */
85 sqlite3_free(zResult); /* Free memory used to hold results */
86 zResult = 0;
87 }
88 }
89 sqlite3_finalize(pStmt);
90}
91~~~
92
93<a id="spec"></a>
94## 2.0 The `sqlite3_qrf_spec` object
95
96The `sqlite3_qrf_spec` looks like this:
97
98> ~~~
99typedef struct sqlite3_qrf_spec sqlite3_qrf_spec;
100struct sqlite3_qrf_spec {
101 unsigned char iVersion; /* Version number of this structure */
102 unsigned char eStyle; /* Formatting style. "box", "csv", etc... */
103 unsigned char eEsc; /* How to escape control characters in text */
104 unsigned char eText; /* Quoting style for text */
105 unsigned char eTitle; /* Quating style for the text of column names */
106 unsigned char eBlob; /* Quoting style for BLOBs */
107 unsigned char bTitles; /* True to show column names */
108 unsigned char bWordWrap; /* Try to wrap on word boundaries */
109 unsigned char bTextJsonb; /* Render JSONB blobs as JSON text */
110 unsigned char eDfltAlign; /* Default alignment, no covered by aAlignment */
111 unsigned char eTitleAlign; /* Alignment for column headers */
112 unsigned char bSplitColumn; /* Wrap single-column output into many columns */
113 unsigned char bBorder; /* Show outer border in Box and Table styles */
114 short int nWrap; /* Wrap columns wider than this */
115 short int nScreenWidth; /* Maximum overall table width */
116 short int nLineLimit; /* Maximum number of lines for any row */
117 short int nTitleLimit; /* Maximum number of characters in a title */
118 unsigned int nMultiInsert; /* Add rows to one INSERT until size exceeds */
119 int nCharLimit; /* Maximum number of characters in a cell */
120 int nWidth; /* Number of entries in aWidth[] */
121 int nAlign; /* Number of entries in aAlignment[] */
122 short int *aWidth; /* Column widths */
123 unsigned char *aAlign; /* Column alignments */
124 char *zColumnSep; /* Alternative column separator */
125 char *zRowSep; /* Alternative row separator */
126 char *zTableName; /* Output table name */
127 char *zNull; /* Rendering of NULL */
128 char *(*xRender)(void*,sqlite3_value*); /* Render a value */
129 int (*xWrite)(void*,const char*,sqlite3_int64); /* Write output */
130 void *pRenderArg; /* First argument to the xRender callback */
131 void *pWriteArg; /* First argument to the xWrite callback */
132 char **pzOutput; /* Storage location for output string */
133 /* The following are available in iVersion 2 and later */
134 unsigned char bRowCount; /* Show the number of rows at end of each query */
135 char *zIFmt; /* Format string for integers */
136 char *zFpFmt; /* Format string for floating point */
137 /* Additional fields may be added in the future */
138};
139~~~
140
141Do not be alarmed by the complexity of this structure. Everything can
142be zeroed except for:
143
144 * `.iVersion`
145 * One of `.pzOutput` or `.xWrite`.
146
147You do not need to understand and configure every field of this object
148in order to use QRF effectively. Start by zeroing out the whole structure,
149then initializing iVersion and one of pzOutput or xWrite. Then maybe
150tweak one or two other settings to get the output you want.
151
152Further detail on the meanings of each of the fields in the
153`sqlite3_qrf_spec` object is in the subsequent sections.
154
155### 2.1 Structure Version Number
156
157The sqlite3_qrf_spec.iVersion field must be 1 or 2. Future enhancements to
158the QRF might add new fields to the bottom of the sqlite3_qrf_spec
159object. Those new fields will only be accessible if the iVersion is greater
160than 2. Thus the iVersion field is used to support upgradability.
161
162### 2.2 Output Deposition (xWrite and pzOutput)
163
164The formatted output can either be sent to a callback function
165or accumulated into an output buffer in memory obtained
166from sqlite3_malloc(). If the sqlite3_qrf_spec.xWrite column is not NULL,
167then that function is invoked (using sqlite3_qrf_spec.xWriteArg as its
168first argument) to transmit the formatted output. Or, if
169sqlite3_qrf_spec.pzOutput points to a pointer to a character, then that
170pointer is made to point to memory obtained from sqlite3_malloc() that
171contains the complete text of the formatted output. If spec.pzOutput\[0\]
172is initially non-NULL, then it is assumed to already point to memory obtained
173from sqlite3_malloc(). In that case, the buffer is resized using
174sqlite3_realloc() and the new text is appended.
175
176One of either sqlite3_qrf_spec.xWrite and sqlite3_qrf_spec.pzOutput must be
177non-NULL and the other must be NULL.
178
179The return value from xWrite is an SQLITE result code. The usual return
180should be SQLITE_OK. But if for some reason the write fails, a different
181value might be returned.
182
183### 2.3 Output Format
184
185The sqlite3_qrf_spec.eStyle field is an integer code that defines the
186specific output format that will be generated. See [section 4.0](#style)
187below for details on the meaning of the various style options.
188
189Other fields in sqlite3_qrf_spec might be used or might be
190ignored, depending on the value of eStyle.
191
192### 2.4 Show Column Names (bTitles)
193
194The sqlite3_qrf_spec.bTitles field can be one of QRF_SW_Auto,
195QRF_SW_On, QRF_SW_Off, or QRF_Always. The first three constants also
196have shorter alternative spellings: QRF_Auto, QRF_No, and QRF_Yes.
197
198> ~~~
199#define QRF_SW_Auto 0 /* Let QRF choose the best value */
200#define QRF_SW_Off 1 /* This setting is forced off */
201#define QRF_SW_On 2 /* This setting is forced on */
202#define QRF_Auto 0 /* Alternate spelling for QRF_SW_Auto and others */
203#define QRF_No 1 /* Alternate spelling for QRF_SW_Off */
204#define QRF_Yes 2 /* Alternate spelling for QRF_SW_On */
205#define QRF_Always 3 /* Always try to show column names */
206~~~
207
208If the value is QRF_Yes, then column names appear in the output when
209there are one or more rows of output.
210If the value is QRF_No, column names are omitted. If the
211value is QRF_Auto, then an appropriate default is chosen.
212The value QRF_Always is like QRF_Yes except that the output might
213still show column headers even if the number of result rows is zero,
214depending on eStyle.
215
216### 2.5 Control Character Escapes (eEsc)
217
218The sqlite3_qrf_spec.eEsc determines how ASCII control characters are
219formatted when displaying TEXT values in the result. These are the allowed
220values:
221
222> ~~~
223#define QRF_ESC_Auto 0 /* Choose the ctrl-char escape automatically */
224#define QRF_ESC_Off 1 /* Do not escape control characters */
225#define QRF_ESC_Ascii 2 /* Unix-style escapes. Ex: U+0007 shows ^G */
226#define QRF_ESC_Symbol 3 /* Unicode escapes. Ex: U+0007 shows U+2407 */
227~~~
228
229If the value of eEsc is QRF_ESC_Ascii, then the control character
230with value X is displayed as ^Y where Y is X+0x40. Hence, a
231backspace character (U+0008) is shown as "^H".
232
233If eEsc is QRF_ESC_Symbol, then control characters in the range of U+0001
234through U+001f are mapped into U+2401 through U+241f, respectively.
235
236If the value of eEsc is QRF_ESC_Off, then no translation occurs
237and control characters that appear in TEXT strings are transmitted
238to the formatted output as-is. This can be dangerous in applications,
239since an adversary who can control TEXT values might be able to
240inject ANSI cursor movement sequences to hide nefarious values.
241
242The QRF_ESC_Auto value for eEsc means that the query result formatter
243gets to pick whichever control-character encoding it thinks is best for
244the situation. This will usually be QRF_ESC_Ascii, but there can be
245exceptions.
246
247The TAB (U+0009), LF (U+000a) and CR-LF (U+000d,U+000a) character
248sequence are always output literally and are not mapped to alternative
249display values, regardless of this setting.
250
251### 2.6 Display of TEXT values (eText, eTitle)
252
253The sqlite3_qrf_spec.eText controls how text values are rendered in the
254display. sqlite3_qrf_spec.eTitle controls how column names are rendered.
255Both fields can have one of the following values:
256
257> ~~~
258#define QRF_TEXT_Auto 0 /* Choose text encoding automatically */
259#define QRF_TEXT_Plain 1 /* Literal text */
260#define QRF_TEXT_Sql 2 /* Quote as an SQL literal */
261#define QRF_TEXT_Csv 3 /* CSV-style quoting */
262#define QRF_TEXT_Html 4 /* HTML-style quoting */
263#define QRF_TEXT_Tcl 5 /* C/Tcl quoting */
264#define QRF_TEXT_Json 6 /* JSON quoting */
265#define QRF_TEXT_Relaxed 7 /* Relaxed SQL quoting */
266~~~
267
268A value of QRF_TEXT_Auto means that the query result formatter will choose
269what it thinks will be the best text encoding.
270
271A value of QRF_TEXT_Plain means that text values appear in the output exactly
272as they are found in the database file, with no translation.
273
274A value of QRF_TEXT_Sql means that text values are escaped so that they
275look like SQL literals. That means the value will be surrounded by
276single-quotes (U+0027) and any single-quotes contained within the text
277will be doubled.
278
279QRF_TEXT_Relaxed is similar to QRF_TEXT_Sql, except that it automatically
280reverts to QRF_TEXT_Plain if the value to be displayed does not contain
281special characters and is not easily confused with a NULL or a numeric
282value. QRF_TEXT_Relaxed strives to minimize the amount of quoting syntax
283while keeping the result unambiguous and easy for humans to read. The
284precise rules for when quoting is omitted in QRF_TEXT_Relaxed, and when
285it is applied, might be adjusted in future releases.
286
287A value of QRF_TEXT_Csv means that text values are escaped in accordance
288with RFC&nbsp;4180, which defines Comma-Separated-Value or CSV files.
289Text strings that contain no special values appears as-is. Text strings
290that contain special values are contained in double-quotes (U+0022) and
291any double-quotes within the value are doubled.
292
293A value of QRF_TEXT_Html means that text values are escaped for use in
294HTML. Special characters "&lt;", "&amp;", "&gt;", "&quot;", and "&#39;"
295are displayed as "&amp;lt;", "&amp;amp;", "&amp;gt;", "&amp;quot;",
296and "&amp;#39;", respectively.
297
298A value of QRF_TEXT_Tcl means that text values are displayed inside of
299double-quotes and special characters within the string are escaped using
300backslash escape, as in ANSI-C or TCL or Perl or other popular programming
301languages.
302
303A value of QRF_TEXT_Json gives similar results as QRF_TEXT_Tcl except that the
304rules are adjusted so that the displayed string is strictly conforming
305the JSON specification.
306
307### 2.7 How to display BLOB values (eBlob and bTextJsonb)
308
309If the sqlite3_qrf_spec.bTextJsonb flag is QRF_SW_On and if the value to be
310displayed is JSONB, then the JSONB is translated into text JSON and the
311text is shown according to the sqlite3_qrf_spec.eText setting as
312described in the previous section.
313
314If the bTextJsonb flag is QRF_SW_Off (the usual case) or if the BLOB value to
315be displayed is not JSONB, then the sqlite3_qrf_spec.eBlob field determines
316how the BLOB value is formatted. The following options are available;
317
318> ~~~
319#define QRF_BLOB_Auto 0 /* Determine BLOB quoting using eText */
320#define QRF_BLOB_Text 1 /* Display content exactly as it is */
321#define QRF_BLOB_Sql 2 /* Quote as an SQL literal */
322#define QRF_BLOB_Hex 3 /* Hexadecimal representation */
323#define QRF_BLOB_Tcl 4 /* "\000" notation */
324#define QRF_BLOB_Json 5 /* A JSON string */
325#define QRF_BLOB_Size 6 /* Display the blob size only */
326~~~
327
328A value of QRF_BLOB_Auto means that display format is selected automatically
329by sqlite3_format_query_result() based on eStyle and eText.
330
331A value of QRF_BLOB_Text means that BLOB values are interpreted as UTF8
332text and are displayed using formatting results set by eEsc and
333eText.
334
335A value of QRF_BLOB_Sql means that BLOB values are shown as SQL BLOB
336literals: a prefix "`x'`" following by hexadecimal and ending with a
337final "`'`".
338
339A value of QRF_BLOB_Hex means that BLOB values are shown as
340hexadecimal text with no delimiters.
341
342A value of QRF_BLOB_Tcl means that BLOB values are shown as a
343C/Tcl/Perl string literal where every byte is an octal backslash
344escape. So a BLOB of `x'052881f3'` would be displayed as
345`"\005\050\201\363"`.
346
347A value of QRF_BLOB_Json is similar to QRF_BLOB_Tcl except that is
348uses unicode backslash escapes, since JSON does not understand
349the C/Tcl/Perl octal backslash escapes. So the string from the
350previous paragraph would be shown as
351`"\u0005\u0028\u0081\u00f3"`.
352
353A value of QRF_BLOB_Size does not show any BLOB content at all.
354Instead, it substitutes a text string that says how many bytes
355the BLOB contains.
356
357### 2.8 Maximum size of displayed content (nLineLimit, nCharLimit, nTitleLimit)
358
359If the sqlite3_qrf_spec.nCharLimit setting is non-zero, then the formatter
360will display only the first nCharLimit characters of each value.
361Only characters that take up space are counted when enforcing this
362limit. Zero-width characters and VT100 escape sequences do not count
363toward this limit. The count is in characters, not bytes. When
364imposing this limit, the formatter adds the three characters "..."
365to the end of the value. Those added characters are not counted
366as part of the limit. Very small limits still result in truncation,
367but might render a few more characters than the limit.
368
369If the sqlite3_qrf_spec.nLineLimit setting is non-zero, then the
370formatter will only display the first nLineLimit lines of each value.
371It does not matter if the value is split because it contains a newline
372character, or if it split by wrapping. This setting merely limits
373the number of displayed lines. The nLineLimit setting currently only
374works for **Box**, **Column**, **Line**, **Markdown**, and **Table**
375styles, though that limitation might change in future releases.
376
377The idea behind both of these settings is to prevent large renderings
378when doing a query that (unexpectedly) contains very large text or
379blob values: perhaps megabyes of text.
380
381If the sqlite3_qrf_spec.nTitleLimit is non-zero, then the formatter
382attempts to limits the size of column titles to at most nTitleLimit
383display characters in width and a single line of text. The nTitleLimit
384is useful for queries that have result columns that are scalar
385subqueries or complex expressions. If those columns lack an AS
386clause, then the name of the column will be a copy of the expression
387that defines the column, which in some queries can be hundreds of
388characters and multiple lines in length, which can reduce the readability
389of tabular displays. An nTitleLimit somewhere in the range of 10 to 20.
390can improve readability. The nTitleLimit setting currently only
391works for **Box**, **Column**, **Line**, **Markdown**, and **Table**
392styles, though that limitation might change in future releases.
393
394### 2.9 Multiple Tuples Per INSERT In QRF_STYLE_Insert (nMultiInsert)
395
396If the sqlite3_qrf_spec.nMultiInsert value is positive, then the
397QRF_STYLE_Insert output mode will generate multiple tuples in
398each INSERT statement until the total number of bytes in the
399statement exceeds nMultiInsert. A value of a few thousand is
400recommended here, in order to generate SQL output that is parsed
401and inserted at maximum speed by SQLite.
402
403### 2.10 Word Wrapping In Columnar Styles (nWrap, bWordWrap)
404
405When using columnar formatting modes (QRF_STYLE_Box, QRF_STYLE_Column,
406QRF_STYLE_Markdown, or QRF_STYLE_Table), the formatter attempts to limit
407the width of any individual column to sqlite3_qrf_spec.nWrap characters
408if nWrap is non-zero. A zero value for nWrap means "unlimited".
409The nWrap limit might be exceeded if the limit is very small.
410
411In order to keep individual columns within requested width limits,
412it is sometimes necessary to wrap the content for a single row of
413a single column across multiple lines. When this
414becomes necessary and if the bWordWrap setting is QRF_Yes, then the
415formatter attempts to split the content on whitespace or at a word boundary.
416If bWordWrap is QRF_No, then the formatter is free to split content
417anywhere, including in the middle of a word.
418
419For narrow columns and wide words, it might sometimes be necessary to split
420a column in the middle of a word, even when bWordWrap is QRF_Yes.
421
422### 2.11 Helping The Output To Fit On The Terminal (nScreenWidth)
423
424The sqlite3_qrf_spec.nScreenWidth field can be set the number of
425characters that will fit on one line on the viewer output device.
426This is typically a number like 80 or 132. The formatter will attempt
427to reduce the length of output lines, depending on the style, so
428that all output fits on that screen.
429
430A value of zero for nScreenWidth means "unknown" or "no width limit".
431When the value is zero, the formatter makes no attempt to keep the
432lines of output short.
433
434The nScreenWidth is a hint to the formatter, not a requirement.
435The formatter trieds to keep lines below the nScreenWidth limit,
436but it does not guarantee that it will.
437
438The nScreenWidth field currently only makes a difference in
439columnar styles (**Box**, **Column**, **Markdown**, and **Table**)
440and in the **Line** style.
441
442### 2.12 Individual Column Width (nWidth and aWidth)
443
444The sqlite3_qrf_spec.aWidth field is a pointer to an array of
445signed 16-bit integers that control the width of individual columns
446in columnar output modes (QRF_STYLE_Box, QRF_STYLE_Column,
447QRF_STYLE_Markdown, or QRF_STYLE_Table). The sqlite3_qrf_spec.nWidth
448field is the number of integers in the aWidth array.
449
450If aWidth is a NULL pointer or if nWidth is zero, then the array is
451assumed to be all zeros. If nWidth is less then the number of
452columns in the output, then zero is used for the width
453for all columns past then end of the aWidth array.
454
455The aWidth array is deliberately an array of 16-bit signed integers.
456Only 16 bits are used because no good comes for having very large
457column widths. The range if further restricted as follows:
458
459> ~~~
460#define QRF_MAX_WIDTH 10000 /* Maximum column width */
461#define QRF_MIN_WIDTH 0 /* Minimum column width */
462~~~
463
464A width greater than then QRF_MAX_WIDTH is interpreted as QRF_MAX_WIDTH.
465
466Any aWidth\[\] value of zero means the formatter should use a flexible
467width column (limited only by sqlite_qrf_spec.mxWidth) that is just
468big enough to hold the largest row.
469
470For historical compatibility, aWidth\[\] can contain negative values,
471down to -QRF_MAX_WIDTH. The column width used is the absolute value
472of the number in aWidth\[\]. The only difference is that negative
473values cause the default horizontal alignment to be QRF_ALIGN_Right.
474The sign of the aWidth\[\] values only affects alignment if the
475alignment is not otherwise specified by aAlign\[\] or eDfltAlign.
476Again, negative values for aWidth\[\] entries are supported for
477backwards compatibility only, and are not recommended for new
478applications.
479
480### 2.13 Alignment (nAlignment, aAlignment, eDfltAlign, eTitleAlign)
481
482Some cells in a display table might contain a lot of text and thus
483be wide, or they might contain newline characters or be wrapped by
484width constraints so that they span many rows of text. Other cells
485might be narrower and shorter. In columnar formats, the display width
486of a cell is the maximum of the widest value in the same column, and the
487display height is the height of the tallest value in the same row.
488So some cells might be much taller and wider than necessary to hold
489their values.
490
491Alignment determines where smaller values are placed within larger cells.
492
493The sqlite3_qrf_spec.aAlign field points to an array of unsigned characters
494that specifies alignment (both vertical and horizontal) of individual
495columns within the table. The sqlite3_qrf_spec.nAlign fields holds
496the number of entries in the aAlign\[\] array.
497
498If sqlite3_qrf_spec.aAlign is a NULL pointer or if sqlite3_qrf_spec.nAlign
499is zero, or for columns to the right of what are specified by
500sqlite3_qrf_spec.nAlign, the sqlite3_qrf_spec.eDfltAlign value is used
501for the alignment. Column names can be (and often are) aligned
502differently, as specified by sqlite3_qrf_spec.eTitleAlign.
503
504Each alignment value specifies both vertical and horizontal alignment.
505Horizontal alignment can be left, center, right, or no preference.
506Vertical alignment can be top, middle, bottom, or no preference.
507Thus there are 16 possible alignment values, as follows:
508
509> ~~~
510/*
511** Horizontal Vertial
512** ---------- -------- */
513#define QRF_ALIGN_Auto 0 /* auto auto */
514#define QRF_ALIGN_Left 1 /* left auto */
515#define QRF_ALIGN_Center 2 /* center auto */
516#define QRF_ALIGN_Right 3 /* right auto */
517#define QRF_ALIGN_Top 4 /* auto top */
518#define QRF_ALIGN_NW 5 /* left top */
519#define QRF_ALIGN_N 6 /* center top */
520#define QRF_ALIGN_NE 7 /* right top */
521#define QRF_ALIGN_Middle 8 /* auto middle */
522#define QRF_ALIGN_W 9 /* left middle */
523#define QRF_ALIGN_C 10 /* center middle */
524#define QRF_ALIGN_E 11 /* right middle */
525#define QRF_ALIGN_Bottom 12 /* auto bottom */
526#define QRF_ALIGN_SW 13 /* left bottom */
527#define QRF_ALIGN_S 14 /* center bottom */
528#define QRF_ALIGN_SE 15 /* right bottom */
529~~~
530
531Notice how alignment values with an unspecified horizontal
532or vertical component can be added to another alignment value
533for which that component is specified, to get a fully
534specified alignment. For eample:
535
536> QRF_ALIGN_Center + QRF_ALIGN_Bottom == QRF_ALIGN_S.
537
538The alignment for column names is always determined by the
539eTitleAlign setting. If eTitleAlign is QRF_Auto, then column
540names use center-bottom alignment, QRF_ALIGN_W, value 14.
541The aAlign\[\] and eDfltAlign settings have no affect on
542column names.
543
544For data in the first nAlign columns, the aAlign\[\] array
545entry for that column takes precedence. If either the horizontal
546or vertical alignment has an "auto" value for that column or if
547a column is beyond the first nAlign entries, then eDfltAlign
548is used as a backup. If neither aAlign\[\] nor eDfltAlign
549specify a horizontal alignment, then values are right-aligned
550(QRF_ALIGN_Right) if they are numeric and left-aligned
551(QRF_ALIGN_Left) otherwise. If neither aAlign\[\] nor eDfltAlign
552specify a vertical alignment, then values are top-aligned
553(QRF_ALIGN_Top).
554
555*As of 2025-11-08, only horizontal alignment is implemented.
556The vertical alignment settings are currently ignored and
557the vertical alignment is always QRF_ALIGN_Top.*
558
559### 2.14 Row and Column Separator Strings
560
561The sqlite3_qrf_spec.zColumnSep and sqlite3_qrf_spec.zRowSep strings
562are alternative column and row separator character sequences. If not
563specified (if these pointers are left as NULL) then appropriate defaults
564are used. Some output styles have hard-coded column and row separators
565and these settings are ignored for those styles.
566
567### 2.15 The Output Table Name
568
569The sqlite3_qrf_spec.zTableName value is the name of the output table
570when eStyle is QRF_STYLE_Insert.
571
572### 2.16 The Rendering Of NULL (zNull)
573
574If a value is NULL then show the NULL using the string
575found in sqlite3_qrf_spec.zNull. If zNull is itself a NULL pointer
576then NULL values are rendered as an empty string.
577
578### 2.17 Optional Value Rendering Callback
579
580If the sqlite3_qrf_spec.xRender field is not NULL, then each
581sqlite3_value coming out of the query is first passed to the
582xRender function, giving that function an opportunity to render
583the results itself, using whatever custom format is desired.
584If xRender chooses to render, it should write the rendering
585into memory obtained from sqlite3_malloc() and return a pointer
586to that memory. The xRender function can decline
587to render (for example, based on the sqlite3_value_type() or other
588characteristics of the value) in which case it can simply return a
589NULL pointer and the usual default rendering will be used instead.
590
591The sqlite3_format_query_result() function (which calls xRender)
592will take responsibility for freeing the string returned by xRender
593after it has finished using it.
594
595The eText, eBlob, and eEsc settings above become no-ops if the xRender
596routine returns non-NULL. In other words, the application-supplied
597xRender routine is expected to do all of its own quoting and formatting.
598
599The xRender routine is expected to do character length limiting itself.
600So the nCharLimit setting becomes a no-op if xRender is used. However
601the nLineLimit setting is still applied. The nTitleLimit setting is
602not applicable to xRender because title values come from the
603sqlite3_column_name() interface not from sqlite3_column_value(),
604and so that names of columns are never processed by xRender.
605
606### 2.18 Show Row Counts On Query Output (bRowCount)
607
608If the value of bRowCount is QRF_Yes, then an extra line of text
609of the form "(N rows)" might be appended to the end of query output,
610depending on eStyle.
611
612### 2.19 Number Formatting (zIFmt and zFpFmt)
613
614If the zIFmt and zFpFmt fields are a short printf-style format
615string, than that formatting string is used to render integer and
616floating-point values, respectively. The width and precision fields
617of the format string (if present) must not exceed three decimal digits.
618An invalid or unsupported format string causes the formatting to
619revert to its default. The sqlite3_qrf_ckformat() API function can
620be used to validate format strings.
621
622## 3.0 The `sqlite3_format_query_result()` Interface
623
624Invoke the `sqlite3_format_query_result(P,S,E)` interface to run
625the prepared statement P and format its results according to the
626specification found in S. The sqlite3_format_query_result() function
627will return an SQLite result code, usually SQLITE_OK, but perhaps
628SQLITE_NOMEM or SQLITE_ERROR or similar. If an error occurs and if
629the E parameter is not NULL, then error message text might be written
630into *E. Any error message text will be stored in memory obtained
631from sqlite3_malloc() and it is the responsibility of the caller to
632free that memory by a subsequent call to sqlite3_free().
633
634<a id="style"></a>
635## 4.0 Output Styles
636
637The result formatter supports a variety of output styles. The
638output style (sometimes called "output mode") is determined by
639the eStyle field of the sqlite3_qrf_spec object. The set of
640supported output modes might increase in future versions.
641The following output modes are currently defined:
642
643> ~~~
644#define QRF_STYLE_Auto 0 /* Choose a style automatically */
645#define QRF_STYLE_Box 1 /* Unicode box-drawing characters */
646#define QRF_STYLE_Column 2 /* One record per line in neat columns */
647#define QRF_STYLE_Count 3 /* Output only a count of the rows of output */
648#define QRF_STYLE_Csv 4 /* Comma-separated-value */
649#define QRF_STYLE_Eqp 5 /* Format EXPLAIN QUERY PLAN output */
650#define QRF_STYLE_Explain 6 /* EXPLAIN output */
651#define QRF_STYLE_Html 7 /* Generate HTML-style <tr><td> output */
652#define QRF_STYLE_Insert 8 /* Generate SQL "insert" statements */
653#define QRF_STYLE_Json 9 /* Output is a list of JSON objects */
654#define QRF_STYLE_JObject 10 /* Independent JSON objects for each row */
655#define QRF_STYLE_Line 11 /* One column per line. */
656#define QRF_STYLE_List 12 /* One record per line with a separator */
657#define QRF_STYLE_Markdown 13 /* Markdown formatting */
658#define QRF_STYLE_Off 14 /* No query output shown */
659#define QRF_STYLE_Quote 15 /* SQL-quoted, comma-separated */
660#define QRF_STYLE_Stats 16 /* EQP-like output but with performance stats */
661#define QRF_STYLE_StatsEst 17 /* EQP-like output with planner estimates */
662#define QRF_STYLE_StatsVm 18 /* EXPLAIN-like output with performance stats */
663#define QRF_STYLE_Table 19 /* MySQL-style table formatting */
664~~~
665
666In the following subsections, these styles will often be referred
667to without the "QRF_STYLE_" prefix.
668
669### 4.1 Default Style (Auto)
670
671The **Auto** style means QRF gets to choose an appropriate output
672style. It will usually choose **Box**, but might also pick one of
673**Explain** or **Eqp** if the `sqlite3_stmt_explain()` function
674returns 1 or 2, respectively.
675
676### 4.2 Columnar Styles (Box, Column, Markdown, Table)
677
678The **Box**, **Column**, **Markdown**, and **Table**
679modes are columnar. This means the output is arranged into neat,
680uniform-width columns. These styles can use more memory, especially when
681the query result has many rows, because they need to load the entire output
682into memory first in order to determine how wide to make each column.
683
684The nWidth, aWidth, and mxWidth fields of the `sqlite3_qrf_spec` object
685are used by these styles only, and are ignored by all other styles.
686The zRowSep and zColumnSep settings are ignored by these styles. The
687bTitles setting is honored by these styles; it defaults to QRF_SW_On.
688
689The **Box** style uses Unicode box-drawing character to draw a grid
690of columns and rows to show the result. The **Table** is the same,
691except that it uses ASCII-art rather than Unicode box-drawing characters
692to draw the grid. The **Column** arranges the results in neat columns
693but does not draw in column or row separator, except that it does draw
694lines horizontal lines using "`-`" characters to separate the column names
695from the data below. This is very similar to default output styling in
696psql. The **Markdown** renders its result in the Markdown table format.
697
698The **Box** and **Table** styles normally have a border that surrounds
699the entire result. However, if sqlite3_qrf_spec.bBorder is QRF_No, then
700that border is omitted, saving a little space both horizontally and
701vertically.
702
703#### 4.2.1 Split Column Mode
704
705If the bSplitColumn field is QRF_Yes, and eStyle is QRF_STYLE_Column,
706and bTitles is QRF_No, and nScreenWidth is greater than zero, and if
707the query only returns a single column, then a special rendering known
708as "Split Column Mode" will be used. In split column mode, instead
709of showing all results in one tall column, the content wraps vertically
710so that it appears on the screen as multiple columns, as many as will
711fit in the available screen width.
712
713### 4.3 Line-oriented Styles
714
715The line-oriented styles output each row of result as it is received from
716the prepared statement.
717
718The **List** style is the most familiar line-oriented output format.
719The **List** style shows output columns for each row on the
720same line, each separated by a single "`|`" character and with lines
721terminated by a single newline (\\u000a or \\n). These column
722and row separator choices can be overridden using the zColumnSep
723and zRowSep fields of the `sqlite3_qrf_spec` structure. The text
724formatting is QRF_TEXT_Plain, and BLOB encoding is QRF_BLOB_Text. So
725characters appear in the output exactly as they appear in the database.
726Except the eEsp mode defaults to `QRF_ESC_On`, so that control
727characters are escaped, for safety.
728
729The **Csv** and **Quote** styles are simply variations on **List**
730with hard-coded values for some of the sqlite3_qrf_spec settings:
731
732<table border=1 cellpadding=2 cellspacing=0>
733<tr><th>&nbsp;<th>Quote<th>Csv
734<tr><td>zColumnSep<td>","<td>","
735<tr><td>zRowSep<td>"\\n"<td>"\\r\\n"
736<tr><td>zNull<td>"NULL"<td>""
737<tr><td>eText<td>QRF_TEXT_Sql<td>QRF_TEXT_Csv
738<tr><td>eBlob<td>QRF_BLOB_Sql<td>QRF_BLOB_Text
739</table>
740
741The **Html** style generates HTML table content, just without
742the `<table>..</table>` around the outside.
743
744The **Insert** style generates a series of SQL "INSERT" statements
745that will inserts the data that is output into a table whose name is defined
746by the zTableName field of `sqlite3_qrf_spec`. If zTableName is NULL,
747then a substitute name is used. If nMultiInsert is positive, then the
748output will add multiple rows to each INSERT statement until the size
749of the INSERT statement exceeds nMultiInsert bytes before starting
750a new INSERT statement.
751
752The **Json** and **JObject** styles generates JSON text for the query result.
753The **Json** style produces a JSON array of structures with one
754structure per row. **JObject** outputs independent JSON objects, one per
755row, with each structure on a separate line all by itself, and not
756part of a larger array. In both cases, the labels on the elements of the
757JSON objects are taken from the column names of the SQL query. So if
758you have an SQL query that has two or more output columns with the same
759name, you will end up with JSON structures that have duplicate elements.
760
761Finally, the **Line** style paints each column of a row on a
762separate line with the column name on the left and a "`=`" separating the
763column name from its value. A single blank line appears between rows.
764
765### 4.4 EXPLAIN Styles (Eqp, Explain)
766
767The **Eqp** and **Explain** styles format output for
768EXPLAIN QUERY PLAN and EXPLAIN statements, respectively. If the input
769statement is not already an EXPLAIN QUERY PLAN or EXPLAIN statement is
770is temporarily converted for the duration of the rendering, but
771is converted back before `sqlite3_format_query_result()` returns.
772
773### 4.5 ScanStatus Styles (Stats, StatsEst, StatsVm)
774
775The **Stats**, **StatsEst**, and **StatsVm** styles are similar to **Eqp**
776and **Explain** except that they include profiling information
777from prior executions of the input prepared statement.
778These modes only work if SQLite has been compiled with
779-DSQLITE_ENABLE_STMT_SCANSTATUS and if the SQLITE_DBCONFIG_STMT_SCANSTATUS
780is enabled for the database connection. The **StatsVm** style
781also requires the bytecode() virtual table which is enabled using
782the -DSQLITE_ENABLE_BYTECODE_VTAB compile-time option.
783
784### 4.6 Other Styles (Count, Off)
785
786The **Count** style discards all query results and returns
787a count of the number of rows of output at the end. The **Off**
788style is completely silent; it generates no output. These corner-case
789modes are sometimes useful for debugging.
790
791### 5.0 Source Code Files
792
793The SQLite Query Result Formatter is implemented in three source code files:
794
795 * `qrf.c` &rarr; The implementation, written in portable C99
796 * `qrf.h` &rarr; A header file defining interfaces
797 * `README.md` &rarr; This documentation
798
799To use the SQLite result formatter, include the "`qrf.h`" header file
800and link the application against the "`qrf.c`" source file.