SQLite

Changes On Branch unistr
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch unistr Excluding Merge-Ins

This is equivalent to a diff from 742827f049 to 17e440781e

2025-02-25
15:57
Enhancements to help avoid problems in the CLI when trying display content that contains ANSI escape codes: (1) Add the --escape MODE option to the CLI where MODE is one of "symbol", "ascii", "off" where the default is "symbol". (2) Add the unistr() SQL function. (3) Add the unistr_quote() SQL function. (4) Add the %#Q and %#q conversions in the built-in printf. (check-in: e3e509ae14 user: drh tags: trunk)
12:18
Small performance improvement for the new %#Q conversion in printf. (Closed-Leaf check-in: 17e440781e user: drh tags: unistr)
11:47
Consolidate two different UTF8 encoders into a single subroutine. (check-in: 6208e49485 user: drh tags: unistr)
2025-02-24
21:27
Support SQLITE_ENABLE_SETLK_TIMEOUT on windows. (check-in: e88212b10a user: dan tags: trunk)
10:52
Merge latest changes from trunk into this branch. (Closed-Leaf check-in: 55324d1c86 user: dan tags: win32-enable-setlk)
2025-02-22
23:18
Prototype implementation of the unistr() SQL function. (check-in: 7cc302de05 user: drh tags: unistr)
16:44
Tamp down various harmless compiler warnings. Use "int" in places instead of "u16" or "i16" since the compiler complains less and generates faster code. (check-in: 742827f049 user: drh tags: trunk)
11:40
Fix an incorrect assert added by [d7729dbbf231d57c]. (check-in: eeea11278b user: drh tags: trunk)

Changes to src/func.c.
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};

/*
** Append to pStr text that is the SQL literal representation of the
** value contained in pValue.
*/
void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){
  /* As currently implemented, the string must be initially empty.
  ** we might relax this requirement in the future, but that will
  ** require enhancements to the implementation. */
  assert( pStr!=0 && pStr->nChar==0 );

  switch( sqlite3_value_type(pValue) ){
    case SQLITE_FLOAT: {







|







1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};

/*
** Append to pStr text that is the SQL literal representation of the
** value contained in pValue.
*/
void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue, int bEscape){
  /* As currently implemented, the string must be initially empty.
  ** we might relax this requirement in the future, but that will
  ** require enhancements to the implementation. */
  assert( pStr!=0 && pStr->nChar==0 );

  switch( sqlite3_value_type(pValue) ){
    case SQLITE_FLOAT: {
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150



































































































1151
1152
1153
1154
1155
1156
1157
1158
1159
1160




1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
        zText[1] = '\'';
        pStr->nChar = nBlob*2 + 3;
      }
      break;
    }
    case SQLITE_TEXT: {
      const unsigned char *zArg = sqlite3_value_text(pValue);
      sqlite3_str_appendf(pStr, "%Q", zArg);
      break;
    }
    default: {
      assert( sqlite3_value_type(pValue)==SQLITE_NULL );
      sqlite3_str_append(pStr, "NULL", 4);
      break;
    }
  }
}




































































































/*
** Implementation of the QUOTE() function. 
**
** The quote(X) function returns the text of an SQL literal which is the
** value of its argument suitable for inclusion into an SQL statement.
** Strings are surrounded by single-quotes with escapes on interior quotes
** as needed. BLOBs are encoded as hexadecimal literals. Strings with
** embedded NUL characters cannot be represented as string literals in SQL
** and hence the returned string literal is truncated prior to the first NUL.




*/
static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  sqlite3_str str;
  sqlite3 *db = sqlite3_context_db_handle(context);
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  sqlite3QuoteValue(&str,argv[0]);
  sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
                      SQLITE_DYNAMIC);
  if( str.accError!=SQLITE_OK ){
    sqlite3_result_null(context);
    sqlite3_result_error_code(context, str.accError);
  }
}







|









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










>
>
>
>







|







1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
        zText[1] = '\'';
        pStr->nChar = nBlob*2 + 3;
      }
      break;
    }
    case SQLITE_TEXT: {
      const unsigned char *zArg = sqlite3_value_text(pValue);
      sqlite3_str_appendf(pStr, bEscape ? "%#Q" : "%Q", zArg);
      break;
    }
    default: {
      assert( sqlite3_value_type(pValue)==SQLITE_NULL );
      sqlite3_str_append(pStr, "NULL", 4);
      break;
    }
  }
}

/*
** Return true if z[] begins with N hexadecimal digits, and write
** a decoding of those digits into *pVal.  Or return false if any
** one of the first N characters in z[] is not a hexadecimal digit.
*/
static int isNHex(const char *z, int N, u32 *pVal){
  int i;
  int v = 0;
  for(i=0; i<N; i++){
    if( !sqlite3Isxdigit(z[i]) ) return 0;
    v = (v<<4) + sqlite3HexToInt(z[i]);
  }
  *pVal = v;
  return 1;
}

/*
** Implementation of the UNISTR() function.
**
** This is intended to be a work-alike of the UNISTR() function in
** PostgreSQL.  Quoting from the PG documentation (PostgreSQL 17 -
** scraped on 2025-02-22):
**
**    Evaluate escaped Unicode characters in the argument. Unicode
**    characters can be specified as \XXXX (4 hexadecimal digits),
**    \+XXXXXX (6 hexadecimal digits), \uXXXX (4 hexadecimal digits),
**    or \UXXXXXXXX (8 hexadecimal digits). To specify a backslash,
**    write two backslashes. All other characters are taken literally.
*/
static void unistrFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  char *zOut;
  const char *zIn;
  int nIn;
  int i, j, n;
  u32 v;

  assert( argc==1 );
  UNUSED_PARAMETER( argc );
  zIn = (const char*)sqlite3_value_text(argv[0]);
  if( zIn==0 ) return;
  nIn = sqlite3_value_bytes(argv[0]);
  zOut = sqlite3_malloc64(nIn+1);
  if( zOut==0 ){
    sqlite3_result_error_nomem(context);
    return;
  }
  i = j = 0;
  while( i<nIn ){
    char *z = strchr(&zIn[i],'\\');
    if( z==0 ){
      n = nIn - i;
      memmove(&zOut[j], &zIn[i], n);
      j += n;
      break;
    }
    n = z - &zIn[i];
    if( n>0 ){
      memmove(&zOut[j], &zIn[i], n);
      j += n;
      i += n;
    }
    if( zIn[i+1]=='\\' ){
      i += 2;
      zOut[j++] = '\\';
    }else if( sqlite3Isxdigit(zIn[i+1]) ){
      if( !isNHex(&zIn[i+1], 4, &v) ) goto unistr_error;
      i += 5;
      j += sqlite3AppendOneUtf8Character(&zOut[j], v);
    }else if( zIn[i+1]=='+' ){
      if( !isNHex(&zIn[i+2], 6, &v) ) goto unistr_error;
      i += 8;
      j += sqlite3AppendOneUtf8Character(&zOut[j], v);
    }else if( zIn[i+1]=='u' ){
      if( !isNHex(&zIn[i+2], 4, &v) ) goto unistr_error;
      i += 6;
      j += sqlite3AppendOneUtf8Character(&zOut[j], v);
    }else if( zIn[i+1]=='U' ){
      if( !isNHex(&zIn[i+2], 8, &v) ) goto unistr_error;
      i += 10;
      j += sqlite3AppendOneUtf8Character(&zOut[j], v);
    }else{
      goto unistr_error;
    }
  }
  zOut[j] = 0;
  sqlite3_result_text64(context, zOut, j, sqlite3_free, SQLITE_UTF8);
  return;

unistr_error:
  sqlite3_free(zOut);
  sqlite3_result_error(context, "invalid Unicode escape", -1);
  return;
}


/*
** Implementation of the QUOTE() function. 
**
** The quote(X) function returns the text of an SQL literal which is the
** value of its argument suitable for inclusion into an SQL statement.
** Strings are surrounded by single-quotes with escapes on interior quotes
** as needed. BLOBs are encoded as hexadecimal literals. Strings with
** embedded NUL characters cannot be represented as string literals in SQL
** and hence the returned string literal is truncated prior to the first NUL.
**
** If sqlite3_user_data() is non-zero, then the UNISTR_QUOTE() function is
** implemented instead.  The difference is that UNISTR_QUOTE() uses the
** UNISTR() function to escape control characters.
*/
static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  sqlite3_str str;
  sqlite3 *db = sqlite3_context_db_handle(context);
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  sqlite3QuoteValue(&str,argv[0],SQLITE_PTR_TO_INT(sqlite3_user_data(context)));
  sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
                      SQLITE_DYNAMIC);
  if( str.accError!=SQLITE_OK ){
    sqlite3_result_null(context);
    sqlite3_result_error_code(context, str.accError);
  }
}
2732
2733
2734
2735
2736
2737
2738

2739

2740
2741
2742
2743
2744
2745
2746
    INLINE_FUNC(ifnull,          2, INLINEFUNC_coalesce, 0 ),
    VFUNCTION(random,            0, 0, 0, randomFunc       ),
    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),

    FUNCTION(quote,              1, 0, 0, quoteFunc        ),

    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
    VFUNCTION(changes,           0, 0, 0, changes          ),
    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
    FUNCTION(substr,             2, 0, 0, substrFunc       ),
    FUNCTION(substr,             3, 0, 0, substrFunc       ),







>

>







2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
    INLINE_FUNC(ifnull,          2, INLINEFUNC_coalesce, 0 ),
    VFUNCTION(random,            0, 0, 0, randomFunc       ),
    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
    FUNCTION(unistr,             1, 0, 0, unistrFunc       ),
    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
    FUNCTION(unistr_quote,       1, 1, 0, quoteFunc        ),
    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
    VFUNCTION(changes,           0, 0, 0, changes          ),
    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
    FUNCTION(substr,             2, 0, 0, substrFunc       ),
    FUNCTION(substr,             3, 0, 0, substrFunc       ),
Changes to src/printf.c.
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
#define etSIZE        4 /* Return number of characters processed so far. %n */
#define etSTRING      5 /* Strings. %s */
#define etDYNSTRING   6 /* Dynamically allocated strings. %z */
#define etPERCENT     7 /* Percent symbol. %% */
#define etCHARX       8 /* Characters. %c */
/* The rest are extensions, not normally found in printf() */
#define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
                          NULL pointers replaced by SQL NULL.  %Q */
#define etTOKEN      11 /* a pointer to a Token structure */
#define etSRCITEM    12 /* a pointer to a SrcItem */
#define etPOINTER    13 /* The %p conversion */
#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
#define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
#define etDECIMAL    16 /* %d or %u, but not %x, %o */

#define etINVALID    17 /* Any unrecognized conversion type */


/*
** An "etByte" is an 8-bit unsigned value.
*/
typedef unsigned char etByte;








|
|
|
|
|
|
|
|
|

|







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
#define etSIZE        4 /* Return number of characters processed so far. %n */
#define etSTRING      5 /* Strings. %s */
#define etDYNSTRING   6 /* Dynamically allocated strings. %z */
#define etPERCENT     7 /* Percent symbol. %% */
#define etCHARX       8 /* Characters. %c */
/* The rest are extensions, not normally found in printf() */
#define etESCAPE_q    9  /* Strings with '\'' doubled.  %q */
#define etESCAPE_Q    10 /* Strings with '\'' doubled and enclosed in '',
                            NULL pointers replaced by SQL NULL.  %Q */
#define etTOKEN       11 /* a pointer to a Token structure */
#define etSRCITEM     12 /* a pointer to a SrcItem */
#define etPOINTER     13 /* The %p conversion */
#define etESCAPE_w    14 /* %w -> Strings with '\"' doubled */
#define etORDINAL     15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
#define etDECIMAL     16 /* %d or %u, but not %x, %o */

#define etINVALID     17 /* Any unrecognized conversion type */


/*
** An "etByte" is an 8-bit unsigned value.
*/
typedef unsigned char etByte;

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
static const char aPrefix[] = "-x0\000X0";
static const et_info fmtinfo[] = {
  {  'd', 10, 1, etDECIMAL,    0,  0 },
  {  's',  0, 4, etSTRING,     0,  0 },
  {  'g',  0, 1, etGENERIC,    30, 0 },
  {  'z',  0, 4, etDYNSTRING,  0,  0 },
  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
  {  'c',  0, 0, etCHARX,      0,  0 },
  {  'o',  8, 0, etRADIX,      0,  2 },
  {  'u', 10, 0, etDECIMAL,    0,  0 },
  {  'x', 16, 0, etRADIX,      16, 1 },
  {  'X', 16, 0, etRADIX,      0,  4 },
#ifndef SQLITE_OMIT_FLOATING_POINT
  {  'f',  0, 1, etFLOAT,      0,  0 },







|
|
|







70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
static const char aPrefix[] = "-x0\000X0";
static const et_info fmtinfo[] = {
  {  'd', 10, 1, etDECIMAL,    0,  0 },
  {  's',  0, 4, etSTRING,     0,  0 },
  {  'g',  0, 1, etGENERIC,    30, 0 },
  {  'z',  0, 4, etDYNSTRING,  0,  0 },
  {  'q',  0, 4, etESCAPE_q,   0,  0 },
  {  'Q',  0, 4, etESCAPE_Q,   0,  0 },
  {  'w',  0, 4, etESCAPE_w,   0,  0 },
  {  'c',  0, 0, etCHARX,      0,  0 },
  {  'o',  8, 0, etRADIX,      0,  2 },
  {  'u', 10, 0, etDECIMAL,    0,  0 },
  {  'x', 16, 0, etRADIX,      16, 1 },
  {  'X', 16, 0, etRADIX,      0,  4 },
#ifndef SQLITE_OMIT_FLOATING_POINT
  {  'f',  0, 1, etFLOAT,      0,  0 },
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
              }
            }
          }else{
            buf[0] = 0;
          }
        }else{
          unsigned int ch = va_arg(ap,unsigned int);
          if( ch<0x00080 ){
            buf[0] = ch & 0xff;
            length = 1;
          }else if( ch<0x00800 ){
            buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
            buf[1] = 0x80 + (u8)(ch & 0x3f);
            length = 2;
          }else if( ch<0x10000 ){
            buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
            buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
            buf[2] = 0x80 + (u8)(ch & 0x3f);
            length = 3;
          }else{
            buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
            buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
            buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
            buf[3] = 0x80 + (u8)(ch & 0x3f);
            length = 4;
          }
        }
        if( precision>1 ){
          i64 nPrior = 1;
          width -= precision-1;
          if( width>1 && !flag_leftjustify ){
            sqlite3_str_appendchar(pAccum, width-1, ' ');
            width = 0;







<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







669
670
671
672
673
674
675


676
















677
678
679
680
681
682
683
              }
            }
          }else{
            buf[0] = 0;
          }
        }else{
          unsigned int ch = va_arg(ap,unsigned int);


          length = sqlite3AppendOneUtf8Character(buf, ch);
















        }
        if( precision>1 ){
          i64 nPrior = 1;
          width -= precision-1;
          if( width>1 && !flag_leftjustify ){
            sqlite3_str_appendchar(pAccum, width-1, ' ');
            width = 0;
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781

782
783
784
785
786
787
788
789









790
791
792
793
794
795
796
797
798
799
800
801


















802





803
804
805
806
807
808
809
810
811







812

813
814
















815
816

817



818
819
820
821
822
823
824
      adjust_width_for_utf8:
        if( flag_altform2 && width>0 ){
          /* Adjust width to account for extra bytes in UTF-8 characters */
          int ii = length - 1;
          while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
        }
        break;
      case etSQLESCAPE:           /* %q: Escape ' characters */
      case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */
      case etSQLESCAPE3: {        /* %w: Escape " characters */
        i64 i, j, k, n;
        int needQuote, isnull;
        char ch;
        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
        char *escarg;


        if( bArgList ){
          escarg = getTextArg(pArgList);
        }else{
          escarg = va_arg(ap,char*);
        }
        isnull = escarg==0;
        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");









        /* For %q, %Q, and %w, the precision is the number of bytes (or
        ** characters if the ! flags is present) to use from the input.
        ** Because of the extra quoting characters inserted, the number
        ** of output characters may be larger than the precision.
        */
        k = precision;
        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
          if( ch==q )  n++;
          if( flag_altform2 && (ch&0xc0)==0xc0 ){
            while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
          }
        }


















        needQuote = !isnull && xtype==etSQLESCAPE2;





        n += i + 3;
        if( n>etBUFSIZE ){
          bufpt = zExtra = printfTempBuf(pAccum, n);
          if( bufpt==0 ) return;
        }else{
          bufpt = buf;
        }
        j = 0;
        if( needQuote ) bufpt[j++] = q;







        k = i;

        for(i=0; i<k; i++){
          bufpt[j++] = ch = escarg[i];
















          if( ch==q ) bufpt[j++] = ch;
        }

        if( needQuote ) bufpt[j++] = q;



        bufpt[j] = 0;
        length = j;
        goto adjust_width_for_utf8;
      }
      case etTOKEN: {
        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
        if( flag_alternateform ){







|
|
|

|

<

>






|
|
>
>
>
>
>
>
>
>
>












>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>








|
>
>
>
>
>
>
>

>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
|
>
>
>







749
750
751
752
753
754
755
756
757
758
759
760
761

762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
      adjust_width_for_utf8:
        if( flag_altform2 && width>0 ){
          /* Adjust width to account for extra bytes in UTF-8 characters */
          int ii = length - 1;
          while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
        }
        break;
      case etESCAPE_q:          /* %q: Escape ' characters */
      case etESCAPE_Q:          /* %Q: Escape ' and enclose in '...' */
      case etESCAPE_w: {        /* %w: Escape " characters */
        i64 i, j, k, n;
        int needQuote = 0;
        char ch;

        char *escarg;
        char q;

        if( bArgList ){
          escarg = getTextArg(pArgList);
        }else{
          escarg = va_arg(ap,char*);
        }
        if( escarg==0 ){
          escarg = (xtype==etESCAPE_Q ? "NULL" : "(NULL)");
        }else if( xtype==etESCAPE_Q ){
          needQuote = 1;
        }
        if( xtype==etESCAPE_w ){
          q = '"';
          flag_alternateform = 0;
        }else{
          q = '\'';
        }
        /* For %q, %Q, and %w, the precision is the number of bytes (or
        ** characters if the ! flags is present) to use from the input.
        ** Because of the extra quoting characters inserted, the number
        ** of output characters may be larger than the precision.
        */
        k = precision;
        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
          if( ch==q )  n++;
          if( flag_altform2 && (ch&0xc0)==0xc0 ){
            while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
          }
        }
        if( flag_alternateform ){
          /* For %#q, do unistr()-style backslash escapes for
          ** all control characters, and for backslash itself.
          ** For %#Q, do the same but only if there is at least
          ** one control character. */
          u32 nBack = 0;
          u32 nCtrl = 0;
          for(k=0; k<i; k++){
            if( escarg[k]=='\\' ){
              nBack++;
            }else if( escarg[k]<=0x1f ){
              nCtrl++;
            }
          }
          if( nCtrl || xtype==etESCAPE_q ){
            n += nBack + 5*nCtrl;
            if( xtype==etESCAPE_Q ){
              n += 10;
              needQuote = 2;
            }
          }else{
            flag_alternateform = 0;
          }
        }
        n += i + 3;
        if( n>etBUFSIZE ){
          bufpt = zExtra = printfTempBuf(pAccum, n);
          if( bufpt==0 ) return;
        }else{
          bufpt = buf;
        }
        j = 0;
        if( needQuote ){
          if( needQuote==2 ){
            memcpy(&bufpt[j], "unistr('", 8);
            j += 8;
          }else{
            bufpt[j++] = '\'';
          }
        }
        k = i;
        if( flag_alternateform ){
          for(i=0; i<k; i++){
            bufpt[j++] = ch = escarg[i];
            if( ch==q ){
              bufpt[j++] = ch;
            }else if( ch=='\\' ){
              bufpt[j++] = '\\';
            }else if( ch<=0x1f ){
              bufpt[j-1] = '\\';
              bufpt[j++] = 'u';
              bufpt[j++] = '0';
              bufpt[j++] = '0';
              bufpt[j++] = ch>=0x10 ? '1' : '0';
              bufpt[j++] = "0123456789abcdef"[ch&0xf];
            }
          }
        }else{
          for(i=0; i<k; i++){
            bufpt[j++] = ch = escarg[i];
            if( ch==q ) bufpt[j++] = ch;
          }
        }
        if( needQuote ){
          bufpt[j++] = '\'';
          if( needQuote==2 ) bufpt[j++] = ')';
        }
        bufpt[j] = 0;
        length = j;
        goto adjust_width_for_utf8;
      }
      case etTOKEN: {
        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
        if( flag_alternateform ){
Changes to src/shell.c.in.
1442
1443
1444
1445
1446
1447
1448

1449
1450
1451
1452
1453
1454
1455
  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
  u8 nEqpLevel;          /* Depth of the EQP output graph */
  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
  u8 bSafeMode;          /* True to prohibit unsafe operations */
  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
  u8 eRestoreState;      /* See comments above doAutoDetectRestore() */
  u8 crlfMode;           /* Do NL-to-CRLF translations when enabled (maybe) */

  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
  unsigned statsOn;      /* True to display memory stats before each finalize */
  unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
  int inputNesting;      /* Track nesting level of .read and other redirects */
  int outCount;          /* Revert to stdout when reaching zero */
  int cnt;               /* Number of records displayed so far */
  int lineno;            /* Line number of last line read from in */







>







1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
  u8 nEqpLevel;          /* Depth of the EQP output graph */
  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
  u8 bSafeMode;          /* True to prohibit unsafe operations */
  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
  u8 eRestoreState;      /* See comments above doAutoDetectRestore() */
  u8 crlfMode;           /* Do NL-to-CRLF translations when enabled (maybe) */
  u8 eEscMode;           /* Escape mode for text output */
  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
  unsigned statsOn;      /* True to display memory stats before each finalize */
  unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
  int inputNesting;      /* Track nesting level of .read and other redirects */
  int outCount;          /* Revert to stdout when reaching zero */
  int cnt;               /* Number of records displayed so far */
  int lineno;            /* Line number of last line read from in */
1542
1543
1544
1545
1546
1547
1548








1549
1550
1551
1552
1553
1554
1555
/* Bits in the ShellState.flgProgress variable */
#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
                                   ** callback limit is reached, and for each
                                   ** top-level SQL statement */
#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */









/*
** These are the allowed shellFlgs values
*/
#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */







>
>
>
>
>
>
>
>







1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
/* Bits in the ShellState.flgProgress variable */
#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
                                   ** callback limit is reached, and for each
                                   ** top-level SQL statement */
#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */

/* Allowed values for ShellState.eEscMode
*/
#define SHELL_ESC_SYMBOL       0      /* Substitute U+2400 graphics */
#define SHELL_ESC_ASCII        1      /* Substitute ^Y for X where Y=X+0x40 */
#define SHELL_ESC_OFF          2      /* Send characters verbatim */

static const char *shell_EscModeNames[] = { "symbol", "ascii", "off" };

/*
** These are the allowed shellFlgs values
*/
#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892

1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907

1908
1909

1910
1911
1912



1913
1914
1915
1916
1917
1918









1919




1920



1921

1922
1923
1924





1925
1926
1927
1928

1929
1930
1931
1932
1933
1934
1935
1936
1937



1938

1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
  zStr[i*2] = '\0';

  sqlite3_fprintf(out, "X'%s'", zStr);
  sqlite3_free(zStr);
}

/*
** Find a string that is not found anywhere in z[].  Return a pointer
** to that string.
**
** Try to use zA and zB first.  If both of those are already found in z[]
** then make up some string and store it in the buffer zBuf.
*/
static const char *unused_string(

  const char *z,                    /* Result must not appear anywhere in z */
  const char *zA, const char *zB,   /* Try these first */
  char *zBuf                        /* Space to store a generated string */
){
  unsigned i = 0;
  if( strstr(z, zA)==0 ) return zA;
  if( strstr(z, zB)==0 ) return zB;
  do{
    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  }while( strstr(z,zBuf)!=0 );
  return zBuf;
}

/*
** Output the given string as a quoted string using SQL quoting conventions.

**
** See also: output_quoted_escaped_string()

*/
static void output_quoted_string(ShellState *p, const char *z){
  int i;



  char c;
  FILE *out = p->out;
  sqlite3_fsetmode(out, _O_BINARY);
  if( z==0 ) return;
  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  if( c==0 ){









    sqlite3_fprintf(out, "'%s'",z);




  }else{



    sqlite3_fputs("'", out);

    while( *z ){
      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
      if( c=='\'' ) i++;





      if( i ){
        sqlite3_fprintf(out, "%.*s", i, z);
        z += i;
      }

      if( c=='\'' ){
        sqlite3_fputs("'", out);
        continue;
      }
      if( c==0 ){
        break;
      }
      z++;
    }



    sqlite3_fputs("'", out);

  }
  setCrlfMode(p);
}

/*
** Output the given string as a quoted string using SQL quoting conventions.
** Additionallly , escape the "\n" and "\r" characters so that they do not
** get corrupted by end-of-line translation facilities in some operating
** systems.
**
** This is like output_quoted_string() but with the addition of the \r\n
** escape mechanism.
*/
static void output_quoted_escaped_string(ShellState *p, const char *z){
  int i;
  char c;
  FILE *out = p->out;
  sqlite3_fsetmode(out, _O_BINARY);
  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  if( c==0 ){
    sqlite3_fprintf(out, "'%s'",z);
  }else{
    const char *zNL = 0;
    const char *zCR = 0;
    int nNL = 0;
    int nCR = 0;
    char zBuf1[20], zBuf2[20];
    for(i=0; z[i]; i++){
      if( z[i]=='\n' ) nNL++;
      if( z[i]=='\r' ) nCR++;
    }
    if( nNL ){
      sqlite3_fputs("replace(", out);
      zNL = unused_string(z, "\\n", "\\012", zBuf1);
    }
    if( nCR ){
      sqlite3_fputs("replace(", out);
      zCR = unused_string(z, "\\r", "\\015", zBuf2);
    }
    sqlite3_fputs("'", out);
    while( *z ){
      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
      if( c=='\'' ) i++;
      if( i ){
        sqlite3_fprintf(out, "%.*s", i, z);
        z += i;
      }
      if( c=='\'' ){
        sqlite3_fputs("'", out);
        continue;
      }
      if( c==0 ){
        break;
      }
      z++;
      if( c=='\n' ){
        sqlite3_fputs(zNL, out);
        continue;
      }
      sqlite3_fputs(zCR, out);
    }
    sqlite3_fputs("'", out);
    if( nCR ){
      sqlite3_fprintf(out, ",'%s',char(13))", zCR);
    }
    if( nNL ){
      sqlite3_fprintf(out, ",'%s',char(10))", zNL);
    }
  }
  setCrlfMode(p);
}

/*
** Find earliest of chars within s specified in zAny.
** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
*/







<
|

<
|
<
|
>
|
<
<
<
<
<
<
<
<
<
<
<
|
|
<
>

|
>

|

>
>
>
|



|
|
>
>
>
>
>
>
>
>
>

>
>
>
>

>
>
>
|
>

|
|
>
>
>
>
>




>

|
<
|
|
<



>
>
>
|
>














<
|
<
|
<
|
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
|
<
<
|
<
<
<
<
<
<
<
<
<







1888
1889
1890
1891
1892
1893
1894

1895
1896

1897

1898
1899
1900











1901
1902

1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953

1954
1955

1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977

1978

1979

1980
1981
1982

















1983






1984









1985


1986









1987
1988
1989
1990
1991
1992
1993
  zStr[i*2] = '\0';

  sqlite3_fprintf(out, "X'%s'", zStr);
  sqlite3_free(zStr);
}

/*

** Output the given string as a quoted string using SQL quoting conventions:
**

**   (1)   Single quotes (') within the string are doubled

**   (2)   The whle string is enclosed in '...'
**   (3)   Control characters other than \n, \t, and \r\n are escaped
**         using \u00XX notation and if such substitutions occur,











**         the whole string is enclosed in unistr('...') instead of '...'.
**         

** Step (3) is omitted if the control-character escape mode is OFF.
**
** See also: output_quoted_escaped_string() which does the same except
** that it does not make exceptions for \n, \t, and \r\n in step (3).
*/
static void output_quoted_string(ShellState *p, const char *zInX){
  int i;
  int needUnistr = 0;
  int needDblQuote = 0;
  const unsigned char *z = (const unsigned char*)zInX;
  unsigned char c;
  FILE *out = p->out;
  sqlite3_fsetmode(out, _O_BINARY);
  if( z==0 ) return;
  for(i=0; (c = z[i])!=0; i++){
    if( c=='\'' ){ needDblQuote = 1; }
    if( c>0x1f ) continue;
    if( c=='\t' || c=='\n' ) continue;
    if( c=='\r' && z[i+1]=='\n' ) continue;
    needUnistr = 1;
    break;
  }
  if( (needDblQuote==0 && needUnistr==0)
   || (needDblQuote==0 && p->eEscMode==SHELL_ESC_OFF)
  ){
    sqlite3_fprintf(out, "'%s'",z);
  }else if( p->eEscMode==SHELL_ESC_OFF ){
    char *zEncoded = sqlite3_mprintf("%Q", z);
    sqlite3_fputs(zEncoded, out);
    sqlite3_free(zEncoded);
  }else{
    if( needUnistr ){
      sqlite3_fputs("unistr('", out);
    }else{
      sqlite3_fputs("'", out);
    }
    while( *z ){
      for(i=0; (c = z[i])!=0; i++){
        if( c=='\'' ) break;
        if( c>0x1f ) continue;
        if( c=='\t' || c=='\n' ) continue;
        if( c=='\r' && z[i+1]=='\n' ) continue;
        break;
      }
      if( i ){
        sqlite3_fprintf(out, "%.*s", i, z);
        z += i;
      }
      if( c==0 ) break;
      if( c=='\'' ){
        sqlite3_fputs("''", out);

      }else{
        sqlite3_fprintf(out, "\\u%04x", c);

      }
      z++;
    }
    if( needUnistr ){
      sqlite3_fputs("')", out);
    }else{
      sqlite3_fputs("'", out);
    }
  }
  setCrlfMode(p);
}

/*
** Output the given string as a quoted string using SQL quoting conventions.
** Additionallly , escape the "\n" and "\r" characters so that they do not
** get corrupted by end-of-line translation facilities in some operating
** systems.
**
** This is like output_quoted_string() but with the addition of the \r\n
** escape mechanism.
*/
static void output_quoted_escaped_string(ShellState *p, const char *z){

  char *zEscaped;

  sqlite3_fsetmode(p->out, _O_BINARY);

  if( p->eEscMode==SHELL_ESC_OFF ){
    zEscaped = sqlite3_mprintf("%Q", z);
  }else{

















    zEscaped = sqlite3_mprintf("%#Q", z);






  }









  sqlite3_fputs(zEscaped, p->out);


  sqlite3_free(zEscaped);









  setCrlfMode(p);
}

/*
** Find earliest of chars within s specified in zAny.
** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
*/
2149
2150
2151
2152
2153
2154
2155























































































2156
2157
2158
2159
2160
2161
2162
    }else{
      ace[1] = (char)c;
      sqlite3_fputs(ace+1, out);
    }
  }
  sqlite3_fputs(zq, out);
}
























































































/*
** Output the given string with characters that are special to
** HTML escaped.
*/
static void output_html_string(FILE *out, const char *z){
  int i;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
    }else{
      ace[1] = (char)c;
      sqlite3_fputs(ace+1, out);
    }
  }
  sqlite3_fputs(zq, out);
}

/*
** Escape the input string if it is needed and in accordance with
** eEscMode.
**
** Escaping is needed if the string contains any control characters
** other than \t, \n, and \r\n
**
** If no escaping is needed (the common case) then set *ppFree to NULL
** and return the original string.  If escapingn is needed, write the
** escaped string into memory obtained from sqlite3_malloc64() or the
** equivalent, and return the new string and set *ppFree to the new string
** as well.
**
** The caller is responsible for freeing *ppFree if it is non-NULL in order
** to reclaim memory.
*/
static const char *escapeOutput(
  ShellState *p,
  const char *zInX,
  char **ppFree
){
  i64 i, j;
  i64 nCtrl = 0;
  unsigned char *zIn;
  unsigned char c;
  unsigned char *zOut;


  /* No escaping if disabled */
  if( p->eEscMode==SHELL_ESC_OFF ){
    *ppFree = 0;
     return zInX;
  }

  /* Count the number of control characters in the string. */
  zIn = (unsigned char*)zInX;
  for(i=0; (c = zIn[i])!=0; i++){
    if( c<=0x1f
     && c!='\t'
     && c!='\n'
     && (c!='\r' || zIn[i+1]!='\n')
    ){
      nCtrl++;
    }
  }
  if( nCtrl==0 ){
    *ppFree = 0;
    return zInX;
  }
  if( p->eEscMode==SHELL_ESC_SYMBOL ) nCtrl *= 2;
  zOut = sqlite3_malloc64( i + nCtrl + 1 );
  shell_check_oom(zOut);
  for(i=j=0; (c = zIn[i])!=0; i++){
    if( c>0x1f
     || c=='\t'
     || c=='\n'
     || (c=='\r' && zIn[i+1]=='\n')
    ){
      continue;
    }
    if( i>0 ){
      memcpy(&zOut[j], zIn, i);
      j += i;
    }
    zIn += i+1;
    i = -1;
    switch( p->eEscMode ){
      case SHELL_ESC_SYMBOL: 
        zOut[j++] = 0xe2;
        zOut[j++] = 0x90;
        zOut[j++] = 0x80+c;
        break;
      case SHELL_ESC_ASCII:
        zOut[j++] = '^';
        zOut[j++] = 0x40+c;
        break;
    }
  }
  if( i>0 ){
    memcpy(&zOut[j], zIn, i);
    j += i;
  }
  zOut[j] = 0;
  *ppFree = (char*)zOut;
  return (char*)zOut;
}

/*
** Output the given string with characters that are special to
** HTML escaped.
*/
static void output_html_string(FILE *out, const char *z){
  int i;
2593
2594
2595
2596
2597
2598
2599



2600
2601

2602
2603
2604
2605
2606
2607
2608
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        int len = strlen30(azCol[i] ? azCol[i] : "");
        if( len>w ) w = len;
      }
      if( p->cnt++>0 ) sqlite3_fputs(p->rowSeparator, p->out);
      for(i=0; i<nArg; i++){



        sqlite3_fprintf(p->out, "%*s = %s%s", w, azCol[i],
              azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);

      }
      break;
    }
    case MODE_ScanExp:
    case MODE_Explain: {
      static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
      static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };







>
>
>

|
>







2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        int len = strlen30(azCol[i] ? azCol[i] : "");
        if( len>w ) w = len;
      }
      if( p->cnt++>0 ) sqlite3_fputs(p->rowSeparator, p->out);
      for(i=0; i<nArg; i++){
        char *pFree = 0;
        const char *pDisplay;
        pDisplay = escapeOutput(p, azArg[i] ? azArg[i] : p->nullValue, &pFree);
        sqlite3_fprintf(p->out, "%*s = %s%s", w, azCol[i],
                        pDisplay, p->rowSeparator);
        if( pFree ) sqlite3_free(pFree);
      }
      break;
    }
    case MODE_ScanExp:
    case MODE_Explain: {
      static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
      static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
2726
2727
2728
2729
2730
2731
2732



2733
2734

2735
2736
2737
2738
2739


2740

2741

2742
2743
2744
2745
2746
2747
2748
      printSchemaLine(p->out, z, ";\n");
      sqlite3_free(z);
      break;
    }
    case MODE_List: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){



          sqlite3_fprintf(p->out, "%s%s", azCol[i],
                          i==nArg-1 ? p->rowSeparator : p->colSeparator);

        }
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        char *z = azArg[i];


        if( z==0 ) z = p->nullValue;

        sqlite3_fputs(z, p->out);

        sqlite3_fputs((i<nArg-1)? p->colSeparator : p->rowSeparator, p->out);
      }
      break;
    }
    case MODE_Www:
    case MODE_Html: {
      if( p->cnt==0 && p->cMode==MODE_Www ){







>
>
>
|

>





>
>

>
|
>







2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
      printSchemaLine(p->out, z, ";\n");
      sqlite3_free(z);
      break;
    }
    case MODE_List: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
          char *z = azCol[i];
          char *pFree;
          const char *zOut = escapeOutput(p, z, &pFree);
          sqlite3_fprintf(p->out, "%s%s", zOut,
                          i==nArg-1 ? p->rowSeparator : p->colSeparator);
          if( pFree ) sqlite3_free(pFree);
        }
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        char *z = azArg[i];
        char *pFree;
        const char *zOut;
        if( z==0 ) z = p->nullValue;
        zOut = escapeOutput(p, z, &pFree);
        sqlite3_fputs(zOut, p->out);
        if( pFree ) sqlite3_free(pFree);
        sqlite3_fputs((i<nArg-1)? p->colSeparator : p->rowSeparator, p->out);
      }
      break;
    }
    case MODE_Www:
    case MODE_Html: {
      if( p->cnt==0 && p->cMode==MODE_Www ){
3853
3854
3855
3856
3857
3858
3859

3860
3861
3862
3863
3864
3865
3866
** Compute characters to display on the first line of z[].  Stop at the
** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
** from malloc()) of that first line, which caller should free sometime.
** Write anything to display on the next line into *pzTail.  If this is
** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
*/
static char *translateForDisplayAndDup(

  const unsigned char *z,            /* Input text to be transformed */
  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
  int mxWidth,                       /* Max width.  0 means no limit */
  u8 bWordWrap                       /* If true, avoid breaking mid-word */
){
  int i;                 /* Input bytes consumed */
  int j;                 /* Output bytes generated */







>







3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
** Compute characters to display on the first line of z[].  Stop at the
** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
** from malloc()) of that first line, which caller should free sometime.
** Write anything to display on the next line into *pzTail.  If this is
** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
*/
static char *translateForDisplayAndDup(
  ShellState *p,                     /* To access current settings */
  const unsigned char *z,            /* Input text to be transformed */
  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
  int mxWidth,                       /* Max width.  0 means no limit */
  u8 bWordWrap                       /* If true, avoid breaking mid-word */
){
  int i;                 /* Input bytes consumed */
  int j;                 /* Output bytes generated */
3887
3888
3889
3890
3891
3892
3893

3894
3895
3896
3897
3898
3899
3900
3901
3902



3903
3904
3905
3906
3907
3908
3909
    }
    if( c>=' ' ){
      n++;
      i++;
      j++;
      continue;
    }

    if( c=='\t' ){
      do{
        n++;
        j++;
      }while( (n&7)!=0 && n<mxWidth );
      i++;
      continue;
    }
    break;



  }
  if( n>=mxWidth && bWordWrap  ){
    /* Perhaps try to back up to a better place to break the line */
    for(k=i; k>i/2; k--){
      if( isspace(z[k-1]) ) break;
    }
    if( k<=i/2 ){







>








<
>
>
>







3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981

3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
    }
    if( c>=' ' ){
      n++;
      i++;
      j++;
      continue;
    }
    if( c==0 || c=='\n' || (c=='\r' && z[i+1]=='\n') ) break;
    if( c=='\t' ){
      do{
        n++;
        j++;
      }while( (n&7)!=0 && n<mxWidth );
      i++;
      continue;
    }

    n++;
    j += 3;
    i++;
  }
  if( n>=mxWidth && bWordWrap  ){
    /* Perhaps try to back up to a better place to break the line */
    for(k=i; k>i/2; k--){
      if( isspace(z[k-1]) ) break;
    }
    if( k<=i/2 ){
3942
3943
3944
3945
3946
3947
3948

3949
3950
3951
3952
3953
3954
3955
3956





3957









3958
3959
3960
3961










3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977

3978
3979
3980
3981
3982
3983
3984
      continue;
    }
    if( c>=' ' ){
      n++;
      zOut[j++] = z[i++];
      continue;
    }

    if( z[i]=='\t' ){
      do{
        n++;
        zOut[j++] = ' ';
      }while( (n&7)!=0 && n<mxWidth );
      i++;
      continue;
    }





    break;









  }
  zOut[j] = 0;
  return (char*)zOut;
}











/* Extract the value of the i-th current column for pStmt as an SQL literal
** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
** the caller.
*/
static char *quoted_column(sqlite3_stmt *pStmt, int i){
  switch( sqlite3_column_type(pStmt, i) ){
    case SQLITE_NULL: {
      return sqlite3_mprintf("NULL");
    }
    case SQLITE_INTEGER:
    case SQLITE_FLOAT: {
      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
    }
    case SQLITE_TEXT: {
      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));

    }
    case SQLITE_BLOB: {
      int j;
      sqlite3_str *pStr = sqlite3_str_new(0);
      const unsigned char *a = sqlite3_column_blob(pStmt,i);
      int n = sqlite3_column_bytes(pStmt,i);
      sqlite3_str_append(pStr, "x'", 2);







>








>
>
>
>
>
|
>
>
>
>
>
>
>
>
>




>
>
>
>
>
>
>
>
>
>















|
>







4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
      continue;
    }
    if( c>=' ' ){
      n++;
      zOut[j++] = z[i++];
      continue;
    }
    if( c==0 ) break;
    if( z[i]=='\t' ){
      do{
        n++;
        zOut[j++] = ' ';
      }while( (n&7)!=0 && n<mxWidth );
      i++;
      continue;
    }
    switch( p->eEscMode ){
      case SHELL_ESC_SYMBOL:
        zOut[j++] = 0xe2;
        zOut[j++] = 0x90;
        zOut[j++] = 0x80 + c;
        break;
      case SHELL_ESC_ASCII:
        zOut[j++] = '^';
        zOut[j++] = 0x40 + c;
        break;
      case SHELL_ESC_OFF:
        zOut[j++] = c;
        break;
    }
    i++;
  }
  zOut[j] = 0;
  return (char*)zOut;
}

/* Return true if the text string z[] contains characters that need
** unistr() escaping.
*/
static int needUnistr(const unsigned char *z){
  unsigned char c;
  if( z==0 ) return 0;
  while( (c = *z)>0x1f || c=='\t' || c=='\n' || (c=='\r' && z[1]=='\n') ){ z++; }
  return c!=0;
}

/* Extract the value of the i-th current column for pStmt as an SQL literal
** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
** the caller.
*/
static char *quoted_column(sqlite3_stmt *pStmt, int i){
  switch( sqlite3_column_type(pStmt, i) ){
    case SQLITE_NULL: {
      return sqlite3_mprintf("NULL");
    }
    case SQLITE_INTEGER:
    case SQLITE_FLOAT: {
      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
    }
    case SQLITE_TEXT: {
      const unsigned char *zText = sqlite3_column_text(pStmt,i);
      return sqlite3_mprintf(needUnistr(zText)?"%#Q":"%Q",zText);
    }
    case SQLITE_BLOB: {
      int j;
      sqlite3_str *pStr = sqlite3_str_new(0);
      const unsigned char *a = sqlite3_column_blob(pStmt,i);
      int n = sqlite3_column_bytes(pStmt,i);
      sqlite3_str_append(pStr, "x'", 2);
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
    int wx = p->colWidth[i];
    if( wx==0 ){
      wx = p->cmOpts.iWrap;
    }
    if( wx<0 ) wx = -wx;
    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
    if( uz==0 ) uz = (u8*)"";
    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
  }
  do{
    int useNextLine = bNextLine;
    bNextLine = 0;
    if( (nRow+2)*nColumn >= nAlloc ){
      nAlloc *= 2;
      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));







|







4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
    int wx = p->colWidth[i];
    if( wx==0 ){
      wx = p->cmOpts.iWrap;
    }
    if( wx<0 ) wx = -wx;
    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
    if( uz==0 ) uz = (u8*)"";
    azData[i] = translateForDisplayAndDup(p, uz, &zNotUsed, wx, bw);
  }
  do{
    int useNextLine = bNextLine;
    bNextLine = 0;
    if( (nRow+2)*nColumn >= nAlloc ){
      nAlloc *= 2;
      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
4086
4087
4088
4089
4090
4091
4092

4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
        wx = p->cmOpts.iWrap;
      }
      if( wx<0 ) wx = -wx;
      if( useNextLine ){
        uz = azNextLine[i];
        if( uz==0 ) uz = (u8*)zEmpty;
      }else if( p->cmOpts.bQuote ){

        sqlite3_free(azQuoted[i]);
        azQuoted[i] = quoted_column(pStmt,i);
        uz = (const unsigned char*)azQuoted[i];
      }else{
        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
        if( uz==0 ) uz = (u8*)zShowNull;
      }
      azData[nRow*nColumn + i]
        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
      if( azNextLine[i] ){
        bNextLine = 1;
        abRowDiv[nRow-1] = 0;
        bMultiLineRowExists = 1;
      }
    }
  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );







>








|







4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
        wx = p->cmOpts.iWrap;
      }
      if( wx<0 ) wx = -wx;
      if( useNextLine ){
        uz = azNextLine[i];
        if( uz==0 ) uz = (u8*)zEmpty;
      }else if( p->cmOpts.bQuote ){
        assert( azQuoted!=0 );
        sqlite3_free(azQuoted[i]);
        azQuoted[i] = quoted_column(pStmt,i);
        uz = (const unsigned char*)azQuoted[i];
      }else{
        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
        if( uz==0 ) uz = (u8*)zShowNull;
      }
      azData[nRow*nColumn + i]
        = translateForDisplayAndDup(p, uz, &azNextLine[i], wx, bw);
      if( azNextLine[i] ){
        bNextLine = 1;
        abRowDiv[nRow-1] = 0;
        bMultiLineRowExists = 1;
      }
    }
  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
9775
9776
9777
9778
9779
9780
9781

9782
9783
9784
9785
9786

9787
9788

9789
9790

9791
9792

9793
9794






















9795
9796
9797
9798
9799

9800
9801
9802
9803
9804
9805
9806
9807
9808
9809

9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828

9829
9830
9831


9832
9833
9834



9835


9836

9837
9838
9839
9840
9841
9842
9843
    }
  }else

  if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
    const char *zMode = 0;
    const char *zTabname = 0;
    int i, n2;

    ColModeOpts cmOpts = ColModeOpts_default;
    for(i=1; i<nArg; i++){
      const char *z = azArg[i];
      if( optionMatch(z,"wrap") && i+1<nArg ){
        cmOpts.iWrap = integerValue(azArg[++i]);

      }else if( optionMatch(z,"ww") ){
        cmOpts.bWordWrap = 1;

      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);

      }else if( optionMatch(z,"quote") ){
        cmOpts.bQuote = 1;

      }else if( optionMatch(z,"noquote") ){
        cmOpts.bQuote = 0;






















      }else if( zMode==0 ){
        zMode = z;
        /* Apply defaults for qbox pseudo-mode.  If that
         * overwrites already-set values, user was informed of this.
         */

        if( cli_strcmp(z, "qbox")==0 ){
          ColModeOpts cmo = ColModeOpts_default_qbox;
          zMode = "box";
          cmOpts = cmo;
        }
      }else if( zTabname==0 ){
        zTabname = z;
      }else if( z[0]=='-' ){
        sqlite3_fprintf(stderr,"unknown option: %s\n", z);
        eputz("options:\n"

              "  --noquote\n"
              "  --quote\n"
              "  --wordwrap on/off\n"
              "  --wrap N\n"
              "  --ww\n");
        rc = 1;
        goto meta_command_exit;
      }else{
        sqlite3_fprintf(stderr,"extra argument: \"%s\"\n", z);
        rc = 1;
        goto meta_command_exit;
      }
    }
    if( zMode==0 ){
      if( p->mode==MODE_Column
       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
      ){
        sqlite3_fprintf(p->out,
              "current output mode: %s --wrap %d --wordwrap %s --%squote\n",

              modeDescr[p->mode], p->cmOpts.iWrap,
              p->cmOpts.bWordWrap ? "on" : "off",
              p->cmOpts.bQuote ? "" : "no");


      }else{
        sqlite3_fprintf(p->out,
              "current output mode: %s\n", modeDescr[p->mode]);



      }


      zMode = modeDescr[p->mode];

    }
    n2 = strlen30(zMode);
    if( cli_strncmp(zMode,"lines",n2)==0 ){
      p->mode = MODE_Line;
      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
    }else if( cli_strncmp(zMode,"columns",n2)==0 ){
      p->mode = MODE_Column;







>





>


>


>


>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





>










>













|




|
>


|
>
>


|
>
>
>

>
>

>







9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
    }
  }else

  if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
    const char *zMode = 0;
    const char *zTabname = 0;
    int i, n2;
    int chng = 0;       /* 0x01:  change to cmopts.  0x02:  Any other change */
    ColModeOpts cmOpts = ColModeOpts_default;
    for(i=1; i<nArg; i++){
      const char *z = azArg[i];
      if( optionMatch(z,"wrap") && i+1<nArg ){
        cmOpts.iWrap = integerValue(azArg[++i]);
        chng |= 1;
      }else if( optionMatch(z,"ww") ){
        cmOpts.bWordWrap = 1;
        chng |= 1;
      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
        chng |= 1;
      }else if( optionMatch(z,"quote") ){
        cmOpts.bQuote = 1;
        chng |= 1;
      }else if( optionMatch(z,"noquote") ){
        cmOpts.bQuote = 0;
        chng |= 1;
      }else if( optionMatch(z,"escape") && i+1<nArg ){
        /* See similar code at tag-20250224-1 */
        const char *zEsc = azArg[++i];
        int k;
        for(k=0; k<ArraySize(shell_EscModeNames); k++){
          if( sqlite3_stricmp(zEsc,shell_EscModeNames[k])==0 ){
            p->eEscMode = k;
            chng |= 2;
            break;
          }
        }
        if( k>=ArraySize(shell_EscModeNames) ){
          sqlite3_fprintf(stderr, "unknown control character escape mode \"%s\""
                                  " - choices:", zEsc);
          for(k=0; k<ArraySize(shell_EscModeNames); k++){
            sqlite3_fprintf(stderr, " %s", shell_EscModeNames[k]);
          }
          sqlite3_fprintf(stderr, "\n");
          rc = 1;
          goto meta_command_exit;
        }
      }else if( zMode==0 ){
        zMode = z;
        /* Apply defaults for qbox pseudo-mode.  If that
         * overwrites already-set values, user was informed of this.
         */
        chng |= 1;
        if( cli_strcmp(z, "qbox")==0 ){
          ColModeOpts cmo = ColModeOpts_default_qbox;
          zMode = "box";
          cmOpts = cmo;
        }
      }else if( zTabname==0 ){
        zTabname = z;
      }else if( z[0]=='-' ){
        sqlite3_fprintf(stderr,"unknown option: %s\n", z);
        eputz("options:\n"
              "  --escape MODE\n"
              "  --noquote\n"
              "  --quote\n"
              "  --wordwrap on/off\n"
              "  --wrap N\n"
              "  --ww\n");
        rc = 1;
        goto meta_command_exit;
      }else{
        sqlite3_fprintf(stderr,"extra argument: \"%s\"\n", z);
        rc = 1;
        goto meta_command_exit;
      }
    }
    if( !chng ){
      if( p->mode==MODE_Column
       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
      ){
        sqlite3_fprintf(p->out,
              "current output mode: %s --wrap %d --wordwrap %s "
              "--%squote --escape %s\n",
              modeDescr[p->mode], p->cmOpts.iWrap,
              p->cmOpts.bWordWrap ? "on" : "off",
              p->cmOpts.bQuote ? "" : "no",
              shell_EscModeNames[p->eEscMode]
        );
      }else{
        sqlite3_fprintf(p->out,
              "current output mode: %s --escape %s\n",
              modeDescr[p->mode],
              shell_EscModeNames[p->eEscMode]
        );
      }
    }
    if( zMode==0 ){
      zMode = modeDescr[p->mode];
      if( (chng&1)==0 ) cmOpts = p->cmOpts;
    }
    n2 = strlen30(zMode);
    if( cli_strncmp(zMode,"lines",n2)==0 ){
      p->mode = MODE_Line;
      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
    }else if( cli_strncmp(zMode,"columns",n2)==0 ){
      p->mode = MODE_Column;
9862
9863
9864
9865
9866
9867
9868





9869
9870
9871
9872
9873
9874
9875
      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
    }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
      p->mode = MODE_List;
      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
    }else if( cli_strncmp(zMode,"insert",n2)==0 ){
      p->mode = MODE_Insert;
      set_table_name(p, zTabname ? zTabname : "table");





    }else if( cli_strncmp(zMode,"quote",n2)==0 ){
      p->mode = MODE_Quote;
      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
    }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
      p->mode = MODE_Ascii;
      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);







>
>
>
>
>







10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
    }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
      p->mode = MODE_List;
      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
    }else if( cli_strncmp(zMode,"insert",n2)==0 ){
      p->mode = MODE_Insert;
      set_table_name(p, zTabname ? zTabname : "table");
      if( p->eEscMode==SHELL_ESC_OFF ){
        ShellSetFlag(p, SHFLG_Newlines);
      }else{
        ShellClearFlag(p, SHFLG_Newlines);
      }
    }else if( cli_strncmp(zMode,"quote",n2)==0 ){
      p->mode = MODE_Quote;
      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
    }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
      p->mode = MODE_Ascii;
      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
12582
12583
12584
12585
12586
12587
12588

12589
12590
12591
12592
12593
12594
12595
  "   -column              set output mode to 'column'\n"
  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
  "   -csv                 set output mode to 'csv'\n"
#if !defined(SQLITE_OMIT_DESERIALIZE)
  "   -deserialize         open the database using sqlite3_deserialize()\n"
#endif
  "   -echo                print inputs before execution\n"

  "   -init FILENAME       read/process named file\n"
  "   -[no]header          turn headers on or off\n"
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
#endif
  "   -help                show this message\n"
  "   -html                set output mode to HTML\n"







>







12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
  "   -column              set output mode to 'column'\n"
  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
  "   -csv                 set output mode to 'csv'\n"
#if !defined(SQLITE_OMIT_DESERIALIZE)
  "   -deserialize         open the database using sqlite3_deserialize()\n"
#endif
  "   -echo                print inputs before execution\n"
  "   -escape MODE         ctrl-char escape mode, one of: symbol, ascii, off\n"
  "   -init FILENAME       read/process named file\n"
  "   -[no]header          turn headers on or off\n"
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
#endif
  "   -help                show this message\n"
  "   -html                set output mode to HTML\n"
13015
13016
13017
13018
13019
13020
13021



13022
13023
13024
13025
13026
13027
13028
    }else if( cli_strcmp(z,"-nonce")==0 ){
      free(data.zNonce);
      data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
    }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
      ShellSetFlag(&data,SHFLG_TestingMode);
    }else if( cli_strcmp(z,"-safe")==0 ){
      /* no-op - catch this on the second pass */



    }
  }
#ifndef SQLITE_SHELL_FIDDLE
  if( !bEnableVfstrace ) verify_uninitialized();
#endif









>
>
>







13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
    }else if( cli_strcmp(z,"-nonce")==0 ){
      free(data.zNonce);
      data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
    }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
      ShellSetFlag(&data,SHFLG_TestingMode);
    }else if( cli_strcmp(z,"-safe")==0 ){
      /* no-op - catch this on the second pass */
    }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
      /* skip over the argument */
      i++;
    }
  }
#ifndef SQLITE_SHELL_FIDDLE
  if( !bEnableVfstrace ) verify_uninitialized();
#endif


13114
13115
13116
13117
13118
13119
13120



















13121
13122
13123
13124
13125
13126
13127
    }else if( cli_strcmp(z,"-table")==0 ){
      data.mode = MODE_Table;
    }else if( cli_strcmp(z,"-box")==0 ){
      data.mode = MODE_Box;
    }else if( cli_strcmp(z,"-csv")==0 ){
      data.mode = MODE_Csv;
      memcpy(data.colSeparator,",",2);



















#ifdef SQLITE_HAVE_ZLIB
    }else if( cli_strcmp(z,"-zip")==0 ){
      data.openMode = SHELL_OPEN_ZIPFILE;
#endif
    }else if( cli_strcmp(z,"-append")==0 ){
      data.openMode = SHELL_OPEN_APPENDVFS;
#ifndef SQLITE_OMIT_DESERIALIZE







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
    }else if( cli_strcmp(z,"-table")==0 ){
      data.mode = MODE_Table;
    }else if( cli_strcmp(z,"-box")==0 ){
      data.mode = MODE_Box;
    }else if( cli_strcmp(z,"-csv")==0 ){
      data.mode = MODE_Csv;
      memcpy(data.colSeparator,",",2);
    }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
      /* See similar code at tag-20250224-1 */
      const char *zEsc = argv[++i];
      int k;
      for(k=0; k<ArraySize(shell_EscModeNames); k++){
        if( sqlite3_stricmp(zEsc,shell_EscModeNames[k])==0 ){
          data.eEscMode = k;
          break;
        }
      }
      if( k>=ArraySize(shell_EscModeNames) ){
        sqlite3_fprintf(stderr, "unknown control character escape mode \"%s\""
                                " - choices:", zEsc);
        for(k=0; k<ArraySize(shell_EscModeNames); k++){
          sqlite3_fprintf(stderr, " %s", shell_EscModeNames[k]);
        }
        sqlite3_fprintf(stderr, "\n");
        exit(1);
      }
#ifdef SQLITE_HAVE_ZLIB
    }else if( cli_strcmp(z,"-zip")==0 ){
      data.openMode = SHELL_OPEN_ZIPFILE;
#endif
    }else if( cli_strcmp(z,"-append")==0 ){
      data.openMode = SHELL_OPEN_APPENDVFS;
#ifndef SQLITE_OMIT_DESERIALIZE
Changes to src/sqliteInt.h.
5138
5139
5140
5141
5142
5143
5144
5145

5146
5147
5148
5149
5150
5151
5152
ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
IdList *sqlite3IdListDup(sqlite3*,const IdList*);
Select *sqlite3SelectDup(sqlite3*,const Select*,int);
FuncDef *sqlite3FunctionSearch(int,const char*);
void sqlite3InsertBuiltinFuncs(FuncDef*,int);
FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
void sqlite3QuoteValue(StrAccum*,sqlite3_value*);

void sqlite3RegisterBuiltinFunctions(void);
void sqlite3RegisterDateTimeFunctions(void);
void sqlite3RegisterJsonFunctions(void);
void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
  int sqlite3JsonTableFunctions(sqlite3*);
#endif







|
>







5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
IdList *sqlite3IdListDup(sqlite3*,const IdList*);
Select *sqlite3SelectDup(sqlite3*,const Select*,int);
FuncDef *sqlite3FunctionSearch(int,const char*);
void sqlite3InsertBuiltinFuncs(FuncDef*,int);
FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
void sqlite3QuoteValue(StrAccum*,sqlite3_value*,int);
int sqlite3AppendOneUtf8Character(char*, u32);
void sqlite3RegisterBuiltinFunctions(void);
void sqlite3RegisterDateTimeFunctions(void);
void sqlite3RegisterJsonFunctions(void);
void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
  int sqlite3JsonTableFunctions(sqlite3*);
#endif
Changes to src/utf.c.
100
101
102
103
104
105
106





























107
108
109
110
111
112
113
  }else{                                                            \
    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
    *zOut++ = (u8)(c&0x00FF);                                       \
  }                                                                 \
}






























/*
** Translate a single UTF-8 character.  Return the unicode value.
**
** During translation, assume that the byte that zTerm points
** is a 0x00.
**







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
  }else{                                                            \
    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
    *zOut++ = (u8)(c&0x00FF);                                       \
  }                                                                 \
}

/*
** Write a single UTF8 character whose value is v into the
** buffer starting at zOut.  zOut must be sized to hold at
** least for bytes.  Return the number of bytes needed
** to encode the new character.
*/
int sqlite3AppendOneUtf8Character(char *zOut, u32 v){
  if( v<0x00080 ){
    zOut[0] = (u8)(v & 0xff);
    return 1;
  }
  if( v<0x00800 ){
    zOut[0] = 0xc0 + (u8)((v>>6) & 0x1f);
    zOut[1] = 0x80 + (u8)(v & 0x3f);
    return 2;
  }
  if( v<0x10000 ){
    zOut[0] = 0xe0 + (u8)((v>>12) & 0x0f);
    zOut[1] = 0x80 + (u8)((v>>6) & 0x3f);
    zOut[2] = 0x80 + (u8)(v & 0x3f);
    return 3;
  }
  zOut[0] = 0xf0 + (u8)((v>>18) & 0x07);
  zOut[1] = 0x80 + (u8)((v>>12) & 0x3f);
  zOut[2] = 0x80 + (u8)((v>>6) & 0x3f);
  zOut[3] = 0x80 + (u8)(v & 0x3f);
  return 4;
}

/*
** Translate a single UTF-8 character.  Return the unicode value.
**
** During translation, assume that the byte that zTerm points
** is a 0x00.
**
Changes to test/shell1.test.
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#                          insert   SQL insert statements for TABLE
#                          line     One value per line
#                          list     Values delimited by .separator strings
#                          tabs     Tab-separated values
#                          tcl      TCL list elements
do_test shell1-3.13.1 {
  catchcmd "test.db" ".mode"
} {0 {current output mode: list}}
do_test shell1-3.13.2 {
  catchcmd "test.db" ".mode FOO"
} {1 {Error: mode should be one of: ascii box column csv html insert json line list markdown qbox quote table tabs tcl}}
do_test shell1-3.13.3 {
  catchcmd "test.db" ".mode csv"
} {0 {}}
do_test shell1-3.13.4 {







|







446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#                          insert   SQL insert statements for TABLE
#                          line     One value per line
#                          list     Values delimited by .separator strings
#                          tabs     Tab-separated values
#                          tcl      TCL list elements
do_test shell1-3.13.1 {
  catchcmd "test.db" ".mode"
} {0 {current output mode: list --escape symbol}}
do_test shell1-3.13.2 {
  catchcmd "test.db" ".mode FOO"
} {1 {Error: mode should be one of: ascii box column csv html insert json line list markdown qbox quote table tabs tcl}}
do_test shell1-3.13.3 {
  catchcmd "test.db" ".mode csv"
} {0 {}}
do_test shell1-3.13.4 {
Added test/shellA.test.


































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# 2025-02-24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# TESTRUNNER: shell
#
# Test cases for the command-line shell - focusing on .mode and
# especially control-character escaping and the --escape option.
#
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
set CLI [test_cli_invocation]

do_execsql_test shellA-1.0 {
  CREATE TABLE t1(a INT, x TEXT);
  INSERT INTO t1 VALUES
   (1, 'line with '' single quote'),
   (2, concat(char(0x1b),'[31mVT-100 codes',char(0x1b),'[0m')),
   (3, NULL),
   (4, 1234),
   (5, 568.25),
   (6, unistr('new\u000aline')),
   (7, unistr('carriage\u000dreturn')),
   (8, 'last line');
} {}

# Initial verification that the database created correctly
# and that our calls to the CLI are working.
#
do_test shellA-1.2 {
  exec {*}$CLI test.db {.mode box} {SELECT * FROM t1;}
} {
┌───┬──────────────────────────┐
│ a │            x             │
├───┼──────────────────────────┤
│ 1 │ line with ' single quote │
├───┼──────────────────────────┤
│ 2 │ ␛[31mVT-100 codes␛[0m    │
├───┼──────────────────────────┤
│ 3 │                          │
├───┼──────────────────────────┤
│ 4 │ 1234                     │
├───┼──────────────────────────┤
│ 5 │ 568.25                   │
├───┼──────────────────────────┤
│ 6 │ new                      │
│   │ line                     │
├───┼──────────────────────────┤
│ 7 │ carriage␍return          │
├───┼──────────────────────────┤
│ 8 │ last line                │
└───┴──────────────────────────┘
}

# ".mode list"
#
do_test shellA-1.3 {
  exec {*}$CLI test.db {SELECT x FROM t1 WHERE a=2;}
} {
␛[31mVT-100 codes␛[0m
}
do_test shellA-1.4 {
  exec {*}$CLI test.db --escape symbol {SELECT x FROM t1 WHERE a=2;}
} {
␛[31mVT-100 codes␛[0m
}
do_test shellA-1.5 {
  exec {*}$CLI test.db --escape ascii {SELECT x FROM t1 WHERE a=2;}
} {
^[[31mVT-100 codes^[[0m
}
do_test shellA-1.6 {
  exec {*}$CLI test.db {.mode list --escape symbol} {SELECT x FROM t1 WHERE a=2;}
} {
␛[31mVT-100 codes␛[0m
}
do_test shellA-1.7 {
  exec {*}$CLI test.db {.mode list --escape ascii} {SELECT x FROM t1 WHERE a=2;}
} {
^[[31mVT-100 codes^[[0m
}
do_test shellA-1.8 {
  file delete -force out.txt
  exec {*}$CLI test.db {.mode list --escape off} {SELECT x FROM t1 WHERE a=7;} \
     >out.txt
  set fd [open out.txt rb]
  set res [read $fd]
  close $fd
  string trim $res
} "carriage\rreturn"
do_test shellA-1.9 {
  set rc [catch {
     exec {*}$CLI test.db {.mode test --escape xyz}
  } msg]
  lappend rc $msg
} {1 {unknown control character escape mode "xyz" - choices: symbol ascii off}}
do_test shellA-1.10 {
  set rc [catch {
     exec {*}$CLI --escape abc test.db .q
  } msg]
  lappend rc $msg
} {1 {unknown control character escape mode "abc" - choices: symbol ascii off}}

# ".mode quote"
#
do_test shellA-2.1 {
 exec {*}$CLI test.db --quote {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)}
} {
1,'line with '' single quote'
2,unistr('\u001b[31mVT-100 codes\u001b[0m')
6,'new
line'
7,unistr('carriage\u000dreturn')
8,'last line'
}
do_test shellA-2.2 {
  exec {*}$CLI test.db --quote {.mode}
} {current output mode: quote --escape symbol}
do_test shellA-2.3 {
  exec {*}$CLI test.db --quote --escape ASCII {.mode}
} {current output mode: quote --escape ascii}
do_test shellA-2.4 {
  exec {*}$CLI test.db --quote --escape OFF {.mode}
} {current output mode: quote --escape off}


# ".mode line"
#
do_test shellA-3.1 {
 exec {*}$CLI test.db --line --escape symbol \
    {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)}
} {
    a = 1
    x = line with ' single quote

    a = 2
    x = ␛[31mVT-100 codes␛[0m

    a = 6
    x = new
line

    a = 7
    x = carriage␍return

    a = 8
    x = last line
}
do_test shellA-3.2 {
 exec {*}$CLI test.db --line --escape ascii \
    {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)}
} {
    a = 1
    x = line with ' single quote

    a = 2
    x = ^[[31mVT-100 codes^[[0m

    a = 6
    x = new
line

    a = 7
    x = carriage^Mreturn

    a = 8
    x = last line
}

# ".mode box"
#
do_test shellA-4.1 {
 exec {*}$CLI test.db --box --escape ascii \
    {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)}
} {
┌───┬──────────────────────────┐
│ a │            x             │
├───┼──────────────────────────┤
│ 1 │ line with ' single quote │
├───┼──────────────────────────┤
│ 2 │ ^[[31mVT-100 codes^[[0m  │
├───┼──────────────────────────┤
│ 6 │ new                      │
│   │ line                     │
├───┼──────────────────────────┤
│ 7 │ carriage^Mreturn         │
├───┼──────────────────────────┤
│ 8 │ last line                │
└───┴──────────────────────────┘
}
do_test shellA-4.2 {
 exec {*}$CLI test.db {.mode qbox} {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)}
} {
┌───┬───────────────────────────────────────────┐
│ a │                     x                     │
├───┼───────────────────────────────────────────┤
│ 1 │ 'line with '' single quote'               │
├───┼───────────────────────────────────────────┤
│ 2 │ unistr('\u001b[31mVT-100 codes\u001b[0m') │
├───┼───────────────────────────────────────────┤
│ 6 │ 'new                                      │
│   │ line'                                     │
├───┼───────────────────────────────────────────┤
│ 7 │ unistr('carriage\u000dreturn')            │
├───┼───────────────────────────────────────────┤
│ 8 │ 'last line'                               │
└───┴───────────────────────────────────────────┘
}

# ".mode insert"
#
do_test shellA-5.1 {
 exec {*}$CLI test.db {.mode insert t1 --escape ascii} \
    {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)}
} {
INSERT INTO t1 VALUES(1,'line with '' single quote');
INSERT INTO t1 VALUES(2,unistr('\u001b[31mVT-100 codes\u001b[0m'));
INSERT INTO t1 VALUES(6,unistr('new\u000aline'));
INSERT INTO t1 VALUES(7,unistr('carriage\u000dreturn'));
INSERT INTO t1 VALUES(8,'last line');
}
do_test shellA-5.2 {
 exec {*}$CLI test.db {.mode insert t1 --escape symbol} \
    {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)}
} {
INSERT INTO t1 VALUES(1,'line with '' single quote');
INSERT INTO t1 VALUES(2,unistr('\u001b[31mVT-100 codes\u001b[0m'));
INSERT INTO t1 VALUES(6,unistr('new\u000aline'));
INSERT INTO t1 VALUES(7,unistr('carriage\u000dreturn'));
INSERT INTO t1 VALUES(8,'last line');
}
do_test shellA-5.3 {
  file delete -force out.txt
  exec {*}$CLI test.db {.mode insert t1 --escape off} \
    {SELECT a, x FROM t1 WHERE a IN (1,2,6,7,8)} >out.txt
  set fd [open out.txt rb]
  set res [read $fd]
  close $fd
  string trim [string map [list \r\n \n] $res]
} "
INSERT INTO t1 VALUES(1,'line with '' single quote');
INSERT INTO t1 VALUES(2,'\033\13331mVT-100 codes\033\1330m');
INSERT INTO t1 VALUES(6,'new
line');
INSERT INTO t1 VALUES(7,'carriage\rreturn');
INSERT INTO t1 VALUES(8,'last line');
"

finish_test