Snapshot of upstream SQLite 3.42.0
[sqlcipher.git] / src / printf.c
blob3e1782d4667ec0909456dcedcad102e320c51ab5
1 /*
2 ** The "printf" code that follows dates from the 1980's. It is in
3 ** the public domain.
4 **
5 **************************************************************************
6 **
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
10 ** SQLite.
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 */
57 } et_info;
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 },
90 #endif
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 },
102 /* Notes:
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.
124 ** Example:
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
130 ** always returned.
132 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
133 int digit;
134 LONGDOUBLE_TYPE d;
135 if( (*cnt)<=0 ) return '0';
136 (*cnt)--;
137 digit = (int)*val;
138 d = digit;
139 digit += '0';
140 *val = (*val - d)*10.0;
141 return (char)digit;
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);
153 *val -= x*(*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){
195 char *z;
196 if( pAccum->accError ) return 0;
197 if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
198 sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG);
199 return 0;
201 z = sqlite3DbMallocRaw(pAccum->db, n);
202 if( z==0 ){
203 sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM);
205 return z;
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
214 #endif
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
222 #endif
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
252 ** of longvalue */
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 */
263 #endif
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...")
269 ** optimization. */
270 assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
272 bufpt = 0;
273 if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
274 pArgList = va_arg(ap, PrintfArguments*);
275 bArgList = 1;
276 }else{
277 bArgList = 0;
279 for(; (c=(*fmt))!=0; ++fmt){
280 if( c!='%' ){
281 bufpt = (char *)fmt;
282 #if HAVE_STRCHRNUL
283 fmt = strchrnul(fmt, '%');
284 #else
285 do{ fmt++; }while( *fmt && *fmt != '%' );
286 #endif
287 sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
288 if( *fmt==0 ) break;
290 if( (c=(*++fmt))==0 ){
291 sqlite3_str_append(pAccum, "%", 1);
292 break;
294 /* Find out what flags are present */
295 flag_leftjustify = flag_prefix = cThousand =
296 flag_alternateform = flag_altform2 = flag_zeropad = 0;
297 done = 0;
298 width = 0;
299 flag_long = 0;
300 precision = -1;
302 switch( c ){
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;
311 case 'l': {
312 flag_long = 1;
313 c = *++fmt;
314 if( c=='l' ){
315 c = *++fmt;
316 flag_long = 2;
318 done = 1;
319 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;
333 #endif
334 if( c!='.' && c!='l' ){
335 done = 1;
336 }else{
337 fmt--;
339 break;
341 case '*': {
342 if( bArgList ){
343 width = (int)getIntArg(pArgList);
344 }else{
345 width = va_arg(ap,int);
347 if( width<0 ){
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;
355 #endif
356 if( (c = fmt[1])!='.' && c!='l' ){
357 c = *++fmt;
358 done = 1;
360 break;
362 case '.': {
363 c = *++fmt;
364 if( c=='*' ){
365 if( bArgList ){
366 precision = (int)getIntArg(pArgList);
367 }else{
368 precision = va_arg(ap,int);
370 if( precision<0 ){
371 precision = precision >= -2147483647 ? -precision : -1;
373 c = *++fmt;
374 }else{
375 unsigned px = 0;
376 while( c>='0' && c<='9' ){
377 px = px*10 + c - '0';
378 c = *++fmt;
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;
387 #endif
388 if( c=='l' ){
389 --fmt;
390 }else{
391 done = 1;
393 break;
396 }while( !done && (c=(*++fmt))!=0 );
398 /* Fetch the info entry for the field */
399 infop = &fmtinfo[0];
400 xtype = etINVALID;
401 for(idx=0; idx<ArraySize(fmtinfo); idx++){
402 if( c==fmtinfo[idx].fmttype ){
403 infop = &fmtinfo[idx];
404 xtype = infop->type;
405 break;
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
422 ** is -1.
423 ** xtype The class of the conversion.
424 ** infop Pointer to the appropriate info struct.
426 assert( width>=0 );
427 assert( precision>=(-1) );
428 switch( xtype ){
429 case etPOINTER:
430 flag_long = sizeof(char*)==sizeof(i64) ? 2 :
431 sizeof(char*)==sizeof(long int) ? 1 : 0;
432 /* no break */ deliberate_fall_through
433 case etORDINAL:
434 case etRADIX:
435 cThousand = 0;
436 /* no break */ deliberate_fall_through
437 case etDECIMAL:
438 if( infop->flags & FLAG_SIGNED ){
439 i64 v;
440 if( bArgList ){
441 v = getIntArg(pArgList);
442 }else if( flag_long ){
443 if( flag_long==2 ){
444 v = va_arg(ap,i64) ;
445 }else{
446 v = va_arg(ap,long int);
448 }else{
449 v = va_arg(ap,int);
451 if( v<0 ){
452 testcase( v==SMALLEST_INT64 );
453 testcase( v==(-1) );
454 longvalue = ~v;
455 longvalue++;
456 prefix = '-';
457 }else{
458 longvalue = v;
459 prefix = flag_prefix;
461 }else{
462 if( bArgList ){
463 longvalue = (u64)getIntArg(pArgList);
464 }else if( flag_long ){
465 if( flag_long==2 ){
466 longvalue = va_arg(ap,u64);
467 }else{
468 longvalue = va_arg(ap,unsigned long int);
470 }else{
471 longvalue = va_arg(ap,unsigned int);
473 prefix = 0;
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 ){
480 nOut = etBUFSIZE;
481 zOut = buf;
482 }else{
483 u64 n;
484 n = (u64)precision + 10;
485 if( cThousand ) n += precision/3;
486 zOut = zExtra = printfTempBuf(pAccum, n);
487 if( zOut==0 ) return;
488 nOut = (int)n;
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 ){
495 x = 0;
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 */
511 length++;
513 if( cThousand ){
514 int nn = (length - 1)/3; /* Number of "," to insert */
515 int ix = (length - 1)%3 + 1;
516 bufpt -= nn;
517 for(idx=0; nn>0; idx++){
518 bufpt[idx] = bufpt[idx+nn];
519 ix--;
520 if( ix==0 ){
521 bufpt[++idx] = cThousand;
522 nn--;
523 ix = 3;
527 if( prefix ) *(--bufpt) = prefix; /* Add sign */
528 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
529 const char *pre;
530 char x;
531 pre = &aPrefix[infop->prefix];
532 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
534 length = (int)(&zOut[nOut-1]-bufpt);
535 break;
536 case etFLOAT:
537 case etEXP:
538 case etGENERIC:
539 if( bArgList ){
540 realvalue = getDoubleArg(pArgList);
541 }else{
542 realvalue = va_arg(ap,double);
544 #ifdef SQLITE_OMIT_FLOATING_POINT
545 length = 0;
546 #else
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;
552 #endif
553 if( realvalue<0.0 ){
554 realvalue = -realvalue;
555 prefix = '-';
556 }else{
557 prefix = flag_prefix;
559 exp = 0;
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 ){
568 u64 rnd = msd/2;
569 int kk = precision;
570 while( kk-- > 0 ){ rnd /= 10; }
571 longvalue += rnd;
573 }else{
574 msd = 0;
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;
581 sqlite3_uint64 u;
582 int ex;
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) ){
589 if( flag_zeropad ){
590 bufpt = "null";
591 length = 4;
592 }else{
593 bufpt = "NaN";
594 length = 3;
596 break;
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++; }
605 realvalue /= scale;
606 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
607 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
608 if( exp>350 ){
609 if( flag_zeropad ){
610 realvalue = 9.0;
611 exp = 999;
612 }else{
613 bufpt = buf;
614 buf[0] = prefix;
615 memcpy(buf+(prefix!=0),"Inf",4);
616 length = 3+(prefix!=0);
617 break;
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 ){
634 xtype = etEXP;
635 }else{
636 precision = precision - exp;
637 xtype = etFLOAT;
639 }else{
640 flag_rtz = flag_altform2;
642 if( xtype==etEXP ){
643 e2 = 0;
644 }else{
645 e2 = exp;
647 nsd = 16 + flag_altform2*10;
648 bufpt = buf;
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;
658 zOut = bufpt;
659 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
660 /* The sign in front of the number */
661 if( prefix ){
662 *(bufpt++) = prefix;
664 /* Digits prior to the decimal point */
665 if( e2<0 ){
666 *(bufpt++) = '0';
667 }else if( msd>0 ){
668 for(; e2>=0; e2--){
669 *(bufpt++) = et_getdigit_int(&longvalue,&msd);
670 if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ',';
672 }else{
673 for(; e2>=0; e2--){
674 *(bufpt++) = et_getdigit(&realvalue,&nsd);
675 if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ',';
678 /* The decimal point */
679 if( flag_dp ){
680 *(bufpt++) = '.';
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 );
686 *(bufpt++) = '0';
688 /* Significant digits after the decimal point */
689 if( msd>0 ){
690 while( (precision--)>0 ){
691 *(bufpt++) = et_getdigit_int(&longvalue,&msd);
693 }else{
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]=='.' ){
703 if( flag_altform2 ){
704 *(bufpt++) = '0';
705 }else{
706 *(--bufpt) = 0;
710 /* Add the "eNNN" suffix */
711 if( xtype==etEXP ){
712 *(bufpt++) = aDigits[infop->charset];
713 if( exp<0 ){
714 *(bufpt++) = '-'; exp = -exp;
715 }else{
716 *(bufpt++) = '+';
718 if( exp>=100 ){
719 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
720 exp %= 100;
722 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
723 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
725 *bufpt = 0;
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);
731 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){
736 int i;
737 int nPad = width - length;
738 for(i=width; i>=nPad; i--){
739 bufpt[i] = bufpt[i-nPad];
741 i = prefix!=0;
742 while( nPad-- ) bufpt[i++] = '0';
743 length = width;
745 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
746 break;
747 case etSIZE:
748 if( !bArgList ){
749 *(va_arg(ap,int*)) = pAccum->nChar;
751 length = width = 0;
752 break;
753 case etPERCENT:
754 buf[0] = '%';
755 bufpt = buf;
756 length = 1;
757 break;
758 case etCHARX:
759 if( bArgList ){
760 bufpt = getTextArg(pArgList);
761 length = 1;
762 if( bufpt ){
763 buf[0] = c = *(bufpt++);
764 if( (c&0xc0)==0xc0 ){
765 while( length<4 && (bufpt[0]&0xc0)==0x80 ){
766 buf[length++] = *(bufpt++);
769 }else{
770 buf[0] = 0;
772 }else{
773 unsigned int ch = va_arg(ap,unsigned int);
774 if( ch<0x00080 ){
775 buf[0] = ch & 0xff;
776 length = 1;
777 }else if( ch<0x00800 ){
778 buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
779 buf[1] = 0x80 + (u8)(ch & 0x3f);
780 length = 2;
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);
785 length = 3;
786 }else{
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);
791 length = 4;
794 if( precision>1 ){
795 i64 nPrior = 1;
796 width -= precision-1;
797 if( width>1 && !flag_leftjustify ){
798 sqlite3_str_appendchar(pAccum, width-1, ' ');
799 width = 0;
801 sqlite3_str_append(pAccum, buf, length);
802 precision--;
803 while( precision > 1 ){
804 i64 nCopyBytes;
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);
813 precision -= nPrior;
814 nPrior *= 2;
817 bufpt = buf;
818 flag_altform2 = 1;
819 goto adjust_width_for_utf8;
820 case etSTRING:
821 case etDYNSTRING:
822 if( bArgList ){
823 bufpt = getTextArg(pArgList);
824 xtype = etSTRING;
825 }else{
826 bufpt = va_arg(ap,char*);
828 if( bufpt==0 ){
829 bufpt = "";
830 }else if( xtype==etDYNSTRING ){
831 if( pAccum->nChar==0
832 && pAccum->mxAlloc
833 && width==0
834 && precision<0
835 && pAccum->accError==0
837 /* Special optimization for sqlite3_mprintf("%z..."):
838 ** Extend an existing memory allocation rather than creating
839 ** a new one. */
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;
845 length = 0;
846 break;
848 zExtra = bufpt;
850 if( precision>=0 ){
851 if( flag_altform2 ){
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] ){
856 SQLITE_SKIP_UTF8(z);
858 length = (int)(z - (unsigned char*)bufpt);
859 }else{
860 for(length=0; length<precision && bufpt[length]; length++){}
862 }else{
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 */
868 int ii = length - 1;
869 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
871 break;
872 case etSQLESCAPE: /* %q: Escape ' characters */
873 case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
874 case etSQLESCAPE3: { /* %w: Escape " characters */
875 i64 i, j, k, n;
876 int needQuote, isnull;
877 char ch;
878 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
879 char *escarg;
881 if( bArgList ){
882 escarg = getTextArg(pArgList);
883 }else{
884 escarg = va_arg(ap,char*);
886 isnull = escarg==0;
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.
893 k = precision;
894 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
895 if( ch==q ) n++;
896 if( flag_altform2 && (ch&0xc0)==0xc0 ){
897 while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
900 needQuote = !isnull && xtype==etSQLESCAPE2;
901 n += i + 3;
902 if( n>etBUFSIZE ){
903 bufpt = zExtra = printfTempBuf(pAccum, n);
904 if( bufpt==0 ) return;
905 }else{
906 bufpt = buf;
908 j = 0;
909 if( needQuote ) bufpt[j++] = q;
910 k = i;
911 for(i=0; i<k; i++){
912 bufpt[j++] = ch = escarg[i];
913 if( ch==q ) bufpt[j++] = ch;
915 if( needQuote ) bufpt[j++] = q;
916 bufpt[j] = 0;
917 length = j;
918 goto adjust_width_for_utf8;
920 case etTOKEN: {
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);
929 }else{
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);
938 length = width = 0;
939 break;
941 case etSRCITEM: {
942 SrcItem *pItem;
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);
956 }else{
957 Select *pSel = pItem->pSelect;
958 assert( pSel!=0 );
959 if( pSel->selFlags & SF_NestedFrom ){
960 sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId);
961 }else{
962 sqlite3_str_appendf(pAccum, "(subquery-%u)", pSel->selId);
965 length = width = 0;
966 break;
968 default: {
969 assert( xtype==etINVALID );
970 return;
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.
981 width -= length;
982 if( width>0 ){
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, ' ');
986 }else{
987 sqlite3_str_append(pAccum, bufpt, length);
990 if( zExtra ){
991 sqlite3DbFree(pAccum->db, zExtra);
992 zExtra = 0;
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;
1006 const char *zText;
1007 const char *zEnd;
1008 assert( z!=0 );
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){
1026 while( 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){
1043 char *zNew;
1044 assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
1045 if( p->accError ){
1046 testcase(p->accError==SQLITE_TOOBIG);
1047 testcase(p->accError==SQLITE_NOMEM);
1048 return 0;
1050 if( p->mxAlloc==0 ){
1051 sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
1052 return p->nAlloc - p->nChar - 1;
1053 }else{
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 */
1059 szNew += p->nChar;
1061 if( szNew > p->mxAlloc ){
1062 sqlite3_str_reset(p);
1063 sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
1064 return 0;
1065 }else{
1066 p->nAlloc = (int)szNew;
1068 if( p->db ){
1069 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
1070 }else{
1071 zNew = sqlite3Realloc(zOld, p->nAlloc);
1073 if( zNew ){
1074 assert( p->zText!=0 || p->nChar==0 );
1075 if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
1076 p->zText = zNew;
1077 p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
1078 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1079 }else{
1080 sqlite3_str_reset(p);
1081 sqlite3StrAccumSetError(p, SQLITE_NOMEM);
1082 return 0;
1085 assert( N>=0 && N<=0x7fffffff );
1086 return (int)N;
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 ){
1095 return;
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);
1110 if( N>0 ){
1111 memcpy(&p->zText[p->nChar], z, N);
1112 p->nChar += 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 );
1123 assert( N>=0 );
1124 assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
1125 if( p->nChar+N >= p->nAlloc ){
1126 enlargeAndAppend(p,z,N);
1127 }else if( N ){
1128 assert( p->zText );
1129 p->nChar += 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){
1148 char *zText;
1149 assert( p->mxAlloc>0 && !isMalloced(p) );
1150 zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
1151 if( zText ){
1152 memcpy(zText, p->zText, p->nChar+1);
1153 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1154 }else{
1155 sqlite3StrAccumSetError(p, SQLITE_NOMEM);
1157 p->zText = zText;
1158 return zText;
1160 char *sqlite3StrAccumFinish(StrAccum *p){
1161 if( p->zText ){
1162 p->zText[p->nChar] = 0;
1163 if( p->mxAlloc>0 && !isMalloced(p) ){
1164 return strAccumFinishRealloc(p);
1167 return p->zText;
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){
1175 if( p->accError ){
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);
1180 }else{
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){
1199 char *z;
1200 if( p!=0 && p!=&sqlite3OomStr ){
1201 z = sqlite3StrAccumFinish(p);
1202 sqlite3_free(p);
1203 }else{
1204 z = 0;
1206 return z;
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;
1223 return p->zText;
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;
1234 p->nAlloc = 0;
1235 p->nChar = 0;
1236 p->zText = 0;
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
1245 ** when not NULL.
1246 ** zBase: An initial buffer. May be NULL in which case the initial buffer
1247 ** is malloced.
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){
1254 p->zText = zBase;
1255 p->db = db;
1256 p->nAlloc = n;
1257 p->mxAlloc = mx;
1258 p->nChar = 0;
1259 p->accError = 0;
1260 p->printfFlags = 0;
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));
1266 if( p ){
1267 sqlite3StrAccumInit(p, 0, 0, 0,
1268 db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
1269 }else{
1270 p = &sqlite3OomStr;
1272 return p;
1276 ** Print into memory obtained from sqliteMalloc(). Use the internal
1277 ** %-conversion extensions.
1279 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
1280 char *z;
1281 char zBase[SQLITE_PRINT_BUF_SIZE];
1282 StrAccum acc;
1283 assert( db!=0 );
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);
1292 return z;
1296 ** Print into memory obtained from sqliteMalloc(). Use the internal
1297 ** %-conversion extensions.
1299 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
1300 va_list ap;
1301 char *z;
1302 va_start(ap, zFormat);
1303 z = sqlite3VMPrintf(db, zFormat, ap);
1304 va_end(ap);
1305 return z;
1309 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
1310 ** %-conversion extensions.
1312 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
1313 char *z;
1314 char zBase[SQLITE_PRINT_BUF_SIZE];
1315 StrAccum acc;
1317 #ifdef SQLITE_ENABLE_API_ARMOR
1318 if( zFormat==0 ){
1319 (void)SQLITE_MISUSE_BKPT;
1320 return 0;
1322 #endif
1323 #ifndef SQLITE_OMIT_AUTOINIT
1324 if( sqlite3_initialize() ) return 0;
1325 #endif
1326 sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
1327 sqlite3_str_vappendf(&acc, zFormat, ap);
1328 z = sqlite3StrAccumFinish(&acc);
1329 return z;
1333 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
1334 ** %-conversion extensions.
1336 char *sqlite3_mprintf(const char *zFormat, ...){
1337 va_list ap;
1338 char *z;
1339 #ifndef SQLITE_OMIT_AUTOINIT
1340 if( sqlite3_initialize() ) return 0;
1341 #endif
1342 va_start(ap, zFormat);
1343 z = sqlite3_vmprintf(zFormat, ap);
1344 va_end(ap);
1345 return z;
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
1357 ** mistake.
1359 ** sqlite3_vsnprintf() is the varargs version.
1361 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1362 StrAccum acc;
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;
1368 return zBuf;
1370 #endif
1371 sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
1372 sqlite3_str_vappendf(&acc, zFormat, ap);
1373 zBuf[acc.nChar] = 0;
1374 return zBuf;
1376 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
1377 StrAccum acc;
1378 va_list ap;
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;
1384 return zBuf;
1386 #endif
1387 sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
1388 va_start(ap,zFormat);
1389 sqlite3_str_vappendf(&acc, zFormat, ap);
1390 va_end(ap);
1391 zBuf[acc.nChar] = 0;
1392 return zBuf;
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
1402 ** mutex is held.
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);
1427 va_end(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, ...){
1438 va_list ap;
1439 StrAccum acc;
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);
1444 va_end(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));
1451 #else
1452 fprintf(stdout,"%s", zBuf);
1453 fflush(stdout);
1454 #endif
1456 #endif
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, ...){
1464 va_list ap;
1465 va_start(ap,zFormat);
1466 sqlite3_str_vappendf(p, zFormat, ap);
1467 va_end(ap);