2 ** The "printf" code that follows dates from the 1980's. It is in
3 ** the public domain. The original comments are included here for
4 ** completeness. They are very out-of-date but might be useful as
5 ** an historical reference. Most of the "enhancements" have been backed
6 ** out so that the functionality is now the same as standard printf().
8 **************************************************************************
10 ** This file contains code for a set of "printf"-like routines. These
11 ** routines format strings much like the printf() from the standard C
12 ** library, though the implementation here has enhancements to support
15 #include "sqliteInt.h"
18 ** If the strchrnul() library function is available, then set
19 ** HAVE_STRCHRNUL. If that routine is not available, this module
20 ** will supply its own. The built-in version is slower than
21 ** the glibc version so the glibc version is definitely preferred.
23 #if !defined(HAVE_STRCHRNUL)
24 # define HAVE_STRCHRNUL 0
29 ** Conversion types fall into various categories as defined by the
30 ** following enumeration.
32 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
33 #define etFLOAT 2 /* Floating point. %f */
34 #define etEXP 3 /* Exponentional notation. %e and %E */
35 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
36 #define etSIZE 5 /* Return number of characters processed so far. %n */
37 #define etSTRING 6 /* Strings. %s */
38 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
39 #define etPERCENT 8 /* Percent symbol. %% */
40 #define etCHARX 9 /* Characters. %c */
41 /* The rest are extensions, not normally found in printf() */
42 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
43 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
44 NULL pointers replaced by SQL NULL. %Q */
45 #define etTOKEN 12 /* a pointer to a Token structure */
46 #define etSRCLIST 13 /* a pointer to a SrcList */
47 #define etPOINTER 14 /* The %p conversion */
48 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
49 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
51 #define etINVALID 0 /* Any unrecognized conversion type */
55 ** An "etByte" is an 8-bit unsigned value.
57 typedef unsigned char etByte
;
60 ** Each builtin conversion character (ex: the 'd' in "%d") is described
61 ** by an instance of the following structure
63 typedef struct et_info
{ /* Information about each format field */
64 char fmttype
; /* The format field code letter */
65 etByte base
; /* The base for radix conversion */
66 etByte flags
; /* One or more of FLAG_ constants below */
67 etByte type
; /* Conversion paradigm */
68 etByte charset
; /* Offset into aDigits[] of the digits string */
69 etByte prefix
; /* Offset into aPrefix[] of the prefix string */
73 ** Allowed values for et_info.flags
75 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
76 #define FLAG_INTERN 2 /* True if for internal use only */
77 #define FLAG_STRING 4 /* Allow infinity precision */
81 ** The following table is searched linearly, so it is good to put the
82 ** most frequently used conversion types first.
84 static const char aDigits
[] = "0123456789ABCDEF0123456789abcdef";
85 static const char aPrefix
[] = "-x0\000X0";
86 static const et_info fmtinfo
[] = {
87 { 'd', 10, 1, etRADIX
, 0, 0 },
88 { 's', 0, 4, etSTRING
, 0, 0 },
89 { 'g', 0, 1, etGENERIC
, 30, 0 },
90 { 'z', 0, 4, etDYNSTRING
, 0, 0 },
91 { 'q', 0, 4, etSQLESCAPE
, 0, 0 },
92 { 'Q', 0, 4, etSQLESCAPE2
, 0, 0 },
93 { 'w', 0, 4, etSQLESCAPE3
, 0, 0 },
94 { 'c', 0, 0, etCHARX
, 0, 0 },
95 { 'o', 8, 0, etRADIX
, 0, 2 },
96 { 'u', 10, 0, etRADIX
, 0, 0 },
97 { 'x', 16, 0, etRADIX
, 16, 1 },
98 { 'X', 16, 0, etRADIX
, 0, 4 },
99 #ifndef SQLITE_OMIT_FLOATING_POINT
100 { 'f', 0, 1, etFLOAT
, 0, 0 },
101 { 'e', 0, 1, etEXP
, 30, 0 },
102 { 'E', 0, 1, etEXP
, 14, 0 },
103 { 'G', 0, 1, etGENERIC
, 14, 0 },
105 { 'i', 10, 1, etRADIX
, 0, 0 },
106 { 'n', 0, 0, etSIZE
, 0, 0 },
107 { '%', 0, 0, etPERCENT
, 0, 0 },
108 { 'p', 16, 0, etPOINTER
, 0, 1 },
110 /* All the rest have the FLAG_INTERN bit set and are thus for internal
112 { 'T', 0, 2, etTOKEN
, 0, 0 },
113 { 'S', 0, 2, etSRCLIST
, 0, 0 },
114 { 'r', 10, 3, etORDINAL
, 0, 0 },
118 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
119 ** conversions will work.
121 #ifndef SQLITE_OMIT_FLOATING_POINT
123 ** "*val" is a double such that 0.1 <= *val < 10.0
124 ** Return the ascii code for the leading digit of *val, then
125 ** multiply "*val" by 10.0 to renormalize.
128 ** input: *val = 3.14159
129 ** output: *val = 1.4159 function return = '3'
131 ** The counter *cnt is incremented each time. After counter exceeds
132 ** 16 (the number of significant digits in a 64-bit float) '0' is
135 static char et_getdigit(LONGDOUBLE_TYPE
*val
, int *cnt
){
138 if( (*cnt
)<=0 ) return '0';
143 *val
= (*val
- d
)*10.0;
146 #endif /* SQLITE_OMIT_FLOATING_POINT */
149 ** Set the StrAccum object to an error mode.
151 static void setStrAccumError(StrAccum
*p
, u8 eError
){
152 p
->accError
= eError
;
157 ** Extra argument values from a PrintfArguments object
159 static sqlite3_int64
getIntArg(PrintfArguments
*p
){
160 if( p
->nArg
<=p
->nUsed
) return 0;
161 return sqlite3_value_int64(p
->apArg
[p
->nUsed
++]);
163 static double getDoubleArg(PrintfArguments
*p
){
164 if( p
->nArg
<=p
->nUsed
) return 0.0;
165 return sqlite3_value_double(p
->apArg
[p
->nUsed
++]);
167 static char *getTextArg(PrintfArguments
*p
){
168 if( p
->nArg
<=p
->nUsed
) return 0;
169 return (char*)sqlite3_value_text(p
->apArg
[p
->nUsed
++]);
174 ** On machines with a small stack size, you can redefine the
175 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
177 #ifndef SQLITE_PRINT_BUF_SIZE
178 # define SQLITE_PRINT_BUF_SIZE 70
180 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
183 ** Render a string given by "fmt" into the StrAccum object.
185 void sqlite3VXPrintf(
186 StrAccum
*pAccum
, /* Accumulate results here */
187 u32 bFlags
, /* SQLITE_PRINTF_* flags */
188 const char *fmt
, /* Format string */
189 va_list ap
/* arguments */
191 int c
; /* Next character in the format string */
192 char *bufpt
; /* Pointer to the conversion buffer */
193 int precision
; /* Precision of the current field */
194 int length
; /* Length of the field */
195 int idx
; /* A general purpose loop counter */
196 int width
; /* Width of the current field */
197 etByte flag_leftjustify
; /* True if "-" flag is present */
198 etByte flag_plussign
; /* True if "+" flag is present */
199 etByte flag_blanksign
; /* True if " " flag is present */
200 etByte flag_alternateform
; /* True if "#" flag is present */
201 etByte flag_altform2
; /* True if "!" flag is present */
202 etByte flag_zeropad
; /* True if field width constant starts with zero */
203 etByte flag_long
; /* True if "l" flag is present */
204 etByte flag_longlong
; /* True if the "ll" flag is present */
205 etByte done
; /* Loop termination flag */
206 etByte xtype
= 0; /* Conversion paradigm */
207 u8 bArgList
; /* True for SQLITE_PRINTF_SQLFUNC */
208 u8 useIntern
; /* Ok to use internal conversions (ex: %T) */
209 char prefix
; /* Prefix character. "+" or "-" or " " or '\0'. */
210 sqlite_uint64 longvalue
; /* Value for integer types */
211 LONGDOUBLE_TYPE realvalue
; /* Value for real types */
212 const et_info
*infop
; /* Pointer to the appropriate info structure */
213 char *zOut
; /* Rendering buffer */
214 int nOut
; /* Size of the rendering buffer */
215 char *zExtra
= 0; /* Malloced memory used by some conversion */
216 #ifndef SQLITE_OMIT_FLOATING_POINT
217 int exp
, e2
; /* exponent of real numbers */
218 int nsd
; /* Number of significant digits returned */
219 double rounder
; /* Used for rounding floating point values */
220 etByte flag_dp
; /* True if decimal point should be shown */
221 etByte flag_rtz
; /* True if trailing zeros should be removed */
223 PrintfArguments
*pArgList
= 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
224 char buf
[etBUFSIZE
]; /* Conversion buffer */
228 if( (bArgList
= (bFlags
& SQLITE_PRINTF_SQLFUNC
))!=0 ){
229 pArgList
= va_arg(ap
, PrintfArguments
*);
231 useIntern
= bFlags
& SQLITE_PRINTF_INTERNAL
;
233 bArgList
= useIntern
= 0;
235 for(; (c
=(*fmt
))!=0; ++fmt
){
239 fmt
= strchrnul(fmt
, '%');
241 do{ fmt
++; }while( *fmt
&& *fmt
!= '%' );
243 sqlite3StrAccumAppend(pAccum
, bufpt
, (int)(fmt
- bufpt
));
246 if( (c
=(*++fmt
))==0 ){
247 sqlite3StrAccumAppend(pAccum
, "%", 1);
250 /* Find out what flags are present */
251 flag_leftjustify
= flag_plussign
= flag_blanksign
=
252 flag_alternateform
= flag_altform2
= flag_zeropad
= 0;
256 case '-': flag_leftjustify
= 1; break;
257 case '+': flag_plussign
= 1; break;
258 case ' ': flag_blanksign
= 1; break;
259 case '#': flag_alternateform
= 1; break;
260 case '!': flag_altform2
= 1; break;
261 case '0': flag_zeropad
= 1; break;
262 default: done
= 1; break;
264 }while( !done
&& (c
=(*++fmt
))!=0 );
265 /* Get the field width */
269 width
= (int)getIntArg(pArgList
);
271 width
= va_arg(ap
,int);
274 flag_leftjustify
= 1;
279 while( c
>='0' && c
<='9' ){
280 width
= width
*10 + c
- '0';
284 /* Get the precision */
290 precision
= (int)getIntArg(pArgList
);
292 precision
= va_arg(ap
,int);
294 if( precision
<0 ) precision
= -precision
;
297 while( c
>='0' && c
<='9' ){
298 precision
= precision
*10 + c
- '0';
305 /* Get the conversion type modifier */
316 flag_long
= flag_longlong
= 0;
318 /* Fetch the info entry for the field */
321 for(idx
=0; idx
<ArraySize(fmtinfo
); idx
++){
322 if( c
==fmtinfo
[idx
].fmttype
){
323 infop
= &fmtinfo
[idx
];
324 if( useIntern
|| (infop
->flags
& FLAG_INTERN
)==0 ){
334 ** At this point, variables are initialized as follows:
336 ** flag_alternateform TRUE if a '#' is present.
337 ** flag_altform2 TRUE if a '!' is present.
338 ** flag_plussign TRUE if a '+' is present.
339 ** flag_leftjustify TRUE if a '-' is present or if the
340 ** field width was negative.
341 ** flag_zeropad TRUE if the width began with 0.
342 ** flag_long TRUE if the letter 'l' (ell) prefixed
343 ** the conversion character.
344 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
345 ** the conversion character.
346 ** flag_blanksign TRUE if a ' ' is present.
347 ** width The specified field width. This is
348 ** always non-negative. Zero is the default.
349 ** precision The specified precision. The default
351 ** xtype The class of the conversion.
352 ** infop Pointer to the appropriate info struct.
356 flag_longlong
= sizeof(char*)==sizeof(i64
);
357 flag_long
= sizeof(char*)==sizeof(long int);
358 /* Fall through into the next case */
361 if( infop
->flags
& FLAG_SIGNED
){
364 v
= getIntArg(pArgList
);
365 }else if( flag_longlong
){
367 }else if( flag_long
){
368 v
= va_arg(ap
,long int);
373 if( v
==SMALLEST_INT64
){
374 longvalue
= ((u64
)1)<<63;
381 if( flag_plussign
) prefix
= '+';
382 else if( flag_blanksign
) prefix
= ' ';
387 longvalue
= (u64
)getIntArg(pArgList
);
388 }else if( flag_longlong
){
389 longvalue
= va_arg(ap
,u64
);
390 }else if( flag_long
){
391 longvalue
= va_arg(ap
,unsigned long int);
393 longvalue
= va_arg(ap
,unsigned int);
397 if( longvalue
==0 ) flag_alternateform
= 0;
398 if( flag_zeropad
&& precision
<width
-(prefix
!=0) ){
399 precision
= width
-(prefix
!=0);
401 if( precision
<etBUFSIZE
-10 ){
405 nOut
= precision
+ 10;
406 zOut
= zExtra
= sqlite3Malloc( nOut
);
408 setStrAccumError(pAccum
, STRACCUM_NOMEM
);
412 bufpt
= &zOut
[nOut
-1];
413 if( xtype
==etORDINAL
){
414 static const char zOrd
[] = "thstndrd";
415 int x
= (int)(longvalue
% 10);
416 if( x
>=4 || (longvalue
/10)%10==1 ){
419 *(--bufpt
) = zOrd
[x
*2+1];
420 *(--bufpt
) = zOrd
[x
*2];
423 const char *cset
= &aDigits
[infop
->charset
];
424 u8 base
= infop
->base
;
425 do{ /* Convert to ascii */
426 *(--bufpt
) = cset
[longvalue
%base
];
427 longvalue
= longvalue
/base
;
428 }while( longvalue
>0 );
430 length
= (int)(&zOut
[nOut
-1]-bufpt
);
431 for(idx
=precision
-length
; idx
>0; idx
--){
432 *(--bufpt
) = '0'; /* Zero pad */
434 if( prefix
) *(--bufpt
) = prefix
; /* Add sign */
435 if( flag_alternateform
&& infop
->prefix
){ /* Add "0" or "0x" */
438 pre
= &aPrefix
[infop
->prefix
];
439 for(; (x
=(*pre
))!=0; pre
++) *(--bufpt
) = x
;
441 length
= (int)(&zOut
[nOut
-1]-bufpt
);
447 realvalue
= getDoubleArg(pArgList
);
449 realvalue
= va_arg(ap
,double);
451 #ifdef SQLITE_OMIT_FLOATING_POINT
454 if( precision
<0 ) precision
= 6; /* Set default precision */
456 realvalue
= -realvalue
;
459 if( flag_plussign
) prefix
= '+';
460 else if( flag_blanksign
) prefix
= ' ';
463 if( xtype
==etGENERIC
&& precision
>0 ) precision
--;
464 for(idx
=precision
, rounder
=0.5; idx
>0; idx
--, rounder
*=0.1){}
465 if( xtype
==etFLOAT
) realvalue
+= rounder
;
466 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
468 if( sqlite3IsNaN((double)realvalue
) ){
474 LONGDOUBLE_TYPE scale
= 1.0;
475 while( realvalue
>=1e100
*scale
&& exp
<=350 ){ scale
*= 1e100
;exp
+=100;}
476 while( realvalue
>=1e64
*scale
&& exp
<=350 ){ scale
*= 1e64
; exp
+=64; }
477 while( realvalue
>=1e8
*scale
&& exp
<=350 ){ scale
*= 1e8
; exp
+=8; }
478 while( realvalue
>=10.0*scale
&& exp
<=350 ){ scale
*= 10.0; exp
++; }
480 while( realvalue
<1e-8 ){ realvalue
*= 1e8
; exp
-=8; }
481 while( realvalue
<1.0 ){ realvalue
*= 10.0; exp
--; }
485 }else if( prefix
=='+' ){
490 length
= sqlite3Strlen30(bufpt
);
496 ** If the field type is etGENERIC, then convert to either etEXP
497 ** or etFLOAT, as appropriate.
499 if( xtype
!=etFLOAT
){
500 realvalue
+= rounder
;
501 if( realvalue
>=10.0 ){ realvalue
*= 0.1; exp
++; }
503 if( xtype
==etGENERIC
){
504 flag_rtz
= !flag_alternateform
;
505 if( exp
<-4 || exp
>precision
){
508 precision
= precision
- exp
;
512 flag_rtz
= flag_altform2
;
519 if( MAX(e2
,0)+precision
+width
> etBUFSIZE
- 15 ){
520 bufpt
= zExtra
= sqlite3Malloc( MAX(e2
,0)+precision
+width
+15 );
522 setStrAccumError(pAccum
, STRACCUM_NOMEM
);
527 nsd
= 16 + flag_altform2
*10;
528 flag_dp
= (precision
>0 ?1:0) | flag_alternateform
| flag_altform2
;
529 /* The sign in front of the number */
533 /* Digits prior to the decimal point */
538 *(bufpt
++) = et_getdigit(&realvalue
,&nsd
);
541 /* The decimal point */
545 /* "0" digits after the decimal point but before the first
546 ** significant digit of the number */
547 for(e2
++; e2
<0; precision
--, e2
++){
548 assert( precision
>0 );
551 /* Significant digits after the decimal point */
552 while( (precision
--)>0 ){
553 *(bufpt
++) = et_getdigit(&realvalue
,&nsd
);
555 /* Remove trailing zeros and the "." if no digits follow the "." */
556 if( flag_rtz
&& flag_dp
){
557 while( bufpt
[-1]=='0' ) *(--bufpt
) = 0;
558 assert( bufpt
>zOut
);
559 if( bufpt
[-1]=='.' ){
567 /* Add the "eNNN" suffix */
569 *(bufpt
++) = aDigits
[infop
->charset
];
571 *(bufpt
++) = '-'; exp
= -exp
;
576 *(bufpt
++) = (char)((exp
/100)+'0'); /* 100's digit */
579 *(bufpt
++) = (char)(exp
/10+'0'); /* 10's digit */
580 *(bufpt
++) = (char)(exp
%10+'0'); /* 1's digit */
584 /* The converted number is in buf[] and zero terminated. Output it.
585 ** Note that the number is in the usual order, not reversed as with
586 ** integer conversions. */
587 length
= (int)(bufpt
-zOut
);
590 /* Special case: Add leading zeros if the flag_zeropad flag is
591 ** set and we are not left justified */
592 if( flag_zeropad
&& !flag_leftjustify
&& length
< width
){
594 int nPad
= width
- length
;
595 for(i
=width
; i
>=nPad
; i
--){
596 bufpt
[i
] = bufpt
[i
-nPad
];
599 while( nPad
-- ) bufpt
[i
++] = '0';
602 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
606 *(va_arg(ap
,int*)) = pAccum
->nChar
;
617 bufpt
= getTextArg(pArgList
);
618 c
= bufpt
? bufpt
[0] : 0;
623 width
-= precision
-1;
624 if( width
>1 && !flag_leftjustify
){
625 sqlite3AppendChar(pAccum
, width
-1, ' ');
628 sqlite3AppendChar(pAccum
, precision
-1, c
);
637 bufpt
= getTextArg(pArgList
);
639 bufpt
= va_arg(ap
,char*);
643 }else if( xtype
==etDYNSTRING
&& !bArgList
){
647 for(length
=0; length
<precision
&& bufpt
[length
]; length
++){}
649 length
= sqlite3Strlen30(bufpt
);
655 int i
, j
, k
, n
, isnull
;
658 char q
= ((xtype
==etSQLESCAPE3
)?'"':'\''); /* Quote character */
662 escarg
= getTextArg(pArgList
);
664 escarg
= va_arg(ap
,char*);
667 if( isnull
) escarg
= (xtype
==etSQLESCAPE2
? "NULL" : "(NULL)");
669 for(i
=n
=0; k
!=0 && (ch
=escarg
[i
])!=0; i
++, k
--){
672 needQuote
= !isnull
&& xtype
==etSQLESCAPE2
;
673 n
+= i
+ 1 + needQuote
*2;
675 bufpt
= zExtra
= sqlite3Malloc( n
);
677 setStrAccumError(pAccum
, STRACCUM_NOMEM
);
684 if( needQuote
) bufpt
[j
++] = q
;
687 bufpt
[j
++] = ch
= escarg
[i
];
688 if( ch
==q
) bufpt
[j
++] = ch
;
690 if( needQuote
) bufpt
[j
++] = q
;
693 /* The precision in %q and %Q means how many input characters to
694 ** consume, not the length of the output...
695 ** if( precision>=0 && precision<length ) length = precision; */
699 Token
*pToken
= va_arg(ap
, Token
*);
700 assert( bArgList
==0 );
701 if( pToken
&& pToken
->n
){
702 sqlite3StrAccumAppend(pAccum
, (const char*)pToken
->z
, pToken
->n
);
708 SrcList
*pSrc
= va_arg(ap
, SrcList
*);
709 int k
= va_arg(ap
, int);
710 struct SrcList_item
*pItem
= &pSrc
->a
[k
];
711 assert( bArgList
==0 );
712 assert( k
>=0 && k
<pSrc
->nSrc
);
713 if( pItem
->zDatabase
){
714 sqlite3StrAccumAppendAll(pAccum
, pItem
->zDatabase
);
715 sqlite3StrAccumAppend(pAccum
, ".", 1);
717 sqlite3StrAccumAppendAll(pAccum
, pItem
->zName
);
722 assert( xtype
==etINVALID
);
725 }/* End switch over the format type */
727 ** The text of the conversion is pointed to by "bufpt" and is
728 ** "length" characters long. The field width is "width". Do
732 if( width
>0 && !flag_leftjustify
) sqlite3AppendChar(pAccum
, width
, ' ');
733 sqlite3StrAccumAppend(pAccum
, bufpt
, length
);
734 if( width
>0 && flag_leftjustify
) sqlite3AppendChar(pAccum
, width
, ' ');
737 sqlite3_free(zExtra
);
740 }/* End for loop over the format string */
741 } /* End of function */
744 ** Enlarge the memory allocation on a StrAccum object so that it is
745 ** able to accept at least N more bytes of text.
747 ** Return the number of bytes of text that StrAccum is able to accept
748 ** after the attempted enlargement. The value returned might be zero.
750 static int sqlite3StrAccumEnlarge(StrAccum
*p
, int N
){
752 assert( p
->nChar
+N
>= p
->nAlloc
); /* Only called if really needed */
754 testcase(p
->accError
==STRACCUM_TOOBIG
);
755 testcase(p
->accError
==STRACCUM_NOMEM
);
759 N
= p
->nAlloc
- p
->nChar
- 1;
760 setStrAccumError(p
, STRACCUM_TOOBIG
);
763 char *zOld
= (p
->zText
==p
->zBase
? 0 : p
->zText
);
764 i64 szNew
= p
->nChar
;
766 if( szNew
> p
->mxAlloc
){
767 sqlite3StrAccumReset(p
);
768 setStrAccumError(p
, STRACCUM_TOOBIG
);
771 p
->nAlloc
= (int)szNew
;
773 if( p
->useMalloc
==1 ){
774 zNew
= sqlite3DbRealloc(p
->db
, zOld
, p
->nAlloc
);
776 zNew
= sqlite3_realloc(zOld
, p
->nAlloc
);
779 assert( p
->zText
!=0 || p
->nChar
==0 );
780 if( zOld
==0 && p
->nChar
>0 ) memcpy(zNew
, p
->zText
, p
->nChar
);
783 sqlite3StrAccumReset(p
);
784 setStrAccumError(p
, STRACCUM_NOMEM
);
792 ** Append N copies of character c to the given string buffer.
794 void sqlite3AppendChar(StrAccum
*p
, int N
, char c
){
795 if( p
->nChar
+N
>= p
->nAlloc
&& (N
= sqlite3StrAccumEnlarge(p
, N
))<=0 ) return;
796 while( (N
--)>0 ) p
->zText
[p
->nChar
++] = c
;
800 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
801 ** So enlarge if first, then do the append.
803 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
804 ** work (enlarging the buffer) using tail recursion, so that the
805 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
807 static void SQLITE_NOINLINE
enlargeAndAppend(StrAccum
*p
, const char *z
, int N
){
808 N
= sqlite3StrAccumEnlarge(p
, N
);
810 memcpy(&p
->zText
[p
->nChar
], z
, N
);
816 ** Append N bytes of text from z to the StrAccum object. Increase the
817 ** size of the memory allocation for StrAccum if necessary.
819 void sqlite3StrAccumAppend(StrAccum
*p
, const char *z
, int N
){
821 assert( p
->zText
!=0 || p
->nChar
==0 || p
->accError
);
823 assert( p
->accError
==0 || p
->nAlloc
==0 );
824 if( p
->nChar
+N
>= p
->nAlloc
){
825 enlargeAndAppend(p
,z
,N
);
829 memcpy(&p
->zText
[p
->nChar
-N
], z
, N
);
834 ** Append the complete text of zero-terminated string z[] to the p string.
836 void sqlite3StrAccumAppendAll(StrAccum
*p
, const char *z
){
837 sqlite3StrAccumAppend(p
, z
, sqlite3Strlen30(z
));
842 ** Finish off a string by making sure it is zero-terminated.
843 ** Return a pointer to the resulting string. Return a NULL
844 ** pointer if any kind of error was encountered.
846 char *sqlite3StrAccumFinish(StrAccum
*p
){
848 p
->zText
[p
->nChar
] = 0;
849 if( p
->useMalloc
&& p
->zText
==p
->zBase
){
850 if( p
->useMalloc
==1 ){
851 p
->zText
= sqlite3DbMallocRaw(p
->db
, p
->nChar
+1 );
853 p
->zText
= sqlite3_malloc(p
->nChar
+1);
856 memcpy(p
->zText
, p
->zBase
, p
->nChar
+1);
858 setStrAccumError(p
, STRACCUM_NOMEM
);
866 ** Reset an StrAccum string. Reclaim all malloced memory.
868 void sqlite3StrAccumReset(StrAccum
*p
){
869 if( p
->zText
!=p
->zBase
){
870 if( p
->useMalloc
==1 ){
871 sqlite3DbFree(p
->db
, p
->zText
);
873 sqlite3_free(p
->zText
);
880 ** Initialize a string accumulator
882 void sqlite3StrAccumInit(StrAccum
*p
, char *zBase
, int n
, int mx
){
883 p
->zText
= p
->zBase
= zBase
;
893 ** Print into memory obtained from sqliteMalloc(). Use the internal
894 ** %-conversion extensions.
896 char *sqlite3VMPrintf(sqlite3
*db
, const char *zFormat
, va_list ap
){
898 char zBase
[SQLITE_PRINT_BUF_SIZE
];
901 sqlite3StrAccumInit(&acc
, zBase
, sizeof(zBase
),
902 db
->aLimit
[SQLITE_LIMIT_LENGTH
]);
904 sqlite3VXPrintf(&acc
, SQLITE_PRINTF_INTERNAL
, zFormat
, ap
);
905 z
= sqlite3StrAccumFinish(&acc
);
906 if( acc
.accError
==STRACCUM_NOMEM
){
907 db
->mallocFailed
= 1;
913 ** Print into memory obtained from sqliteMalloc(). Use the internal
914 ** %-conversion extensions.
916 char *sqlite3MPrintf(sqlite3
*db
, const char *zFormat
, ...){
919 va_start(ap
, zFormat
);
920 z
= sqlite3VMPrintf(db
, zFormat
, ap
);
926 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
927 ** the string and before returning. This routine is intended to be used
928 ** to modify an existing string. For example:
930 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
933 char *sqlite3MAppendf(sqlite3
*db
, char *zStr
, const char *zFormat
, ...){
936 va_start(ap
, zFormat
);
937 z
= sqlite3VMPrintf(db
, zFormat
, ap
);
939 sqlite3DbFree(db
, zStr
);
944 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
945 ** %-conversion extensions.
947 char *sqlite3_vmprintf(const char *zFormat
, va_list ap
){
949 char zBase
[SQLITE_PRINT_BUF_SIZE
];
951 #ifndef SQLITE_OMIT_AUTOINIT
952 if( sqlite3_initialize() ) return 0;
954 sqlite3StrAccumInit(&acc
, zBase
, sizeof(zBase
), SQLITE_MAX_LENGTH
);
956 sqlite3VXPrintf(&acc
, 0, zFormat
, ap
);
957 z
= sqlite3StrAccumFinish(&acc
);
962 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
963 ** %-conversion extensions.
965 char *sqlite3_mprintf(const char *zFormat
, ...){
968 #ifndef SQLITE_OMIT_AUTOINIT
969 if( sqlite3_initialize() ) return 0;
971 va_start(ap
, zFormat
);
972 z
= sqlite3_vmprintf(zFormat
, ap
);
978 ** sqlite3_snprintf() works like snprintf() except that it ignores the
979 ** current locale settings. This is important for SQLite because we
980 ** are not able to use a "," as the decimal point in place of "." as
981 ** specified by some locales.
983 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
984 ** from the snprintf() standard. Unfortunately, it is too late to change
985 ** this without breaking compatibility, so we just have to live with the
988 ** sqlite3_vsnprintf() is the varargs version.
990 char *sqlite3_vsnprintf(int n
, char *zBuf
, const char *zFormat
, va_list ap
){
992 if( n
<=0 ) return zBuf
;
993 sqlite3StrAccumInit(&acc
, zBuf
, n
, 0);
995 sqlite3VXPrintf(&acc
, 0, zFormat
, ap
);
996 return sqlite3StrAccumFinish(&acc
);
998 char *sqlite3_snprintf(int n
, char *zBuf
, const char *zFormat
, ...){
1001 va_start(ap
,zFormat
);
1002 z
= sqlite3_vsnprintf(n
, zBuf
, zFormat
, ap
);
1008 ** This is the routine that actually formats the sqlite3_log() message.
1009 ** We house it in a separate routine from sqlite3_log() to avoid using
1010 ** stack space on small-stack systems when logging is disabled.
1012 ** sqlite3_log() must render into a static buffer. It cannot dynamically
1013 ** allocate memory because it might be called while the memory allocator
1016 static void renderLogMsg(int iErrCode
, const char *zFormat
, va_list ap
){
1017 StrAccum acc
; /* String accumulator */
1018 char zMsg
[SQLITE_PRINT_BUF_SIZE
*3]; /* Complete log message */
1020 sqlite3StrAccumInit(&acc
, zMsg
, sizeof(zMsg
), 0);
1022 sqlite3VXPrintf(&acc
, 0, zFormat
, ap
);
1023 sqlite3GlobalConfig
.xLog(sqlite3GlobalConfig
.pLogArg
, iErrCode
,
1024 sqlite3StrAccumFinish(&acc
));
1028 ** Format and write a message to the log if logging is enabled.
1030 void sqlite3_log(int iErrCode
, const char *zFormat
, ...){
1031 va_list ap
; /* Vararg list */
1032 if( sqlite3GlobalConfig
.xLog
){
1033 va_start(ap
, zFormat
);
1034 renderLogMsg(iErrCode
, zFormat
, ap
);
1039 #if defined(SQLITE_DEBUG)
1041 ** A version of printf() that understands %lld. Used for debugging.
1042 ** The printf() built into some versions of windows does not understand %lld
1043 ** and segfaults if you give it a long long int.
1045 void sqlite3DebugPrintf(const char *zFormat
, ...){
1049 sqlite3StrAccumInit(&acc
, zBuf
, sizeof(zBuf
), 0);
1051 va_start(ap
,zFormat
);
1052 sqlite3VXPrintf(&acc
, 0, zFormat
, ap
);
1054 sqlite3StrAccumFinish(&acc
);
1055 fprintf(stdout
,"%s", zBuf
);
1061 /*************************************************************************
1062 ** Routines for implementing the "TreeView" display of hierarchical
1063 ** data structures for debugging.
1065 ** The main entry points (coded elsewhere) are:
1066 ** sqlite3TreeViewExpr(0, pExpr, 0);
1067 ** sqlite3TreeViewExprList(0, pList, 0, 0);
1068 ** sqlite3TreeViewSelect(0, pSelect, 0);
1069 ** Insert calls to those routines while debugging in order to display
1070 ** a diagram of Expr, ExprList, and Select objects.
1073 /* Add a new subitem to the tree. The moreToFollow flag indicates that this
1074 ** is not the last item in the tree. */
1075 TreeView
*sqlite3TreeViewPush(TreeView
*p
, u8 moreToFollow
){
1077 p
= sqlite3_malloc( sizeof(*p
) );
1078 if( p
==0 ) return 0;
1079 memset(p
, 0, sizeof(*p
));
1083 assert( moreToFollow
==0 || moreToFollow
==1 );
1084 if( p
->iLevel
<sizeof(p
->bLine
) ) p
->bLine
[p
->iLevel
] = moreToFollow
;
1087 /* Finished with one layer of the tree */
1088 void sqlite3TreeViewPop(TreeView
*p
){
1091 if( p
->iLevel
<0 ) sqlite3_free(p
);
1093 /* Generate a single line of output for the tree, with a prefix that contains
1094 ** all the appropriate tree lines */
1095 void sqlite3TreeViewLine(TreeView
*p
, const char *zFormat
, ...){
1100 sqlite3StrAccumInit(&acc
, zBuf
, sizeof(zBuf
), 0);
1103 for(i
=0; i
<p
->iLevel
&& i
<sizeof(p
->bLine
)-1; i
++){
1104 sqlite3StrAccumAppend(&acc
, p
->bLine
[i
] ? "| " : " ", 4);
1106 sqlite3StrAccumAppend(&acc
, p
->bLine
[i
] ? "|-- " : "'-- ", 4);
1108 va_start(ap
, zFormat
);
1109 sqlite3VXPrintf(&acc
, 0, zFormat
, ap
);
1111 if( zBuf
[acc
.nChar
-1]!='\n' ) sqlite3StrAccumAppend(&acc
, "\n", 1);
1112 sqlite3StrAccumFinish(&acc
);
1113 fprintf(stdout
,"%s", zBuf
);
1116 /* Shorthand for starting a new tree item that consists of a single label */
1117 void sqlite3TreeViewItem(TreeView
*p
, const char *zLabel
, u8 moreToFollow
){
1118 p
= sqlite3TreeViewPush(p
, moreToFollow
);
1119 sqlite3TreeViewLine(p
, "%s", zLabel
);
1121 #endif /* SQLITE_DEBUG */
1124 ** variable-argument wrapper around sqlite3VXPrintf().
1126 void sqlite3XPrintf(StrAccum
*p
, u32 bFlags
, const char *zFormat
, ...){
1128 va_start(ap
,zFormat
);
1129 sqlite3VXPrintf(p
, bFlags
, zFormat
, ap
);