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