xref: /sqlite-3.40.0/src/printf.c (revision b08cd3f3)
1a18c5681Sdrh /*
2a18c5681Sdrh ** The "printf" code that follows dates from the 1980's.  It is in
3a18c5681Sdrh ** the public domain.  The original comments are included here for
4e84a306bSdrh ** completeness.  They are very out-of-date but might be useful as
5e84a306bSdrh ** an historical reference.  Most of the "enhancements" have been backed
6e84a306bSdrh ** out so that the functionality is now the same as standard printf().
7e84a306bSdrh **
8e84a306bSdrh **************************************************************************
9a18c5681Sdrh **
10ed1fddf4Sdrh ** This file contains code for a set of "printf"-like routines.  These
11ed1fddf4Sdrh ** routines format strings much like the printf() from the standard C
12ed1fddf4Sdrh ** library, though the implementation here has enhancements to support
13ed1fddf4Sdrh ** SQLlite.
14a18c5681Sdrh */
15a18c5681Sdrh #include "sqliteInt.h"
167c68d60bSdrh 
17a18c5681Sdrh /*
18760b1598Sdrh ** If the strchrnul() library function is available, then set
19760b1598Sdrh ** HAVE_STRCHRNUL.  If that routine is not available, this module
20760b1598Sdrh ** will supply its own.  The built-in version is slower than
21760b1598Sdrh ** the glibc version so the glibc version is definitely preferred.
22760b1598Sdrh */
23760b1598Sdrh #if !defined(HAVE_STRCHRNUL)
244e7a4795Sdrh # if defined(linux)
25760b1598Sdrh #  define HAVE_STRCHRNUL 1
26760b1598Sdrh # else
27760b1598Sdrh #  define HAVE_STRCHRNUL 0
28760b1598Sdrh # endif
29760b1598Sdrh #endif
30760b1598Sdrh 
31760b1598Sdrh 
32760b1598Sdrh /*
33a18c5681Sdrh ** Conversion types fall into various categories as defined by the
34a18c5681Sdrh ** following enumeration.
35a18c5681Sdrh */
36e84a306bSdrh #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
37e84a306bSdrh #define etFLOAT       2 /* Floating point.  %f */
38e84a306bSdrh #define etEXP         3 /* Exponentional notation. %e and %E */
39e84a306bSdrh #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
40e84a306bSdrh #define etSIZE        5 /* Return number of characters processed so far. %n */
41e84a306bSdrh #define etSTRING      6 /* Strings. %s */
42e84a306bSdrh #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
43e84a306bSdrh #define etPERCENT     8 /* Percent symbol. %% */
44e84a306bSdrh #define etCHARX       9 /* Characters. %c */
45a18c5681Sdrh /* The rest are extensions, not normally found in printf() */
46af005fbcSdrh #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
47af005fbcSdrh #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
480cfcf3fbSchw                           NULL pointers replaced by SQL NULL.  %Q */
49af005fbcSdrh #define etTOKEN      12 /* a pointer to a Token structure */
50af005fbcSdrh #define etSRCLIST    13 /* a pointer to a SrcList */
51af005fbcSdrh #define etPOINTER    14 /* The %p conversion */
52af005fbcSdrh #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
53af005fbcSdrh #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
54e84a306bSdrh 
55874ba04cSdrh #define etINVALID     0 /* Any unrecognized conversion type */
56874ba04cSdrh 
57e84a306bSdrh 
58e84a306bSdrh /*
59e84a306bSdrh ** An "etByte" is an 8-bit unsigned value.
60e84a306bSdrh */
61e84a306bSdrh typedef unsigned char etByte;
62a18c5681Sdrh 
63a18c5681Sdrh /*
64a18c5681Sdrh ** Each builtin conversion character (ex: the 'd' in "%d") is described
65a18c5681Sdrh ** by an instance of the following structure
66a18c5681Sdrh */
67a18c5681Sdrh typedef struct et_info {   /* Information about each format field */
68e84a306bSdrh   char fmttype;            /* The format field code letter */
69e84a306bSdrh   etByte base;             /* The base for radix conversion */
70e84a306bSdrh   etByte flags;            /* One or more of FLAG_ constants below */
71e84a306bSdrh   etByte type;             /* Conversion paradigm */
7276ff3a0eSdrh   etByte charset;          /* Offset into aDigits[] of the digits string */
7376ff3a0eSdrh   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
74a18c5681Sdrh } et_info;
75a18c5681Sdrh 
76a18c5681Sdrh /*
77e84a306bSdrh ** Allowed values for et_info.flags
78e84a306bSdrh */
79e84a306bSdrh #define FLAG_SIGNED  1     /* True if the value to convert is signed */
80e84a306bSdrh #define FLAG_INTERN  2     /* True if for internal use only */
814794f735Sdrh #define FLAG_STRING  4     /* Allow infinity precision */
82e84a306bSdrh 
83e84a306bSdrh 
84e84a306bSdrh /*
85a18c5681Sdrh ** The following table is searched linearly, so it is good to put the
86a18c5681Sdrh ** most frequently used conversion types first.
87a18c5681Sdrh */
8876ff3a0eSdrh static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
8976ff3a0eSdrh static const char aPrefix[] = "-x0\000X0";
905719628aSdrh static const et_info fmtinfo[] = {
9176ff3a0eSdrh   {  'd', 10, 1, etRADIX,      0,  0 },
924794f735Sdrh   {  's',  0, 4, etSTRING,     0,  0 },
93557cc60fSdrh   {  'g',  0, 1, etGENERIC,    30, 0 },
94153c62c4Sdrh   {  'z',  0, 4, etDYNSTRING,  0,  0 },
954794f735Sdrh   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
964794f735Sdrh   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
97f3b863edSdanielk1977   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
98e84a306bSdrh   {  'c',  0, 0, etCHARX,      0,  0 },
9976ff3a0eSdrh   {  'o',  8, 0, etRADIX,      0,  2 },
10076ff3a0eSdrh   {  'u', 10, 0, etRADIX,      0,  0 },
10176ff3a0eSdrh   {  'x', 16, 0, etRADIX,      16, 1 },
10276ff3a0eSdrh   {  'X', 16, 0, etRADIX,      0,  4 },
103b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
104e84a306bSdrh   {  'f',  0, 1, etFLOAT,      0,  0 },
10576ff3a0eSdrh   {  'e',  0, 1, etEXP,        30, 0 },
10676ff3a0eSdrh   {  'E',  0, 1, etEXP,        14, 0 },
10776ff3a0eSdrh   {  'G',  0, 1, etGENERIC,    14, 0 },
108b37df7b9Sdrh #endif
10976ff3a0eSdrh   {  'i', 10, 1, etRADIX,      0,  0 },
110e84a306bSdrh   {  'n',  0, 0, etSIZE,       0,  0 },
111e84a306bSdrh   {  '%',  0, 0, etPERCENT,    0,  0 },
11276ff3a0eSdrh   {  'p', 16, 0, etPOINTER,    0,  1 },
1137e3ff5d8Sdrh 
1147e3ff5d8Sdrh /* All the rest have the FLAG_INTERN bit set and are thus for internal
1157e3ff5d8Sdrh ** use only */
1165f968436Sdrh   {  'T',  0, 2, etTOKEN,      0,  0 },
1175f968436Sdrh   {  'S',  0, 2, etSRCLIST,    0,  0 },
1189a99334dSdrh   {  'r', 10, 3, etORDINAL,    0,  0 },
119a18c5681Sdrh };
120a18c5681Sdrh 
121a18c5681Sdrh /*
122b37df7b9Sdrh ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
123a18c5681Sdrh ** conversions will work.
124a18c5681Sdrh */
125b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
126a18c5681Sdrh /*
127a18c5681Sdrh ** "*val" is a double such that 0.1 <= *val < 10.0
128a18c5681Sdrh ** Return the ascii code for the leading digit of *val, then
129a18c5681Sdrh ** multiply "*val" by 10.0 to renormalize.
130a18c5681Sdrh **
131a18c5681Sdrh ** Example:
132a18c5681Sdrh **     input:     *val = 3.14159
133a18c5681Sdrh **     output:    *val = 1.4159    function return = '3'
134a18c5681Sdrh **
135a18c5681Sdrh ** The counter *cnt is incremented each time.  After counter exceeds
136a18c5681Sdrh ** 16 (the number of significant digits in a 64-bit float) '0' is
137a18c5681Sdrh ** always returned.
138a18c5681Sdrh */
139ea678832Sdrh static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
140a18c5681Sdrh   int digit;
141384eef32Sdrh   LONGDOUBLE_TYPE d;
14272b3fbc7Sdrh   if( (*cnt)<=0 ) return '0';
14372b3fbc7Sdrh   (*cnt)--;
144a18c5681Sdrh   digit = (int)*val;
145a18c5681Sdrh   d = digit;
146a18c5681Sdrh   digit += '0';
147a18c5681Sdrh   *val = (*val - d)*10.0;
148ea678832Sdrh   return (char)digit;
149a18c5681Sdrh }
150b37df7b9Sdrh #endif /* SQLITE_OMIT_FLOATING_POINT */
151a18c5681Sdrh 
15279158e18Sdrh /*
153a6353a3fSdrh ** Set the StrAccum object to an error mode.
154a6353a3fSdrh */
155a5c1416dSdrh static void setStrAccumError(StrAccum *p, u8 eError){
156a6353a3fSdrh   p->accError = eError;
157a6353a3fSdrh   p->nAlloc = 0;
158a6353a3fSdrh }
159a6353a3fSdrh 
160a6353a3fSdrh /*
161a5c1416dSdrh ** Extra argument values from a PrintfArguments object
162a5c1416dSdrh */
163a5c1416dSdrh static sqlite3_int64 getIntArg(PrintfArguments *p){
164a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
165a5c1416dSdrh   return sqlite3_value_int64(p->apArg[p->nUsed++]);
166a5c1416dSdrh }
167a5c1416dSdrh static double getDoubleArg(PrintfArguments *p){
168a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0.0;
169a5c1416dSdrh   return sqlite3_value_double(p->apArg[p->nUsed++]);
170a5c1416dSdrh }
171a5c1416dSdrh static char *getTextArg(PrintfArguments *p){
172a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
173a5c1416dSdrh   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
174a5c1416dSdrh }
175a5c1416dSdrh 
176a5c1416dSdrh 
177a5c1416dSdrh /*
17879158e18Sdrh ** On machines with a small stack size, you can redefine the
179ed1fddf4Sdrh ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
18079158e18Sdrh */
18179158e18Sdrh #ifndef SQLITE_PRINT_BUF_SIZE
18259eedf79Sdrh # define SQLITE_PRINT_BUF_SIZE 70
18350d654daSdrh #endif
18479158e18Sdrh #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
185a18c5681Sdrh 
186a18c5681Sdrh /*
187ed1fddf4Sdrh ** Render a string given by "fmt" into the StrAccum object.
188a18c5681Sdrh */
189f089aa45Sdrh void sqlite3VXPrintf(
190ade86483Sdrh   StrAccum *pAccum,          /* Accumulate results here */
191a5c1416dSdrh   u32 bFlags,                /* SQLITE_PRINTF_* flags */
1925f968436Sdrh   const char *fmt,           /* Format string */
1935f968436Sdrh   va_list ap                 /* arguments */
194a18c5681Sdrh ){
195e84a306bSdrh   int c;                     /* Next character in the format string */
196e84a306bSdrh   char *bufpt;               /* Pointer to the conversion buffer */
197e84a306bSdrh   int precision;             /* Precision of the current field */
198e84a306bSdrh   int length;                /* Length of the field */
199e84a306bSdrh   int idx;                   /* A general purpose loop counter */
200a18c5681Sdrh   int width;                 /* Width of the current field */
201e84a306bSdrh   etByte flag_leftjustify;   /* True if "-" flag is present */
202e84a306bSdrh   etByte flag_plussign;      /* True if "+" flag is present */
203e84a306bSdrh   etByte flag_blanksign;     /* True if " " flag is present */
204e84a306bSdrh   etByte flag_alternateform; /* True if "#" flag is present */
205531fe878Sdrh   etByte flag_altform2;      /* True if "!" flag is present */
206e84a306bSdrh   etByte flag_zeropad;       /* True if field width constant starts with zero */
207e84a306bSdrh   etByte flag_long;          /* True if "l" flag is present */
208a34b6764Sdrh   etByte flag_longlong;      /* True if the "ll" flag is present */
2093e9aeec0Sdrh   etByte done;               /* Loop termination flag */
210ed1fddf4Sdrh   etByte xtype = 0;          /* Conversion paradigm */
211a5c1416dSdrh   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
212a5c1416dSdrh   u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
213ed1fddf4Sdrh   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
21427436af7Sdrh   sqlite_uint64 longvalue;   /* Value for integer types */
215384eef32Sdrh   LONGDOUBLE_TYPE realvalue; /* Value for real types */
2165719628aSdrh   const et_info *infop;      /* Pointer to the appropriate info structure */
21759eedf79Sdrh   char *zOut;                /* Rendering buffer */
21859eedf79Sdrh   int nOut;                  /* Size of the rendering buffer */
219ed1fddf4Sdrh   char *zExtra;              /* Malloced memory used by some conversion */
220b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
221557cc60fSdrh   int  exp, e2;              /* exponent of real numbers */
222ed1fddf4Sdrh   int nsd;                   /* Number of significant digits returned */
223a18c5681Sdrh   double rounder;            /* Used for rounding floating point values */
224e84a306bSdrh   etByte flag_dp;            /* True if decimal point should be shown */
225e84a306bSdrh   etByte flag_rtz;           /* True if trailing zeros should be removed */
226a18c5681Sdrh #endif
227a5c1416dSdrh   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
228ed1fddf4Sdrh   char buf[etBUFSIZE];       /* Conversion buffer */
229a18c5681Sdrh 
230a18c5681Sdrh   bufpt = 0;
231a5c1416dSdrh   if( bFlags ){
232a5c1416dSdrh     if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
233a5c1416dSdrh       pArgList = va_arg(ap, PrintfArguments*);
234a5c1416dSdrh     }
235a5c1416dSdrh     useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
236a5c1416dSdrh   }else{
237a5c1416dSdrh     bArgList = useIntern = 0;
238a5c1416dSdrh   }
239a18c5681Sdrh   for(; (c=(*fmt))!=0; ++fmt){
240a18c5681Sdrh     if( c!='%' ){
241a18c5681Sdrh       bufpt = (char *)fmt;
242760b1598Sdrh #if HAVE_STRCHRNUL
243760b1598Sdrh       fmt = strchrnul(fmt, '%');
244760b1598Sdrh #else
245760b1598Sdrh       do{ fmt++; }while( *fmt && *fmt != '%' );
246760b1598Sdrh #endif
247a70a073bSdrh       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
248760b1598Sdrh       if( *fmt==0 ) break;
249a18c5681Sdrh     }
250a18c5681Sdrh     if( (c=(*++fmt))==0 ){
251ade86483Sdrh       sqlite3StrAccumAppend(pAccum, "%", 1);
252a18c5681Sdrh       break;
253a18c5681Sdrh     }
254a18c5681Sdrh     /* Find out what flags are present */
255a18c5681Sdrh     flag_leftjustify = flag_plussign = flag_blanksign =
256557cc60fSdrh      flag_alternateform = flag_altform2 = flag_zeropad = 0;
2573e9aeec0Sdrh     done = 0;
258a18c5681Sdrh     do{
259a18c5681Sdrh       switch( c ){
2603e9aeec0Sdrh         case '-':   flag_leftjustify = 1;     break;
2613e9aeec0Sdrh         case '+':   flag_plussign = 1;        break;
2623e9aeec0Sdrh         case ' ':   flag_blanksign = 1;       break;
2633e9aeec0Sdrh         case '#':   flag_alternateform = 1;   break;
2643e9aeec0Sdrh         case '!':   flag_altform2 = 1;        break;
2653e9aeec0Sdrh         case '0':   flag_zeropad = 1;         break;
2663e9aeec0Sdrh         default:    done = 1;                 break;
267a18c5681Sdrh       }
2683e9aeec0Sdrh     }while( !done && (c=(*++fmt))!=0 );
269a18c5681Sdrh     /* Get the field width */
270a18c5681Sdrh     width = 0;
271a18c5681Sdrh     if( c=='*' ){
272a5c1416dSdrh       if( bArgList ){
273a5c1416dSdrh         width = (int)getIntArg(pArgList);
274a5c1416dSdrh       }else{
275a18c5681Sdrh         width = va_arg(ap,int);
276a5c1416dSdrh       }
277a18c5681Sdrh       if( width<0 ){
278a18c5681Sdrh         flag_leftjustify = 1;
279a18c5681Sdrh         width = -width;
280a18c5681Sdrh       }
281a18c5681Sdrh       c = *++fmt;
282a18c5681Sdrh     }else{
28317a68934Sdrh       while( c>='0' && c<='9' ){
284a18c5681Sdrh         width = width*10 + c - '0';
285a18c5681Sdrh         c = *++fmt;
286a18c5681Sdrh       }
287a18c5681Sdrh     }
288a18c5681Sdrh     /* Get the precision */
289a18c5681Sdrh     if( c=='.' ){
290a18c5681Sdrh       precision = 0;
291a18c5681Sdrh       c = *++fmt;
292a18c5681Sdrh       if( c=='*' ){
293a5c1416dSdrh         if( bArgList ){
294a5c1416dSdrh           precision = (int)getIntArg(pArgList);
295a5c1416dSdrh         }else{
296a18c5681Sdrh           precision = va_arg(ap,int);
297a5c1416dSdrh         }
298a18c5681Sdrh         if( precision<0 ) precision = -precision;
299a18c5681Sdrh         c = *++fmt;
300a18c5681Sdrh       }else{
30117a68934Sdrh         while( c>='0' && c<='9' ){
302a18c5681Sdrh           precision = precision*10 + c - '0';
303a18c5681Sdrh           c = *++fmt;
304a18c5681Sdrh         }
305a18c5681Sdrh       }
306a18c5681Sdrh     }else{
307a18c5681Sdrh       precision = -1;
308a18c5681Sdrh     }
309a18c5681Sdrh     /* Get the conversion type modifier */
310a18c5681Sdrh     if( c=='l' ){
311a18c5681Sdrh       flag_long = 1;
312a18c5681Sdrh       c = *++fmt;
313a34b6764Sdrh       if( c=='l' ){
314a34b6764Sdrh         flag_longlong = 1;
315a34b6764Sdrh         c = *++fmt;
316a18c5681Sdrh       }else{
317a34b6764Sdrh         flag_longlong = 0;
318a34b6764Sdrh       }
319a34b6764Sdrh     }else{
320a34b6764Sdrh       flag_long = flag_longlong = 0;
321a18c5681Sdrh     }
322a18c5681Sdrh     /* Fetch the info entry for the field */
323874ba04cSdrh     infop = &fmtinfo[0];
324874ba04cSdrh     xtype = etINVALID;
32500e13613Sdanielk1977     for(idx=0; idx<ArraySize(fmtinfo); idx++){
326a18c5681Sdrh       if( c==fmtinfo[idx].fmttype ){
327a18c5681Sdrh         infop = &fmtinfo[idx];
328a5c1416dSdrh         if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
329e84a306bSdrh           xtype = infop->type;
330c4413565Sdrh         }else{
331ade86483Sdrh           return;
3325f968436Sdrh         }
333a18c5681Sdrh         break;
334a18c5681Sdrh       }
335a18c5681Sdrh     }
336a18c5681Sdrh     zExtra = 0;
33743617e9aSdrh 
338a18c5681Sdrh     /*
339a18c5681Sdrh     ** At this point, variables are initialized as follows:
340a18c5681Sdrh     **
341a18c5681Sdrh     **   flag_alternateform          TRUE if a '#' is present.
3423e9aeec0Sdrh     **   flag_altform2               TRUE if a '!' is present.
343a18c5681Sdrh     **   flag_plussign               TRUE if a '+' is present.
344a18c5681Sdrh     **   flag_leftjustify            TRUE if a '-' is present or if the
345a18c5681Sdrh     **                               field width was negative.
346a18c5681Sdrh     **   flag_zeropad                TRUE if the width began with 0.
347a18c5681Sdrh     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
348a18c5681Sdrh     **                               the conversion character.
349a34b6764Sdrh     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
350a34b6764Sdrh     **                               the conversion character.
351a18c5681Sdrh     **   flag_blanksign              TRUE if a ' ' is present.
352a18c5681Sdrh     **   width                       The specified field width.  This is
353a18c5681Sdrh     **                               always non-negative.  Zero is the default.
354a18c5681Sdrh     **   precision                   The specified precision.  The default
355a18c5681Sdrh     **                               is -1.
356a18c5681Sdrh     **   xtype                       The class of the conversion.
357a18c5681Sdrh     **   infop                       Pointer to the appropriate info struct.
358a18c5681Sdrh     */
359a18c5681Sdrh     switch( xtype ){
360fe63d1c9Sdrh       case etPOINTER:
361fe63d1c9Sdrh         flag_longlong = sizeof(char*)==sizeof(i64);
362fe63d1c9Sdrh         flag_long = sizeof(char*)==sizeof(long int);
363fe63d1c9Sdrh         /* Fall through into the next case */
3649a99334dSdrh       case etORDINAL:
365a18c5681Sdrh       case etRADIX:
366e84a306bSdrh         if( infop->flags & FLAG_SIGNED ){
367e9707671Sdrh           i64 v;
368a5c1416dSdrh           if( bArgList ){
369a5c1416dSdrh             v = getIntArg(pArgList);
370a5c1416dSdrh           }else if( flag_longlong ){
371eeb23a4cSdrh             v = va_arg(ap,i64);
372eeb23a4cSdrh           }else if( flag_long ){
373eeb23a4cSdrh             v = va_arg(ap,long int);
374eeb23a4cSdrh           }else{
375eeb23a4cSdrh             v = va_arg(ap,int);
376eeb23a4cSdrh           }
377e9707671Sdrh           if( v<0 ){
378158b9cb9Sdrh             if( v==SMALLEST_INT64 ){
379158b9cb9Sdrh               longvalue = ((u64)1)<<63;
380158b9cb9Sdrh             }else{
381158b9cb9Sdrh               longvalue = -v;
382158b9cb9Sdrh             }
383cfcdaefeSdanielk1977             prefix = '-';
384cfcdaefeSdanielk1977           }else{
385e9707671Sdrh             longvalue = v;
386e9707671Sdrh             if( flag_plussign )        prefix = '+';
387a18c5681Sdrh             else if( flag_blanksign )  prefix = ' ';
388a18c5681Sdrh             else                       prefix = 0;
389cfcdaefeSdanielk1977           }
390e9707671Sdrh         }else{
391a5c1416dSdrh           if( bArgList ){
392a5c1416dSdrh             longvalue = (u64)getIntArg(pArgList);
393a5c1416dSdrh           }else if( flag_longlong ){
394eeb23a4cSdrh             longvalue = va_arg(ap,u64);
395eeb23a4cSdrh           }else if( flag_long ){
396eeb23a4cSdrh             longvalue = va_arg(ap,unsigned long int);
397eeb23a4cSdrh           }else{
398eeb23a4cSdrh             longvalue = va_arg(ap,unsigned int);
399eeb23a4cSdrh           }
400e9707671Sdrh           prefix = 0;
401e9707671Sdrh         }
402e9707671Sdrh         if( longvalue==0 ) flag_alternateform = 0;
403a18c5681Sdrh         if( flag_zeropad && precision<width-(prefix!=0) ){
404a18c5681Sdrh           precision = width-(prefix!=0);
405a18c5681Sdrh         }
40659eedf79Sdrh         if( precision<etBUFSIZE-10 ){
40759eedf79Sdrh           nOut = etBUFSIZE;
40859eedf79Sdrh           zOut = buf;
40959eedf79Sdrh         }else{
41059eedf79Sdrh           nOut = precision + 10;
41159eedf79Sdrh           zOut = zExtra = sqlite3Malloc( nOut );
41259eedf79Sdrh           if( zOut==0 ){
413a6353a3fSdrh             setStrAccumError(pAccum, STRACCUM_NOMEM);
41459eedf79Sdrh             return;
41559eedf79Sdrh           }
41659eedf79Sdrh         }
41759eedf79Sdrh         bufpt = &zOut[nOut-1];
4189a99334dSdrh         if( xtype==etORDINAL ){
41943f6e064Sdrh           static const char zOrd[] = "thstndrd";
420ea678832Sdrh           int x = (int)(longvalue % 10);
42143f6e064Sdrh           if( x>=4 || (longvalue/10)%10==1 ){
42243f6e064Sdrh             x = 0;
42343f6e064Sdrh           }
42459eedf79Sdrh           *(--bufpt) = zOrd[x*2+1];
42559eedf79Sdrh           *(--bufpt) = zOrd[x*2];
4269a99334dSdrh         }
427a18c5681Sdrh         {
4280e682099Sdrh           const char *cset = &aDigits[infop->charset];
4290e682099Sdrh           u8 base = infop->base;
430a18c5681Sdrh           do{                                           /* Convert to ascii */
431a18c5681Sdrh             *(--bufpt) = cset[longvalue%base];
432a18c5681Sdrh             longvalue = longvalue/base;
433a18c5681Sdrh           }while( longvalue>0 );
434a18c5681Sdrh         }
43559eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
436a18c5681Sdrh         for(idx=precision-length; idx>0; idx--){
437a18c5681Sdrh           *(--bufpt) = '0';                             /* Zero pad */
438a18c5681Sdrh         }
439a18c5681Sdrh         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
440a18c5681Sdrh         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
44176ff3a0eSdrh           const char *pre;
44276ff3a0eSdrh           char x;
44376ff3a0eSdrh           pre = &aPrefix[infop->prefix];
44476ff3a0eSdrh           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
445a18c5681Sdrh         }
44659eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
447a18c5681Sdrh         break;
448a18c5681Sdrh       case etFLOAT:
449a18c5681Sdrh       case etEXP:
450a18c5681Sdrh       case etGENERIC:
451a5c1416dSdrh         if( bArgList ){
452a5c1416dSdrh           realvalue = getDoubleArg(pArgList);
453a5c1416dSdrh         }else{
454a18c5681Sdrh           realvalue = va_arg(ap,double);
455a5c1416dSdrh         }
45669ef7036Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
45769ef7036Sdrh         length = 0;
45869ef7036Sdrh #else
459a18c5681Sdrh         if( precision<0 ) precision = 6;         /* Set default precision */
460a18c5681Sdrh         if( realvalue<0.0 ){
461a18c5681Sdrh           realvalue = -realvalue;
462a18c5681Sdrh           prefix = '-';
463a18c5681Sdrh         }else{
464a18c5681Sdrh           if( flag_plussign )          prefix = '+';
465a18c5681Sdrh           else if( flag_blanksign )    prefix = ' ';
466a18c5681Sdrh           else                         prefix = 0;
467a18c5681Sdrh         }
4683e9aeec0Sdrh         if( xtype==etGENERIC && precision>0 ) precision--;
46974161705Sdrh         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
4703e9aeec0Sdrh         if( xtype==etFLOAT ) realvalue += rounder;
471a18c5681Sdrh         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
472a18c5681Sdrh         exp = 0;
473ea678832Sdrh         if( sqlite3IsNaN((double)realvalue) ){
47453c14021Sdrh           bufpt = "NaN";
47553c14021Sdrh           length = 3;
47653c14021Sdrh           break;
47753c14021Sdrh         }
478a18c5681Sdrh         if( realvalue>0.0 ){
47972b3fbc7Sdrh           LONGDOUBLE_TYPE scale = 1.0;
4804ef94130Sdrh           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
48172b3fbc7Sdrh           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
48272b3fbc7Sdrh           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
48372b3fbc7Sdrh           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
48472b3fbc7Sdrh           realvalue /= scale;
485af005fbcSdrh           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
486af005fbcSdrh           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
487af005fbcSdrh           if( exp>350 ){
48853c14021Sdrh             if( prefix=='-' ){
48953c14021Sdrh               bufpt = "-Inf";
49053c14021Sdrh             }else if( prefix=='+' ){
49153c14021Sdrh               bufpt = "+Inf";
49253c14021Sdrh             }else{
49353c14021Sdrh               bufpt = "Inf";
49453c14021Sdrh             }
495ea678832Sdrh             length = sqlite3Strlen30(bufpt);
496a18c5681Sdrh             break;
497a18c5681Sdrh           }
498a18c5681Sdrh         }
499a18c5681Sdrh         bufpt = buf;
500a18c5681Sdrh         /*
501a18c5681Sdrh         ** If the field type is etGENERIC, then convert to either etEXP
502a18c5681Sdrh         ** or etFLOAT, as appropriate.
503a18c5681Sdrh         */
504a18c5681Sdrh         if( xtype!=etFLOAT ){
505a18c5681Sdrh           realvalue += rounder;
506a18c5681Sdrh           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
507a18c5681Sdrh         }
508a18c5681Sdrh         if( xtype==etGENERIC ){
509a18c5681Sdrh           flag_rtz = !flag_alternateform;
510a18c5681Sdrh           if( exp<-4 || exp>precision ){
511a18c5681Sdrh             xtype = etEXP;
512a18c5681Sdrh           }else{
513a18c5681Sdrh             precision = precision - exp;
514a18c5681Sdrh             xtype = etFLOAT;
515a18c5681Sdrh           }
516a18c5681Sdrh         }else{
51772b3fbc7Sdrh           flag_rtz = flag_altform2;
518a18c5681Sdrh         }
519557cc60fSdrh         if( xtype==etEXP ){
520557cc60fSdrh           e2 = 0;
521557cc60fSdrh         }else{
522557cc60fSdrh           e2 = exp;
523557cc60fSdrh         }
524e8c13bf2Sdrh         if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
525e8c13bf2Sdrh           bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
52659eedf79Sdrh           if( bufpt==0 ){
527a6353a3fSdrh             setStrAccumError(pAccum, STRACCUM_NOMEM);
52859eedf79Sdrh             return;
52959eedf79Sdrh           }
53059eedf79Sdrh         }
53159eedf79Sdrh         zOut = bufpt;
53272b3fbc7Sdrh         nsd = 16 + flag_altform2*10;
533ea678832Sdrh         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
534557cc60fSdrh         /* The sign in front of the number */
535557cc60fSdrh         if( prefix ){
536557cc60fSdrh           *(bufpt++) = prefix;
537557cc60fSdrh         }
538557cc60fSdrh         /* Digits prior to the decimal point */
539557cc60fSdrh         if( e2<0 ){
540557cc60fSdrh           *(bufpt++) = '0';
541557cc60fSdrh         }else{
542557cc60fSdrh           for(; e2>=0; e2--){
543557cc60fSdrh             *(bufpt++) = et_getdigit(&realvalue,&nsd);
544557cc60fSdrh           }
545557cc60fSdrh         }
546557cc60fSdrh         /* The decimal point */
547557cc60fSdrh         if( flag_dp ){
548557cc60fSdrh           *(bufpt++) = '.';
549557cc60fSdrh         }
550557cc60fSdrh         /* "0" digits after the decimal point but before the first
551557cc60fSdrh         ** significant digit of the number */
552af005fbcSdrh         for(e2++; e2<0; precision--, e2++){
553af005fbcSdrh           assert( precision>0 );
554a18c5681Sdrh           *(bufpt++) = '0';
555a18c5681Sdrh         }
556557cc60fSdrh         /* Significant digits after the decimal point */
557557cc60fSdrh         while( (precision--)>0 ){
558557cc60fSdrh           *(bufpt++) = et_getdigit(&realvalue,&nsd);
559a18c5681Sdrh         }
560557cc60fSdrh         /* Remove trailing zeros and the "." if no digits follow the "." */
561557cc60fSdrh         if( flag_rtz && flag_dp ){
5623e9aeec0Sdrh           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
56359eedf79Sdrh           assert( bufpt>zOut );
5643e9aeec0Sdrh           if( bufpt[-1]=='.' ){
565557cc60fSdrh             if( flag_altform2 ){
566557cc60fSdrh               *(bufpt++) = '0';
567557cc60fSdrh             }else{
568557cc60fSdrh               *(--bufpt) = 0;
569a18c5681Sdrh             }
570557cc60fSdrh           }
571557cc60fSdrh         }
572557cc60fSdrh         /* Add the "eNNN" suffix */
57359eedf79Sdrh         if( xtype==etEXP ){
57476ff3a0eSdrh           *(bufpt++) = aDigits[infop->charset];
575557cc60fSdrh           if( exp<0 ){
576557cc60fSdrh             *(bufpt++) = '-'; exp = -exp;
577557cc60fSdrh           }else{
578557cc60fSdrh             *(bufpt++) = '+';
579557cc60fSdrh           }
580a18c5681Sdrh           if( exp>=100 ){
581ea678832Sdrh             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
582a18c5681Sdrh             exp %= 100;
583a18c5681Sdrh           }
584ea678832Sdrh           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
585ea678832Sdrh           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
586a18c5681Sdrh         }
587557cc60fSdrh         *bufpt = 0;
588557cc60fSdrh 
589a18c5681Sdrh         /* The converted number is in buf[] and zero terminated. Output it.
590a18c5681Sdrh         ** Note that the number is in the usual order, not reversed as with
591a18c5681Sdrh         ** integer conversions. */
59259eedf79Sdrh         length = (int)(bufpt-zOut);
59359eedf79Sdrh         bufpt = zOut;
594a18c5681Sdrh 
595a18c5681Sdrh         /* Special case:  Add leading zeros if the flag_zeropad flag is
596a18c5681Sdrh         ** set and we are not left justified */
597a18c5681Sdrh         if( flag_zeropad && !flag_leftjustify && length < width){
598a18c5681Sdrh           int i;
599a18c5681Sdrh           int nPad = width - length;
600a18c5681Sdrh           for(i=width; i>=nPad; i--){
601a18c5681Sdrh             bufpt[i] = bufpt[i-nPad];
602a18c5681Sdrh           }
603a18c5681Sdrh           i = prefix!=0;
604a18c5681Sdrh           while( nPad-- ) bufpt[i++] = '0';
605a18c5681Sdrh           length = width;
606a18c5681Sdrh         }
60769ef7036Sdrh #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
608a18c5681Sdrh         break;
609a18c5681Sdrh       case etSIZE:
610fc6ee9dfSdrh         if( !bArgList ){
611fc6ee9dfSdrh           *(va_arg(ap,int*)) = pAccum->nChar;
612fc6ee9dfSdrh         }
613a18c5681Sdrh         length = width = 0;
614a18c5681Sdrh         break;
615a18c5681Sdrh       case etPERCENT:
616a18c5681Sdrh         buf[0] = '%';
617a18c5681Sdrh         bufpt = buf;
618a18c5681Sdrh         length = 1;
619a18c5681Sdrh         break;
620a18c5681Sdrh       case etCHARX:
621a5c1416dSdrh         if( bArgList ){
622fc6ee9dfSdrh           bufpt = getTextArg(pArgList);
623fc6ee9dfSdrh           c = bufpt ? bufpt[0] : 0;
624a5c1416dSdrh         }else{
625ea678832Sdrh           c = va_arg(ap,int);
626a5c1416dSdrh         }
627ea678832Sdrh         buf[0] = (char)c;
628a18c5681Sdrh         if( precision>=0 ){
629ea678832Sdrh           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
630a18c5681Sdrh           length = precision;
631a18c5681Sdrh         }else{
632a18c5681Sdrh           length =1;
633a18c5681Sdrh         }
634a18c5681Sdrh         bufpt = buf;
635a18c5681Sdrh         break;
636a18c5681Sdrh       case etSTRING:
637d93d8a81Sdrh       case etDYNSTRING:
638a5c1416dSdrh         if( bArgList ){
639a5c1416dSdrh           bufpt = getTextArg(pArgList);
640a5c1416dSdrh         }else{
641cb485882Sdrh           bufpt = va_arg(ap,char*);
642a5c1416dSdrh         }
643d93d8a81Sdrh         if( bufpt==0 ){
644d93d8a81Sdrh           bufpt = "";
645a5c1416dSdrh         }else if( xtype==etDYNSTRING && !bArgList ){
646d93d8a81Sdrh           zExtra = bufpt;
647d93d8a81Sdrh         }
648e509094bSdrh         if( precision>=0 ){
649e509094bSdrh           for(length=0; length<precision && bufpt[length]; length++){}
650e509094bSdrh         }else{
651ea678832Sdrh           length = sqlite3Strlen30(bufpt);
652e509094bSdrh         }
653a18c5681Sdrh         break;
654a18c5681Sdrh       case etSQLESCAPE:
655f3b863edSdanielk1977       case etSQLESCAPE2:
656f3b863edSdanielk1977       case etSQLESCAPE3: {
6578965b50eSdrh         int i, j, k, n, isnull;
6584794f735Sdrh         int needQuote;
659ea678832Sdrh         char ch;
660f3b863edSdanielk1977         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
661a5c1416dSdrh         char *escarg;
662a5c1416dSdrh 
663a5c1416dSdrh         if( bArgList ){
664a5c1416dSdrh           escarg = getTextArg(pArgList);
665a5c1416dSdrh         }else{
666a5c1416dSdrh           escarg = va_arg(ap,char*);
667a5c1416dSdrh         }
668f0113000Sdanielk1977         isnull = escarg==0;
669f0113000Sdanielk1977         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
6708965b50eSdrh         k = precision;
67160d4a304Sdan         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
672f3b863edSdanielk1977           if( ch==q )  n++;
673a18c5681Sdrh         }
6744794f735Sdrh         needQuote = !isnull && xtype==etSQLESCAPE2;
6754794f735Sdrh         n += i + 1 + needQuote*2;
676a18c5681Sdrh         if( n>etBUFSIZE ){
677e5ae5735Sdrh           bufpt = zExtra = sqlite3Malloc( n );
678d164fd34Sdrh           if( bufpt==0 ){
679a6353a3fSdrh             setStrAccumError(pAccum, STRACCUM_NOMEM);
680d164fd34Sdrh             return;
681d164fd34Sdrh           }
682a18c5681Sdrh         }else{
683a18c5681Sdrh           bufpt = buf;
684a18c5681Sdrh         }
6850cfcf3fbSchw         j = 0;
686f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
6878965b50eSdrh         k = i;
6888965b50eSdrh         for(i=0; i<k; i++){
6898965b50eSdrh           bufpt[j++] = ch = escarg[i];
690f3b863edSdanielk1977           if( ch==q ) bufpt[j++] = ch;
691a18c5681Sdrh         }
692f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
693a18c5681Sdrh         bufpt[j] = 0;
694a18c5681Sdrh         length = j;
6958965b50eSdrh         /* The precision in %q and %Q means how many input characters to
6968965b50eSdrh         ** consume, not the length of the output...
6978965b50eSdrh         ** if( precision>=0 && precision<length ) length = precision; */
698a18c5681Sdrh         break;
6995eba8c09Sdrh       }
7005f968436Sdrh       case etTOKEN: {
7015f968436Sdrh         Token *pToken = va_arg(ap, Token*);
702a5c1416dSdrh         assert( bArgList==0 );
703a9ab481fSdrh         if( pToken && pToken->n ){
704ade86483Sdrh           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
705ad6d9460Sdrh         }
7065f968436Sdrh         length = width = 0;
7075f968436Sdrh         break;
7085f968436Sdrh       }
7095f968436Sdrh       case etSRCLIST: {
7105f968436Sdrh         SrcList *pSrc = va_arg(ap, SrcList*);
7115f968436Sdrh         int k = va_arg(ap, int);
7125f968436Sdrh         struct SrcList_item *pItem = &pSrc->a[k];
713a5c1416dSdrh         assert( bArgList==0 );
7145f968436Sdrh         assert( k>=0 && k<pSrc->nSrc );
71593a960a0Sdrh         if( pItem->zDatabase ){
716a6353a3fSdrh           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
717ade86483Sdrh           sqlite3StrAccumAppend(pAccum, ".", 1);
7185f968436Sdrh         }
719a6353a3fSdrh         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
7205f968436Sdrh         length = width = 0;
7215f968436Sdrh         break;
7225f968436Sdrh       }
723874ba04cSdrh       default: {
724874ba04cSdrh         assert( xtype==etINVALID );
725874ba04cSdrh         return;
726874ba04cSdrh       }
727a18c5681Sdrh     }/* End switch over the format type */
728a18c5681Sdrh     /*
729a18c5681Sdrh     ** The text of the conversion is pointed to by "bufpt" and is
730a18c5681Sdrh     ** "length" characters long.  The field width is "width".  Do
731a18c5681Sdrh     ** the output.
732a18c5681Sdrh     */
733a70a073bSdrh     width -= length;
734a70a073bSdrh     if( width>0 && !flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
735ade86483Sdrh     sqlite3StrAccumAppend(pAccum, bufpt, length);
736a70a073bSdrh     if( width>0 && flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
737a70a073bSdrh 
73840f22bedSdrh     if( zExtra ) sqlite3_free(zExtra);
739a18c5681Sdrh   }/* End for loop over the format string */
740a18c5681Sdrh } /* End of function */
741a18c5681Sdrh 
742a18c5681Sdrh /*
743a70a073bSdrh ** Enlarge the memory allocation on a StrAccum object so that it is
744a70a073bSdrh ** able to accept at least N more bytes of text.
745a70a073bSdrh **
746a70a073bSdrh ** Return the number of bytes of text that StrAccum is able to accept
747a70a073bSdrh ** after the attempted enlargement.  The value returned might be zero.
748a18c5681Sdrh */
749a70a073bSdrh static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
750a6353a3fSdrh   char *zNew;
751a70a073bSdrh   assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
752b49bc86aSdrh   if( p->accError ){
753b49bc86aSdrh     testcase(p->accError==STRACCUM_TOOBIG);
754b49bc86aSdrh     testcase(p->accError==STRACCUM_NOMEM);
755a70a073bSdrh     return 0;
756ade86483Sdrh   }
757ade86483Sdrh   if( !p->useMalloc ){
758ade86483Sdrh     N = p->nAlloc - p->nChar - 1;
759a6353a3fSdrh     setStrAccumError(p, STRACCUM_TOOBIG);
760a70a073bSdrh     return N;
761a18c5681Sdrh   }else{
762a9ef7097Sdan     char *zOld = (p->zText==p->zBase ? 0 : p->zText);
76393a960a0Sdrh     i64 szNew = p->nChar;
764b1a6c3c1Sdrh     szNew += N + 1;
765b1a6c3c1Sdrh     if( szNew > p->mxAlloc ){
766ade86483Sdrh       sqlite3StrAccumReset(p);
767a6353a3fSdrh       setStrAccumError(p, STRACCUM_TOOBIG);
768a70a073bSdrh       return 0;
769b1a6c3c1Sdrh     }else{
770ea678832Sdrh       p->nAlloc = (int)szNew;
771a18c5681Sdrh     }
772b975598eSdrh     if( p->useMalloc==1 ){
773a9ef7097Sdan       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
774b975598eSdrh     }else{
775a9ef7097Sdan       zNew = sqlite3_realloc(zOld, p->nAlloc);
776b975598eSdrh     }
77753f733c7Sdrh     if( zNew ){
7787ef4d1c4Sdrh       assert( p->zText!=0 || p->nChar==0 );
779b07028f7Sdrh       if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
780ade86483Sdrh       p->zText = zNew;
781ade86483Sdrh     }else{
782ade86483Sdrh       sqlite3StrAccumReset(p);
783a6353a3fSdrh       setStrAccumError(p, STRACCUM_NOMEM);
784a70a073bSdrh       return 0;
785a70a073bSdrh     }
786a70a073bSdrh   }
787a70a073bSdrh   return N;
788a70a073bSdrh }
789a70a073bSdrh 
790a70a073bSdrh /*
791a70a073bSdrh ** Append N space characters to the given string buffer.
792a70a073bSdrh */
793a70a073bSdrh void sqlite3AppendSpace(StrAccum *p, int N){
794a70a073bSdrh   if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
795a70a073bSdrh   while( (N--)>0 ) p->zText[p->nChar++] = ' ';
796a70a073bSdrh }
797a70a073bSdrh 
798a70a073bSdrh /*
799a70a073bSdrh ** The StrAccum "p" is not large enough to accept N new bytes of z[].
800a70a073bSdrh ** So enlarge if first, then do the append.
801a70a073bSdrh **
802a70a073bSdrh ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
803a70a073bSdrh ** work (enlarging the buffer) using tail recursion, so that the
804a70a073bSdrh ** sqlite3StrAccumAppend() routine can use fast calling semantics.
805a70a073bSdrh */
806172087fbSdrh static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
807a70a073bSdrh   N = sqlite3StrAccumEnlarge(p, N);
808a70a073bSdrh   if( N>0 ){
809a70a073bSdrh     memcpy(&p->zText[p->nChar], z, N);
810a70a073bSdrh     p->nChar += N;
811a70a073bSdrh   }
812a70a073bSdrh }
813a70a073bSdrh 
814a70a073bSdrh /*
815a70a073bSdrh ** Append N bytes of text from z to the StrAccum object.  Increase the
816a70a073bSdrh ** size of the memory allocation for StrAccum if necessary.
817a70a073bSdrh */
818a70a073bSdrh void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
819a70a073bSdrh   assert( z!=0 );
820a70a073bSdrh   assert( p->zText!=0 || p->nChar==0 || p->accError );
821a70a073bSdrh   assert( N>=0 );
822a70a073bSdrh   assert( p->accError==0 || p->nAlloc==0 );
823a70a073bSdrh   if( p->nChar+N >= p->nAlloc ){
824a70a073bSdrh     enlargeAndAppend(p,z,N);
825172087fbSdrh   }else{
826b07028f7Sdrh     assert( p->zText );
827ade86483Sdrh     p->nChar += N;
828172087fbSdrh     memcpy(&p->zText[p->nChar-N], z, N);
829172087fbSdrh   }
830483750baSdrh }
831483750baSdrh 
832483750baSdrh /*
833a6353a3fSdrh ** Append the complete text of zero-terminated string z[] to the p string.
834a6353a3fSdrh */
835a6353a3fSdrh void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
83653cd9646Smistachkin   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
837a6353a3fSdrh }
838a6353a3fSdrh 
839a6353a3fSdrh 
840a6353a3fSdrh /*
841ade86483Sdrh ** Finish off a string by making sure it is zero-terminated.
842ade86483Sdrh ** Return a pointer to the resulting string.  Return a NULL
843ade86483Sdrh ** pointer if any kind of error was encountered.
8445f968436Sdrh */
845ade86483Sdrh char *sqlite3StrAccumFinish(StrAccum *p){
846ade86483Sdrh   if( p->zText ){
847ade86483Sdrh     p->zText[p->nChar] = 0;
848ade86483Sdrh     if( p->useMalloc && p->zText==p->zBase ){
849b975598eSdrh       if( p->useMalloc==1 ){
850633e6d57Sdrh         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
851b975598eSdrh       }else{
852b975598eSdrh         p->zText = sqlite3_malloc(p->nChar+1);
853b975598eSdrh       }
854ade86483Sdrh       if( p->zText ){
855ade86483Sdrh         memcpy(p->zText, p->zBase, p->nChar+1);
856ade86483Sdrh       }else{
857a6353a3fSdrh         setStrAccumError(p, STRACCUM_NOMEM);
858ade86483Sdrh       }
859ade86483Sdrh     }
860ade86483Sdrh   }
861ade86483Sdrh   return p->zText;
862ade86483Sdrh }
863ade86483Sdrh 
864ade86483Sdrh /*
865ade86483Sdrh ** Reset an StrAccum string.  Reclaim all malloced memory.
866ade86483Sdrh */
867ade86483Sdrh void sqlite3StrAccumReset(StrAccum *p){
868ade86483Sdrh   if( p->zText!=p->zBase ){
869b975598eSdrh     if( p->useMalloc==1 ){
870633e6d57Sdrh       sqlite3DbFree(p->db, p->zText);
871b975598eSdrh     }else{
872b975598eSdrh       sqlite3_free(p->zText);
873b975598eSdrh     }
874ade86483Sdrh   }
875f089aa45Sdrh   p->zText = 0;
876ade86483Sdrh }
877ade86483Sdrh 
878ade86483Sdrh /*
879ade86483Sdrh ** Initialize a string accumulator
880ade86483Sdrh */
881f089aa45Sdrh void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
882ade86483Sdrh   p->zText = p->zBase = zBase;
883633e6d57Sdrh   p->db = 0;
884ade86483Sdrh   p->nChar = 0;
885ade86483Sdrh   p->nAlloc = n;
886bb4957f8Sdrh   p->mxAlloc = mx;
887ade86483Sdrh   p->useMalloc = 1;
888b49bc86aSdrh   p->accError = 0;
8895f968436Sdrh }
8905f968436Sdrh 
8915f968436Sdrh /*
8925f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
8935f968436Sdrh ** %-conversion extensions.
8945f968436Sdrh */
89517435752Sdrh char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
89617435752Sdrh   char *z;
89779158e18Sdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
898ade86483Sdrh   StrAccum acc;
899bc6160b0Sdrh   assert( db!=0 );
900bb4957f8Sdrh   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
901bc6160b0Sdrh                       db->aLimit[SQLITE_LIMIT_LENGTH]);
902633e6d57Sdrh   acc.db = db;
903a5c1416dSdrh   sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
904ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
905b49bc86aSdrh   if( acc.accError==STRACCUM_NOMEM ){
90617435752Sdrh     db->mallocFailed = 1;
90717435752Sdrh   }
90817435752Sdrh   return z;
9095f968436Sdrh }
9105f968436Sdrh 
9115f968436Sdrh /*
9125f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
9135f968436Sdrh ** %-conversion extensions.
9145f968436Sdrh */
91517435752Sdrh char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
9165f968436Sdrh   va_list ap;
9175f968436Sdrh   char *z;
9185f968436Sdrh   va_start(ap, zFormat);
919ade86483Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
9205f968436Sdrh   va_end(ap);
9215f968436Sdrh   return z;
9225f968436Sdrh }
9235f968436Sdrh 
9245f968436Sdrh /*
925633e6d57Sdrh ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
92660ec914cSpeter.d.reid ** the string and before returning.  This routine is intended to be used
927633e6d57Sdrh ** to modify an existing string.  For example:
928633e6d57Sdrh **
929633e6d57Sdrh **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
930633e6d57Sdrh **
931633e6d57Sdrh */
932633e6d57Sdrh char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
933633e6d57Sdrh   va_list ap;
934633e6d57Sdrh   char *z;
935633e6d57Sdrh   va_start(ap, zFormat);
936633e6d57Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
937633e6d57Sdrh   va_end(ap);
938633e6d57Sdrh   sqlite3DbFree(db, zStr);
939633e6d57Sdrh   return z;
940633e6d57Sdrh }
941633e6d57Sdrh 
942633e6d57Sdrh /*
94328dd479cSdrh ** Print into memory obtained from sqlite3_malloc().  Omit the internal
94428dd479cSdrh ** %-conversion extensions.
94528dd479cSdrh */
94628dd479cSdrh char *sqlite3_vmprintf(const char *zFormat, va_list ap){
947ade86483Sdrh   char *z;
94828dd479cSdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
949ade86483Sdrh   StrAccum acc;
950ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
951ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
952ff1590eeSdrh #endif
953bb4957f8Sdrh   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
954b975598eSdrh   acc.useMalloc = 2;
955f089aa45Sdrh   sqlite3VXPrintf(&acc, 0, zFormat, ap);
956ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
957ade86483Sdrh   return z;
95828dd479cSdrh }
95928dd479cSdrh 
96028dd479cSdrh /*
96128dd479cSdrh ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
96228dd479cSdrh ** %-conversion extensions.
963483750baSdrh */
9646f8a503dSdanielk1977 char *sqlite3_mprintf(const char *zFormat, ...){
965a18c5681Sdrh   va_list ap;
9665f968436Sdrh   char *z;
967ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
968ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
969ff1590eeSdrh #endif
970a18c5681Sdrh   va_start(ap, zFormat);
971b3738b6cSdrh   z = sqlite3_vmprintf(zFormat, ap);
972a18c5681Sdrh   va_end(ap);
9735f968436Sdrh   return z;
974a18c5681Sdrh }
975a18c5681Sdrh 
976a18c5681Sdrh /*
9776f8a503dSdanielk1977 ** sqlite3_snprintf() works like snprintf() except that it ignores the
97893a5c6bdSdrh ** current locale settings.  This is important for SQLite because we
97993a5c6bdSdrh ** are not able to use a "," as the decimal point in place of "." as
98093a5c6bdSdrh ** specified by some locales.
981db26d4c9Sdrh **
982db26d4c9Sdrh ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
983db26d4c9Sdrh ** from the snprintf() standard.  Unfortunately, it is too late to change
984db26d4c9Sdrh ** this without breaking compatibility, so we just have to live with the
985db26d4c9Sdrh ** mistake.
986db26d4c9Sdrh **
987db26d4c9Sdrh ** sqlite3_vsnprintf() is the varargs version.
98893a5c6bdSdrh */
989db26d4c9Sdrh char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
990db26d4c9Sdrh   StrAccum acc;
991db26d4c9Sdrh   if( n<=0 ) return zBuf;
992db26d4c9Sdrh   sqlite3StrAccumInit(&acc, zBuf, n, 0);
993db26d4c9Sdrh   acc.useMalloc = 0;
994db26d4c9Sdrh   sqlite3VXPrintf(&acc, 0, zFormat, ap);
995db26d4c9Sdrh   return sqlite3StrAccumFinish(&acc);
996db26d4c9Sdrh }
9976f8a503dSdanielk1977 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
9985f968436Sdrh   char *z;
99993a5c6bdSdrh   va_list ap;
100093a5c6bdSdrh   va_start(ap,zFormat);
1001db26d4c9Sdrh   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
100293a5c6bdSdrh   va_end(ap);
10035f968436Sdrh   return z;
100493a5c6bdSdrh }
100593a5c6bdSdrh 
10063f280701Sdrh /*
10077c0c460fSdrh ** This is the routine that actually formats the sqlite3_log() message.
10087c0c460fSdrh ** We house it in a separate routine from sqlite3_log() to avoid using
10097c0c460fSdrh ** stack space on small-stack systems when logging is disabled.
10107c0c460fSdrh **
10117c0c460fSdrh ** sqlite3_log() must render into a static buffer.  It cannot dynamically
10127c0c460fSdrh ** allocate memory because it might be called while the memory allocator
10137c0c460fSdrh ** mutex is held.
10147c0c460fSdrh */
10157c0c460fSdrh static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
10167c0c460fSdrh   StrAccum acc;                          /* String accumulator */
1017a64fa912Sdrh   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
10187c0c460fSdrh 
10197c0c460fSdrh   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
10207c0c460fSdrh   acc.useMalloc = 0;
10217c0c460fSdrh   sqlite3VXPrintf(&acc, 0, zFormat, ap);
10227c0c460fSdrh   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
10237c0c460fSdrh                            sqlite3StrAccumFinish(&acc));
10247c0c460fSdrh }
10257c0c460fSdrh 
10267c0c460fSdrh /*
10273f280701Sdrh ** Format and write a message to the log if logging is enabled.
10283f280701Sdrh */
1029a7564663Sdrh void sqlite3_log(int iErrCode, const char *zFormat, ...){
10303f280701Sdrh   va_list ap;                             /* Vararg list */
10317c0c460fSdrh   if( sqlite3GlobalConfig.xLog ){
10323f280701Sdrh     va_start(ap, zFormat);
10337c0c460fSdrh     renderLogMsg(iErrCode, zFormat, ap);
10343f280701Sdrh     va_end(ap);
10353f280701Sdrh   }
10363f280701Sdrh }
10373f280701Sdrh 
103885e9e22bSdrh #if defined(SQLITE_DEBUG)
1039e54ca3feSdrh /*
1040e54ca3feSdrh ** A version of printf() that understands %lld.  Used for debugging.
1041e54ca3feSdrh ** The printf() built into some versions of windows does not understand %lld
1042e54ca3feSdrh ** and segfaults if you give it a long long int.
1043e54ca3feSdrh */
1044e54ca3feSdrh void sqlite3DebugPrintf(const char *zFormat, ...){
1045e54ca3feSdrh   va_list ap;
1046ade86483Sdrh   StrAccum acc;
1047e54ca3feSdrh   char zBuf[500];
1048bb4957f8Sdrh   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
1049ade86483Sdrh   acc.useMalloc = 0;
1050e54ca3feSdrh   va_start(ap,zFormat);
1051f089aa45Sdrh   sqlite3VXPrintf(&acc, 0, zFormat, ap);
1052e54ca3feSdrh   va_end(ap);
1053bed8e7e5Sdrh   sqlite3StrAccumFinish(&acc);
1054485f0039Sdrh   fprintf(stdout,"%s", zBuf);
10552ac3ee97Sdrh   fflush(stdout);
1056e54ca3feSdrh }
1057e54ca3feSdrh #endif
1058c7bc4fdeSdrh 
10594fa4a54fSdrh #ifdef SQLITE_DEBUG
10604fa4a54fSdrh /*************************************************************************
10614fa4a54fSdrh ** Routines for implementing the "TreeView" display of hierarchical
10624fa4a54fSdrh ** data structures for debugging.
10634fa4a54fSdrh **
10644fa4a54fSdrh ** The main entry points (coded elsewhere) are:
10654fa4a54fSdrh **     sqlite3TreeViewExpr(0, pExpr, 0);
10664fa4a54fSdrh **     sqlite3TreeViewExprList(0, pList, 0, 0);
10674fa4a54fSdrh **     sqlite3TreeViewSelect(0, pSelect, 0);
10684fa4a54fSdrh ** Insert calls to those routines while debugging in order to display
10694fa4a54fSdrh ** a diagram of Expr, ExprList, and Select objects.
10704fa4a54fSdrh **
10714fa4a54fSdrh */
10724fa4a54fSdrh /* Add a new subitem to the tree.  The moreToFollow flag indicates that this
10734fa4a54fSdrh ** is not the last item in the tree. */
10744fa4a54fSdrh TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
10754fa4a54fSdrh   if( p==0 ){
10764fa4a54fSdrh     p = sqlite3_malloc( sizeof(*p) );
10774fa4a54fSdrh     if( p==0 ) return 0;
10784fa4a54fSdrh     memset(p, 0, sizeof(*p));
10794fa4a54fSdrh   }else{
10804fa4a54fSdrh     p->iLevel++;
10814fa4a54fSdrh   }
10824fa4a54fSdrh   assert( moreToFollow==0 || moreToFollow==1 );
1083*b08cd3f3Sdrh   if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
10844fa4a54fSdrh   return p;
10854fa4a54fSdrh }
10864fa4a54fSdrh /* Finished with one layer of the tree */
10874fa4a54fSdrh void sqlite3TreeViewPop(TreeView *p){
10884fa4a54fSdrh   if( p==0 ) return;
10894fa4a54fSdrh   p->iLevel--;
10904fa4a54fSdrh   if( p->iLevel<0 ) sqlite3_free(p);
10914fa4a54fSdrh }
10924fa4a54fSdrh /* Generate a single line of output for the tree, with a prefix that contains
10934fa4a54fSdrh ** all the appropriate tree lines */
10944fa4a54fSdrh void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
10954fa4a54fSdrh   va_list ap;
10964fa4a54fSdrh   int i;
10974fa4a54fSdrh   StrAccum acc;
10984fa4a54fSdrh   char zBuf[500];
10994fa4a54fSdrh   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
11004fa4a54fSdrh   acc.useMalloc = 0;
11014fa4a54fSdrh   if( p ){
1102*b08cd3f3Sdrh     for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
1103*b08cd3f3Sdrh       sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
11044fa4a54fSdrh     }
1105*b08cd3f3Sdrh     sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
11064fa4a54fSdrh   }
11074fa4a54fSdrh   va_start(ap, zFormat);
11084fa4a54fSdrh   sqlite3VXPrintf(&acc, 0, zFormat, ap);
11094fa4a54fSdrh   va_end(ap);
11104fa4a54fSdrh   if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
11114fa4a54fSdrh   sqlite3StrAccumFinish(&acc);
11124fa4a54fSdrh   fprintf(stdout,"%s", zBuf);
11134fa4a54fSdrh   fflush(stdout);
11144fa4a54fSdrh }
11154fa4a54fSdrh /* Shorthand for starting a new tree item that consists of a single label */
11164fa4a54fSdrh void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
11174fa4a54fSdrh   p = sqlite3TreeViewPush(p, moreToFollow);
11184fa4a54fSdrh   sqlite3TreeViewLine(p, "%s", zLabel);
11194fa4a54fSdrh }
11204fa4a54fSdrh #endif /* SQLITE_DEBUG */
11214fa4a54fSdrh 
1122c7bc4fdeSdrh /*
1123c7bc4fdeSdrh ** variable-argument wrapper around sqlite3VXPrintf().
1124c7bc4fdeSdrh */
1125a5c1416dSdrh void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
1126c7bc4fdeSdrh   va_list ap;
1127c7bc4fdeSdrh   va_start(ap,zFormat);
1128a5c1416dSdrh   sqlite3VXPrintf(p, bFlags, zFormat, ap);
1129c7bc4fdeSdrh   va_end(ap);
1130c7bc4fdeSdrh }
1131