xref: /sqlite-3.40.0/src/func.c (revision f442e33e)
1 /*
2 ** 2002 February 23
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains the C-language implementations for many of the SQL
13 ** functions of SQLite.  (Some function, and in particular the date and
14 ** time functions, are implemented separately.)
15 */
16 #include "sqliteInt.h"
17 #include <stdlib.h>
18 #include <assert.h>
19 #include "vdbeInt.h"
20 
21 /*
22 ** Return the collating function associated with a function.
23 */
24 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
25   return context->pColl;
26 }
27 
28 /*
29 ** Indicate that the accumulator load should be skipped on this
30 ** iteration of the aggregate loop.
31 */
32 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
33   context->skipFlag = 1;
34 }
35 
36 /*
37 ** Implementation of the non-aggregate min() and max() functions
38 */
39 static void minmaxFunc(
40   sqlite3_context *context,
41   int argc,
42   sqlite3_value **argv
43 ){
44   int i;
45   int mask;    /* 0 for min() or 0xffffffff for max() */
46   int iBest;
47   CollSeq *pColl;
48 
49   assert( argc>1 );
50   mask = sqlite3_user_data(context)==0 ? 0 : -1;
51   pColl = sqlite3GetFuncCollSeq(context);
52   assert( pColl );
53   assert( mask==-1 || mask==0 );
54   iBest = 0;
55   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56   for(i=1; i<argc; i++){
57     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
58     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
59       testcase( mask==0 );
60       iBest = i;
61     }
62   }
63   sqlite3_result_value(context, argv[iBest]);
64 }
65 
66 /*
67 ** Return the type of the argument.
68 */
69 static void typeofFunc(
70   sqlite3_context *context,
71   int NotUsed,
72   sqlite3_value **argv
73 ){
74   const char *z = 0;
75   UNUSED_PARAMETER(NotUsed);
76   switch( sqlite3_value_type(argv[0]) ){
77     case SQLITE_INTEGER: z = "integer"; break;
78     case SQLITE_TEXT:    z = "text";    break;
79     case SQLITE_FLOAT:   z = "real";    break;
80     case SQLITE_BLOB:    z = "blob";    break;
81     default:             z = "null";    break;
82   }
83   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
84 }
85 
86 
87 /*
88 ** Implementation of the length() function
89 */
90 static void lengthFunc(
91   sqlite3_context *context,
92   int argc,
93   sqlite3_value **argv
94 ){
95   int len;
96 
97   assert( argc==1 );
98   UNUSED_PARAMETER(argc);
99   switch( sqlite3_value_type(argv[0]) ){
100     case SQLITE_BLOB:
101     case SQLITE_INTEGER:
102     case SQLITE_FLOAT: {
103       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
104       break;
105     }
106     case SQLITE_TEXT: {
107       const unsigned char *z = sqlite3_value_text(argv[0]);
108       if( z==0 ) return;
109       len = 0;
110       while( *z ){
111         len++;
112         SQLITE_SKIP_UTF8(z);
113       }
114       sqlite3_result_int(context, len);
115       break;
116     }
117     default: {
118       sqlite3_result_null(context);
119       break;
120     }
121   }
122 }
123 
124 /*
125 ** Implementation of the abs() function.
126 **
127 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
128 ** the numeric argument X.
129 */
130 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
131   assert( argc==1 );
132   UNUSED_PARAMETER(argc);
133   switch( sqlite3_value_type(argv[0]) ){
134     case SQLITE_INTEGER: {
135       i64 iVal = sqlite3_value_int64(argv[0]);
136       if( iVal<0 ){
137         if( iVal==SMALLEST_INT64 ){
138           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
139           ** then abs(X) throws an integer overflow error since there is no
140           ** equivalent positive 64-bit two complement value. */
141           sqlite3_result_error(context, "integer overflow", -1);
142           return;
143         }
144         iVal = -iVal;
145       }
146       sqlite3_result_int64(context, iVal);
147       break;
148     }
149     case SQLITE_NULL: {
150       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
151       sqlite3_result_null(context);
152       break;
153     }
154     default: {
155       /* Because sqlite3_value_double() returns 0.0 if the argument is not
156       ** something that can be converted into a number, we have:
157       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
158       ** cannot be converted to a numeric value.
159       */
160       double rVal = sqlite3_value_double(argv[0]);
161       if( rVal<0 ) rVal = -rVal;
162       sqlite3_result_double(context, rVal);
163       break;
164     }
165   }
166 }
167 
168 /*
169 ** Implementation of the instr() function.
170 **
171 ** instr(haystack,needle) finds the first occurrence of needle
172 ** in haystack and returns the number of previous characters plus 1,
173 ** or 0 if needle does not occur within haystack.
174 **
175 ** If both haystack and needle are BLOBs, then the result is one more than
176 ** the number of bytes in haystack prior to the first occurrence of needle,
177 ** or 0 if needle never occurs in haystack.
178 */
179 static void instrFunc(
180   sqlite3_context *context,
181   int argc,
182   sqlite3_value **argv
183 ){
184   const unsigned char *zHaystack;
185   const unsigned char *zNeedle;
186   int nHaystack;
187   int nNeedle;
188   int typeHaystack, typeNeedle;
189   int N = 1;
190   int isText;
191 
192   UNUSED_PARAMETER(argc);
193   typeHaystack = sqlite3_value_type(argv[0]);
194   typeNeedle = sqlite3_value_type(argv[1]);
195   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
196   nHaystack = sqlite3_value_bytes(argv[0]);
197   nNeedle = sqlite3_value_bytes(argv[1]);
198   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
199     zHaystack = sqlite3_value_blob(argv[0]);
200     zNeedle = sqlite3_value_blob(argv[1]);
201     isText = 0;
202   }else{
203     zHaystack = sqlite3_value_text(argv[0]);
204     zNeedle = sqlite3_value_text(argv[1]);
205     isText = 1;
206   }
207   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
208     N++;
209     do{
210       nHaystack--;
211       zHaystack++;
212     }while( isText && (zHaystack[0]&0xc0)==0x80 );
213   }
214   if( nNeedle>nHaystack ) N = 0;
215   sqlite3_result_int(context, N);
216 }
217 
218 /*
219 ** Implementation of the printf() function.
220 */
221 static void printfFunc(
222   sqlite3_context *context,
223   int argc,
224   sqlite3_value **argv
225 ){
226   PrintfArguments x;
227   StrAccum str;
228   const char *zFormat;
229   int n;
230 
231   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
232     x.nArg = argc-1;
233     x.nUsed = 0;
234     x.apArg = argv+1;
235     sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
236     str.db = sqlite3_context_db_handle(context);
237     sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
238     n = str.nChar;
239     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
240                         SQLITE_DYNAMIC);
241   }
242 }
243 
244 /*
245 ** Implementation of the substr() function.
246 **
247 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
248 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
249 ** of x.  If x is text, then we actually count UTF-8 characters.
250 ** If x is a blob, then we count bytes.
251 **
252 ** If p1 is negative, then we begin abs(p1) from the end of x[].
253 **
254 ** If p2 is negative, return the p2 characters preceding p1.
255 */
256 static void substrFunc(
257   sqlite3_context *context,
258   int argc,
259   sqlite3_value **argv
260 ){
261   const unsigned char *z;
262   const unsigned char *z2;
263   int len;
264   int p0type;
265   i64 p1, p2;
266   int negP2 = 0;
267 
268   assert( argc==3 || argc==2 );
269   if( sqlite3_value_type(argv[1])==SQLITE_NULL
270    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
271   ){
272     return;
273   }
274   p0type = sqlite3_value_type(argv[0]);
275   p1 = sqlite3_value_int(argv[1]);
276   if( p0type==SQLITE_BLOB ){
277     len = sqlite3_value_bytes(argv[0]);
278     z = sqlite3_value_blob(argv[0]);
279     if( z==0 ) return;
280     assert( len==sqlite3_value_bytes(argv[0]) );
281   }else{
282     z = sqlite3_value_text(argv[0]);
283     if( z==0 ) return;
284     len = 0;
285     if( p1<0 ){
286       for(z2=z; *z2; len++){
287         SQLITE_SKIP_UTF8(z2);
288       }
289     }
290   }
291   if( argc==3 ){
292     p2 = sqlite3_value_int(argv[2]);
293     if( p2<0 ){
294       p2 = -p2;
295       negP2 = 1;
296     }
297   }else{
298     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
299   }
300   if( p1<0 ){
301     p1 += len;
302     if( p1<0 ){
303       p2 += p1;
304       if( p2<0 ) p2 = 0;
305       p1 = 0;
306     }
307   }else if( p1>0 ){
308     p1--;
309   }else if( p2>0 ){
310     p2--;
311   }
312   if( negP2 ){
313     p1 -= p2;
314     if( p1<0 ){
315       p2 += p1;
316       p1 = 0;
317     }
318   }
319   assert( p1>=0 && p2>=0 );
320   if( p0type!=SQLITE_BLOB ){
321     while( *z && p1 ){
322       SQLITE_SKIP_UTF8(z);
323       p1--;
324     }
325     for(z2=z; *z2 && p2; p2--){
326       SQLITE_SKIP_UTF8(z2);
327     }
328     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
329   }else{
330     if( p1+p2>len ){
331       p2 = len-p1;
332       if( p2<0 ) p2 = 0;
333     }
334     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
335   }
336 }
337 
338 /*
339 ** Implementation of the round() function
340 */
341 #ifndef SQLITE_OMIT_FLOATING_POINT
342 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
343   int n = 0;
344   double r;
345   char *zBuf;
346   assert( argc==1 || argc==2 );
347   if( argc==2 ){
348     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
349     n = sqlite3_value_int(argv[1]);
350     if( n>30 ) n = 30;
351     if( n<0 ) n = 0;
352   }
353   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
354   r = sqlite3_value_double(argv[0]);
355   /* If Y==0 and X will fit in a 64-bit int,
356   ** handle the rounding directly,
357   ** otherwise use printf.
358   */
359   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
360     r = (double)((sqlite_int64)(r+0.5));
361   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
362     r = -(double)((sqlite_int64)((-r)+0.5));
363   }else{
364     zBuf = sqlite3_mprintf("%.*f",n,r);
365     if( zBuf==0 ){
366       sqlite3_result_error_nomem(context);
367       return;
368     }
369     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
370     sqlite3_free(zBuf);
371   }
372   sqlite3_result_double(context, r);
373 }
374 #endif
375 
376 /*
377 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
378 ** allocation fails, call sqlite3_result_error_nomem() to notify
379 ** the database handle that malloc() has failed and return NULL.
380 ** If nByte is larger than the maximum string or blob length, then
381 ** raise an SQLITE_TOOBIG exception and return NULL.
382 */
383 static void *contextMalloc(sqlite3_context *context, i64 nByte){
384   char *z;
385   sqlite3 *db = sqlite3_context_db_handle(context);
386   assert( nByte>0 );
387   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
388   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
389   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
390     sqlite3_result_error_toobig(context);
391     z = 0;
392   }else{
393     z = sqlite3Malloc((int)nByte);
394     if( !z ){
395       sqlite3_result_error_nomem(context);
396     }
397   }
398   return z;
399 }
400 
401 /*
402 ** Implementation of the upper() and lower() SQL functions.
403 */
404 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
405   char *z1;
406   const char *z2;
407   int i, n;
408   UNUSED_PARAMETER(argc);
409   z2 = (char*)sqlite3_value_text(argv[0]);
410   n = sqlite3_value_bytes(argv[0]);
411   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
412   assert( z2==(char*)sqlite3_value_text(argv[0]) );
413   if( z2 ){
414     z1 = contextMalloc(context, ((i64)n)+1);
415     if( z1 ){
416       for(i=0; i<n; i++){
417         z1[i] = (char)sqlite3Toupper(z2[i]);
418       }
419       sqlite3_result_text(context, z1, n, sqlite3_free);
420     }
421   }
422 }
423 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
424   char *z1;
425   const char *z2;
426   int i, n;
427   UNUSED_PARAMETER(argc);
428   z2 = (char*)sqlite3_value_text(argv[0]);
429   n = sqlite3_value_bytes(argv[0]);
430   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
431   assert( z2==(char*)sqlite3_value_text(argv[0]) );
432   if( z2 ){
433     z1 = contextMalloc(context, ((i64)n)+1);
434     if( z1 ){
435       for(i=0; i<n; i++){
436         z1[i] = sqlite3Tolower(z2[i]);
437       }
438       sqlite3_result_text(context, z1, n, sqlite3_free);
439     }
440   }
441 }
442 
443 /*
444 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
445 ** as VDBE code so that unused argument values do not have to be computed.
446 ** However, we still need some kind of function implementation for this
447 ** routines in the function table.  The noopFunc macro provides this.
448 ** noopFunc will never be called so it doesn't matter what the implementation
449 ** is.  We might as well use the "version()" function as a substitute.
450 */
451 #define noopFunc versionFunc   /* Substitute function - never called */
452 
453 /*
454 ** Implementation of random().  Return a random integer.
455 */
456 static void randomFunc(
457   sqlite3_context *context,
458   int NotUsed,
459   sqlite3_value **NotUsed2
460 ){
461   sqlite_int64 r;
462   UNUSED_PARAMETER2(NotUsed, NotUsed2);
463   sqlite3_randomness(sizeof(r), &r);
464   if( r<0 ){
465     /* We need to prevent a random number of 0x8000000000000000
466     ** (or -9223372036854775808) since when you do abs() of that
467     ** number of you get the same value back again.  To do this
468     ** in a way that is testable, mask the sign bit off of negative
469     ** values, resulting in a positive value.  Then take the
470     ** 2s complement of that positive value.  The end result can
471     ** therefore be no less than -9223372036854775807.
472     */
473     r = -(r & LARGEST_INT64);
474   }
475   sqlite3_result_int64(context, r);
476 }
477 
478 /*
479 ** Implementation of randomblob(N).  Return a random blob
480 ** that is N bytes long.
481 */
482 static void randomBlob(
483   sqlite3_context *context,
484   int argc,
485   sqlite3_value **argv
486 ){
487   int n;
488   unsigned char *p;
489   assert( argc==1 );
490   UNUSED_PARAMETER(argc);
491   n = sqlite3_value_int(argv[0]);
492   if( n<1 ){
493     n = 1;
494   }
495   p = contextMalloc(context, n);
496   if( p ){
497     sqlite3_randomness(n, p);
498     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
499   }
500 }
501 
502 /*
503 ** Implementation of the last_insert_rowid() SQL function.  The return
504 ** value is the same as the sqlite3_last_insert_rowid() API function.
505 */
506 static void last_insert_rowid(
507   sqlite3_context *context,
508   int NotUsed,
509   sqlite3_value **NotUsed2
510 ){
511   sqlite3 *db = sqlite3_context_db_handle(context);
512   UNUSED_PARAMETER2(NotUsed, NotUsed2);
513   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
514   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
515   ** function. */
516   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
517 }
518 
519 /*
520 ** Implementation of the changes() SQL function.
521 **
522 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
523 ** around the sqlite3_changes() C/C++ function and hence follows the same
524 ** rules for counting changes.
525 */
526 static void changes(
527   sqlite3_context *context,
528   int NotUsed,
529   sqlite3_value **NotUsed2
530 ){
531   sqlite3 *db = sqlite3_context_db_handle(context);
532   UNUSED_PARAMETER2(NotUsed, NotUsed2);
533   sqlite3_result_int(context, sqlite3_changes(db));
534 }
535 
536 /*
537 ** Implementation of the total_changes() SQL function.  The return value is
538 ** the same as the sqlite3_total_changes() API function.
539 */
540 static void total_changes(
541   sqlite3_context *context,
542   int NotUsed,
543   sqlite3_value **NotUsed2
544 ){
545   sqlite3 *db = sqlite3_context_db_handle(context);
546   UNUSED_PARAMETER2(NotUsed, NotUsed2);
547   /* IMP: R-52756-41993 This function is a wrapper around the
548   ** sqlite3_total_changes() C/C++ interface. */
549   sqlite3_result_int(context, sqlite3_total_changes(db));
550 }
551 
552 /*
553 ** A structure defining how to do GLOB-style comparisons.
554 */
555 struct compareInfo {
556   u8 matchAll;
557   u8 matchOne;
558   u8 matchSet;
559   u8 noCase;
560 };
561 
562 /*
563 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
564 ** character is exactly one byte in size.  Also, all characters are
565 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
566 ** whereas only characters less than 0x80 do in ASCII.
567 */
568 #if defined(SQLITE_EBCDIC)
569 # define sqlite3Utf8Read(A)    (*((*A)++))
570 # define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
571 #else
572 # define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
573 #endif
574 
575 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
576 /* The correct SQL-92 behavior is for the LIKE operator to ignore
577 ** case.  Thus  'a' LIKE 'A' would be true. */
578 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
579 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
580 ** is case sensitive causing 'a' LIKE 'A' to be false */
581 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
582 
583 /*
584 ** Compare two UTF-8 strings for equality where the first string can
585 ** potentially be a "glob" expression.  Return true (1) if they
586 ** are the same and false (0) if they are different.
587 **
588 ** Globbing rules:
589 **
590 **      '*'       Matches any sequence of zero or more characters.
591 **
592 **      '?'       Matches exactly one character.
593 **
594 **     [...]      Matches one character from the enclosed list of
595 **                characters.
596 **
597 **     [^...]     Matches one character not in the enclosed list.
598 **
599 ** With the [...] and [^...] matching, a ']' character can be included
600 ** in the list by making it the first character after '[' or '^'.  A
601 ** range of characters can be specified using '-'.  Example:
602 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
603 ** it the last character in the list.
604 **
605 ** This routine is usually quick, but can be N**2 in the worst case.
606 **
607 ** Hints: to match '*' or '?', put them in "[]".  Like this:
608 **
609 **         abc[*]xyz        Matches "abc*xyz" only
610 */
611 static int patternCompare(
612   const u8 *zPattern,              /* The glob pattern */
613   const u8 *zString,               /* The string to compare against the glob */
614   const struct compareInfo *pInfo, /* Information about how to do the compare */
615   u32 esc                          /* The escape character */
616 ){
617   u32 c, c2;
618   int invert;
619   int seen;
620   u8 matchOne = pInfo->matchOne;
621   u8 matchAll = pInfo->matchAll;
622   u8 matchSet = pInfo->matchSet;
623   u8 noCase = pInfo->noCase;
624   int prevEscape = 0;     /* True if the previous character was 'escape' */
625 
626   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
627     if( c==matchAll && !prevEscape ){
628       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
629                || c == matchOne ){
630         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
631           return 0;
632         }
633       }
634       if( c==0 ){
635         return 1;
636       }else if( c==esc ){
637         c = sqlite3Utf8Read(&zPattern);
638         if( c==0 ){
639           return 0;
640         }
641       }else if( c==matchSet ){
642         assert( esc==0 );         /* This is GLOB, not LIKE */
643         assert( matchSet<0x80 );  /* '[' is a single-byte character */
644         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
645           SQLITE_SKIP_UTF8(zString);
646         }
647         return *zString!=0;
648       }
649       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
650         if( noCase ){
651           GlobUpperToLower(c2);
652           GlobUpperToLower(c);
653           while( c2 != 0 && c2 != c ){
654             c2 = sqlite3Utf8Read(&zString);
655             GlobUpperToLower(c2);
656           }
657         }else{
658           while( c2 != 0 && c2 != c ){
659             c2 = sqlite3Utf8Read(&zString);
660           }
661         }
662         if( c2==0 ) return 0;
663         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
664       }
665       return 0;
666     }else if( c==matchOne && !prevEscape ){
667       if( sqlite3Utf8Read(&zString)==0 ){
668         return 0;
669       }
670     }else if( c==matchSet ){
671       u32 prior_c = 0;
672       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
673       seen = 0;
674       invert = 0;
675       c = sqlite3Utf8Read(&zString);
676       if( c==0 ) return 0;
677       c2 = sqlite3Utf8Read(&zPattern);
678       if( c2=='^' ){
679         invert = 1;
680         c2 = sqlite3Utf8Read(&zPattern);
681       }
682       if( c2==']' ){
683         if( c==']' ) seen = 1;
684         c2 = sqlite3Utf8Read(&zPattern);
685       }
686       while( c2 && c2!=']' ){
687         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
688           c2 = sqlite3Utf8Read(&zPattern);
689           if( c>=prior_c && c<=c2 ) seen = 1;
690           prior_c = 0;
691         }else{
692           if( c==c2 ){
693             seen = 1;
694           }
695           prior_c = c2;
696         }
697         c2 = sqlite3Utf8Read(&zPattern);
698       }
699       if( c2==0 || (seen ^ invert)==0 ){
700         return 0;
701       }
702     }else if( esc==c && !prevEscape ){
703       prevEscape = 1;
704     }else{
705       c2 = sqlite3Utf8Read(&zString);
706       if( noCase ){
707         GlobUpperToLower(c);
708         GlobUpperToLower(c2);
709       }
710       if( c!=c2 ){
711         return 0;
712       }
713       prevEscape = 0;
714     }
715   }
716   return *zString==0;
717 }
718 
719 /*
720 ** The sqlite3_strglob() interface.
721 */
722 int sqlite3_strglob(const char *zGlobPattern, const char *zString){
723   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
724 }
725 
726 /*
727 ** Count the number of times that the LIKE operator (or GLOB which is
728 ** just a variation of LIKE) gets called.  This is used for testing
729 ** only.
730 */
731 #ifdef SQLITE_TEST
732 int sqlite3_like_count = 0;
733 #endif
734 
735 
736 /*
737 ** Implementation of the like() SQL function.  This function implements
738 ** the build-in LIKE operator.  The first argument to the function is the
739 ** pattern and the second argument is the string.  So, the SQL statements:
740 **
741 **       A LIKE B
742 **
743 ** is implemented as like(B,A).
744 **
745 ** This same function (with a different compareInfo structure) computes
746 ** the GLOB operator.
747 */
748 static void likeFunc(
749   sqlite3_context *context,
750   int argc,
751   sqlite3_value **argv
752 ){
753   const unsigned char *zA, *zB;
754   u32 escape = 0;
755   int nPat;
756   sqlite3 *db = sqlite3_context_db_handle(context);
757 
758   zB = sqlite3_value_text(argv[0]);
759   zA = sqlite3_value_text(argv[1]);
760 
761   /* Limit the length of the LIKE or GLOB pattern to avoid problems
762   ** of deep recursion and N*N behavior in patternCompare().
763   */
764   nPat = sqlite3_value_bytes(argv[0]);
765   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
766   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
767   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
768     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
769     return;
770   }
771   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
772 
773   if( argc==3 ){
774     /* The escape character string must consist of a single UTF-8 character.
775     ** Otherwise, return an error.
776     */
777     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
778     if( zEsc==0 ) return;
779     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
780       sqlite3_result_error(context,
781           "ESCAPE expression must be a single character", -1);
782       return;
783     }
784     escape = sqlite3Utf8Read(&zEsc);
785   }
786   if( zA && zB ){
787     struct compareInfo *pInfo = sqlite3_user_data(context);
788 #ifdef SQLITE_TEST
789     sqlite3_like_count++;
790 #endif
791 
792     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
793   }
794 }
795 
796 /*
797 ** Implementation of the NULLIF(x,y) function.  The result is the first
798 ** argument if the arguments are different.  The result is NULL if the
799 ** arguments are equal to each other.
800 */
801 static void nullifFunc(
802   sqlite3_context *context,
803   int NotUsed,
804   sqlite3_value **argv
805 ){
806   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
807   UNUSED_PARAMETER(NotUsed);
808   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
809     sqlite3_result_value(context, argv[0]);
810   }
811 }
812 
813 /*
814 ** Implementation of the sqlite_version() function.  The result is the version
815 ** of the SQLite library that is running.
816 */
817 static void versionFunc(
818   sqlite3_context *context,
819   int NotUsed,
820   sqlite3_value **NotUsed2
821 ){
822   UNUSED_PARAMETER2(NotUsed, NotUsed2);
823   /* IMP: R-48699-48617 This function is an SQL wrapper around the
824   ** sqlite3_libversion() C-interface. */
825   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
826 }
827 
828 /*
829 ** Implementation of the sqlite_source_id() function. The result is a string
830 ** that identifies the particular version of the source code used to build
831 ** SQLite.
832 */
833 static void sourceidFunc(
834   sqlite3_context *context,
835   int NotUsed,
836   sqlite3_value **NotUsed2
837 ){
838   UNUSED_PARAMETER2(NotUsed, NotUsed2);
839   /* IMP: R-24470-31136 This function is an SQL wrapper around the
840   ** sqlite3_sourceid() C interface. */
841   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
842 }
843 
844 /*
845 ** Implementation of the sqlite_log() function.  This is a wrapper around
846 ** sqlite3_log().  The return value is NULL.  The function exists purely for
847 ** its side-effects.
848 */
849 static void errlogFunc(
850   sqlite3_context *context,
851   int argc,
852   sqlite3_value **argv
853 ){
854   UNUSED_PARAMETER(argc);
855   UNUSED_PARAMETER(context);
856   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
857 }
858 
859 /*
860 ** Implementation of the sqlite_compileoption_used() function.
861 ** The result is an integer that identifies if the compiler option
862 ** was used to build SQLite.
863 */
864 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
865 static void compileoptionusedFunc(
866   sqlite3_context *context,
867   int argc,
868   sqlite3_value **argv
869 ){
870   const char *zOptName;
871   assert( argc==1 );
872   UNUSED_PARAMETER(argc);
873   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
874   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
875   ** function.
876   */
877   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
878     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
879   }
880 }
881 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
882 
883 /*
884 ** Implementation of the sqlite_compileoption_get() function.
885 ** The result is a string that identifies the compiler options
886 ** used to build SQLite.
887 */
888 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
889 static void compileoptiongetFunc(
890   sqlite3_context *context,
891   int argc,
892   sqlite3_value **argv
893 ){
894   int n;
895   assert( argc==1 );
896   UNUSED_PARAMETER(argc);
897   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
898   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
899   */
900   n = sqlite3_value_int(argv[0]);
901   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
902 }
903 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
904 
905 /* Array for converting from half-bytes (nybbles) into ASCII hex
906 ** digits. */
907 static const char hexdigits[] = {
908   '0', '1', '2', '3', '4', '5', '6', '7',
909   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
910 };
911 
912 /*
913 ** Implementation of the QUOTE() function.  This function takes a single
914 ** argument.  If the argument is numeric, the return value is the same as
915 ** the argument.  If the argument is NULL, the return value is the string
916 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
917 ** single-quote escapes.
918 */
919 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
920   assert( argc==1 );
921   UNUSED_PARAMETER(argc);
922   switch( sqlite3_value_type(argv[0]) ){
923     case SQLITE_FLOAT: {
924       double r1, r2;
925       char zBuf[50];
926       r1 = sqlite3_value_double(argv[0]);
927       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
928       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
929       if( r1!=r2 ){
930         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
931       }
932       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
933       break;
934     }
935     case SQLITE_INTEGER: {
936       sqlite3_result_value(context, argv[0]);
937       break;
938     }
939     case SQLITE_BLOB: {
940       char *zText = 0;
941       char const *zBlob = sqlite3_value_blob(argv[0]);
942       int nBlob = sqlite3_value_bytes(argv[0]);
943       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
944       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
945       if( zText ){
946         int i;
947         for(i=0; i<nBlob; i++){
948           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
949           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
950         }
951         zText[(nBlob*2)+2] = '\'';
952         zText[(nBlob*2)+3] = '\0';
953         zText[0] = 'X';
954         zText[1] = '\'';
955         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
956         sqlite3_free(zText);
957       }
958       break;
959     }
960     case SQLITE_TEXT: {
961       int i,j;
962       u64 n;
963       const unsigned char *zArg = sqlite3_value_text(argv[0]);
964       char *z;
965 
966       if( zArg==0 ) return;
967       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
968       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
969       if( z ){
970         z[0] = '\'';
971         for(i=0, j=1; zArg[i]; i++){
972           z[j++] = zArg[i];
973           if( zArg[i]=='\'' ){
974             z[j++] = '\'';
975           }
976         }
977         z[j++] = '\'';
978         z[j] = 0;
979         sqlite3_result_text(context, z, j, sqlite3_free);
980       }
981       break;
982     }
983     default: {
984       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
985       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
986       break;
987     }
988   }
989 }
990 
991 /*
992 ** The unicode() function.  Return the integer unicode code-point value
993 ** for the first character of the input string.
994 */
995 static void unicodeFunc(
996   sqlite3_context *context,
997   int argc,
998   sqlite3_value **argv
999 ){
1000   const unsigned char *z = sqlite3_value_text(argv[0]);
1001   (void)argc;
1002   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
1003 }
1004 
1005 /*
1006 ** The char() function takes zero or more arguments, each of which is
1007 ** an integer.  It constructs a string where each character of the string
1008 ** is the unicode character for the corresponding integer argument.
1009 */
1010 static void charFunc(
1011   sqlite3_context *context,
1012   int argc,
1013   sqlite3_value **argv
1014 ){
1015   unsigned char *z, *zOut;
1016   int i;
1017   zOut = z = sqlite3_malloc( argc*4+1 );
1018   if( z==0 ){
1019     sqlite3_result_error_nomem(context);
1020     return;
1021   }
1022   for(i=0; i<argc; i++){
1023     sqlite3_int64 x;
1024     unsigned c;
1025     x = sqlite3_value_int64(argv[i]);
1026     if( x<0 || x>0x10ffff ) x = 0xfffd;
1027     c = (unsigned)(x & 0x1fffff);
1028     if( c<0x00080 ){
1029       *zOut++ = (u8)(c&0xFF);
1030     }else if( c<0x00800 ){
1031       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
1032       *zOut++ = 0x80 + (u8)(c & 0x3F);
1033     }else if( c<0x10000 ){
1034       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
1035       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1036       *zOut++ = 0x80 + (u8)(c & 0x3F);
1037     }else{
1038       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
1039       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
1040       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1041       *zOut++ = 0x80 + (u8)(c & 0x3F);
1042     }                                                    \
1043   }
1044   sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
1045 }
1046 
1047 /*
1048 ** The hex() function.  Interpret the argument as a blob.  Return
1049 ** a hexadecimal rendering as text.
1050 */
1051 static void hexFunc(
1052   sqlite3_context *context,
1053   int argc,
1054   sqlite3_value **argv
1055 ){
1056   int i, n;
1057   const unsigned char *pBlob;
1058   char *zHex, *z;
1059   assert( argc==1 );
1060   UNUSED_PARAMETER(argc);
1061   pBlob = sqlite3_value_blob(argv[0]);
1062   n = sqlite3_value_bytes(argv[0]);
1063   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
1064   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
1065   if( zHex ){
1066     for(i=0; i<n; i++, pBlob++){
1067       unsigned char c = *pBlob;
1068       *(z++) = hexdigits[(c>>4)&0xf];
1069       *(z++) = hexdigits[c&0xf];
1070     }
1071     *z = 0;
1072     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
1073   }
1074 }
1075 
1076 /*
1077 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
1078 */
1079 static void zeroblobFunc(
1080   sqlite3_context *context,
1081   int argc,
1082   sqlite3_value **argv
1083 ){
1084   i64 n;
1085   sqlite3 *db = sqlite3_context_db_handle(context);
1086   assert( argc==1 );
1087   UNUSED_PARAMETER(argc);
1088   n = sqlite3_value_int64(argv[0]);
1089   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
1090   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
1091   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1092     sqlite3_result_error_toobig(context);
1093   }else{
1094     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
1095   }
1096 }
1097 
1098 /*
1099 ** The replace() function.  Three arguments are all strings: call
1100 ** them A, B, and C. The result is also a string which is derived
1101 ** from A by replacing every occurrence of B with C.  The match
1102 ** must be exact.  Collating sequences are not used.
1103 */
1104 static void replaceFunc(
1105   sqlite3_context *context,
1106   int argc,
1107   sqlite3_value **argv
1108 ){
1109   const unsigned char *zStr;        /* The input string A */
1110   const unsigned char *zPattern;    /* The pattern string B */
1111   const unsigned char *zRep;        /* The replacement string C */
1112   unsigned char *zOut;              /* The output */
1113   int nStr;                /* Size of zStr */
1114   int nPattern;            /* Size of zPattern */
1115   int nRep;                /* Size of zRep */
1116   i64 nOut;                /* Maximum size of zOut */
1117   int loopLimit;           /* Last zStr[] that might match zPattern[] */
1118   int i, j;                /* Loop counters */
1119 
1120   assert( argc==3 );
1121   UNUSED_PARAMETER(argc);
1122   zStr = sqlite3_value_text(argv[0]);
1123   if( zStr==0 ) return;
1124   nStr = sqlite3_value_bytes(argv[0]);
1125   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
1126   zPattern = sqlite3_value_text(argv[1]);
1127   if( zPattern==0 ){
1128     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
1129             || sqlite3_context_db_handle(context)->mallocFailed );
1130     return;
1131   }
1132   if( zPattern[0]==0 ){
1133     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
1134     sqlite3_result_value(context, argv[0]);
1135     return;
1136   }
1137   nPattern = sqlite3_value_bytes(argv[1]);
1138   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
1139   zRep = sqlite3_value_text(argv[2]);
1140   if( zRep==0 ) return;
1141   nRep = sqlite3_value_bytes(argv[2]);
1142   assert( zRep==sqlite3_value_text(argv[2]) );
1143   nOut = nStr + 1;
1144   assert( nOut<SQLITE_MAX_LENGTH );
1145   zOut = contextMalloc(context, (i64)nOut);
1146   if( zOut==0 ){
1147     return;
1148   }
1149   loopLimit = nStr - nPattern;
1150   for(i=j=0; i<=loopLimit; i++){
1151     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
1152       zOut[j++] = zStr[i];
1153     }else{
1154       u8 *zOld;
1155       sqlite3 *db = sqlite3_context_db_handle(context);
1156       nOut += nRep - nPattern;
1157       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
1158       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
1159       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1160         sqlite3_result_error_toobig(context);
1161         sqlite3_free(zOut);
1162         return;
1163       }
1164       zOld = zOut;
1165       zOut = sqlite3_realloc(zOut, (int)nOut);
1166       if( zOut==0 ){
1167         sqlite3_result_error_nomem(context);
1168         sqlite3_free(zOld);
1169         return;
1170       }
1171       memcpy(&zOut[j], zRep, nRep);
1172       j += nRep;
1173       i += nPattern-1;
1174     }
1175   }
1176   assert( j+nStr-i+1==nOut );
1177   memcpy(&zOut[j], &zStr[i], nStr-i);
1178   j += nStr - i;
1179   assert( j<=nOut );
1180   zOut[j] = 0;
1181   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
1182 }
1183 
1184 /*
1185 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
1186 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
1187 */
1188 static void trimFunc(
1189   sqlite3_context *context,
1190   int argc,
1191   sqlite3_value **argv
1192 ){
1193   const unsigned char *zIn;         /* Input string */
1194   const unsigned char *zCharSet;    /* Set of characters to trim */
1195   int nIn;                          /* Number of bytes in input */
1196   int flags;                        /* 1: trimleft  2: trimright  3: trim */
1197   int i;                            /* Loop counter */
1198   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
1199   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
1200   int nChar;                        /* Number of characters in zCharSet */
1201 
1202   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1203     return;
1204   }
1205   zIn = sqlite3_value_text(argv[0]);
1206   if( zIn==0 ) return;
1207   nIn = sqlite3_value_bytes(argv[0]);
1208   assert( zIn==sqlite3_value_text(argv[0]) );
1209   if( argc==1 ){
1210     static const unsigned char lenOne[] = { 1 };
1211     static unsigned char * const azOne[] = { (u8*)" " };
1212     nChar = 1;
1213     aLen = (u8*)lenOne;
1214     azChar = (unsigned char **)azOne;
1215     zCharSet = 0;
1216   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
1217     return;
1218   }else{
1219     const unsigned char *z;
1220     for(z=zCharSet, nChar=0; *z; nChar++){
1221       SQLITE_SKIP_UTF8(z);
1222     }
1223     if( nChar>0 ){
1224       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
1225       if( azChar==0 ){
1226         return;
1227       }
1228       aLen = (unsigned char*)&azChar[nChar];
1229       for(z=zCharSet, nChar=0; *z; nChar++){
1230         azChar[nChar] = (unsigned char *)z;
1231         SQLITE_SKIP_UTF8(z);
1232         aLen[nChar] = (u8)(z - azChar[nChar]);
1233       }
1234     }
1235   }
1236   if( nChar>0 ){
1237     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
1238     if( flags & 1 ){
1239       while( nIn>0 ){
1240         int len = 0;
1241         for(i=0; i<nChar; i++){
1242           len = aLen[i];
1243           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
1244         }
1245         if( i>=nChar ) break;
1246         zIn += len;
1247         nIn -= len;
1248       }
1249     }
1250     if( flags & 2 ){
1251       while( nIn>0 ){
1252         int len = 0;
1253         for(i=0; i<nChar; i++){
1254           len = aLen[i];
1255           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
1256         }
1257         if( i>=nChar ) break;
1258         nIn -= len;
1259       }
1260     }
1261     if( zCharSet ){
1262       sqlite3_free(azChar);
1263     }
1264   }
1265   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
1266 }
1267 
1268 
1269 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
1270 ** is only available if the SQLITE_SOUNDEX compile-time option is used
1271 ** when SQLite is built.
1272 */
1273 #ifdef SQLITE_SOUNDEX
1274 /*
1275 ** Compute the soundex encoding of a word.
1276 **
1277 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
1278 ** soundex encoding of the string X.
1279 */
1280 static void soundexFunc(
1281   sqlite3_context *context,
1282   int argc,
1283   sqlite3_value **argv
1284 ){
1285   char zResult[8];
1286   const u8 *zIn;
1287   int i, j;
1288   static const unsigned char iCode[] = {
1289     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1290     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1291     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1292     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1293     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1294     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1295     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1296     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1297   };
1298   assert( argc==1 );
1299   zIn = (u8*)sqlite3_value_text(argv[0]);
1300   if( zIn==0 ) zIn = (u8*)"";
1301   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
1302   if( zIn[i] ){
1303     u8 prevcode = iCode[zIn[i]&0x7f];
1304     zResult[0] = sqlite3Toupper(zIn[i]);
1305     for(j=1; j<4 && zIn[i]; i++){
1306       int code = iCode[zIn[i]&0x7f];
1307       if( code>0 ){
1308         if( code!=prevcode ){
1309           prevcode = code;
1310           zResult[j++] = code + '0';
1311         }
1312       }else{
1313         prevcode = 0;
1314       }
1315     }
1316     while( j<4 ){
1317       zResult[j++] = '0';
1318     }
1319     zResult[j] = 0;
1320     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
1321   }else{
1322     /* IMP: R-64894-50321 The string "?000" is returned if the argument
1323     ** is NULL or contains no ASCII alphabetic characters. */
1324     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
1325   }
1326 }
1327 #endif /* SQLITE_SOUNDEX */
1328 
1329 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1330 /*
1331 ** A function that loads a shared-library extension then returns NULL.
1332 */
1333 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
1334   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
1335   const char *zProc;
1336   sqlite3 *db = sqlite3_context_db_handle(context);
1337   char *zErrMsg = 0;
1338 
1339   if( argc==2 ){
1340     zProc = (const char *)sqlite3_value_text(argv[1]);
1341   }else{
1342     zProc = 0;
1343   }
1344   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
1345     sqlite3_result_error(context, zErrMsg, -1);
1346     sqlite3_free(zErrMsg);
1347   }
1348 }
1349 #endif
1350 
1351 
1352 /*
1353 ** An instance of the following structure holds the context of a
1354 ** sum() or avg() aggregate computation.
1355 */
1356 typedef struct SumCtx SumCtx;
1357 struct SumCtx {
1358   double rSum;      /* Floating point sum */
1359   i64 iSum;         /* Integer sum */
1360   i64 cnt;          /* Number of elements summed */
1361   u8 overflow;      /* True if integer overflow seen */
1362   u8 approx;        /* True if non-integer value was input to the sum */
1363 };
1364 
1365 /*
1366 ** Routines used to compute the sum, average, and total.
1367 **
1368 ** The SUM() function follows the (broken) SQL standard which means
1369 ** that it returns NULL if it sums over no inputs.  TOTAL returns
1370 ** 0.0 in that case.  In addition, TOTAL always returns a float where
1371 ** SUM might return an integer if it never encounters a floating point
1372 ** value.  TOTAL never fails, but SUM might through an exception if
1373 ** it overflows an integer.
1374 */
1375 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1376   SumCtx *p;
1377   int type;
1378   assert( argc==1 );
1379   UNUSED_PARAMETER(argc);
1380   p = sqlite3_aggregate_context(context, sizeof(*p));
1381   type = sqlite3_value_numeric_type(argv[0]);
1382   if( p && type!=SQLITE_NULL ){
1383     p->cnt++;
1384     if( type==SQLITE_INTEGER ){
1385       i64 v = sqlite3_value_int64(argv[0]);
1386       p->rSum += v;
1387       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
1388         p->overflow = 1;
1389       }
1390     }else{
1391       p->rSum += sqlite3_value_double(argv[0]);
1392       p->approx = 1;
1393     }
1394   }
1395 }
1396 static void sumFinalize(sqlite3_context *context){
1397   SumCtx *p;
1398   p = sqlite3_aggregate_context(context, 0);
1399   if( p && p->cnt>0 ){
1400     if( p->overflow ){
1401       sqlite3_result_error(context,"integer overflow",-1);
1402     }else if( p->approx ){
1403       sqlite3_result_double(context, p->rSum);
1404     }else{
1405       sqlite3_result_int64(context, p->iSum);
1406     }
1407   }
1408 }
1409 static void avgFinalize(sqlite3_context *context){
1410   SumCtx *p;
1411   p = sqlite3_aggregate_context(context, 0);
1412   if( p && p->cnt>0 ){
1413     sqlite3_result_double(context, p->rSum/(double)p->cnt);
1414   }
1415 }
1416 static void totalFinalize(sqlite3_context *context){
1417   SumCtx *p;
1418   p = sqlite3_aggregate_context(context, 0);
1419   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1420   sqlite3_result_double(context, p ? p->rSum : (double)0);
1421 }
1422 
1423 /*
1424 ** The following structure keeps track of state information for the
1425 ** count() aggregate function.
1426 */
1427 typedef struct CountCtx CountCtx;
1428 struct CountCtx {
1429   i64 n;
1430 };
1431 
1432 /*
1433 ** Routines to implement the count() aggregate function.
1434 */
1435 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1436   CountCtx *p;
1437   p = sqlite3_aggregate_context(context, sizeof(*p));
1438   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
1439     p->n++;
1440   }
1441 
1442 #ifndef SQLITE_OMIT_DEPRECATED
1443   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
1444   ** sure it still operates correctly, verify that its count agrees with our
1445   ** internal count when using count(*) and when the total count can be
1446   ** expressed as a 32-bit integer. */
1447   assert( argc==1 || p==0 || p->n>0x7fffffff
1448           || p->n==sqlite3_aggregate_count(context) );
1449 #endif
1450 }
1451 static void countFinalize(sqlite3_context *context){
1452   CountCtx *p;
1453   p = sqlite3_aggregate_context(context, 0);
1454   sqlite3_result_int64(context, p ? p->n : 0);
1455 }
1456 
1457 /*
1458 ** Routines to implement min() and max() aggregate functions.
1459 */
1460 static void minmaxStep(
1461   sqlite3_context *context,
1462   int NotUsed,
1463   sqlite3_value **argv
1464 ){
1465   Mem *pArg  = (Mem *)argv[0];
1466   Mem *pBest;
1467   UNUSED_PARAMETER(NotUsed);
1468 
1469   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
1470   if( !pBest ) return;
1471 
1472   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1473     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
1474   }else if( pBest->flags ){
1475     int max;
1476     int cmp;
1477     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
1478     /* This step function is used for both the min() and max() aggregates,
1479     ** the only difference between the two being that the sense of the
1480     ** comparison is inverted. For the max() aggregate, the
1481     ** sqlite3_user_data() function returns (void *)-1. For min() it
1482     ** returns (void *)db, where db is the sqlite3* database pointer.
1483     ** Therefore the next statement sets variable 'max' to 1 for the max()
1484     ** aggregate, or 0 for min().
1485     */
1486     max = sqlite3_user_data(context)!=0;
1487     cmp = sqlite3MemCompare(pBest, pArg, pColl);
1488     if( (max && cmp<0) || (!max && cmp>0) ){
1489       sqlite3VdbeMemCopy(pBest, pArg);
1490     }else{
1491       sqlite3SkipAccumulatorLoad(context);
1492     }
1493   }else{
1494     sqlite3VdbeMemCopy(pBest, pArg);
1495   }
1496 }
1497 static void minMaxFinalize(sqlite3_context *context){
1498   sqlite3_value *pRes;
1499   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
1500   if( pRes ){
1501     if( pRes->flags ){
1502       sqlite3_result_value(context, pRes);
1503     }
1504     sqlite3VdbeMemRelease(pRes);
1505   }
1506 }
1507 
1508 /*
1509 ** group_concat(EXPR, ?SEPARATOR?)
1510 */
1511 static void groupConcatStep(
1512   sqlite3_context *context,
1513   int argc,
1514   sqlite3_value **argv
1515 ){
1516   const char *zVal;
1517   StrAccum *pAccum;
1518   const char *zSep;
1519   int nVal, nSep;
1520   assert( argc==1 || argc==2 );
1521   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
1522   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
1523 
1524   if( pAccum ){
1525     sqlite3 *db = sqlite3_context_db_handle(context);
1526     int firstTerm = pAccum->useMalloc==0;
1527     pAccum->useMalloc = 2;
1528     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
1529     if( !firstTerm ){
1530       if( argc==2 ){
1531         zSep = (char*)sqlite3_value_text(argv[1]);
1532         nSep = sqlite3_value_bytes(argv[1]);
1533       }else{
1534         zSep = ",";
1535         nSep = 1;
1536       }
1537       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
1538     }
1539     zVal = (char*)sqlite3_value_text(argv[0]);
1540     nVal = sqlite3_value_bytes(argv[0]);
1541     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
1542   }
1543 }
1544 static void groupConcatFinalize(sqlite3_context *context){
1545   StrAccum *pAccum;
1546   pAccum = sqlite3_aggregate_context(context, 0);
1547   if( pAccum ){
1548     if( pAccum->accError==STRACCUM_TOOBIG ){
1549       sqlite3_result_error_toobig(context);
1550     }else if( pAccum->accError==STRACCUM_NOMEM ){
1551       sqlite3_result_error_nomem(context);
1552     }else{
1553       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
1554                           sqlite3_free);
1555     }
1556   }
1557 }
1558 
1559 /*
1560 ** This routine does per-connection function registration.  Most
1561 ** of the built-in functions above are part of the global function set.
1562 ** This routine only deals with those that are not global.
1563 */
1564 void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
1565   int rc = sqlite3_overload_function(db, "MATCH", 2);
1566   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
1567   if( rc==SQLITE_NOMEM ){
1568     db->mallocFailed = 1;
1569   }
1570 }
1571 
1572 /*
1573 ** Set the LIKEOPT flag on the 2-argument function with the given name.
1574 */
1575 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
1576   FuncDef *pDef;
1577   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
1578                              2, SQLITE_UTF8, 0);
1579   if( ALWAYS(pDef) ){
1580     pDef->funcFlags |= flagVal;
1581   }
1582 }
1583 
1584 /*
1585 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
1586 ** parameter determines whether or not the LIKE operator is case
1587 ** sensitive.  GLOB is always case sensitive.
1588 */
1589 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
1590   struct compareInfo *pInfo;
1591   if( caseSensitive ){
1592     pInfo = (struct compareInfo*)&likeInfoAlt;
1593   }else{
1594     pInfo = (struct compareInfo*)&likeInfoNorm;
1595   }
1596   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
1597   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
1598   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
1599       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
1600   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
1601   setLikeOptFlag(db, "like",
1602       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
1603 }
1604 
1605 /*
1606 ** pExpr points to an expression which implements a function.  If
1607 ** it is appropriate to apply the LIKE optimization to that function
1608 ** then set aWc[0] through aWc[2] to the wildcard characters and
1609 ** return TRUE.  If the function is not a LIKE-style function then
1610 ** return FALSE.
1611 */
1612 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
1613   FuncDef *pDef;
1614   if( pExpr->op!=TK_FUNCTION
1615    || !pExpr->x.pList
1616    || pExpr->x.pList->nExpr!=2
1617   ){
1618     return 0;
1619   }
1620   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
1621   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
1622                              sqlite3Strlen30(pExpr->u.zToken),
1623                              2, SQLITE_UTF8, 0);
1624   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
1625     return 0;
1626   }
1627 
1628   /* The memcpy() statement assumes that the wildcard characters are
1629   ** the first three statements in the compareInfo structure.  The
1630   ** asserts() that follow verify that assumption
1631   */
1632   memcpy(aWc, pDef->pUserData, 3);
1633   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
1634   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
1635   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1636   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
1637   return 1;
1638 }
1639 
1640 /*
1641 ** All of the FuncDef structures in the aBuiltinFunc[] array above
1642 ** to the global function hash table.  This occurs at start-time (as
1643 ** a consequence of calling sqlite3_initialize()).
1644 **
1645 ** After this routine runs
1646 */
1647 void sqlite3RegisterGlobalFunctions(void){
1648   /*
1649   ** The following array holds FuncDef structures for all of the functions
1650   ** defined in this file.
1651   **
1652   ** The array cannot be constant since changes are made to the
1653   ** FuncDef.pHash elements at start-time.  The elements of this array
1654   ** are read-only after initialization is complete.
1655   */
1656   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
1657     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
1658     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
1659     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
1660     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
1661     FUNCTION(trim,               1, 3, 0, trimFunc         ),
1662     FUNCTION(trim,               2, 3, 0, trimFunc         ),
1663     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
1664     FUNCTION(min,                0, 0, 1, 0                ),
1665     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
1666     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
1667     FUNCTION(max,                0, 1, 1, 0                ),
1668     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
1669     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
1670     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
1671     FUNCTION(instr,              2, 0, 0, instrFunc        ),
1672     FUNCTION(substr,             2, 0, 0, substrFunc       ),
1673     FUNCTION(substr,             3, 0, 0, substrFunc       ),
1674     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
1675     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
1676     FUNCTION(char,              -1, 0, 0, charFunc         ),
1677     FUNCTION(abs,                1, 0, 0, absFunc          ),
1678 #ifndef SQLITE_OMIT_FLOATING_POINT
1679     FUNCTION(round,              1, 0, 0, roundFunc        ),
1680     FUNCTION(round,              2, 0, 0, roundFunc        ),
1681 #endif
1682     FUNCTION(upper,              1, 0, 0, upperFunc        ),
1683     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
1684     FUNCTION(coalesce,           1, 0, 0, 0                ),
1685     FUNCTION(coalesce,           0, 0, 0, 0                ),
1686     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
1687     FUNCTION(hex,                1, 0, 0, hexFunc          ),
1688     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
1689     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
1690     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
1691     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
1692     VFUNCTION(random,            0, 0, 0, randomFunc       ),
1693     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
1694     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
1695     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
1696     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
1697     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
1698 #if SQLITE_USER_AUTHENTICATION
1699     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
1700 #endif
1701 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1702     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
1703     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
1704 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1705     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
1706     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
1707     VFUNCTION(changes,           0, 0, 0, changes          ),
1708     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
1709     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
1710     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
1711   #ifdef SQLITE_SOUNDEX
1712     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
1713   #endif
1714   #ifndef SQLITE_OMIT_LOAD_EXTENSION
1715     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
1716     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
1717   #endif
1718     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
1719     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
1720     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
1721  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
1722     {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
1723     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
1724     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
1725     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
1726 
1727     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
1728   #ifdef SQLITE_CASE_SENSITIVE_LIKE
1729     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
1730     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
1731   #else
1732     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
1733     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
1734   #endif
1735   };
1736 
1737   int i;
1738   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
1739   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
1740 
1741   for(i=0; i<ArraySize(aBuiltinFunc); i++){
1742     sqlite3FuncDefInsert(pHash, &aFunc[i]);
1743   }
1744   sqlite3RegisterDateTimeFunctions();
1745 #ifndef SQLITE_OMIT_ALTERTABLE
1746   sqlite3AlterFunctions();
1747 #endif
1748 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
1749   sqlite3AnalyzeFunctions();
1750 #endif
1751 }
1752