xref: /sqlite-3.40.0/src/func.c (revision 74e4352a)
1 /*
2 ** 2002 February 23
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains the C functions that implement various SQL
13 ** functions of SQLite.
14 **
15 ** There is only one exported symbol in this file - the function
16 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
17 ** All other code has file scope.
18 **
19 ** $Id: func.c,v 1.136 2007/01/29 17:58:28 drh Exp $
20 */
21 #include "sqliteInt.h"
22 #include <ctype.h>
23 /* #include <math.h> */
24 #include <stdlib.h>
25 #include <assert.h>
26 #include "vdbeInt.h"
27 #include "os.h"
28 
29 /*
30 ** Return the collating function associated with a function.
31 */
32 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
33   return context->pColl;
34 }
35 
36 /*
37 ** Implementation of the non-aggregate min() and max() functions
38 */
39 static void minmaxFunc(
40   sqlite3_context *context,
41   int argc,
42   sqlite3_value **argv
43 ){
44   int i;
45   int mask;    /* 0 for min() or 0xffffffff for max() */
46   int iBest;
47   CollSeq *pColl;
48 
49   if( argc==0 ) return;
50   mask = sqlite3_user_data(context)==0 ? 0 : -1;
51   pColl = sqlite3GetFuncCollSeq(context);
52   assert( pColl );
53   assert( mask==-1 || mask==0 );
54   iBest = 0;
55   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56   for(i=1; i<argc; i++){
57     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
58     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
59       iBest = i;
60     }
61   }
62   sqlite3_result_value(context, argv[iBest]);
63 }
64 
65 /*
66 ** Return the type of the argument.
67 */
68 static void typeofFunc(
69   sqlite3_context *context,
70   int argc,
71   sqlite3_value **argv
72 ){
73   const char *z = 0;
74   switch( sqlite3_value_type(argv[0]) ){
75     case SQLITE_NULL:    z = "null";    break;
76     case SQLITE_INTEGER: z = "integer"; break;
77     case SQLITE_TEXT:    z = "text";    break;
78     case SQLITE_FLOAT:   z = "real";    break;
79     case SQLITE_BLOB:    z = "blob";    break;
80   }
81   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
82 }
83 
84 
85 /*
86 ** Implementation of the length() function
87 */
88 static void lengthFunc(
89   sqlite3_context *context,
90   int argc,
91   sqlite3_value **argv
92 ){
93   int len;
94 
95   assert( argc==1 );
96   switch( sqlite3_value_type(argv[0]) ){
97     case SQLITE_BLOB:
98     case SQLITE_INTEGER:
99     case SQLITE_FLOAT: {
100       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
101       break;
102     }
103     case SQLITE_TEXT: {
104       const unsigned char *z = sqlite3_value_text(argv[0]);
105       for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
106       sqlite3_result_int(context, len);
107       break;
108     }
109     default: {
110       sqlite3_result_null(context);
111       break;
112     }
113   }
114 }
115 
116 /*
117 ** Implementation of the abs() function
118 */
119 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
120   assert( argc==1 );
121   switch( sqlite3_value_type(argv[0]) ){
122     case SQLITE_INTEGER: {
123       i64 iVal = sqlite3_value_int64(argv[0]);
124       if( iVal<0 ){
125         if( (iVal<<1)==0 ){
126           sqlite3_result_error(context, "integer overflow", -1);
127           return;
128         }
129         iVal = -iVal;
130       }
131       sqlite3_result_int64(context, iVal);
132       break;
133     }
134     case SQLITE_NULL: {
135       sqlite3_result_null(context);
136       break;
137     }
138     default: {
139       double rVal = sqlite3_value_double(argv[0]);
140       if( rVal<0 ) rVal = -rVal;
141       sqlite3_result_double(context, rVal);
142       break;
143     }
144   }
145 }
146 
147 /*
148 ** Implementation of the substr() function
149 */
150 static void substrFunc(
151   sqlite3_context *context,
152   int argc,
153   sqlite3_value **argv
154 ){
155   const unsigned char *z;
156   const unsigned char *z2;
157   int i;
158   int p1, p2, len;
159 
160   assert( argc==3 );
161   z = sqlite3_value_text(argv[0]);
162   if( z==0 ) return;
163   p1 = sqlite3_value_int(argv[1]);
164   p2 = sqlite3_value_int(argv[2]);
165   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
166   if( p1<0 ){
167     p1 += len;
168     if( p1<0 ){
169       p2 += p1;
170       p1 = 0;
171     }
172   }else if( p1>0 ){
173     p1--;
174   }
175   if( p1+p2>len ){
176     p2 = len-p1;
177   }
178   for(i=0; i<p1 && z[i]; i++){
179     if( (z[i]&0xc0)==0x80 ) p1++;
180   }
181   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
182   for(; i<p1+p2 && z[i]; i++){
183     if( (z[i]&0xc0)==0x80 ) p2++;
184   }
185   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
186   if( p2<0 ) p2 = 0;
187   sqlite3_result_text(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
188 }
189 
190 /*
191 ** Implementation of the round() function
192 */
193 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
194   int n = 0;
195   double r;
196   char zBuf[500];  /* larger than the %f representation of the largest double */
197   assert( argc==1 || argc==2 );
198   if( argc==2 ){
199     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
200     n = sqlite3_value_int(argv[1]);
201     if( n>30 ) n = 30;
202     if( n<0 ) n = 0;
203   }
204   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
205   r = sqlite3_value_double(argv[0]);
206   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
207   sqlite3AtoF(zBuf, &r);
208   sqlite3_result_double(context, r);
209 }
210 
211 /*
212 ** Implementation of the upper() and lower() SQL functions.
213 */
214 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
215   unsigned char *z;
216   int i;
217   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
218   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
219   if( z==0 ) return;
220   strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
221   for(i=0; z[i]; i++){
222     z[i] = toupper(z[i]);
223   }
224   sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
225   sqliteFree(z);
226 }
227 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
228   unsigned char *z;
229   int i;
230   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
231   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
232   if( z==0 ) return;
233   strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
234   for(i=0; z[i]; i++){
235     z[i] = tolower(z[i]);
236   }
237   sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
238   sqliteFree(z);
239 }
240 
241 /*
242 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
243 ** All three do the same thing.  They return the first non-NULL
244 ** argument.
245 */
246 static void ifnullFunc(
247   sqlite3_context *context,
248   int argc,
249   sqlite3_value **argv
250 ){
251   int i;
252   for(i=0; i<argc; i++){
253     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
254       sqlite3_result_value(context, argv[i]);
255       break;
256     }
257   }
258 }
259 
260 /*
261 ** Implementation of random().  Return a random integer.
262 */
263 static void randomFunc(
264   sqlite3_context *context,
265   int argc,
266   sqlite3_value **argv
267 ){
268   sqlite_int64 r;
269   sqlite3Randomness(sizeof(r), &r);
270   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
271                           /* can always do abs() of the result */
272   sqlite3_result_int64(context, r);
273 }
274 
275 /*
276 ** Implementation of randomblob(N).  Return a random blob
277 ** that is N bytes long.
278 */
279 static void randomBlob(
280   sqlite3_context *context,
281   int argc,
282   sqlite3_value **argv
283 ){
284   int n;
285   unsigned char *p;
286   assert( argc==1 );
287   n = sqlite3_value_int(argv[0]);
288   if( n<1 ) n = 1;
289   p = sqlite3_malloc(n);
290   sqlite3Randomness(n, p);
291   sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
292 }
293 
294 /*
295 ** Implementation of the last_insert_rowid() SQL function.  The return
296 ** value is the same as the sqlite3_last_insert_rowid() API function.
297 */
298 static void last_insert_rowid(
299   sqlite3_context *context,
300   int arg,
301   sqlite3_value **argv
302 ){
303   sqlite3 *db = sqlite3_user_data(context);
304   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
305 }
306 
307 /*
308 ** Implementation of the changes() SQL function.  The return value is the
309 ** same as the sqlite3_changes() API function.
310 */
311 static void changes(
312   sqlite3_context *context,
313   int arg,
314   sqlite3_value **argv
315 ){
316   sqlite3 *db = sqlite3_user_data(context);
317   sqlite3_result_int(context, sqlite3_changes(db));
318 }
319 
320 /*
321 ** Implementation of the total_changes() SQL function.  The return value is
322 ** the same as the sqlite3_total_changes() API function.
323 */
324 static void total_changes(
325   sqlite3_context *context,
326   int arg,
327   sqlite3_value **argv
328 ){
329   sqlite3 *db = sqlite3_user_data(context);
330   sqlite3_result_int(context, sqlite3_total_changes(db));
331 }
332 
333 /*
334 ** A structure defining how to do GLOB-style comparisons.
335 */
336 struct compareInfo {
337   u8 matchAll;
338   u8 matchOne;
339   u8 matchSet;
340   u8 noCase;
341 };
342 
343 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
344 /* The correct SQL-92 behavior is for the LIKE operator to ignore
345 ** case.  Thus  'a' LIKE 'A' would be true. */
346 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
347 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
348 ** is case sensitive causing 'a' LIKE 'A' to be false */
349 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
350 
351 /*
352 ** X is a pointer to the first byte of a UTF-8 character.  Increment
353 ** X so that it points to the next character.  This only works right
354 ** if X points to a well-formed UTF-8 string.
355 */
356 #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
357 #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
358 
359 
360 /*
361 ** Compare two UTF-8 strings for equality where the first string can
362 ** potentially be a "glob" expression.  Return true (1) if they
363 ** are the same and false (0) if they are different.
364 **
365 ** Globbing rules:
366 **
367 **      '*'       Matches any sequence of zero or more characters.
368 **
369 **      '?'       Matches exactly one character.
370 **
371 **     [...]      Matches one character from the enclosed list of
372 **                characters.
373 **
374 **     [^...]     Matches one character not in the enclosed list.
375 **
376 ** With the [...] and [^...] matching, a ']' character can be included
377 ** in the list by making it the first character after '[' or '^'.  A
378 ** range of characters can be specified using '-'.  Example:
379 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
380 ** it the last character in the list.
381 **
382 ** This routine is usually quick, but can be N**2 in the worst case.
383 **
384 ** Hints: to match '*' or '?', put them in "[]".  Like this:
385 **
386 **         abc[*]xyz        Matches "abc*xyz" only
387 */
388 static int patternCompare(
389   const u8 *zPattern,              /* The glob pattern */
390   const u8 *zString,               /* The string to compare against the glob */
391   const struct compareInfo *pInfo, /* Information about how to do the compare */
392   const int esc                    /* The escape character */
393 ){
394   register int c;
395   int invert;
396   int seen;
397   int c2;
398   u8 matchOne = pInfo->matchOne;
399   u8 matchAll = pInfo->matchAll;
400   u8 matchSet = pInfo->matchSet;
401   u8 noCase = pInfo->noCase;
402   int prevEscape = 0;     /* True if the previous character was 'escape' */
403 
404   while( (c = *zPattern)!=0 ){
405     if( !prevEscape && c==matchAll ){
406       while( (c=zPattern[1]) == matchAll || c == matchOne ){
407         if( c==matchOne ){
408           if( *zString==0 ) return 0;
409           sqliteNextChar(zString);
410         }
411         zPattern++;
412       }
413       if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
414         u8 const *zTemp = &zPattern[1];
415         sqliteNextChar(zTemp);
416         c = *zTemp;
417       }
418       if( c==0 ) return 1;
419       if( c==matchSet ){
420         assert( esc==0 );   /* This is GLOB, not LIKE */
421         while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
422           sqliteNextChar(zString);
423         }
424         return *zString!=0;
425       }else{
426         while( (c2 = *zString)!=0 ){
427           if( noCase ){
428             c2 = sqlite3UpperToLower[c2];
429             c = sqlite3UpperToLower[c];
430             while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
431           }else{
432             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
433           }
434           if( c2==0 ) return 0;
435           if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
436           sqliteNextChar(zString);
437         }
438         return 0;
439       }
440     }else if( !prevEscape && c==matchOne ){
441       if( *zString==0 ) return 0;
442       sqliteNextChar(zString);
443       zPattern++;
444     }else if( c==matchSet ){
445       int prior_c = 0;
446       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
447       seen = 0;
448       invert = 0;
449       c = sqliteCharVal(zString);
450       if( c==0 ) return 0;
451       c2 = *++zPattern;
452       if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
453       if( c2==']' ){
454         if( c==']' ) seen = 1;
455         c2 = *++zPattern;
456       }
457       while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
458         if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
459           zPattern++;
460           c2 = sqliteCharVal(zPattern);
461           if( c>=prior_c && c<=c2 ) seen = 1;
462           prior_c = 0;
463         }else if( c==c2 ){
464           seen = 1;
465           prior_c = c2;
466         }else{
467           prior_c = c2;
468         }
469         sqliteNextChar(zPattern);
470       }
471       if( c2==0 || (seen ^ invert)==0 ) return 0;
472       sqliteNextChar(zString);
473       zPattern++;
474     }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
475       prevEscape = 1;
476       sqliteNextChar(zPattern);
477     }else{
478       if( noCase ){
479         if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
480       }else{
481         if( c != *zString ) return 0;
482       }
483       zPattern++;
484       zString++;
485       prevEscape = 0;
486     }
487   }
488   return *zString==0;
489 }
490 
491 /*
492 ** Count the number of times that the LIKE operator (or GLOB which is
493 ** just a variation of LIKE) gets called.  This is used for testing
494 ** only.
495 */
496 #ifdef SQLITE_TEST
497 int sqlite3_like_count = 0;
498 #endif
499 
500 
501 /*
502 ** Implementation of the like() SQL function.  This function implements
503 ** the build-in LIKE operator.  The first argument to the function is the
504 ** pattern and the second argument is the string.  So, the SQL statements:
505 **
506 **       A LIKE B
507 **
508 ** is implemented as like(B,A).
509 **
510 ** This same function (with a different compareInfo structure) computes
511 ** the GLOB operator.
512 */
513 static void likeFunc(
514   sqlite3_context *context,
515   int argc,
516   sqlite3_value **argv
517 ){
518   const unsigned char *zA = sqlite3_value_text(argv[0]);
519   const unsigned char *zB = sqlite3_value_text(argv[1]);
520   int escape = 0;
521   if( argc==3 ){
522     /* The escape character string must consist of a single UTF-8 character.
523     ** Otherwise, return an error.
524     */
525     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
526     if( sqlite3utf8CharLen((char*)zEsc, -1)!=1 ){
527       sqlite3_result_error(context,
528           "ESCAPE expression must be a single character", -1);
529       return;
530     }
531     escape = sqlite3ReadUtf8(zEsc);
532   }
533   if( zA && zB ){
534     struct compareInfo *pInfo = sqlite3_user_data(context);
535 #ifdef SQLITE_TEST
536     sqlite3_like_count++;
537 #endif
538     sqlite3_result_int(context, patternCompare(zA, zB, pInfo, escape));
539   }
540 }
541 
542 /*
543 ** Implementation of the NULLIF(x,y) function.  The result is the first
544 ** argument if the arguments are different.  The result is NULL if the
545 ** arguments are equal to each other.
546 */
547 static void nullifFunc(
548   sqlite3_context *context,
549   int argc,
550   sqlite3_value **argv
551 ){
552   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
553   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
554     sqlite3_result_value(context, argv[0]);
555   }
556 }
557 
558 /*
559 ** Implementation of the VERSION(*) function.  The result is the version
560 ** of the SQLite library that is running.
561 */
562 static void versionFunc(
563   sqlite3_context *context,
564   int argc,
565   sqlite3_value **argv
566 ){
567   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
568 }
569 
570 /* Array for converting from half-bytes (nybbles) into ASCII hex
571 ** digits. */
572 static const char hexdigits[] = {
573   '0', '1', '2', '3', '4', '5', '6', '7',
574   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
575 };
576 
577 /*
578 ** EXPERIMENTAL - This is not an official function.  The interface may
579 ** change.  This function may disappear.  Do not write code that depends
580 ** on this function.
581 **
582 ** Implementation of the QUOTE() function.  This function takes a single
583 ** argument.  If the argument is numeric, the return value is the same as
584 ** the argument.  If the argument is NULL, the return value is the string
585 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
586 ** single-quote escapes.
587 */
588 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
589   if( argc<1 ) return;
590   switch( sqlite3_value_type(argv[0]) ){
591     case SQLITE_NULL: {
592       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
593       break;
594     }
595     case SQLITE_INTEGER:
596     case SQLITE_FLOAT: {
597       sqlite3_result_value(context, argv[0]);
598       break;
599     }
600     case SQLITE_BLOB: {
601       char *zText = 0;
602       int nBlob = sqlite3_value_bytes(argv[0]);
603       char const *zBlob = sqlite3_value_blob(argv[0]);
604 
605       zText = (char *)sqliteMalloc((2*nBlob)+4);
606       if( !zText ){
607         sqlite3_result_error(context, "out of memory", -1);
608       }else{
609         int i;
610         for(i=0; i<nBlob; i++){
611           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
612           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
613         }
614         zText[(nBlob*2)+2] = '\'';
615         zText[(nBlob*2)+3] = '\0';
616         zText[0] = 'X';
617         zText[1] = '\'';
618         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
619         sqliteFree(zText);
620       }
621       break;
622     }
623     case SQLITE_TEXT: {
624       int i,j,n;
625       const unsigned char *zArg = sqlite3_value_text(argv[0]);
626       char *z;
627 
628       for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
629       z = sqliteMalloc( i+n+3 );
630       if( z==0 ) return;
631       z[0] = '\'';
632       for(i=0, j=1; zArg[i]; i++){
633         z[j++] = zArg[i];
634         if( zArg[i]=='\'' ){
635           z[j++] = '\'';
636         }
637       }
638       z[j++] = '\'';
639       z[j] = 0;
640       sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
641       sqliteFree(z);
642     }
643   }
644 }
645 
646 /*
647 ** The hex() function.  Interpret the argument as a blob.  Return
648 ** a hexadecimal rendering as text.
649 */
650 static void hexFunc(
651   sqlite3_context *context,
652   int argc,
653   sqlite3_value **argv
654 ){
655   int i, n;
656   const unsigned char *pBlob;
657   char *zHex, *z;
658   assert( argc==1 );
659   pBlob = sqlite3_value_blob(argv[0]);
660   n = sqlite3_value_bytes(argv[0]);
661   z = zHex = sqlite3_malloc(n*2 + 1);
662   if( zHex==0 ) return;
663   for(i=0; i<n; i++, pBlob++){
664     unsigned char c = *pBlob;
665     *(z++) = hexdigits[(c>>4)&0xf];
666     *(z++) = hexdigits[c&0xf];
667   }
668   *z = 0;
669   sqlite3_result_text(context, zHex, n*2, sqlite3_free);
670 }
671 
672 #ifdef SQLITE_SOUNDEX
673 /*
674 ** Compute the soundex encoding of a word.
675 */
676 static void soundexFunc(
677   sqlite3_context *context,
678   int argc,
679   sqlite3_value **argv
680 ){
681   char zResult[8];
682   const u8 *zIn;
683   int i, j;
684   static const unsigned char iCode[] = {
685     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
686     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
687     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
688     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
689     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
690     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
691     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
692     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
693   };
694   assert( argc==1 );
695   zIn = (u8*)sqlite3_value_text(argv[0]);
696   if( zIn==0 ) zIn = (u8*)"";
697   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
698   if( zIn[i] ){
699     u8 prevcode = iCode[zIn[i]&0x7f];
700     zResult[0] = toupper(zIn[i]);
701     for(j=1; j<4 && zIn[i]; i++){
702       int code = iCode[zIn[i]&0x7f];
703       if( code>0 ){
704         if( code!=prevcode ){
705           prevcode = code;
706           zResult[j++] = code + '0';
707         }
708       }else{
709         prevcode = 0;
710       }
711     }
712     while( j<4 ){
713       zResult[j++] = '0';
714     }
715     zResult[j] = 0;
716     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
717   }else{
718     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
719   }
720 }
721 #endif
722 
723 #ifndef SQLITE_OMIT_LOAD_EXTENSION
724 /*
725 ** A function that loads a shared-library extension then returns NULL.
726 */
727 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
728   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
729   const char *zProc = 0;
730   sqlite3 *db = sqlite3_user_data(context);
731   char *zErrMsg = 0;
732 
733   if( argc==2 ){
734     zProc = (const char *)sqlite3_value_text(argv[1]);
735   }
736   if( sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
737     sqlite3_result_error(context, zErrMsg, -1);
738     sqlite3_free(zErrMsg);
739   }
740 }
741 #endif
742 
743 #ifdef SQLITE_TEST
744 /*
745 ** This function generates a string of random characters.  Used for
746 ** generating test data.
747 */
748 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
749   static const unsigned char zSrc[] =
750      "abcdefghijklmnopqrstuvwxyz"
751      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
752      "0123456789"
753      ".-!,:*^+=_|?/<> ";
754   int iMin, iMax, n, r, i;
755   unsigned char zBuf[1000];
756   if( argc>=1 ){
757     iMin = sqlite3_value_int(argv[0]);
758     if( iMin<0 ) iMin = 0;
759     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
760   }else{
761     iMin = 1;
762   }
763   if( argc>=2 ){
764     iMax = sqlite3_value_int(argv[1]);
765     if( iMax<iMin ) iMax = iMin;
766     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
767   }else{
768     iMax = 50;
769   }
770   n = iMin;
771   if( iMax>iMin ){
772     sqlite3Randomness(sizeof(r), &r);
773     r &= 0x7fffffff;
774     n += r%(iMax + 1 - iMin);
775   }
776   assert( n<sizeof(zBuf) );
777   sqlite3Randomness(n, zBuf);
778   for(i=0; i<n; i++){
779     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
780   }
781   zBuf[n] = 0;
782   sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
783 }
784 #endif /* SQLITE_TEST */
785 
786 #ifdef SQLITE_TEST
787 /*
788 ** The following two SQL functions are used to test returning a text
789 ** result with a destructor. Function 'test_destructor' takes one argument
790 ** and returns the same argument interpreted as TEXT. A destructor is
791 ** passed with the sqlite3_result_text() call.
792 **
793 ** SQL function 'test_destructor_count' returns the number of outstanding
794 ** allocations made by 'test_destructor';
795 **
796 ** WARNING: Not threadsafe.
797 */
798 static int test_destructor_count_var = 0;
799 static void destructor(void *p){
800   char *zVal = (char *)p;
801   assert(zVal);
802   zVal--;
803   sqliteFree(zVal);
804   test_destructor_count_var--;
805 }
806 static void test_destructor(
807   sqlite3_context *pCtx,
808   int nArg,
809   sqlite3_value **argv
810 ){
811   char *zVal;
812   int len;
813   sqlite3 *db = sqlite3_user_data(pCtx);
814 
815   test_destructor_count_var++;
816   assert( nArg==1 );
817   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
818   len = sqlite3ValueBytes(argv[0], ENC(db));
819   zVal = sqliteMalloc(len+3);
820   zVal[len] = 0;
821   zVal[len-1] = 0;
822   assert( zVal );
823   zVal++;
824   memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
825   if( ENC(db)==SQLITE_UTF8 ){
826     sqlite3_result_text(pCtx, zVal, -1, destructor);
827 #ifndef SQLITE_OMIT_UTF16
828   }else if( ENC(db)==SQLITE_UTF16LE ){
829     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
830   }else{
831     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
832 #endif /* SQLITE_OMIT_UTF16 */
833   }
834 }
835 static void test_destructor_count(
836   sqlite3_context *pCtx,
837   int nArg,
838   sqlite3_value **argv
839 ){
840   sqlite3_result_int(pCtx, test_destructor_count_var);
841 }
842 #endif /* SQLITE_TEST */
843 
844 #ifdef SQLITE_TEST
845 /*
846 ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
847 ** interface.
848 **
849 ** The test_auxdata() SQL function attempts to register each of its arguments
850 ** as auxiliary data.  If there are no prior registrations of aux data for
851 ** that argument (meaning the argument is not a constant or this is its first
852 ** call) then the result for that argument is 0.  If there is a prior
853 ** registration, the result for that argument is 1.  The overall result
854 ** is the individual argument results separated by spaces.
855 */
856 static void free_test_auxdata(void *p) {sqliteFree(p);}
857 static void test_auxdata(
858   sqlite3_context *pCtx,
859   int nArg,
860   sqlite3_value **argv
861 ){
862   int i;
863   char *zRet = sqliteMalloc(nArg*2);
864   if( !zRet ) return;
865   for(i=0; i<nArg; i++){
866     char const *z = (char*)sqlite3_value_text(argv[i]);
867     if( z ){
868       char *zAux = sqlite3_get_auxdata(pCtx, i);
869       if( zAux ){
870         zRet[i*2] = '1';
871         if( strcmp(zAux, z) ){
872           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
873           return;
874         }
875       }else{
876         zRet[i*2] = '0';
877         zAux = sqliteStrDup(z);
878         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
879       }
880       zRet[i*2+1] = ' ';
881     }
882   }
883   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
884 }
885 #endif /* SQLITE_TEST */
886 
887 #ifdef SQLITE_TEST
888 /*
889 ** A function to test error reporting from user functions. This function
890 ** returns a copy of it's first argument as an error.
891 */
892 static void test_error(
893   sqlite3_context *pCtx,
894   int nArg,
895   sqlite3_value **argv
896 ){
897   sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
898 }
899 #endif /* SQLITE_TEST */
900 
901 /*
902 ** An instance of the following structure holds the context of a
903 ** sum() or avg() aggregate computation.
904 */
905 typedef struct SumCtx SumCtx;
906 struct SumCtx {
907   double rSum;      /* Floating point sum */
908   i64 iSum;         /* Integer sum */
909   i64 cnt;          /* Number of elements summed */
910   u8 overflow;      /* True if integer overflow seen */
911   u8 approx;        /* True if non-integer value was input to the sum */
912 };
913 
914 /*
915 ** Routines used to compute the sum, average, and total.
916 **
917 ** The SUM() function follows the (broken) SQL standard which means
918 ** that it returns NULL if it sums over no inputs.  TOTAL returns
919 ** 0.0 in that case.  In addition, TOTAL always returns a float where
920 ** SUM might return an integer if it never encounters a floating point
921 ** value.  TOTAL never fails, but SUM might through an exception if
922 ** it overflows an integer.
923 */
924 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
925   SumCtx *p;
926   int type;
927   assert( argc==1 );
928   p = sqlite3_aggregate_context(context, sizeof(*p));
929   type = sqlite3_value_numeric_type(argv[0]);
930   if( p && type!=SQLITE_NULL ){
931     p->cnt++;
932     if( type==SQLITE_INTEGER ){
933       i64 v = sqlite3_value_int64(argv[0]);
934       p->rSum += v;
935       if( (p->approx|p->overflow)==0 ){
936         i64 iNewSum = p->iSum + v;
937         int s1 = p->iSum >> (sizeof(i64)*8-1);
938         int s2 = v       >> (sizeof(i64)*8-1);
939         int s3 = iNewSum >> (sizeof(i64)*8-1);
940         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
941         p->iSum = iNewSum;
942       }
943     }else{
944       p->rSum += sqlite3_value_double(argv[0]);
945       p->approx = 1;
946     }
947   }
948 }
949 static void sumFinalize(sqlite3_context *context){
950   SumCtx *p;
951   p = sqlite3_aggregate_context(context, 0);
952   if( p && p->cnt>0 ){
953     if( p->overflow ){
954       sqlite3_result_error(context,"integer overflow",-1);
955     }else if( p->approx ){
956       sqlite3_result_double(context, p->rSum);
957     }else{
958       sqlite3_result_int64(context, p->iSum);
959     }
960   }
961 }
962 static void avgFinalize(sqlite3_context *context){
963   SumCtx *p;
964   p = sqlite3_aggregate_context(context, 0);
965   if( p && p->cnt>0 ){
966     sqlite3_result_double(context, p->rSum/(double)p->cnt);
967   }
968 }
969 static void totalFinalize(sqlite3_context *context){
970   SumCtx *p;
971   p = sqlite3_aggregate_context(context, 0);
972   sqlite3_result_double(context, p ? p->rSum : 0.0);
973 }
974 
975 /*
976 ** The following structure keeps track of state information for the
977 ** count() aggregate function.
978 */
979 typedef struct CountCtx CountCtx;
980 struct CountCtx {
981   i64 n;
982 };
983 
984 /*
985 ** Routines to implement the count() aggregate function.
986 */
987 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
988   CountCtx *p;
989   p = sqlite3_aggregate_context(context, sizeof(*p));
990   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
991     p->n++;
992   }
993 }
994 static void countFinalize(sqlite3_context *context){
995   CountCtx *p;
996   p = sqlite3_aggregate_context(context, 0);
997   sqlite3_result_int64(context, p ? p->n : 0);
998 }
999 
1000 /*
1001 ** Routines to implement min() and max() aggregate functions.
1002 */
1003 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1004   Mem *pArg  = (Mem *)argv[0];
1005   Mem *pBest;
1006 
1007   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
1008   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
1009   if( !pBest ) return;
1010 
1011   if( pBest->flags ){
1012     int max;
1013     int cmp;
1014     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
1015     /* This step function is used for both the min() and max() aggregates,
1016     ** the only difference between the two being that the sense of the
1017     ** comparison is inverted. For the max() aggregate, the
1018     ** sqlite3_user_data() function returns (void *)-1. For min() it
1019     ** returns (void *)db, where db is the sqlite3* database pointer.
1020     ** Therefore the next statement sets variable 'max' to 1 for the max()
1021     ** aggregate, or 0 for min().
1022     */
1023     max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
1024     cmp = sqlite3MemCompare(pBest, pArg, pColl);
1025     if( (max && cmp<0) || (!max && cmp>0) ){
1026       sqlite3VdbeMemCopy(pBest, pArg);
1027     }
1028   }else{
1029     sqlite3VdbeMemCopy(pBest, pArg);
1030   }
1031 }
1032 static void minMaxFinalize(sqlite3_context *context){
1033   sqlite3_value *pRes;
1034   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
1035   if( pRes ){
1036     if( pRes->flags ){
1037       sqlite3_result_value(context, pRes);
1038     }
1039     sqlite3VdbeMemRelease(pRes);
1040   }
1041 }
1042 
1043 
1044 /*
1045 ** This function registered all of the above C functions as SQL
1046 ** functions.  This should be the only routine in this file with
1047 ** external linkage.
1048 */
1049 void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
1050   static const struct {
1051      char *zName;
1052      signed char nArg;
1053      u8 argType;           /* 0: none.  1: db  2: (-1) */
1054      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
1055      u8 needCollSeq;
1056      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
1057   } aFuncs[] = {
1058     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
1059     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
1060     { "max",               -1, 2, SQLITE_UTF8,    1, minmaxFunc },
1061     { "max",                0, 2, SQLITE_UTF8,    1, 0          },
1062     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
1063     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
1064     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
1065 #ifndef SQLITE_OMIT_UTF16
1066     { "substr",             3, 0, SQLITE_UTF16LE, 0, sqlite3utf16Substr },
1067 #endif
1068     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
1069     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
1070     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
1071     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
1072     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
1073     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
1074     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
1075     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
1076     { "hex",                1, 0, SQLITE_UTF8,    0, hexFunc    },
1077     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
1078     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
1079     { "randomblob",         1, 0, SQLITE_UTF8,    0, randomBlob },
1080     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
1081     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
1082     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
1083     { "last_insert_rowid",  0, 1, SQLITE_UTF8,    0, last_insert_rowid },
1084     { "changes",            0, 1, SQLITE_UTF8,    0, changes    },
1085     { "total_changes",      0, 1, SQLITE_UTF8,    0, total_changes },
1086 #ifdef SQLITE_SOUNDEX
1087     { "soundex",            1, 0, SQLITE_UTF8, 0, soundexFunc},
1088 #endif
1089 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1090     { "load_extension",     1, 1, SQLITE_UTF8,    0, loadExt },
1091     { "load_extension",     2, 1, SQLITE_UTF8,    0, loadExt },
1092 #endif
1093 #ifdef SQLITE_TEST
1094     { "randstr",               2, 0, SQLITE_UTF8, 0, randStr    },
1095     { "test_destructor",       1, 1, SQLITE_UTF8, 0, test_destructor},
1096     { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
1097     { "test_auxdata",         -1, 0, SQLITE_UTF8, 0, test_auxdata},
1098     { "test_error",            1, 0, SQLITE_UTF8, 0, test_error},
1099 #endif
1100   };
1101   static const struct {
1102     char *zName;
1103     signed char nArg;
1104     u8 argType;
1105     u8 needCollSeq;
1106     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
1107     void (*xFinalize)(sqlite3_context*);
1108   } aAggs[] = {
1109     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
1110     { "max",    1, 2, 1, minmaxStep,   minMaxFinalize },
1111     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
1112     { "total",  1, 0, 0, sumStep,      totalFinalize    },
1113     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
1114     { "count",  0, 0, 0, countStep,    countFinalize  },
1115     { "count",  1, 0, 0, countStep,    countFinalize  },
1116   };
1117   int i;
1118 
1119   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1120     void *pArg = 0;
1121     switch( aFuncs[i].argType ){
1122       case 1: pArg = db; break;
1123       case 2: pArg = (void *)(-1); break;
1124     }
1125     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
1126         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1127     if( aFuncs[i].needCollSeq ){
1128       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1129           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1130       if( pFunc && aFuncs[i].needCollSeq ){
1131         pFunc->needCollSeq = 1;
1132       }
1133     }
1134   }
1135 #ifndef SQLITE_OMIT_ALTERTABLE
1136   sqlite3AlterFunctions(db);
1137 #endif
1138 #ifndef SQLITE_OMIT_PARSER
1139   sqlite3AttachFunctions(db);
1140 #endif
1141   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1142     void *pArg = 0;
1143     switch( aAggs[i].argType ){
1144       case 1: pArg = db; break;
1145       case 2: pArg = (void *)(-1); break;
1146     }
1147     sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1148         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1149     if( aAggs[i].needCollSeq ){
1150       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1151           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1152       if( pFunc && aAggs[i].needCollSeq ){
1153         pFunc->needCollSeq = 1;
1154       }
1155     }
1156   }
1157   sqlite3RegisterDateTimeFunctions(db);
1158   sqlite3_overload_function(db, "MATCH", 2);
1159 #ifdef SQLITE_SSE
1160   (void)sqlite3SseFunctions(db);
1161 #endif
1162 #ifdef SQLITE_CASE_SENSITIVE_LIKE
1163   sqlite3RegisterLikeFunctions(db, 1);
1164 #else
1165   sqlite3RegisterLikeFunctions(db, 0);
1166 #endif
1167 }
1168 
1169 /*
1170 ** Set the LIKEOPT flag on the 2-argument function with the given name.
1171 */
1172 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
1173   FuncDef *pDef;
1174   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
1175   if( pDef ){
1176     pDef->flags = flagVal;
1177   }
1178 }
1179 
1180 /*
1181 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
1182 ** parameter determines whether or not the LIKE operator is case
1183 ** sensitive.  GLOB is always case sensitive.
1184 */
1185 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
1186   struct compareInfo *pInfo;
1187   if( caseSensitive ){
1188     pInfo = (struct compareInfo*)&likeInfoAlt;
1189   }else{
1190     pInfo = (struct compareInfo*)&likeInfoNorm;
1191   }
1192   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
1193   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
1194   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
1195       (struct compareInfo*)&globInfo, likeFunc, 0,0);
1196   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
1197   setLikeOptFlag(db, "like",
1198       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
1199 }
1200 
1201 /*
1202 ** pExpr points to an expression which implements a function.  If
1203 ** it is appropriate to apply the LIKE optimization to that function
1204 ** then set aWc[0] through aWc[2] to the wildcard characters and
1205 ** return TRUE.  If the function is not a LIKE-style function then
1206 ** return FALSE.
1207 */
1208 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
1209   FuncDef *pDef;
1210   if( pExpr->op!=TK_FUNCTION ){
1211     return 0;
1212   }
1213   if( pExpr->pList->nExpr!=2 ){
1214     return 0;
1215   }
1216   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
1217                              SQLITE_UTF8, 0);
1218   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
1219     return 0;
1220   }
1221 
1222   /* The memcpy() statement assumes that the wildcard characters are
1223   ** the first three statements in the compareInfo structure.  The
1224   ** asserts() that follow verify that assumption
1225   */
1226   memcpy(aWc, pDef->pUserData, 3);
1227   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
1228   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
1229   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1230   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
1231   return 1;
1232 }
1233