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