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