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