2 ** The "printf" code that follows dates from the 1980's. It is in
5 **************************************************************************
7 ** This file contains code for a set of "printf"-like routines. These
8 ** routines format strings much like the printf() from the standard C
9 ** library, though the implementation here has enhancements to support
12 #include "sqliteInt.h"
15 ** Conversion types fall into various categories as defined by the
16 ** following enumeration.
18 #define etRADIX 0 /* non-decimal integer types. %x %o */
19 #define etFLOAT 1 /* Floating point. %f */
20 #define etEXP 2 /* Exponentional notation. %e and %E */
21 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
22 #define etSIZE 4 /* Return number of characters processed so far. %n */
23 #define etSTRING 5 /* Strings. %s */
24 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
25 #define etPERCENT 7 /* Percent symbol. %% */
26 #define etCHARX 8 /* Characters. %c */
27 /* The rest are extensions, not normally found in printf() */
28 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
29 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
30 NULL pointers replaced by SQL NULL. %Q */
31 #define etTOKEN 11 /* a pointer to a Token structure */
32 #define etSRCITEM 12 /* a pointer to a SrcItem */
33 #define etPOINTER 13 /* The %p conversion */
34 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
35 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
36 #define etDECIMAL 16 /* %d or %u, but not %x, %o */
38 #define etINVALID 17 /* Any unrecognized conversion type */
42 ** An "etByte" is an 8-bit unsigned value.
44 typedef unsigned char etByte
;
47 ** Each builtin conversion character (ex: the 'd' in "%d") is described
48 ** by an instance of the following structure
50 typedef struct et_info
{ /* Information about each format field */
51 char fmttype
; /* The format field code letter */
52 etByte base
; /* The base for radix conversion */
53 etByte flags
; /* One or more of FLAG_ constants below */
54 etByte type
; /* Conversion paradigm */
55 etByte charset
; /* Offset into aDigits[] of the digits string */
56 etByte prefix
; /* Offset into aPrefix[] of the prefix string */
60 ** Allowed values for et_info.flags
62 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
63 #define FLAG_STRING 4 /* Allow infinite precision */
67 ** The following table is searched linearly, so it is good to put the
68 ** most frequently used conversion types first.
70 static const char aDigits
[] = "0123456789ABCDEF0123456789abcdef";
71 static const char aPrefix
[] = "-x0\000X0";
72 static const et_info fmtinfo
[] = {
73 { 'd', 10, 1, etDECIMAL
, 0, 0 },
74 { 's', 0, 4, etSTRING
, 0, 0 },
75 { 'g', 0, 1, etGENERIC
, 30, 0 },
76 { 'z', 0, 4, etDYNSTRING
, 0, 0 },
77 { 'q', 0, 4, etSQLESCAPE
, 0, 0 },
78 { 'Q', 0, 4, etSQLESCAPE2
, 0, 0 },
79 { 'w', 0, 4, etSQLESCAPE3
, 0, 0 },
80 { 'c', 0, 0, etCHARX
, 0, 0 },
81 { 'o', 8, 0, etRADIX
, 0, 2 },
82 { 'u', 10, 0, etDECIMAL
, 0, 0 },
83 { 'x', 16, 0, etRADIX
, 16, 1 },
84 { 'X', 16, 0, etRADIX
, 0, 4 },
85 #ifndef SQLITE_OMIT_FLOATING_POINT
86 { 'f', 0, 1, etFLOAT
, 0, 0 },
87 { 'e', 0, 1, etEXP
, 30, 0 },
88 { 'E', 0, 1, etEXP
, 14, 0 },
89 { 'G', 0, 1, etGENERIC
, 14, 0 },
91 { 'i', 10, 1, etDECIMAL
, 0, 0 },
92 { 'n', 0, 0, etSIZE
, 0, 0 },
93 { '%', 0, 0, etPERCENT
, 0, 0 },
94 { 'p', 16, 0, etPOINTER
, 0, 1 },
96 /* All the rest are undocumented and are for internal use only */
97 { 'T', 0, 0, etTOKEN
, 0, 0 },
98 { 'S', 0, 0, etSRCITEM
, 0, 0 },
99 { 'r', 10, 1, etORDINAL
, 0, 0 },
104 ** %S Takes a pointer to SrcItem. Shows name or database.name
105 ** %!S Like %S but prefer the zName over the zAlias
108 /* Floating point constants used for rounding */
109 static const double arRound
[] = {
110 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
111 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
115 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
116 ** conversions will work.
118 #ifndef SQLITE_OMIT_FLOATING_POINT
120 ** "*val" is a double such that 0.1 <= *val < 10.0
121 ** Return the ascii code for the leading digit of *val, then
122 ** multiply "*val" by 10.0 to renormalize.
125 ** input: *val = 3.14159
126 ** output: *val = 1.4159 function return = '3'
128 ** The counter *cnt is incremented each time. After counter exceeds
129 ** 16 (the number of significant digits in a 64-bit float) '0' is
132 static char et_getdigit(LONGDOUBLE_TYPE
*val
, int *cnt
){
135 if( (*cnt
)<=0 ) return '0';
140 *val
= (*val
- d
)*10.0;
143 #endif /* SQLITE_OMIT_FLOATING_POINT */
145 #ifndef SQLITE_OMIT_FLOATING_POINT
147 ** "*val" is a u64. *msd is a divisor used to extract the
148 ** most significant digit of *val. Extract that most significant
149 ** digit and return it.
151 static char et_getdigit_int(u64
*val
, u64
*msd
){
152 u64 x
= (*val
)/(*msd
);
154 if( *msd
>=10 ) *msd
/= 10;
155 return '0' + (char)(x
& 15);
157 #endif /* SQLITE_OMIT_FLOATING_POINT */
160 ** Set the StrAccum object to an error mode.
162 void sqlite3StrAccumSetError(StrAccum
*p
, u8 eError
){
163 assert( eError
==SQLITE_NOMEM
|| eError
==SQLITE_TOOBIG
);
164 p
->accError
= eError
;
165 if( p
->mxAlloc
) sqlite3_str_reset(p
);
166 if( eError
==SQLITE_TOOBIG
) sqlite3ErrorToParser(p
->db
, eError
);
170 ** Extra argument values from a PrintfArguments object
172 static sqlite3_int64
getIntArg(PrintfArguments
*p
){
173 if( p
->nArg
<=p
->nUsed
) return 0;
174 return sqlite3_value_int64(p
->apArg
[p
->nUsed
++]);
176 static double getDoubleArg(PrintfArguments
*p
){
177 if( p
->nArg
<=p
->nUsed
) return 0.0;
178 return sqlite3_value_double(p
->apArg
[p
->nUsed
++]);
180 static char *getTextArg(PrintfArguments
*p
){
181 if( p
->nArg
<=p
->nUsed
) return 0;
182 return (char*)sqlite3_value_text(p
->apArg
[p
->nUsed
++]);
186 ** Allocate memory for a temporary buffer needed for printf rendering.
188 ** If the requested size of the temp buffer is larger than the size
189 ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
190 ** Do the size check before the memory allocation to prevent rogue
191 ** SQL from requesting large allocations using the precision or width
192 ** field of the printf() function.
194 static char *printfTempBuf(sqlite3_str
*pAccum
, sqlite3_int64 n
){
196 if( pAccum
->accError
) return 0;
197 if( n
>pAccum
->nAlloc
&& n
>pAccum
->mxAlloc
){
198 sqlite3StrAccumSetError(pAccum
, SQLITE_TOOBIG
);
201 z
= sqlite3DbMallocRaw(pAccum
->db
, n
);
203 sqlite3StrAccumSetError(pAccum
, SQLITE_NOMEM
);
209 ** On machines with a small stack size, you can redefine the
210 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
212 #ifndef SQLITE_PRINT_BUF_SIZE
213 # define SQLITE_PRINT_BUF_SIZE 70
215 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
218 ** Hard limit on the precision of floating-point conversions.
220 #ifndef SQLITE_PRINTF_PRECISION_LIMIT
221 # define SQLITE_FP_PRECISION_LIMIT 100000000
225 ** Render a string given by "fmt" into the StrAccum object.
227 void sqlite3_str_vappendf(
228 sqlite3_str
*pAccum
, /* Accumulate results here */
229 const char *fmt
, /* Format string */
230 va_list ap
/* arguments */
232 int c
; /* Next character in the format string */
233 char *bufpt
; /* Pointer to the conversion buffer */
234 int precision
; /* Precision of the current field */
235 int length
; /* Length of the field */
236 int idx
; /* A general purpose loop counter */
237 int width
; /* Width of the current field */
238 etByte flag_leftjustify
; /* True if "-" flag is present */
239 etByte flag_prefix
; /* '+' or ' ' or 0 for prefix */
240 etByte flag_alternateform
; /* True if "#" flag is present */
241 etByte flag_altform2
; /* True if "!" flag is present */
242 etByte flag_zeropad
; /* True if field width constant starts with zero */
243 etByte flag_long
; /* 1 for the "l" flag, 2 for "ll", 0 by default */
244 etByte done
; /* Loop termination flag */
245 etByte cThousand
; /* Thousands separator for %d and %u */
246 etByte xtype
= etINVALID
; /* Conversion paradigm */
247 u8 bArgList
; /* True for SQLITE_PRINTF_SQLFUNC */
248 char prefix
; /* Prefix character. "+" or "-" or " " or '\0'. */
249 sqlite_uint64 longvalue
; /* Value for integer types */
250 LONGDOUBLE_TYPE realvalue
; /* Value for real types */
251 sqlite_uint64 msd
; /* Divisor to get most-significant-digit
253 const et_info
*infop
; /* Pointer to the appropriate info structure */
254 char *zOut
; /* Rendering buffer */
255 int nOut
; /* Size of the rendering buffer */
256 char *zExtra
= 0; /* Malloced memory used by some conversion */
257 #ifndef SQLITE_OMIT_FLOATING_POINT
258 int exp
, e2
; /* exponent of real numbers */
259 int nsd
; /* Number of significant digits returned */
260 double rounder
; /* Used for rounding floating point values */
261 etByte flag_dp
; /* True if decimal point should be shown */
262 etByte flag_rtz
; /* True if trailing zeros should be removed */
264 PrintfArguments
*pArgList
= 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
265 char buf
[etBUFSIZE
]; /* Conversion buffer */
267 /* pAccum never starts out with an empty buffer that was obtained from
268 ** malloc(). This precondition is required by the mprintf("%z...")
270 assert( pAccum
->nChar
>0 || (pAccum
->printfFlags
&SQLITE_PRINTF_MALLOCED
)==0 );
273 if( (pAccum
->printfFlags
& SQLITE_PRINTF_SQLFUNC
)!=0 ){
274 pArgList
= va_arg(ap
, PrintfArguments
*);
279 for(; (c
=(*fmt
))!=0; ++fmt
){
283 fmt
= strchrnul(fmt
, '%');
285 do{ fmt
++; }while( *fmt
&& *fmt
!= '%' );
287 sqlite3_str_append(pAccum
, bufpt
, (int)(fmt
- bufpt
));
290 if( (c
=(*++fmt
))==0 ){
291 sqlite3_str_append(pAccum
, "%", 1);
294 /* Find out what flags are present */
295 flag_leftjustify
= flag_prefix
= cThousand
=
296 flag_alternateform
= flag_altform2
= flag_zeropad
= 0;
303 case '-': flag_leftjustify
= 1; break;
304 case '+': flag_prefix
= '+'; break;
305 case ' ': flag_prefix
= ' '; break;
306 case '#': flag_alternateform
= 1; break;
307 case '!': flag_altform2
= 1; break;
308 case '0': flag_zeropad
= 1; break;
309 case ',': cThousand
= ','; break;
310 default: done
= 1; break;
321 case '1': case '2': case '3': case '4': case '5':
322 case '6': case '7': case '8': case '9': {
323 unsigned wx
= c
- '0';
324 while( (c
= *++fmt
)>='0' && c
<='9' ){
325 wx
= wx
*10 + c
- '0';
327 testcase( wx
>0x7fffffff );
328 width
= wx
& 0x7fffffff;
329 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
330 if( width
>SQLITE_PRINTF_PRECISION_LIMIT
){
331 width
= SQLITE_PRINTF_PRECISION_LIMIT
;
334 if( c
!='.' && c
!='l' ){
343 width
= (int)getIntArg(pArgList
);
345 width
= va_arg(ap
,int);
348 flag_leftjustify
= 1;
349 width
= width
>= -2147483647 ? -width
: 0;
351 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
352 if( width
>SQLITE_PRINTF_PRECISION_LIMIT
){
353 width
= SQLITE_PRINTF_PRECISION_LIMIT
;
356 if( (c
= fmt
[1])!='.' && c
!='l' ){
366 precision
= (int)getIntArg(pArgList
);
368 precision
= va_arg(ap
,int);
371 precision
= precision
>= -2147483647 ? -precision
: -1;
376 while( c
>='0' && c
<='9' ){
377 px
= px
*10 + c
- '0';
380 testcase( px
>0x7fffffff );
381 precision
= px
& 0x7fffffff;
383 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
384 if( precision
>SQLITE_PRINTF_PRECISION_LIMIT
){
385 precision
= SQLITE_PRINTF_PRECISION_LIMIT
;
396 }while( !done
&& (c
=(*++fmt
))!=0 );
398 /* Fetch the info entry for the field */
401 for(idx
=0; idx
<ArraySize(fmtinfo
); idx
++){
402 if( c
==fmtinfo
[idx
].fmttype
){
403 infop
= &fmtinfo
[idx
];
410 ** At this point, variables are initialized as follows:
412 ** flag_alternateform TRUE if a '#' is present.
413 ** flag_altform2 TRUE if a '!' is present.
414 ** flag_prefix '+' or ' ' or zero
415 ** flag_leftjustify TRUE if a '-' is present or if the
416 ** field width was negative.
417 ** flag_zeropad TRUE if the width began with 0.
418 ** flag_long 1 for "l", 2 for "ll"
419 ** width The specified field width. This is
420 ** always non-negative. Zero is the default.
421 ** precision The specified precision. The default
423 ** xtype The class of the conversion.
424 ** infop Pointer to the appropriate info struct.
427 assert( precision
>=(-1) );
430 flag_long
= sizeof(char*)==sizeof(i64
) ? 2 :
431 sizeof(char*)==sizeof(long int) ? 1 : 0;
432 /* no break */ deliberate_fall_through
436 /* no break */ deliberate_fall_through
438 if( infop
->flags
& FLAG_SIGNED
){
441 v
= getIntArg(pArgList
);
442 }else if( flag_long
){
446 v
= va_arg(ap
,long int);
452 testcase( v
==SMALLEST_INT64
);
459 prefix
= flag_prefix
;
463 longvalue
= (u64
)getIntArg(pArgList
);
464 }else if( flag_long
){
466 longvalue
= va_arg(ap
,u64
);
468 longvalue
= va_arg(ap
,unsigned long int);
471 longvalue
= va_arg(ap
,unsigned int);
475 if( longvalue
==0 ) flag_alternateform
= 0;
476 if( flag_zeropad
&& precision
<width
-(prefix
!=0) ){
477 precision
= width
-(prefix
!=0);
479 if( precision
<etBUFSIZE
-10-etBUFSIZE
/3 ){
484 n
= (u64
)precision
+ 10;
485 if( cThousand
) n
+= precision
/3;
486 zOut
= zExtra
= printfTempBuf(pAccum
, n
);
487 if( zOut
==0 ) return;
490 bufpt
= &zOut
[nOut
-1];
491 if( xtype
==etORDINAL
){
492 static const char zOrd
[] = "thstndrd";
493 int x
= (int)(longvalue
% 10);
494 if( x
>=4 || (longvalue
/10)%10==1 ){
497 *(--bufpt
) = zOrd
[x
*2+1];
498 *(--bufpt
) = zOrd
[x
*2];
501 const char *cset
= &aDigits
[infop
->charset
];
502 u8 base
= infop
->base
;
503 do{ /* Convert to ascii */
504 *(--bufpt
) = cset
[longvalue
%base
];
505 longvalue
= longvalue
/base
;
506 }while( longvalue
>0 );
508 length
= (int)(&zOut
[nOut
-1]-bufpt
);
509 while( precision
>length
){
510 *(--bufpt
) = '0'; /* Zero pad */
514 int nn
= (length
- 1)/3; /* Number of "," to insert */
515 int ix
= (length
- 1)%3 + 1;
517 for(idx
=0; nn
>0; idx
++){
518 bufpt
[idx
] = bufpt
[idx
+nn
];
521 bufpt
[++idx
] = cThousand
;
527 if( prefix
) *(--bufpt
) = prefix
; /* Add sign */
528 if( flag_alternateform
&& infop
->prefix
){ /* Add "0" or "0x" */
531 pre
= &aPrefix
[infop
->prefix
];
532 for(; (x
=(*pre
))!=0; pre
++) *(--bufpt
) = x
;
534 length
= (int)(&zOut
[nOut
-1]-bufpt
);
540 realvalue
= getDoubleArg(pArgList
);
542 realvalue
= va_arg(ap
,double);
544 #ifdef SQLITE_OMIT_FLOATING_POINT
547 if( precision
<0 ) precision
= 6; /* Set default precision */
548 #ifdef SQLITE_FP_PRECISION_LIMIT
549 if( precision
>SQLITE_FP_PRECISION_LIMIT
){
550 precision
= SQLITE_FP_PRECISION_LIMIT
;
554 realvalue
= -realvalue
;
557 prefix
= flag_prefix
;
560 if( xtype
==etGENERIC
&& precision
>0 ) precision
--;
561 testcase( precision
>0xfff );
562 if( realvalue
<1.0e+16
563 && realvalue
==(LONGDOUBLE_TYPE
)(longvalue
= (u64
)realvalue
)
565 /* Number is a pure integer that can be represented as u64 */
566 for(msd
=1; msd
*10<=longvalue
; msd
*= 10, exp
++){}
567 if( exp
>precision
&& xtype
!=etFLOAT
){
570 while( kk
-- > 0 ){ rnd
/= 10; }
575 longvalue
= 0; /* To prevent a compiler warning */
576 idx
= precision
& 0xfff;
577 rounder
= arRound
[idx
%10];
578 while( idx
>=10 ){ rounder
*= 1.0e-10; idx
-= 10; }
579 if( xtype
==etFLOAT
){
580 double rx
= (double)realvalue
;
583 memcpy(&u
, &rx
, sizeof(u
));
584 ex
= -1023 + (int)((u
>>52)&0x7ff);
585 if( precision
+(ex
/3) < 15 ) rounder
+= realvalue
*3e-16;
586 realvalue
+= rounder
;
588 if( sqlite3IsNaN((double)realvalue
) ){
599 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
600 if( ALWAYS(realvalue
>0.0) ){
601 LONGDOUBLE_TYPE scale
= 1.0;
602 while( realvalue
>=1e100
*scale
&& exp
<=350){ scale
*=1e100
;exp
+=100;}
603 while( realvalue
>=1e10
*scale
&& exp
<=350 ){ scale
*=1e10
; exp
+=10; }
604 while( realvalue
>=10.0*scale
&& exp
<=350 ){ scale
*= 10.0; exp
++; }
606 while( realvalue
<1e-8 ){ realvalue
*= 1e8
; exp
-=8; }
607 while( realvalue
<1.0 ){ realvalue
*= 10.0; exp
--; }
615 memcpy(buf
+(prefix
!=0),"Inf",4);
616 length
= 3+(prefix
!=0);
620 if( xtype
!=etFLOAT
){
621 realvalue
+= rounder
;
622 if( realvalue
>=10.0 ){ realvalue
*= 0.1; exp
++; }
628 ** If the field type is etGENERIC, then convert to either etEXP
629 ** or etFLOAT, as appropriate.
631 if( xtype
==etGENERIC
){
632 flag_rtz
= !flag_alternateform
;
633 if( exp
<-4 || exp
>precision
){
636 precision
= precision
- exp
;
640 flag_rtz
= flag_altform2
;
647 nsd
= 16 + flag_altform2
*10;
650 i64 szBufNeeded
; /* Size of a temporary buffer needed */
651 szBufNeeded
= MAX(e2
,0)+(i64
)precision
+(i64
)width
+15;
652 if( cThousand
&& e2
>0 ) szBufNeeded
+= (e2
+2)/3;
653 if( szBufNeeded
> etBUFSIZE
){
654 bufpt
= zExtra
= printfTempBuf(pAccum
, szBufNeeded
);
655 if( bufpt
==0 ) return;
659 flag_dp
= (precision
>0 ?1:0) | flag_alternateform
| flag_altform2
;
660 /* The sign in front of the number */
664 /* Digits prior to the decimal point */
669 *(bufpt
++) = et_getdigit_int(&longvalue
,&msd
);
670 if( cThousand
&& (e2
%3)==0 && e2
>1 ) *(bufpt
++) = ',';
674 *(bufpt
++) = et_getdigit(&realvalue
,&nsd
);
675 if( cThousand
&& (e2
%3)==0 && e2
>1 ) *(bufpt
++) = ',';
678 /* The decimal point */
682 /* "0" digits after the decimal point but before the first
683 ** significant digit of the number */
684 for(e2
++; e2
<0; precision
--, e2
++){
685 assert( precision
>0 );
688 /* Significant digits after the decimal point */
690 while( (precision
--)>0 ){
691 *(bufpt
++) = et_getdigit_int(&longvalue
,&msd
);
694 while( (precision
--)>0 ){
695 *(bufpt
++) = et_getdigit(&realvalue
,&nsd
);
698 /* Remove trailing zeros and the "." if no digits follow the "." */
699 if( flag_rtz
&& flag_dp
){
700 while( bufpt
[-1]=='0' ) *(--bufpt
) = 0;
701 assert( bufpt
>zOut
);
702 if( bufpt
[-1]=='.' ){
710 /* Add the "eNNN" suffix */
712 *(bufpt
++) = aDigits
[infop
->charset
];
714 *(bufpt
++) = '-'; exp
= -exp
;
719 *(bufpt
++) = (char)((exp
/100)+'0'); /* 100's digit */
722 *(bufpt
++) = (char)(exp
/10+'0'); /* 10's digit */
723 *(bufpt
++) = (char)(exp
%10+'0'); /* 1's digit */
727 /* The converted number is in buf[] and zero terminated. Output it.
728 ** Note that the number is in the usual order, not reversed as with
729 ** integer conversions. */
730 length
= (int)(bufpt
-zOut
);
733 /* Special case: Add leading zeros if the flag_zeropad flag is
734 ** set and we are not left justified */
735 if( flag_zeropad
&& !flag_leftjustify
&& length
< width
){
737 int nPad
= width
- length
;
738 for(i
=width
; i
>=nPad
; i
--){
739 bufpt
[i
] = bufpt
[i
-nPad
];
742 while( nPad
-- ) bufpt
[i
++] = '0';
745 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
749 *(va_arg(ap
,int*)) = pAccum
->nChar
;
760 bufpt
= getTextArg(pArgList
);
763 buf
[0] = c
= *(bufpt
++);
764 if( (c
&0xc0)==0xc0 ){
765 while( length
<4 && (bufpt
[0]&0xc0)==0x80 ){
766 buf
[length
++] = *(bufpt
++);
773 unsigned int ch
= va_arg(ap
,unsigned int);
777 }else if( ch
<0x00800 ){
778 buf
[0] = 0xc0 + (u8
)((ch
>>6)&0x1f);
779 buf
[1] = 0x80 + (u8
)(ch
& 0x3f);
781 }else if( ch
<0x10000 ){
782 buf
[0] = 0xe0 + (u8
)((ch
>>12)&0x0f);
783 buf
[1] = 0x80 + (u8
)((ch
>>6) & 0x3f);
784 buf
[2] = 0x80 + (u8
)(ch
& 0x3f);
787 buf
[0] = 0xf0 + (u8
)((ch
>>18) & 0x07);
788 buf
[1] = 0x80 + (u8
)((ch
>>12) & 0x3f);
789 buf
[2] = 0x80 + (u8
)((ch
>>6) & 0x3f);
790 buf
[3] = 0x80 + (u8
)(ch
& 0x3f);
796 width
-= precision
-1;
797 if( width
>1 && !flag_leftjustify
){
798 sqlite3_str_appendchar(pAccum
, width
-1, ' ');
801 sqlite3_str_append(pAccum
, buf
, length
);
803 while( precision
> 1 ){
805 if( nPrior
> precision
-1 ) nPrior
= precision
- 1;
806 nCopyBytes
= length
*nPrior
;
807 if( nCopyBytes
+ pAccum
->nChar
>= pAccum
->nAlloc
){
808 sqlite3StrAccumEnlarge(pAccum
, nCopyBytes
);
810 if( pAccum
->accError
) break;
811 sqlite3_str_append(pAccum
,
812 &pAccum
->zText
[pAccum
->nChar
-nCopyBytes
], nCopyBytes
);
819 goto adjust_width_for_utf8
;
823 bufpt
= getTextArg(pArgList
);
826 bufpt
= va_arg(ap
,char*);
830 }else if( xtype
==etDYNSTRING
){
835 && pAccum
->accError
==0
837 /* Special optimization for sqlite3_mprintf("%z..."):
838 ** Extend an existing memory allocation rather than creating
840 assert( (pAccum
->printfFlags
&SQLITE_PRINTF_MALLOCED
)==0 );
841 pAccum
->zText
= bufpt
;
842 pAccum
->nAlloc
= sqlite3DbMallocSize(pAccum
->db
, bufpt
);
843 pAccum
->nChar
= 0x7fffffff & (int)strlen(bufpt
);
844 pAccum
->printfFlags
|= SQLITE_PRINTF_MALLOCED
;
852 /* Set length to the number of bytes needed in order to display
853 ** precision characters */
854 unsigned char *z
= (unsigned char*)bufpt
;
855 while( precision
-- > 0 && z
[0] ){
858 length
= (int)(z
- (unsigned char*)bufpt
);
860 for(length
=0; length
<precision
&& bufpt
[length
]; length
++){}
863 length
= 0x7fffffff & (int)strlen(bufpt
);
865 adjust_width_for_utf8
:
866 if( flag_altform2
&& width
>0 ){
867 /* Adjust width to account for extra bytes in UTF-8 characters */
869 while( ii
>=0 ) if( (bufpt
[ii
--] & 0xc0)==0x80 ) width
++;
872 case etSQLESCAPE
: /* %q: Escape ' characters */
873 case etSQLESCAPE2
: /* %Q: Escape ' and enclose in '...' */
874 case etSQLESCAPE3
: { /* %w: Escape " characters */
876 int needQuote
, isnull
;
878 char q
= ((xtype
==etSQLESCAPE3
)?'"':'\''); /* Quote character */
882 escarg
= getTextArg(pArgList
);
884 escarg
= va_arg(ap
,char*);
887 if( isnull
) escarg
= (xtype
==etSQLESCAPE2
? "NULL" : "(NULL)");
888 /* For %q, %Q, and %w, the precision is the number of bytes (or
889 ** characters if the ! flags is present) to use from the input.
890 ** Because of the extra quoting characters inserted, the number
891 ** of output characters may be larger than the precision.
894 for(i
=n
=0; k
!=0 && (ch
=escarg
[i
])!=0; i
++, k
--){
896 if( flag_altform2
&& (ch
&0xc0)==0xc0 ){
897 while( (escarg
[i
+1]&0xc0)==0x80 ){ i
++; }
900 needQuote
= !isnull
&& xtype
==etSQLESCAPE2
;
903 bufpt
= zExtra
= printfTempBuf(pAccum
, n
);
904 if( bufpt
==0 ) return;
909 if( needQuote
) bufpt
[j
++] = q
;
912 bufpt
[j
++] = ch
= escarg
[i
];
913 if( ch
==q
) bufpt
[j
++] = ch
;
915 if( needQuote
) bufpt
[j
++] = q
;
918 goto adjust_width_for_utf8
;
921 if( (pAccum
->printfFlags
& SQLITE_PRINTF_INTERNAL
)==0 ) return;
922 if( flag_alternateform
){
923 /* %#T means an Expr pointer that uses Expr.u.zToken */
924 Expr
*pExpr
= va_arg(ap
,Expr
*);
925 if( ALWAYS(pExpr
) && ALWAYS(!ExprHasProperty(pExpr
,EP_IntValue
)) ){
926 sqlite3_str_appendall(pAccum
, (const char*)pExpr
->u
.zToken
);
927 sqlite3RecordErrorOffsetOfExpr(pAccum
->db
, pExpr
);
930 /* %T means a Token pointer */
931 Token
*pToken
= va_arg(ap
, Token
*);
932 assert( bArgList
==0 );
933 if( pToken
&& pToken
->n
){
934 sqlite3_str_append(pAccum
, (const char*)pToken
->z
, pToken
->n
);
935 sqlite3RecordErrorByteOffset(pAccum
->db
, pToken
->z
);
943 if( (pAccum
->printfFlags
& SQLITE_PRINTF_INTERNAL
)==0 ) return;
944 pItem
= va_arg(ap
, SrcItem
*);
945 assert( bArgList
==0 );
946 if( pItem
->zAlias
&& !flag_altform2
){
947 sqlite3_str_appendall(pAccum
, pItem
->zAlias
);
948 }else if( pItem
->zName
){
949 if( pItem
->zDatabase
){
950 sqlite3_str_appendall(pAccum
, pItem
->zDatabase
);
951 sqlite3_str_append(pAccum
, ".", 1);
953 sqlite3_str_appendall(pAccum
, pItem
->zName
);
954 }else if( pItem
->zAlias
){
955 sqlite3_str_appendall(pAccum
, pItem
->zAlias
);
957 Select
*pSel
= pItem
->pSelect
;
959 if( pSel
->selFlags
& SF_NestedFrom
){
960 sqlite3_str_appendf(pAccum
, "(join-%u)", pSel
->selId
);
962 sqlite3_str_appendf(pAccum
, "(subquery-%u)", pSel
->selId
);
969 assert( xtype
==etINVALID
);
972 }/* End switch over the format type */
974 ** The text of the conversion is pointed to by "bufpt" and is
975 ** "length" characters long. The field width is "width". Do
976 ** the output. Both length and width are in bytes, not characters,
977 ** at this point. If the "!" flag was present on string conversions
978 ** indicating that width and precision should be expressed in characters,
979 ** then the values have been translated prior to reaching this point.
983 if( !flag_leftjustify
) sqlite3_str_appendchar(pAccum
, width
, ' ');
984 sqlite3_str_append(pAccum
, bufpt
, length
);
985 if( flag_leftjustify
) sqlite3_str_appendchar(pAccum
, width
, ' ');
987 sqlite3_str_append(pAccum
, bufpt
, length
);
991 sqlite3DbFree(pAccum
->db
, zExtra
);
994 }/* End for loop over the format string */
995 } /* End of function */
999 ** The z string points to the first character of a token that is
1000 ** associated with an error. If db does not already have an error
1001 ** byte offset recorded, try to compute the error byte offset for
1002 ** z and set the error byte offset in db.
1004 void sqlite3RecordErrorByteOffset(sqlite3
*db
, const char *z
){
1005 const Parse
*pParse
;
1009 if( NEVER(db
==0) ) return;
1010 if( db
->errByteOffset
!=(-2) ) return;
1011 pParse
= db
->pParse
;
1012 if( NEVER(pParse
==0) ) return;
1013 zText
=pParse
->zTail
;
1014 if( NEVER(zText
==0) ) return;
1015 zEnd
= &zText
[strlen(zText
)];
1016 if( SQLITE_WITHIN(z
,zText
,zEnd
) ){
1017 db
->errByteOffset
= (int)(z
-zText
);
1022 ** If pExpr has a byte offset for the start of a token, record that as
1023 ** as the error offset.
1025 void sqlite3RecordErrorOffsetOfExpr(sqlite3
*db
, const Expr
*pExpr
){
1027 && (ExprHasProperty(pExpr
,EP_OuterON
|EP_InnerON
) || pExpr
->w
.iOfst
<=0)
1029 pExpr
= pExpr
->pLeft
;
1031 if( pExpr
==0 ) return;
1032 db
->errByteOffset
= pExpr
->w
.iOfst
;
1036 ** Enlarge the memory allocation on a StrAccum object so that it is
1037 ** able to accept at least N more bytes of text.
1039 ** Return the number of bytes of text that StrAccum is able to accept
1040 ** after the attempted enlargement. The value returned might be zero.
1042 int sqlite3StrAccumEnlarge(StrAccum
*p
, i64 N
){
1044 assert( p
->nChar
+N
>= p
->nAlloc
); /* Only called if really needed */
1046 testcase(p
->accError
==SQLITE_TOOBIG
);
1047 testcase(p
->accError
==SQLITE_NOMEM
);
1050 if( p
->mxAlloc
==0 ){
1051 sqlite3StrAccumSetError(p
, SQLITE_TOOBIG
);
1052 return p
->nAlloc
- p
->nChar
- 1;
1054 char *zOld
= isMalloced(p
) ? p
->zText
: 0;
1055 i64 szNew
= p
->nChar
+ N
+ 1;
1056 if( szNew
+p
->nChar
<=p
->mxAlloc
){
1057 /* Force exponential buffer size growth as long as it does not overflow,
1058 ** to avoid having to call this routine too often */
1061 if( szNew
> p
->mxAlloc
){
1062 sqlite3_str_reset(p
);
1063 sqlite3StrAccumSetError(p
, SQLITE_TOOBIG
);
1066 p
->nAlloc
= (int)szNew
;
1069 zNew
= sqlite3DbRealloc(p
->db
, zOld
, p
->nAlloc
);
1071 zNew
= sqlite3Realloc(zOld
, p
->nAlloc
);
1074 assert( p
->zText
!=0 || p
->nChar
==0 );
1075 if( !isMalloced(p
) && p
->nChar
>0 ) memcpy(zNew
, p
->zText
, p
->nChar
);
1077 p
->nAlloc
= sqlite3DbMallocSize(p
->db
, zNew
);
1078 p
->printfFlags
|= SQLITE_PRINTF_MALLOCED
;
1080 sqlite3_str_reset(p
);
1081 sqlite3StrAccumSetError(p
, SQLITE_NOMEM
);
1085 assert( N
>=0 && N
<=0x7fffffff );
1090 ** Append N copies of character c to the given string buffer.
1092 void sqlite3_str_appendchar(sqlite3_str
*p
, int N
, char c
){
1093 testcase( p
->nChar
+ (i64
)N
> 0x7fffffff );
1094 if( p
->nChar
+(i64
)N
>= p
->nAlloc
&& (N
= sqlite3StrAccumEnlarge(p
, N
))<=0 ){
1097 while( (N
--)>0 ) p
->zText
[p
->nChar
++] = c
;
1101 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
1102 ** So enlarge if first, then do the append.
1104 ** This is a helper routine to sqlite3_str_append() that does special-case
1105 ** work (enlarging the buffer) using tail recursion, so that the
1106 ** sqlite3_str_append() routine can use fast calling semantics.
1108 static void SQLITE_NOINLINE
enlargeAndAppend(StrAccum
*p
, const char *z
, int N
){
1109 N
= sqlite3StrAccumEnlarge(p
, N
);
1111 memcpy(&p
->zText
[p
->nChar
], z
, N
);
1117 ** Append N bytes of text from z to the StrAccum object. Increase the
1118 ** size of the memory allocation for StrAccum if necessary.
1120 void sqlite3_str_append(sqlite3_str
*p
, const char *z
, int N
){
1121 assert( z
!=0 || N
==0 );
1122 assert( p
->zText
!=0 || p
->nChar
==0 || p
->accError
);
1124 assert( p
->accError
==0 || p
->nAlloc
==0 || p
->mxAlloc
==0 );
1125 if( p
->nChar
+N
>= p
->nAlloc
){
1126 enlargeAndAppend(p
,z
,N
);
1130 memcpy(&p
->zText
[p
->nChar
-N
], z
, N
);
1135 ** Append the complete text of zero-terminated string z[] to the p string.
1137 void sqlite3_str_appendall(sqlite3_str
*p
, const char *z
){
1138 sqlite3_str_append(p
, z
, sqlite3Strlen30(z
));
1143 ** Finish off a string by making sure it is zero-terminated.
1144 ** Return a pointer to the resulting string. Return a NULL
1145 ** pointer if any kind of error was encountered.
1147 static SQLITE_NOINLINE
char *strAccumFinishRealloc(StrAccum
*p
){
1149 assert( p
->mxAlloc
>0 && !isMalloced(p
) );
1150 zText
= sqlite3DbMallocRaw(p
->db
, p
->nChar
+1 );
1152 memcpy(zText
, p
->zText
, p
->nChar
+1);
1153 p
->printfFlags
|= SQLITE_PRINTF_MALLOCED
;
1155 sqlite3StrAccumSetError(p
, SQLITE_NOMEM
);
1160 char *sqlite3StrAccumFinish(StrAccum
*p
){
1162 p
->zText
[p
->nChar
] = 0;
1163 if( p
->mxAlloc
>0 && !isMalloced(p
) ){
1164 return strAccumFinishRealloc(p
);
1171 ** Use the content of the StrAccum passed as the second argument
1172 ** as the result of an SQL function.
1174 void sqlite3ResultStrAccum(sqlite3_context
*pCtx
, StrAccum
*p
){
1176 sqlite3_result_error_code(pCtx
, p
->accError
);
1177 sqlite3_str_reset(p
);
1178 }else if( isMalloced(p
) ){
1179 sqlite3_result_text(pCtx
, p
->zText
, p
->nChar
, SQLITE_DYNAMIC
);
1181 sqlite3_result_text(pCtx
, "", 0, SQLITE_STATIC
);
1182 sqlite3_str_reset(p
);
1187 ** This singleton is an sqlite3_str object that is returned if
1188 ** sqlite3_malloc() fails to provide space for a real one. This
1189 ** sqlite3_str object accepts no new text and always returns
1190 ** an SQLITE_NOMEM error.
1192 static sqlite3_str sqlite3OomStr
= {
1193 0, 0, 0, 0, 0, SQLITE_NOMEM
, 0
1196 /* Finalize a string created using sqlite3_str_new().
1198 char *sqlite3_str_finish(sqlite3_str
*p
){
1200 if( p
!=0 && p
!=&sqlite3OomStr
){
1201 z
= sqlite3StrAccumFinish(p
);
1209 /* Return any error code associated with p */
1210 int sqlite3_str_errcode(sqlite3_str
*p
){
1211 return p
? p
->accError
: SQLITE_NOMEM
;
1214 /* Return the current length of p in bytes */
1215 int sqlite3_str_length(sqlite3_str
*p
){
1216 return p
? p
->nChar
: 0;
1219 /* Return the current value for p */
1220 char *sqlite3_str_value(sqlite3_str
*p
){
1221 if( p
==0 || p
->nChar
==0 ) return 0;
1222 p
->zText
[p
->nChar
] = 0;
1227 ** Reset an StrAccum string. Reclaim all malloced memory.
1229 void sqlite3_str_reset(StrAccum
*p
){
1230 if( isMalloced(p
) ){
1231 sqlite3DbFree(p
->db
, p
->zText
);
1232 p
->printfFlags
&= ~SQLITE_PRINTF_MALLOCED
;
1240 ** Initialize a string accumulator.
1242 ** p: The accumulator to be initialized.
1243 ** db: Pointer to a database connection. May be NULL. Lookaside
1244 ** memory is used if not NULL. db->mallocFailed is set appropriately
1246 ** zBase: An initial buffer. May be NULL in which case the initial buffer
1248 ** n: Size of zBase in bytes. If total space requirements never exceed
1249 ** n then no memory allocations ever occur.
1250 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
1251 ** allocations will ever occur.
1253 void sqlite3StrAccumInit(StrAccum
*p
, sqlite3
*db
, char *zBase
, int n
, int mx
){
1263 /* Allocate and initialize a new dynamic string object */
1264 sqlite3_str
*sqlite3_str_new(sqlite3
*db
){
1265 sqlite3_str
*p
= sqlite3_malloc64(sizeof(*p
));
1267 sqlite3StrAccumInit(p
, 0, 0, 0,
1268 db
? db
->aLimit
[SQLITE_LIMIT_LENGTH
] : SQLITE_MAX_LENGTH
);
1276 ** Print into memory obtained from sqliteMalloc(). Use the internal
1277 ** %-conversion extensions.
1279 char *sqlite3VMPrintf(sqlite3
*db
, const char *zFormat
, va_list ap
){
1281 char zBase
[SQLITE_PRINT_BUF_SIZE
];
1284 sqlite3StrAccumInit(&acc
, db
, zBase
, sizeof(zBase
),
1285 db
->aLimit
[SQLITE_LIMIT_LENGTH
]);
1286 acc
.printfFlags
= SQLITE_PRINTF_INTERNAL
;
1287 sqlite3_str_vappendf(&acc
, zFormat
, ap
);
1288 z
= sqlite3StrAccumFinish(&acc
);
1289 if( acc
.accError
==SQLITE_NOMEM
){
1290 sqlite3OomFault(db
);
1296 ** Print into memory obtained from sqliteMalloc(). Use the internal
1297 ** %-conversion extensions.
1299 char *sqlite3MPrintf(sqlite3
*db
, const char *zFormat
, ...){
1302 va_start(ap
, zFormat
);
1303 z
= sqlite3VMPrintf(db
, zFormat
, ap
);
1309 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
1310 ** %-conversion extensions.
1312 char *sqlite3_vmprintf(const char *zFormat
, va_list ap
){
1314 char zBase
[SQLITE_PRINT_BUF_SIZE
];
1317 #ifdef SQLITE_ENABLE_API_ARMOR
1319 (void)SQLITE_MISUSE_BKPT
;
1323 #ifndef SQLITE_OMIT_AUTOINIT
1324 if( sqlite3_initialize() ) return 0;
1326 sqlite3StrAccumInit(&acc
, 0, zBase
, sizeof(zBase
), SQLITE_MAX_LENGTH
);
1327 sqlite3_str_vappendf(&acc
, zFormat
, ap
);
1328 z
= sqlite3StrAccumFinish(&acc
);
1333 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
1334 ** %-conversion extensions.
1336 char *sqlite3_mprintf(const char *zFormat
, ...){
1339 #ifndef SQLITE_OMIT_AUTOINIT
1340 if( sqlite3_initialize() ) return 0;
1342 va_start(ap
, zFormat
);
1343 z
= sqlite3_vmprintf(zFormat
, ap
);
1349 ** sqlite3_snprintf() works like snprintf() except that it ignores the
1350 ** current locale settings. This is important for SQLite because we
1351 ** are not able to use a "," as the decimal point in place of "." as
1352 ** specified by some locales.
1354 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
1355 ** from the snprintf() standard. Unfortunately, it is too late to change
1356 ** this without breaking compatibility, so we just have to live with the
1359 ** sqlite3_vsnprintf() is the varargs version.
1361 char *sqlite3_vsnprintf(int n
, char *zBuf
, const char *zFormat
, va_list ap
){
1363 if( n
<=0 ) return zBuf
;
1364 #ifdef SQLITE_ENABLE_API_ARMOR
1365 if( zBuf
==0 || zFormat
==0 ) {
1366 (void)SQLITE_MISUSE_BKPT
;
1367 if( zBuf
) zBuf
[0] = 0;
1371 sqlite3StrAccumInit(&acc
, 0, zBuf
, n
, 0);
1372 sqlite3_str_vappendf(&acc
, zFormat
, ap
);
1373 zBuf
[acc
.nChar
] = 0;
1376 char *sqlite3_snprintf(int n
, char *zBuf
, const char *zFormat
, ...){
1379 if( n
<=0 ) return zBuf
;
1380 #ifdef SQLITE_ENABLE_API_ARMOR
1381 if( zBuf
==0 || zFormat
==0 ) {
1382 (void)SQLITE_MISUSE_BKPT
;
1383 if( zBuf
) zBuf
[0] = 0;
1387 sqlite3StrAccumInit(&acc
, 0, zBuf
, n
, 0);
1388 va_start(ap
,zFormat
);
1389 sqlite3_str_vappendf(&acc
, zFormat
, ap
);
1391 zBuf
[acc
.nChar
] = 0;
1396 ** This is the routine that actually formats the sqlite3_log() message.
1397 ** We house it in a separate routine from sqlite3_log() to avoid using
1398 ** stack space on small-stack systems when logging is disabled.
1400 ** sqlite3_log() must render into a static buffer. It cannot dynamically
1401 ** allocate memory because it might be called while the memory allocator
1404 ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
1405 ** certain format characters (%q) or for very large precisions or widths.
1406 ** Care must be taken that any sqlite3_log() calls that occur while the
1407 ** memory mutex is held do not use these mechanisms.
1409 static void renderLogMsg(int iErrCode
, const char *zFormat
, va_list ap
){
1410 StrAccum acc
; /* String accumulator */
1411 char zMsg
[SQLITE_PRINT_BUF_SIZE
*3]; /* Complete log message */
1413 sqlite3StrAccumInit(&acc
, 0, zMsg
, sizeof(zMsg
), 0);
1414 sqlite3_str_vappendf(&acc
, zFormat
, ap
);
1415 sqlite3GlobalConfig
.xLog(sqlite3GlobalConfig
.pLogArg
, iErrCode
,
1416 sqlite3StrAccumFinish(&acc
));
1420 ** Format and write a message to the log if logging is enabled.
1422 void sqlite3_log(int iErrCode
, const char *zFormat
, ...){
1423 va_list ap
; /* Vararg list */
1424 if( sqlite3GlobalConfig
.xLog
){
1425 va_start(ap
, zFormat
);
1426 renderLogMsg(iErrCode
, zFormat
, ap
);
1431 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1433 ** A version of printf() that understands %lld. Used for debugging.
1434 ** The printf() built into some versions of windows does not understand %lld
1435 ** and segfaults if you give it a long long int.
1437 void sqlite3DebugPrintf(const char *zFormat
, ...){
1440 char zBuf
[SQLITE_PRINT_BUF_SIZE
*10];
1441 sqlite3StrAccumInit(&acc
, 0, zBuf
, sizeof(zBuf
), 0);
1442 va_start(ap
,zFormat
);
1443 sqlite3_str_vappendf(&acc
, zFormat
, ap
);
1445 sqlite3StrAccumFinish(&acc
);
1446 #ifdef SQLITE_OS_TRACE_PROC
1448 extern void SQLITE_OS_TRACE_PROC(const char *zBuf
, int nBuf
);
1449 SQLITE_OS_TRACE_PROC(zBuf
, sizeof(zBuf
));
1452 fprintf(stdout
,"%s", zBuf
);
1460 ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
1461 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1463 void sqlite3_str_appendf(StrAccum
*p
, const char *zFormat
, ...){
1465 va_start(ap
,zFormat
);
1466 sqlite3_str_vappendf(p
, zFormat
, ap
);