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