Fix a problem causing the recovery extension to use excessive memory and CPU time...
[sqlite.git] / src / func.c
blob18004984d983d07b3fc6ac986dc03bf89c1e8634
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.
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.)
16 #include "sqliteInt.h"
17 #include <stdlib.h>
18 #include <assert.h>
19 #ifndef SQLITE_OMIT_FLOATING_POINT
20 #include <math.h>
21 #endif
22 #include "vdbeInt.h"
25 ** Return the collating function associated with a function.
27 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
28 VdbeOp *pOp;
29 assert( context->pVdbe!=0 );
30 pOp = &context->pVdbe->aOp[context->iOp-1];
31 assert( pOp->opcode==OP_CollSeq );
32 assert( pOp->p4type==P4_COLLSEQ );
33 return pOp->p4.pColl;
37 ** Indicate that the accumulator load should be skipped on this
38 ** iteration of the aggregate loop.
40 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
41 assert( context->isError<=0 );
42 context->isError = -1;
43 context->skipFlag = 1;
47 ** Implementation of the non-aggregate min() and max() functions
49 static void minmaxFunc(
50 sqlite3_context *context,
51 int argc,
52 sqlite3_value **argv
54 int i;
55 int mask; /* 0 for min() or 0xffffffff for max() */
56 int iBest;
57 CollSeq *pColl;
59 assert( argc>1 );
60 mask = sqlite3_user_data(context)==0 ? 0 : -1;
61 pColl = sqlite3GetFuncCollSeq(context);
62 assert( pColl );
63 assert( mask==-1 || mask==0 );
64 iBest = 0;
65 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
66 for(i=1; i<argc; i++){
67 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
68 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
69 testcase( mask==0 );
70 iBest = i;
73 sqlite3_result_value(context, argv[iBest]);
77 ** Return the type of the argument.
79 static void typeofFunc(
80 sqlite3_context *context,
81 int NotUsed,
82 sqlite3_value **argv
84 static const char *azType[] = { "integer", "real", "text", "blob", "null" };
85 int i = sqlite3_value_type(argv[0]) - 1;
86 UNUSED_PARAMETER(NotUsed);
87 assert( i>=0 && i<ArraySize(azType) );
88 assert( SQLITE_INTEGER==1 );
89 assert( SQLITE_FLOAT==2 );
90 assert( SQLITE_TEXT==3 );
91 assert( SQLITE_BLOB==4 );
92 assert( SQLITE_NULL==5 );
93 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
94 ** the datatype code for the initial datatype of the sqlite3_value object
95 ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
96 ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
97 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
100 /* subtype(X)
102 ** Return the subtype of X
104 static void subtypeFunc(
105 sqlite3_context *context,
106 int argc,
107 sqlite3_value **argv
109 UNUSED_PARAMETER(argc);
110 sqlite3_result_int(context, sqlite3_value_subtype(argv[0]));
114 ** Implementation of the length() function
116 static void lengthFunc(
117 sqlite3_context *context,
118 int argc,
119 sqlite3_value **argv
121 assert( argc==1 );
122 UNUSED_PARAMETER(argc);
123 switch( sqlite3_value_type(argv[0]) ){
124 case SQLITE_BLOB:
125 case SQLITE_INTEGER:
126 case SQLITE_FLOAT: {
127 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
128 break;
130 case SQLITE_TEXT: {
131 const unsigned char *z = sqlite3_value_text(argv[0]);
132 const unsigned char *z0;
133 unsigned char c;
134 if( z==0 ) return;
135 z0 = z;
136 while( (c = *z)!=0 ){
137 z++;
138 if( c>=0xc0 ){
139 while( (*z & 0xc0)==0x80 ){ z++; z0++; }
142 sqlite3_result_int(context, (int)(z-z0));
143 break;
145 default: {
146 sqlite3_result_null(context);
147 break;
153 ** Implementation of the octet_length() function
155 static void bytelengthFunc(
156 sqlite3_context *context,
157 int argc,
158 sqlite3_value **argv
160 assert( argc==1 );
161 UNUSED_PARAMETER(argc);
162 switch( sqlite3_value_type(argv[0]) ){
163 case SQLITE_BLOB: {
164 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
165 break;
167 case SQLITE_INTEGER:
168 case SQLITE_FLOAT: {
169 i64 m = sqlite3_context_db_handle(context)->enc<=SQLITE_UTF8 ? 1 : 2;
170 sqlite3_result_int64(context, sqlite3_value_bytes(argv[0])*m);
171 break;
173 case SQLITE_TEXT: {
174 if( sqlite3_value_encoding(argv[0])<=SQLITE_UTF8 ){
175 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
176 }else{
177 sqlite3_result_int(context, sqlite3_value_bytes16(argv[0]));
179 break;
181 default: {
182 sqlite3_result_null(context);
183 break;
189 ** Implementation of the abs() function.
191 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
192 ** the numeric argument X.
194 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
195 assert( argc==1 );
196 UNUSED_PARAMETER(argc);
197 switch( sqlite3_value_type(argv[0]) ){
198 case SQLITE_INTEGER: {
199 i64 iVal = sqlite3_value_int64(argv[0]);
200 if( iVal<0 ){
201 if( iVal==SMALLEST_INT64 ){
202 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
203 ** then abs(X) throws an integer overflow error since there is no
204 ** equivalent positive 64-bit two complement value. */
205 sqlite3_result_error(context, "integer overflow", -1);
206 return;
208 iVal = -iVal;
210 sqlite3_result_int64(context, iVal);
211 break;
213 case SQLITE_NULL: {
214 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
215 sqlite3_result_null(context);
216 break;
218 default: {
219 /* Because sqlite3_value_double() returns 0.0 if the argument is not
220 ** something that can be converted into a number, we have:
221 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
222 ** that cannot be converted to a numeric value.
224 double rVal = sqlite3_value_double(argv[0]);
225 if( rVal<0 ) rVal = -rVal;
226 sqlite3_result_double(context, rVal);
227 break;
233 ** Implementation of the instr() function.
235 ** instr(haystack,needle) finds the first occurrence of needle
236 ** in haystack and returns the number of previous characters plus 1,
237 ** or 0 if needle does not occur within haystack.
239 ** If both haystack and needle are BLOBs, then the result is one more than
240 ** the number of bytes in haystack prior to the first occurrence of needle,
241 ** or 0 if needle never occurs in haystack.
243 static void instrFunc(
244 sqlite3_context *context,
245 int argc,
246 sqlite3_value **argv
248 const unsigned char *zHaystack;
249 const unsigned char *zNeedle;
250 int nHaystack;
251 int nNeedle;
252 int typeHaystack, typeNeedle;
253 int N = 1;
254 int isText;
255 unsigned char firstChar;
256 sqlite3_value *pC1 = 0;
257 sqlite3_value *pC2 = 0;
259 UNUSED_PARAMETER(argc);
260 typeHaystack = sqlite3_value_type(argv[0]);
261 typeNeedle = sqlite3_value_type(argv[1]);
262 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
263 nHaystack = sqlite3_value_bytes(argv[0]);
264 nNeedle = sqlite3_value_bytes(argv[1]);
265 if( nNeedle>0 ){
266 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
267 zHaystack = sqlite3_value_blob(argv[0]);
268 zNeedle = sqlite3_value_blob(argv[1]);
269 isText = 0;
270 }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){
271 zHaystack = sqlite3_value_text(argv[0]);
272 zNeedle = sqlite3_value_text(argv[1]);
273 isText = 1;
274 }else{
275 pC1 = sqlite3_value_dup(argv[0]);
276 zHaystack = sqlite3_value_text(pC1);
277 if( zHaystack==0 ) goto endInstrOOM;
278 nHaystack = sqlite3_value_bytes(pC1);
279 pC2 = sqlite3_value_dup(argv[1]);
280 zNeedle = sqlite3_value_text(pC2);
281 if( zNeedle==0 ) goto endInstrOOM;
282 nNeedle = sqlite3_value_bytes(pC2);
283 isText = 1;
285 if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM;
286 firstChar = zNeedle[0];
287 while( nNeedle<=nHaystack
288 && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
290 N++;
292 nHaystack--;
293 zHaystack++;
294 }while( isText && (zHaystack[0]&0xc0)==0x80 );
296 if( nNeedle>nHaystack ) N = 0;
298 sqlite3_result_int(context, N);
299 endInstr:
300 sqlite3_value_free(pC1);
301 sqlite3_value_free(pC2);
302 return;
303 endInstrOOM:
304 sqlite3_result_error_nomem(context);
305 goto endInstr;
309 ** Implementation of the printf() (a.k.a. format()) SQL function.
311 static void printfFunc(
312 sqlite3_context *context,
313 int argc,
314 sqlite3_value **argv
316 PrintfArguments x;
317 StrAccum str;
318 const char *zFormat;
319 int n;
320 sqlite3 *db = sqlite3_context_db_handle(context);
322 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
323 x.nArg = argc-1;
324 x.nUsed = 0;
325 x.apArg = argv+1;
326 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
327 str.printfFlags = SQLITE_PRINTF_SQLFUNC;
328 sqlite3_str_appendf(&str, zFormat, &x);
329 n = str.nChar;
330 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
331 SQLITE_DYNAMIC);
336 ** Implementation of the substr() function.
338 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
339 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
340 ** of x. If x is text, then we actually count UTF-8 characters.
341 ** If x is a blob, then we count bytes.
343 ** If p1 is negative, then we begin abs(p1) from the end of x[].
345 ** If p2 is negative, return the p2 characters preceding p1.
347 static void substrFunc(
348 sqlite3_context *context,
349 int argc,
350 sqlite3_value **argv
352 const unsigned char *z;
353 const unsigned char *z2;
354 int len;
355 int p0type;
356 i64 p1, p2;
357 int negP2 = 0;
359 assert( argc==3 || argc==2 );
360 if( sqlite3_value_type(argv[1])==SQLITE_NULL
361 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
363 return;
365 p0type = sqlite3_value_type(argv[0]);
366 p1 = sqlite3_value_int(argv[1]);
367 if( p0type==SQLITE_BLOB ){
368 len = sqlite3_value_bytes(argv[0]);
369 z = sqlite3_value_blob(argv[0]);
370 if( z==0 ) return;
371 assert( len==sqlite3_value_bytes(argv[0]) );
372 }else{
373 z = sqlite3_value_text(argv[0]);
374 if( z==0 ) return;
375 len = 0;
376 if( p1<0 ){
377 for(z2=z; *z2; len++){
378 SQLITE_SKIP_UTF8(z2);
382 #ifdef SQLITE_SUBSTR_COMPATIBILITY
383 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
384 ** as substr(X,1,N) - it returns the first N characters of X. This
385 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
386 ** from 2009-02-02 for compatibility of applications that exploited the
387 ** old buggy behavior. */
388 if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
389 #endif
390 if( argc==3 ){
391 p2 = sqlite3_value_int(argv[2]);
392 if( p2<0 ){
393 p2 = -p2;
394 negP2 = 1;
396 }else{
397 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
399 if( p1<0 ){
400 p1 += len;
401 if( p1<0 ){
402 p2 += p1;
403 if( p2<0 ) p2 = 0;
404 p1 = 0;
406 }else if( p1>0 ){
407 p1--;
408 }else if( p2>0 ){
409 p2--;
411 if( negP2 ){
412 p1 -= p2;
413 if( p1<0 ){
414 p2 += p1;
415 p1 = 0;
418 assert( p1>=0 && p2>=0 );
419 if( p0type!=SQLITE_BLOB ){
420 while( *z && p1 ){
421 SQLITE_SKIP_UTF8(z);
422 p1--;
424 for(z2=z; *z2 && p2; p2--){
425 SQLITE_SKIP_UTF8(z2);
427 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
428 SQLITE_UTF8);
429 }else{
430 if( p1+p2>len ){
431 p2 = len-p1;
432 if( p2<0 ) p2 = 0;
434 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
439 ** Implementation of the round() function
441 #ifndef SQLITE_OMIT_FLOATING_POINT
442 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
443 int n = 0;
444 double r;
445 char *zBuf;
446 assert( argc==1 || argc==2 );
447 if( argc==2 ){
448 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
449 n = sqlite3_value_int(argv[1]);
450 if( n>30 ) n = 30;
451 if( n<0 ) n = 0;
453 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
454 r = sqlite3_value_double(argv[0]);
455 /* If Y==0 and X will fit in a 64-bit int,
456 ** handle the rounding directly,
457 ** otherwise use printf.
459 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
460 /* The value has no fractional part so there is nothing to round */
461 }else if( n==0 ){
462 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
463 }else{
464 zBuf = sqlite3_mprintf("%!.*f",n,r);
465 if( zBuf==0 ){
466 sqlite3_result_error_nomem(context);
467 return;
469 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
470 sqlite3_free(zBuf);
472 sqlite3_result_double(context, r);
474 #endif
477 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
478 ** allocation fails, call sqlite3_result_error_nomem() to notify
479 ** the database handle that malloc() has failed and return NULL.
480 ** If nByte is larger than the maximum string or blob length, then
481 ** raise an SQLITE_TOOBIG exception and return NULL.
483 static void *contextMalloc(sqlite3_context *context, i64 nByte){
484 char *z;
485 sqlite3 *db = sqlite3_context_db_handle(context);
486 assert( nByte>0 );
487 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
488 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
489 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
490 sqlite3_result_error_toobig(context);
491 z = 0;
492 }else{
493 z = sqlite3Malloc(nByte);
494 if( !z ){
495 sqlite3_result_error_nomem(context);
498 return z;
502 ** Implementation of the upper() and lower() SQL functions.
504 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
505 char *z1;
506 const char *z2;
507 int i, n;
508 UNUSED_PARAMETER(argc);
509 z2 = (char*)sqlite3_value_text(argv[0]);
510 n = sqlite3_value_bytes(argv[0]);
511 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
512 assert( z2==(char*)sqlite3_value_text(argv[0]) );
513 if( z2 ){
514 z1 = contextMalloc(context, ((i64)n)+1);
515 if( z1 ){
516 for(i=0; i<n; i++){
517 z1[i] = (char)sqlite3Toupper(z2[i]);
519 sqlite3_result_text(context, z1, n, sqlite3_free);
523 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
524 char *z1;
525 const char *z2;
526 int i, n;
527 UNUSED_PARAMETER(argc);
528 z2 = (char*)sqlite3_value_text(argv[0]);
529 n = sqlite3_value_bytes(argv[0]);
530 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
531 assert( z2==(char*)sqlite3_value_text(argv[0]) );
532 if( z2 ){
533 z1 = contextMalloc(context, ((i64)n)+1);
534 if( z1 ){
535 for(i=0; i<n; i++){
536 z1[i] = sqlite3Tolower(z2[i]);
538 sqlite3_result_text(context, z1, n, sqlite3_free);
544 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
545 ** as VDBE code so that unused argument values do not have to be computed.
546 ** However, we still need some kind of function implementation for this
547 ** routines in the function table. The noopFunc macro provides this.
548 ** noopFunc will never be called so it doesn't matter what the implementation
549 ** is. We might as well use the "version()" function as a substitute.
551 #define noopFunc versionFunc /* Substitute function - never called */
554 ** Implementation of random(). Return a random integer.
556 static void randomFunc(
557 sqlite3_context *context,
558 int NotUsed,
559 sqlite3_value **NotUsed2
561 sqlite_int64 r;
562 UNUSED_PARAMETER2(NotUsed, NotUsed2);
563 sqlite3_randomness(sizeof(r), &r);
564 if( r<0 ){
565 /* We need to prevent a random number of 0x8000000000000000
566 ** (or -9223372036854775808) since when you do abs() of that
567 ** number of you get the same value back again. To do this
568 ** in a way that is testable, mask the sign bit off of negative
569 ** values, resulting in a positive value. Then take the
570 ** 2s complement of that positive value. The end result can
571 ** therefore be no less than -9223372036854775807.
573 r = -(r & LARGEST_INT64);
575 sqlite3_result_int64(context, r);
579 ** Implementation of randomblob(N). Return a random blob
580 ** that is N bytes long.
582 static void randomBlob(
583 sqlite3_context *context,
584 int argc,
585 sqlite3_value **argv
587 sqlite3_int64 n;
588 unsigned char *p;
589 assert( argc==1 );
590 UNUSED_PARAMETER(argc);
591 n = sqlite3_value_int64(argv[0]);
592 if( n<1 ){
593 n = 1;
595 p = contextMalloc(context, n);
596 if( p ){
597 sqlite3_randomness(n, p);
598 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
603 ** Implementation of the last_insert_rowid() SQL function. The return
604 ** value is the same as the sqlite3_last_insert_rowid() API function.
606 static void last_insert_rowid(
607 sqlite3_context *context,
608 int NotUsed,
609 sqlite3_value **NotUsed2
611 sqlite3 *db = sqlite3_context_db_handle(context);
612 UNUSED_PARAMETER2(NotUsed, NotUsed2);
613 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
614 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
615 ** function. */
616 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
620 ** Implementation of the changes() SQL function.
622 ** IMP: R-32760-32347 The changes() SQL function is a wrapper
623 ** around the sqlite3_changes64() C/C++ function and hence follows the
624 ** same rules for counting changes.
626 static void changes(
627 sqlite3_context *context,
628 int NotUsed,
629 sqlite3_value **NotUsed2
631 sqlite3 *db = sqlite3_context_db_handle(context);
632 UNUSED_PARAMETER2(NotUsed, NotUsed2);
633 sqlite3_result_int64(context, sqlite3_changes64(db));
637 ** Implementation of the total_changes() SQL function. The return value is
638 ** the same as the sqlite3_total_changes64() API function.
640 static void total_changes(
641 sqlite3_context *context,
642 int NotUsed,
643 sqlite3_value **NotUsed2
645 sqlite3 *db = sqlite3_context_db_handle(context);
646 UNUSED_PARAMETER2(NotUsed, NotUsed2);
647 /* IMP: R-11217-42568 This function is a wrapper around the
648 ** sqlite3_total_changes64() C/C++ interface. */
649 sqlite3_result_int64(context, sqlite3_total_changes64(db));
653 ** A structure defining how to do GLOB-style comparisons.
655 struct compareInfo {
656 u8 matchAll; /* "*" or "%" */
657 u8 matchOne; /* "?" or "_" */
658 u8 matchSet; /* "[" or 0 */
659 u8 noCase; /* true to ignore case differences */
663 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
664 ** character is exactly one byte in size. Also, provide the Utf8Read()
665 ** macro for fast reading of the next character in the common case where
666 ** the next character is ASCII.
668 #if defined(SQLITE_EBCDIC)
669 # define sqlite3Utf8Read(A) (*((*A)++))
670 # define Utf8Read(A) (*(A++))
671 #else
672 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
673 #endif
675 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
676 /* The correct SQL-92 behavior is for the LIKE operator to ignore
677 ** case. Thus 'a' LIKE 'A' would be true. */
678 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
679 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
680 ** is case sensitive causing 'a' LIKE 'A' to be false */
681 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
684 ** Possible error returns from patternMatch()
686 #define SQLITE_MATCH 0
687 #define SQLITE_NOMATCH 1
688 #define SQLITE_NOWILDCARDMATCH 2
691 ** Compare two UTF-8 strings for equality where the first string is
692 ** a GLOB or LIKE expression. Return values:
694 ** SQLITE_MATCH: Match
695 ** SQLITE_NOMATCH: No match
696 ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
698 ** Globbing rules:
700 ** '*' Matches any sequence of zero or more characters.
702 ** '?' Matches exactly one character.
704 ** [...] Matches one character from the enclosed list of
705 ** characters.
707 ** [^...] Matches one character not in the enclosed list.
709 ** With the [...] and [^...] matching, a ']' character can be included
710 ** in the list by making it the first character after '[' or '^'. A
711 ** range of characters can be specified using '-'. Example:
712 ** "[a-z]" matches any single lower-case letter. To match a '-', make
713 ** it the last character in the list.
715 ** Like matching rules:
717 ** '%' Matches any sequence of zero or more characters
719 *** '_' Matches any one character
721 ** Ec Where E is the "esc" character and c is any other
722 ** character, including '%', '_', and esc, match exactly c.
724 ** The comments within this routine usually assume glob matching.
726 ** This routine is usually quick, but can be N**2 in the worst case.
728 static int patternCompare(
729 const u8 *zPattern, /* The glob pattern */
730 const u8 *zString, /* The string to compare against the glob */
731 const struct compareInfo *pInfo, /* Information about how to do the compare */
732 u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
734 u32 c, c2; /* Next pattern and input string chars */
735 u32 matchOne = pInfo->matchOne; /* "?" or "_" */
736 u32 matchAll = pInfo->matchAll; /* "*" or "%" */
737 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
738 const u8 *zEscaped = 0; /* One past the last escaped input char */
740 while( (c = Utf8Read(zPattern))!=0 ){
741 if( c==matchAll ){ /* Match "*" */
742 /* Skip over multiple "*" characters in the pattern. If there
743 ** are also "?" characters, skip those as well, but consume a
744 ** single character of the input string for each "?" skipped */
745 while( (c=Utf8Read(zPattern)) == matchAll
746 || (c == matchOne && matchOne!=0) ){
747 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
748 return SQLITE_NOWILDCARDMATCH;
751 if( c==0 ){
752 return SQLITE_MATCH; /* "*" at the end of the pattern matches */
753 }else if( c==matchOther ){
754 if( pInfo->matchSet==0 ){
755 c = sqlite3Utf8Read(&zPattern);
756 if( c==0 ) return SQLITE_NOWILDCARDMATCH;
757 }else{
758 /* "[...]" immediately follows the "*". We have to do a slow
759 ** recursive search in this case, but it is an unusual case. */
760 assert( matchOther<0x80 ); /* '[' is a single-byte character */
761 while( *zString ){
762 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
763 if( bMatch!=SQLITE_NOMATCH ) return bMatch;
764 SQLITE_SKIP_UTF8(zString);
766 return SQLITE_NOWILDCARDMATCH;
770 /* At this point variable c contains the first character of the
771 ** pattern string past the "*". Search in the input string for the
772 ** first matching character and recursively continue the match from
773 ** that point.
775 ** For a case-insensitive search, set variable cx to be the same as
776 ** c but in the other case and search the input string for either
777 ** c or cx.
779 if( c<0x80 ){
780 char zStop[3];
781 int bMatch;
782 if( noCase ){
783 zStop[0] = sqlite3Toupper(c);
784 zStop[1] = sqlite3Tolower(c);
785 zStop[2] = 0;
786 }else{
787 zStop[0] = c;
788 zStop[1] = 0;
790 while(1){
791 zString += strcspn((const char*)zString, zStop);
792 if( zString[0]==0 ) break;
793 zString++;
794 bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
795 if( bMatch!=SQLITE_NOMATCH ) return bMatch;
797 }else{
798 int bMatch;
799 while( (c2 = Utf8Read(zString))!=0 ){
800 if( c2!=c ) continue;
801 bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
802 if( bMatch!=SQLITE_NOMATCH ) return bMatch;
805 return SQLITE_NOWILDCARDMATCH;
807 if( c==matchOther ){
808 if( pInfo->matchSet==0 ){
809 c = sqlite3Utf8Read(&zPattern);
810 if( c==0 ) return SQLITE_NOMATCH;
811 zEscaped = zPattern;
812 }else{
813 u32 prior_c = 0;
814 int seen = 0;
815 int invert = 0;
816 c = sqlite3Utf8Read(&zString);
817 if( c==0 ) return SQLITE_NOMATCH;
818 c2 = sqlite3Utf8Read(&zPattern);
819 if( c2=='^' ){
820 invert = 1;
821 c2 = sqlite3Utf8Read(&zPattern);
823 if( c2==']' ){
824 if( c==']' ) seen = 1;
825 c2 = sqlite3Utf8Read(&zPattern);
827 while( c2 && c2!=']' ){
828 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
829 c2 = sqlite3Utf8Read(&zPattern);
830 if( c>=prior_c && c<=c2 ) seen = 1;
831 prior_c = 0;
832 }else{
833 if( c==c2 ){
834 seen = 1;
836 prior_c = c2;
838 c2 = sqlite3Utf8Read(&zPattern);
840 if( c2==0 || (seen ^ invert)==0 ){
841 return SQLITE_NOMATCH;
843 continue;
846 c2 = Utf8Read(zString);
847 if( c==c2 ) continue;
848 if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
849 continue;
851 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
852 return SQLITE_NOMATCH;
854 return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
858 ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
859 ** non-zero if there is no match.
861 int sqlite3_strglob(const char *zGlobPattern, const char *zString){
862 if( zString==0 ){
863 return zGlobPattern!=0;
864 }else if( zGlobPattern==0 ){
865 return 1;
866 }else {
867 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
872 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
873 ** a miss - like strcmp().
875 int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
876 if( zStr==0 ){
877 return zPattern!=0;
878 }else if( zPattern==0 ){
879 return 1;
880 }else{
881 return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
886 ** Count the number of times that the LIKE operator (or GLOB which is
887 ** just a variation of LIKE) gets called. This is used for testing
888 ** only.
890 #ifdef SQLITE_TEST
891 int sqlite3_like_count = 0;
892 #endif
896 ** Implementation of the like() SQL function. This function implements
897 ** the built-in LIKE operator. The first argument to the function is the
898 ** pattern and the second argument is the string. So, the SQL statements:
900 ** A LIKE B
902 ** is implemented as like(B,A).
904 ** This same function (with a different compareInfo structure) computes
905 ** the GLOB operator.
907 static void likeFunc(
908 sqlite3_context *context,
909 int argc,
910 sqlite3_value **argv
912 const unsigned char *zA, *zB;
913 u32 escape;
914 int nPat;
915 sqlite3 *db = sqlite3_context_db_handle(context);
916 struct compareInfo *pInfo = sqlite3_user_data(context);
917 struct compareInfo backupInfo;
919 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
920 if( sqlite3_value_type(argv[0])==SQLITE_BLOB
921 || sqlite3_value_type(argv[1])==SQLITE_BLOB
923 #ifdef SQLITE_TEST
924 sqlite3_like_count++;
925 #endif
926 sqlite3_result_int(context, 0);
927 return;
929 #endif
931 /* Limit the length of the LIKE or GLOB pattern to avoid problems
932 ** of deep recursion and N*N behavior in patternCompare().
934 nPat = sqlite3_value_bytes(argv[0]);
935 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
936 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
937 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
938 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
939 return;
941 if( argc==3 ){
942 /* The escape character string must consist of a single UTF-8 character.
943 ** Otherwise, return an error.
945 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
946 if( zEsc==0 ) return;
947 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
948 sqlite3_result_error(context,
949 "ESCAPE expression must be a single character", -1);
950 return;
952 escape = sqlite3Utf8Read(&zEsc);
953 if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
954 memcpy(&backupInfo, pInfo, sizeof(backupInfo));
955 pInfo = &backupInfo;
956 if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
957 if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
959 }else{
960 escape = pInfo->matchSet;
962 zB = sqlite3_value_text(argv[0]);
963 zA = sqlite3_value_text(argv[1]);
964 if( zA && zB ){
965 #ifdef SQLITE_TEST
966 sqlite3_like_count++;
967 #endif
968 sqlite3_result_int(context,
969 patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
974 ** Implementation of the NULLIF(x,y) function. The result is the first
975 ** argument if the arguments are different. The result is NULL if the
976 ** arguments are equal to each other.
978 static void nullifFunc(
979 sqlite3_context *context,
980 int NotUsed,
981 sqlite3_value **argv
983 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
984 UNUSED_PARAMETER(NotUsed);
985 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
986 sqlite3_result_value(context, argv[0]);
991 ** Implementation of the sqlite_version() function. The result is the version
992 ** of the SQLite library that is running.
994 static void versionFunc(
995 sqlite3_context *context,
996 int NotUsed,
997 sqlite3_value **NotUsed2
999 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1000 /* IMP: R-48699-48617 This function is an SQL wrapper around the
1001 ** sqlite3_libversion() C-interface. */
1002 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
1006 ** Implementation of the sqlite_source_id() function. The result is a string
1007 ** that identifies the particular version of the source code used to build
1008 ** SQLite.
1010 static void sourceidFunc(
1011 sqlite3_context *context,
1012 int NotUsed,
1013 sqlite3_value **NotUsed2
1015 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1016 /* IMP: R-24470-31136 This function is an SQL wrapper around the
1017 ** sqlite3_sourceid() C interface. */
1018 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
1022 ** Implementation of the sqlite_log() function. This is a wrapper around
1023 ** sqlite3_log(). The return value is NULL. The function exists purely for
1024 ** its side-effects.
1026 static void errlogFunc(
1027 sqlite3_context *context,
1028 int argc,
1029 sqlite3_value **argv
1031 UNUSED_PARAMETER(argc);
1032 UNUSED_PARAMETER(context);
1033 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
1037 ** Implementation of the sqlite_compileoption_used() function.
1038 ** The result is an integer that identifies if the compiler option
1039 ** was used to build SQLite.
1041 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1042 static void compileoptionusedFunc(
1043 sqlite3_context *context,
1044 int argc,
1045 sqlite3_value **argv
1047 const char *zOptName;
1048 assert( argc==1 );
1049 UNUSED_PARAMETER(argc);
1050 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
1051 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
1052 ** function.
1054 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
1055 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
1058 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1061 ** Implementation of the sqlite_compileoption_get() function.
1062 ** The result is a string that identifies the compiler options
1063 ** used to build SQLite.
1065 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1066 static void compileoptiongetFunc(
1067 sqlite3_context *context,
1068 int argc,
1069 sqlite3_value **argv
1071 int n;
1072 assert( argc==1 );
1073 UNUSED_PARAMETER(argc);
1074 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
1075 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
1077 n = sqlite3_value_int(argv[0]);
1078 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
1080 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1082 /* Array for converting from half-bytes (nybbles) into ASCII hex
1083 ** digits. */
1084 static const char hexdigits[] = {
1085 '0', '1', '2', '3', '4', '5', '6', '7',
1086 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
1090 ** Append to pStr text that is the SQL literal representation of the
1091 ** value contained in pValue.
1093 void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){
1094 /* As currently implemented, the string must be initially empty.
1095 ** we might relax this requirement in the future, but that will
1096 ** require enhancements to the implementation. */
1097 assert( pStr!=0 && pStr->nChar==0 );
1099 switch( sqlite3_value_type(pValue) ){
1100 case SQLITE_FLOAT: {
1101 double r1, r2;
1102 const char *zVal;
1103 r1 = sqlite3_value_double(pValue);
1104 sqlite3_str_appendf(pStr, "%!0.15g", r1);
1105 zVal = sqlite3_str_value(pStr);
1106 if( zVal ){
1107 sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8);
1108 if( r1!=r2 ){
1109 sqlite3_str_reset(pStr);
1110 sqlite3_str_appendf(pStr, "%!0.20e", r1);
1113 break;
1115 case SQLITE_INTEGER: {
1116 sqlite3_str_appendf(pStr, "%lld", sqlite3_value_int64(pValue));
1117 break;
1119 case SQLITE_BLOB: {
1120 char const *zBlob = sqlite3_value_blob(pValue);
1121 i64 nBlob = sqlite3_value_bytes(pValue);
1122 assert( zBlob==sqlite3_value_blob(pValue) ); /* No encoding change */
1123 sqlite3StrAccumEnlarge(pStr, nBlob*2 + 4);
1124 if( pStr->accError==0 ){
1125 char *zText = pStr->zText;
1126 int i;
1127 for(i=0; i<nBlob; i++){
1128 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
1129 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
1131 zText[(nBlob*2)+2] = '\'';
1132 zText[(nBlob*2)+3] = '\0';
1133 zText[0] = 'X';
1134 zText[1] = '\'';
1135 pStr->nChar = nBlob*2 + 3;
1137 break;
1139 case SQLITE_TEXT: {
1140 const unsigned char *zArg = sqlite3_value_text(pValue);
1141 sqlite3_str_appendf(pStr, "%Q", zArg);
1142 break;
1144 default: {
1145 assert( sqlite3_value_type(pValue)==SQLITE_NULL );
1146 sqlite3_str_append(pStr, "NULL", 4);
1147 break;
1153 ** Implementation of the QUOTE() function.
1155 ** The quote(X) function returns the text of an SQL literal which is the
1156 ** value of its argument suitable for inclusion into an SQL statement.
1157 ** Strings are surrounded by single-quotes with escapes on interior quotes
1158 ** as needed. BLOBs are encoded as hexadecimal literals. Strings with
1159 ** embedded NUL characters cannot be represented as string literals in SQL
1160 ** and hence the returned string literal is truncated prior to the first NUL.
1162 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1163 sqlite3_str str;
1164 sqlite3 *db = sqlite3_context_db_handle(context);
1165 assert( argc==1 );
1166 UNUSED_PARAMETER(argc);
1167 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
1168 sqlite3QuoteValue(&str,argv[0]);
1169 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
1170 SQLITE_DYNAMIC);
1171 if( str.accError!=SQLITE_OK ){
1172 sqlite3_result_null(context);
1173 sqlite3_result_error_code(context, str.accError);
1178 ** The unicode() function. Return the integer unicode code-point value
1179 ** for the first character of the input string.
1181 static void unicodeFunc(
1182 sqlite3_context *context,
1183 int argc,
1184 sqlite3_value **argv
1186 const unsigned char *z = sqlite3_value_text(argv[0]);
1187 (void)argc;
1188 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
1192 ** The char() function takes zero or more arguments, each of which is
1193 ** an integer. It constructs a string where each character of the string
1194 ** is the unicode character for the corresponding integer argument.
1196 static void charFunc(
1197 sqlite3_context *context,
1198 int argc,
1199 sqlite3_value **argv
1201 unsigned char *z, *zOut;
1202 int i;
1203 zOut = z = sqlite3_malloc64( argc*4+1 );
1204 if( z==0 ){
1205 sqlite3_result_error_nomem(context);
1206 return;
1208 for(i=0; i<argc; i++){
1209 sqlite3_int64 x;
1210 unsigned c;
1211 x = sqlite3_value_int64(argv[i]);
1212 if( x<0 || x>0x10ffff ) x = 0xfffd;
1213 c = (unsigned)(x & 0x1fffff);
1214 if( c<0x00080 ){
1215 *zOut++ = (u8)(c&0xFF);
1216 }else if( c<0x00800 ){
1217 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
1218 *zOut++ = 0x80 + (u8)(c & 0x3F);
1219 }else if( c<0x10000 ){
1220 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
1221 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1222 *zOut++ = 0x80 + (u8)(c & 0x3F);
1223 }else{
1224 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
1225 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
1226 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1227 *zOut++ = 0x80 + (u8)(c & 0x3F);
1230 *zOut = 0;
1231 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
1235 ** The hex() function. Interpret the argument as a blob. Return
1236 ** a hexadecimal rendering as text.
1238 static void hexFunc(
1239 sqlite3_context *context,
1240 int argc,
1241 sqlite3_value **argv
1243 int i, n;
1244 const unsigned char *pBlob;
1245 char *zHex, *z;
1246 assert( argc==1 );
1247 UNUSED_PARAMETER(argc);
1248 pBlob = sqlite3_value_blob(argv[0]);
1249 n = sqlite3_value_bytes(argv[0]);
1250 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
1251 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
1252 if( zHex ){
1253 for(i=0; i<n; i++, pBlob++){
1254 unsigned char c = *pBlob;
1255 *(z++) = hexdigits[(c>>4)&0xf];
1256 *(z++) = hexdigits[c&0xf];
1258 *z = 0;
1259 sqlite3_result_text64(context, zHex, (u64)(z-zHex),
1260 sqlite3_free, SQLITE_UTF8);
1265 ** Buffer zStr contains nStr bytes of utf-8 encoded text. Return 1 if zStr
1266 ** contains character ch, or 0 if it does not.
1268 static int strContainsChar(const u8 *zStr, int nStr, u32 ch){
1269 const u8 *zEnd = &zStr[nStr];
1270 const u8 *z = zStr;
1271 while( z<zEnd ){
1272 u32 tst = Utf8Read(z);
1273 if( tst==ch ) return 1;
1275 return 0;
1279 ** The unhex() function. This function may be invoked with either one or
1280 ** two arguments. In both cases the first argument is interpreted as text
1281 ** a text value containing a set of pairs of hexadecimal digits which are
1282 ** decoded and returned as a blob.
1284 ** If there is only a single argument, then it must consist only of an
1285 ** even number of hexadecimal digits. Otherwise, return NULL.
1287 ** Or, if there is a second argument, then any character that appears in
1288 ** the second argument is also allowed to appear between pairs of hexadecimal
1289 ** digits in the first argument. If any other character appears in the
1290 ** first argument, or if one of the allowed characters appears between
1291 ** two hexadecimal digits that make up a single byte, NULL is returned.
1293 ** The following expressions are all true:
1295 ** unhex('ABCD') IS x'ABCD'
1296 ** unhex('AB CD') IS NULL
1297 ** unhex('AB CD', ' ') IS x'ABCD'
1298 ** unhex('A BCD', ' ') IS NULL
1300 static void unhexFunc(
1301 sqlite3_context *pCtx,
1302 int argc,
1303 sqlite3_value **argv
1305 const u8 *zPass = (const u8*)"";
1306 int nPass = 0;
1307 const u8 *zHex = sqlite3_value_text(argv[0]);
1308 int nHex = sqlite3_value_bytes(argv[0]);
1309 #ifdef SQLITE_DEBUG
1310 const u8 *zEnd = zHex ? &zHex[nHex] : 0;
1311 #endif
1312 u8 *pBlob = 0;
1313 u8 *p = 0;
1315 assert( argc==1 || argc==2 );
1316 if( argc==2 ){
1317 zPass = sqlite3_value_text(argv[1]);
1318 nPass = sqlite3_value_bytes(argv[1]);
1320 if( !zHex || !zPass ) return;
1322 p = pBlob = contextMalloc(pCtx, (nHex/2)+1);
1323 if( pBlob ){
1324 u8 c; /* Most significant digit of next byte */
1325 u8 d; /* Least significant digit of next byte */
1327 while( (c = *zHex)!=0x00 ){
1328 while( !sqlite3Isxdigit(c) ){
1329 u32 ch = Utf8Read(zHex);
1330 assert( zHex<=zEnd );
1331 if( !strContainsChar(zPass, nPass, ch) ) goto unhex_null;
1332 c = *zHex;
1333 if( c==0x00 ) goto unhex_done;
1335 zHex++;
1336 assert( *zEnd==0x00 );
1337 assert( zHex<=zEnd );
1338 d = *(zHex++);
1339 if( !sqlite3Isxdigit(d) ) goto unhex_null;
1340 *(p++) = (sqlite3HexToInt(c)<<4) | sqlite3HexToInt(d);
1344 unhex_done:
1345 sqlite3_result_blob(pCtx, pBlob, (p - pBlob), sqlite3_free);
1346 return;
1348 unhex_null:
1349 sqlite3_free(pBlob);
1350 return;
1355 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
1357 static void zeroblobFunc(
1358 sqlite3_context *context,
1359 int argc,
1360 sqlite3_value **argv
1362 i64 n;
1363 int rc;
1364 assert( argc==1 );
1365 UNUSED_PARAMETER(argc);
1366 n = sqlite3_value_int64(argv[0]);
1367 if( n<0 ) n = 0;
1368 rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
1369 if( rc ){
1370 sqlite3_result_error_code(context, rc);
1375 ** The replace() function. Three arguments are all strings: call
1376 ** them A, B, and C. The result is also a string which is derived
1377 ** from A by replacing every occurrence of B with C. The match
1378 ** must be exact. Collating sequences are not used.
1380 static void replaceFunc(
1381 sqlite3_context *context,
1382 int argc,
1383 sqlite3_value **argv
1385 const unsigned char *zStr; /* The input string A */
1386 const unsigned char *zPattern; /* The pattern string B */
1387 const unsigned char *zRep; /* The replacement string C */
1388 unsigned char *zOut; /* The output */
1389 int nStr; /* Size of zStr */
1390 int nPattern; /* Size of zPattern */
1391 int nRep; /* Size of zRep */
1392 i64 nOut; /* Maximum size of zOut */
1393 int loopLimit; /* Last zStr[] that might match zPattern[] */
1394 int i, j; /* Loop counters */
1395 unsigned cntExpand; /* Number zOut expansions */
1396 sqlite3 *db = sqlite3_context_db_handle(context);
1398 assert( argc==3 );
1399 UNUSED_PARAMETER(argc);
1400 zStr = sqlite3_value_text(argv[0]);
1401 if( zStr==0 ) return;
1402 nStr = sqlite3_value_bytes(argv[0]);
1403 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
1404 zPattern = sqlite3_value_text(argv[1]);
1405 if( zPattern==0 ){
1406 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
1407 || sqlite3_context_db_handle(context)->mallocFailed );
1408 return;
1410 if( zPattern[0]==0 ){
1411 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
1412 sqlite3_result_text(context, (const char*)zStr, nStr, SQLITE_TRANSIENT);
1413 return;
1415 nPattern = sqlite3_value_bytes(argv[1]);
1416 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
1417 zRep = sqlite3_value_text(argv[2]);
1418 if( zRep==0 ) return;
1419 nRep = sqlite3_value_bytes(argv[2]);
1420 assert( zRep==sqlite3_value_text(argv[2]) );
1421 nOut = nStr + 1;
1422 assert( nOut<SQLITE_MAX_LENGTH );
1423 zOut = contextMalloc(context, (i64)nOut);
1424 if( zOut==0 ){
1425 return;
1427 loopLimit = nStr - nPattern;
1428 cntExpand = 0;
1429 for(i=j=0; i<=loopLimit; i++){
1430 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
1431 zOut[j++] = zStr[i];
1432 }else{
1433 if( nRep>nPattern ){
1434 nOut += nRep - nPattern;
1435 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
1436 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
1437 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1438 sqlite3_result_error_toobig(context);
1439 sqlite3_free(zOut);
1440 return;
1442 cntExpand++;
1443 if( (cntExpand&(cntExpand-1))==0 ){
1444 /* Grow the size of the output buffer only on substitutions
1445 ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
1446 u8 *zOld;
1447 zOld = zOut;
1448 zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));
1449 if( zOut==0 ){
1450 sqlite3_result_error_nomem(context);
1451 sqlite3_free(zOld);
1452 return;
1456 memcpy(&zOut[j], zRep, nRep);
1457 j += nRep;
1458 i += nPattern-1;
1461 assert( j+nStr-i+1<=nOut );
1462 memcpy(&zOut[j], &zStr[i], nStr-i);
1463 j += nStr - i;
1464 assert( j<=nOut );
1465 zOut[j] = 0;
1466 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
1470 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
1471 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
1473 static void trimFunc(
1474 sqlite3_context *context,
1475 int argc,
1476 sqlite3_value **argv
1478 const unsigned char *zIn; /* Input string */
1479 const unsigned char *zCharSet; /* Set of characters to trim */
1480 unsigned int nIn; /* Number of bytes in input */
1481 int flags; /* 1: trimleft 2: trimright 3: trim */
1482 int i; /* Loop counter */
1483 unsigned int *aLen = 0; /* Length of each character in zCharSet */
1484 unsigned char **azChar = 0; /* Individual characters in zCharSet */
1485 int nChar; /* Number of characters in zCharSet */
1487 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1488 return;
1490 zIn = sqlite3_value_text(argv[0]);
1491 if( zIn==0 ) return;
1492 nIn = (unsigned)sqlite3_value_bytes(argv[0]);
1493 assert( zIn==sqlite3_value_text(argv[0]) );
1494 if( argc==1 ){
1495 static const unsigned lenOne[] = { 1 };
1496 static unsigned char * const azOne[] = { (u8*)" " };
1497 nChar = 1;
1498 aLen = (unsigned*)lenOne;
1499 azChar = (unsigned char **)azOne;
1500 zCharSet = 0;
1501 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
1502 return;
1503 }else{
1504 const unsigned char *z;
1505 for(z=zCharSet, nChar=0; *z; nChar++){
1506 SQLITE_SKIP_UTF8(z);
1508 if( nChar>0 ){
1509 azChar = contextMalloc(context,
1510 ((i64)nChar)*(sizeof(char*)+sizeof(unsigned)));
1511 if( azChar==0 ){
1512 return;
1514 aLen = (unsigned*)&azChar[nChar];
1515 for(z=zCharSet, nChar=0; *z; nChar++){
1516 azChar[nChar] = (unsigned char *)z;
1517 SQLITE_SKIP_UTF8(z);
1518 aLen[nChar] = (unsigned)(z - azChar[nChar]);
1522 if( nChar>0 ){
1523 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
1524 if( flags & 1 ){
1525 while( nIn>0 ){
1526 unsigned int len = 0;
1527 for(i=0; i<nChar; i++){
1528 len = aLen[i];
1529 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
1531 if( i>=nChar ) break;
1532 zIn += len;
1533 nIn -= len;
1536 if( flags & 2 ){
1537 while( nIn>0 ){
1538 unsigned int len = 0;
1539 for(i=0; i<nChar; i++){
1540 len = aLen[i];
1541 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
1543 if( i>=nChar ) break;
1544 nIn -= len;
1547 if( zCharSet ){
1548 sqlite3_free(azChar);
1551 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
1554 /* The core implementation of the CONCAT(...) and CONCAT_WS(SEP,...)
1555 ** functions.
1557 ** Return a string value that is the concatenation of all non-null
1558 ** entries in argv[]. Use zSep as the separator.
1560 static void concatFuncCore(
1561 sqlite3_context *context,
1562 int argc,
1563 sqlite3_value **argv,
1564 int nSep,
1565 const char *zSep
1567 i64 j, k, n = 0;
1568 int i;
1569 char *z;
1570 for(i=0; i<argc; i++){
1571 n += sqlite3_value_bytes(argv[i]);
1573 n += (argc-1)*nSep;
1574 z = sqlite3_malloc64(n+1);
1575 if( z==0 ){
1576 sqlite3_result_error_nomem(context);
1577 return;
1579 j = 0;
1580 for(i=0; i<argc; i++){
1581 k = sqlite3_value_bytes(argv[i]);
1582 if( k>0 ){
1583 const char *v = (const char*)sqlite3_value_text(argv[i]);
1584 if( v!=0 ){
1585 if( j>0 && nSep>0 ){
1586 memcpy(&z[j], zSep, nSep);
1587 j += nSep;
1589 memcpy(&z[j], v, k);
1590 j += k;
1594 z[j] = 0;
1595 assert( j<=n );
1596 sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8);
1600 ** The CONCAT(...) function. Generate a string result that is the
1601 ** concatentation of all non-null arguments.
1603 static void concatFunc(
1604 sqlite3_context *context,
1605 int argc,
1606 sqlite3_value **argv
1608 concatFuncCore(context, argc, argv, 0, "");
1612 ** The CONCAT_WS(separator, ...) function.
1614 ** Generate a string that is the concatenation of 2nd through the Nth
1615 ** argument. Use the first argument (which must be non-NULL) as the
1616 ** separator.
1618 static void concatwsFunc(
1619 sqlite3_context *context,
1620 int argc,
1621 sqlite3_value **argv
1623 int nSep = sqlite3_value_bytes(argv[0]);
1624 const char *zSep = (const char*)sqlite3_value_text(argv[0]);
1625 if( zSep==0 ) return;
1626 concatFuncCore(context, argc-1, argv+1, nSep, zSep);
1630 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1632 ** The "unknown" function is automatically substituted in place of
1633 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
1634 ** when the SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION compile-time option is used.
1635 ** When the "sqlite3" command-line shell is built using this functionality,
1636 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
1637 ** involving application-defined functions to be examined in a generic
1638 ** sqlite3 shell.
1640 static void unknownFunc(
1641 sqlite3_context *context,
1642 int argc,
1643 sqlite3_value **argv
1645 /* no-op */
1646 (void)context;
1647 (void)argc;
1648 (void)argv;
1650 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
1653 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
1654 ** is only available if the SQLITE_SOUNDEX compile-time option is used
1655 ** when SQLite is built.
1657 #ifdef SQLITE_SOUNDEX
1659 ** Compute the soundex encoding of a word.
1661 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
1662 ** soundex encoding of the string X.
1664 static void soundexFunc(
1665 sqlite3_context *context,
1666 int argc,
1667 sqlite3_value **argv
1669 char zResult[8];
1670 const u8 *zIn;
1671 int i, j;
1672 static const unsigned char iCode[] = {
1673 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1674 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1675 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1676 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1677 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1678 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1679 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1680 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1682 assert( argc==1 );
1683 zIn = (u8*)sqlite3_value_text(argv[0]);
1684 if( zIn==0 ) zIn = (u8*)"";
1685 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
1686 if( zIn[i] ){
1687 u8 prevcode = iCode[zIn[i]&0x7f];
1688 zResult[0] = sqlite3Toupper(zIn[i]);
1689 for(j=1; j<4 && zIn[i]; i++){
1690 int code = iCode[zIn[i]&0x7f];
1691 if( code>0 ){
1692 if( code!=prevcode ){
1693 prevcode = code;
1694 zResult[j++] = code + '0';
1696 }else{
1697 prevcode = 0;
1700 while( j<4 ){
1701 zResult[j++] = '0';
1703 zResult[j] = 0;
1704 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
1705 }else{
1706 /* IMP: R-64894-50321 The string "?000" is returned if the argument
1707 ** is NULL or contains no ASCII alphabetic characters. */
1708 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
1711 #endif /* SQLITE_SOUNDEX */
1713 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1715 ** A function that loads a shared-library extension then returns NULL.
1717 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
1718 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
1719 const char *zProc;
1720 sqlite3 *db = sqlite3_context_db_handle(context);
1721 char *zErrMsg = 0;
1723 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
1724 ** flag is set. See the sqlite3_enable_load_extension() API.
1726 if( (db->flags & SQLITE_LoadExtFunc)==0 ){
1727 sqlite3_result_error(context, "not authorized", -1);
1728 return;
1731 if( argc==2 ){
1732 zProc = (const char *)sqlite3_value_text(argv[1]);
1733 }else{
1734 zProc = 0;
1736 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
1737 sqlite3_result_error(context, zErrMsg, -1);
1738 sqlite3_free(zErrMsg);
1741 #endif
1745 ** An instance of the following structure holds the context of a
1746 ** sum() or avg() aggregate computation.
1748 typedef struct SumCtx SumCtx;
1749 struct SumCtx {
1750 double rSum; /* Running sum as as a double */
1751 double rErr; /* Error term for Kahan-Babushka-Neumaier summation */
1752 i64 iSum; /* Running sum as a signed integer */
1753 i64 cnt; /* Number of elements summed */
1754 u8 approx; /* True if any non-integer value was input to the sum */
1755 u8 ovrfl; /* Integer overflow seen */
1759 ** Do one step of the Kahan-Babushka-Neumaier summation.
1761 ** https://en.wikipedia.org/wiki/Kahan_summation_algorithm
1763 ** Variables are marked "volatile" to defeat c89 x86 floating point
1764 ** optimizations can mess up this algorithm.
1766 static void kahanBabuskaNeumaierStep(
1767 volatile SumCtx *pSum,
1768 volatile double r
1770 volatile double s = pSum->rSum;
1771 volatile double t = s + r;
1772 if( fabs(s) > fabs(r) ){
1773 pSum->rErr += (s - t) + r;
1774 }else{
1775 pSum->rErr += (r - t) + s;
1777 pSum->rSum = t;
1781 ** Add a (possibly large) integer to the running sum.
1783 static void kahanBabuskaNeumaierStepInt64(volatile SumCtx *pSum, i64 iVal){
1784 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){
1785 i64 iBig, iSm;
1786 iSm = iVal % 16384;
1787 iBig = iVal - iSm;
1788 kahanBabuskaNeumaierStep(pSum, iBig);
1789 kahanBabuskaNeumaierStep(pSum, iSm);
1790 }else{
1791 kahanBabuskaNeumaierStep(pSum, (double)iVal);
1796 ** Initialize the Kahan-Babaska-Neumaier sum from a 64-bit integer
1798 static void kahanBabuskaNeumaierInit(
1799 volatile SumCtx *p,
1800 i64 iVal
1802 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){
1803 i64 iSm = iVal % 16384;
1804 p->rSum = (double)(iVal - iSm);
1805 p->rErr = (double)iSm;
1806 }else{
1807 p->rSum = (double)iVal;
1808 p->rErr = 0.0;
1813 ** Routines used to compute the sum, average, and total.
1815 ** The SUM() function follows the (broken) SQL standard which means
1816 ** that it returns NULL if it sums over no inputs. TOTAL returns
1817 ** 0.0 in that case. In addition, TOTAL always returns a float where
1818 ** SUM might return an integer if it never encounters a floating point
1819 ** value. TOTAL never fails, but SUM might through an exception if
1820 ** it overflows an integer.
1822 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1823 SumCtx *p;
1824 int type;
1825 assert( argc==1 );
1826 UNUSED_PARAMETER(argc);
1827 p = sqlite3_aggregate_context(context, sizeof(*p));
1828 type = sqlite3_value_numeric_type(argv[0]);
1829 if( p && type!=SQLITE_NULL ){
1830 p->cnt++;
1831 if( p->approx==0 ){
1832 if( type!=SQLITE_INTEGER ){
1833 kahanBabuskaNeumaierInit(p, p->iSum);
1834 p->approx = 1;
1835 kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0]));
1836 }else{
1837 i64 x = p->iSum;
1838 if( sqlite3AddInt64(&x, sqlite3_value_int64(argv[0]))==0 ){
1839 p->iSum = x;
1840 }else{
1841 p->ovrfl = 1;
1842 kahanBabuskaNeumaierInit(p, p->iSum);
1843 p->approx = 1;
1844 kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0]));
1847 }else{
1848 if( type==SQLITE_INTEGER ){
1849 kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0]));
1850 }else{
1851 p->ovrfl = 0;
1852 kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0]));
1857 #ifndef SQLITE_OMIT_WINDOWFUNC
1858 static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
1859 SumCtx *p;
1860 int type;
1861 assert( argc==1 );
1862 UNUSED_PARAMETER(argc);
1863 p = sqlite3_aggregate_context(context, sizeof(*p));
1864 type = sqlite3_value_numeric_type(argv[0]);
1865 /* p is always non-NULL because sumStep() will have been called first
1866 ** to initialize it */
1867 if( ALWAYS(p) && type!=SQLITE_NULL ){
1868 assert( p->cnt>0 );
1869 p->cnt--;
1870 if( !p->approx ){
1871 p->iSum -= sqlite3_value_int64(argv[0]);
1872 }else if( type==SQLITE_INTEGER ){
1873 i64 iVal = sqlite3_value_int64(argv[0]);
1874 if( iVal!=SMALLEST_INT64 ){
1875 kahanBabuskaNeumaierStepInt64(p, -iVal);
1876 }else{
1877 kahanBabuskaNeumaierStepInt64(p, LARGEST_INT64);
1878 kahanBabuskaNeumaierStepInt64(p, 1);
1880 }else{
1881 kahanBabuskaNeumaierStep(p, -sqlite3_value_double(argv[0]));
1885 #else
1886 # define sumInverse 0
1887 #endif /* SQLITE_OMIT_WINDOWFUNC */
1888 static void sumFinalize(sqlite3_context *context){
1889 SumCtx *p;
1890 p = sqlite3_aggregate_context(context, 0);
1891 if( p && p->cnt>0 ){
1892 if( p->approx ){
1893 if( p->ovrfl ){
1894 sqlite3_result_error(context,"integer overflow",-1);
1895 }else if( !sqlite3IsOverflow(p->rErr) ){
1896 sqlite3_result_double(context, p->rSum+p->rErr);
1897 }else{
1898 sqlite3_result_double(context, p->rSum);
1900 }else{
1901 sqlite3_result_int64(context, p->iSum);
1905 static void avgFinalize(sqlite3_context *context){
1906 SumCtx *p;
1907 p = sqlite3_aggregate_context(context, 0);
1908 if( p && p->cnt>0 ){
1909 double r;
1910 if( p->approx ){
1911 r = p->rSum;
1912 if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr;
1913 }else{
1914 r = (double)(p->iSum);
1916 sqlite3_result_double(context, r/(double)p->cnt);
1919 static void totalFinalize(sqlite3_context *context){
1920 SumCtx *p;
1921 double r = 0.0;
1922 p = sqlite3_aggregate_context(context, 0);
1923 if( p ){
1924 if( p->approx ){
1925 r = p->rSum;
1926 if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr;
1927 }else{
1928 r = (double)(p->iSum);
1931 sqlite3_result_double(context, r);
1935 ** The following structure keeps track of state information for the
1936 ** count() aggregate function.
1938 typedef struct CountCtx CountCtx;
1939 struct CountCtx {
1940 i64 n;
1941 #ifdef SQLITE_DEBUG
1942 int bInverse; /* True if xInverse() ever called */
1943 #endif
1947 ** Routines to implement the count() aggregate function.
1949 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1950 CountCtx *p;
1951 p = sqlite3_aggregate_context(context, sizeof(*p));
1952 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
1953 p->n++;
1956 #ifndef SQLITE_OMIT_DEPRECATED
1957 /* The sqlite3_aggregate_count() function is deprecated. But just to make
1958 ** sure it still operates correctly, verify that its count agrees with our
1959 ** internal count when using count(*) and when the total count can be
1960 ** expressed as a 32-bit integer. */
1961 assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
1962 || p->n==sqlite3_aggregate_count(context) );
1963 #endif
1965 static void countFinalize(sqlite3_context *context){
1966 CountCtx *p;
1967 p = sqlite3_aggregate_context(context, 0);
1968 sqlite3_result_int64(context, p ? p->n : 0);
1970 #ifndef SQLITE_OMIT_WINDOWFUNC
1971 static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
1972 CountCtx *p;
1973 p = sqlite3_aggregate_context(ctx, sizeof(*p));
1974 /* p is always non-NULL since countStep() will have been called first */
1975 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
1976 p->n--;
1977 #ifdef SQLITE_DEBUG
1978 p->bInverse = 1;
1979 #endif
1982 #else
1983 # define countInverse 0
1984 #endif /* SQLITE_OMIT_WINDOWFUNC */
1987 ** Routines to implement min() and max() aggregate functions.
1989 static void minmaxStep(
1990 sqlite3_context *context,
1991 int NotUsed,
1992 sqlite3_value **argv
1994 Mem *pArg = (Mem *)argv[0];
1995 Mem *pBest;
1996 UNUSED_PARAMETER(NotUsed);
1998 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
1999 if( !pBest ) return;
2001 if( sqlite3_value_type(pArg)==SQLITE_NULL ){
2002 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
2003 }else if( pBest->flags ){
2004 int max;
2005 int cmp;
2006 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
2007 /* This step function is used for both the min() and max() aggregates,
2008 ** the only difference between the two being that the sense of the
2009 ** comparison is inverted. For the max() aggregate, the
2010 ** sqlite3_user_data() function returns (void *)-1. For min() it
2011 ** returns (void *)db, where db is the sqlite3* database pointer.
2012 ** Therefore the next statement sets variable 'max' to 1 for the max()
2013 ** aggregate, or 0 for min().
2015 max = sqlite3_user_data(context)!=0;
2016 cmp = sqlite3MemCompare(pBest, pArg, pColl);
2017 if( (max && cmp<0) || (!max && cmp>0) ){
2018 sqlite3VdbeMemCopy(pBest, pArg);
2019 }else{
2020 sqlite3SkipAccumulatorLoad(context);
2022 }else{
2023 pBest->db = sqlite3_context_db_handle(context);
2024 sqlite3VdbeMemCopy(pBest, pArg);
2027 static void minMaxValueFinalize(sqlite3_context *context, int bValue){
2028 sqlite3_value *pRes;
2029 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
2030 if( pRes ){
2031 if( pRes->flags ){
2032 sqlite3_result_value(context, pRes);
2034 if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
2037 #ifndef SQLITE_OMIT_WINDOWFUNC
2038 static void minMaxValue(sqlite3_context *context){
2039 minMaxValueFinalize(context, 1);
2041 #else
2042 # define minMaxValue 0
2043 #endif /* SQLITE_OMIT_WINDOWFUNC */
2044 static void minMaxFinalize(sqlite3_context *context){
2045 minMaxValueFinalize(context, 0);
2049 ** group_concat(EXPR, ?SEPARATOR?)
2050 ** string_agg(EXPR, SEPARATOR)
2052 ** The SEPARATOR goes before the EXPR string. This is tragic. The
2053 ** groupConcatInverse() implementation would have been easier if the
2054 ** SEPARATOR were appended after EXPR. And the order is undocumented,
2055 ** so we could change it, in theory. But the old behavior has been
2056 ** around for so long that we dare not, for fear of breaking something.
2058 typedef struct {
2059 StrAccum str; /* The accumulated concatenation */
2060 #ifndef SQLITE_OMIT_WINDOWFUNC
2061 int nAccum; /* Number of strings presently concatenated */
2062 int nFirstSepLength; /* Used to detect separator length change */
2063 /* If pnSepLengths!=0, refs an array of inter-string separator lengths,
2064 ** stored as actually incorporated into presently accumulated result.
2065 ** (Hence, its slots in use number nAccum-1 between method calls.)
2066 ** If pnSepLengths==0, nFirstSepLength is the length used throughout.
2068 int *pnSepLengths;
2069 #endif
2070 } GroupConcatCtx;
2072 static void groupConcatStep(
2073 sqlite3_context *context,
2074 int argc,
2075 sqlite3_value **argv
2077 const char *zVal;
2078 GroupConcatCtx *pGCC;
2079 const char *zSep;
2080 int nVal, nSep;
2081 assert( argc==1 || argc==2 );
2082 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2083 pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
2084 if( pGCC ){
2085 sqlite3 *db = sqlite3_context_db_handle(context);
2086 int firstTerm = pGCC->str.mxAlloc==0;
2087 pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
2088 if( argc==1 ){
2089 if( !firstTerm ){
2090 sqlite3_str_appendchar(&pGCC->str, 1, ',');
2092 #ifndef SQLITE_OMIT_WINDOWFUNC
2093 else{
2094 pGCC->nFirstSepLength = 1;
2096 #endif
2097 }else if( !firstTerm ){
2098 zSep = (char*)sqlite3_value_text(argv[1]);
2099 nSep = sqlite3_value_bytes(argv[1]);
2100 if( zSep ){
2101 sqlite3_str_append(&pGCC->str, zSep, nSep);
2103 #ifndef SQLITE_OMIT_WINDOWFUNC
2104 else{
2105 nSep = 0;
2107 if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){
2108 int *pnsl = pGCC->pnSepLengths;
2109 if( pnsl == 0 ){
2110 /* First separator length variation seen, start tracking them. */
2111 pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int));
2112 if( pnsl!=0 ){
2113 int i = 0, nA = pGCC->nAccum-1;
2114 while( i<nA ) pnsl[i++] = pGCC->nFirstSepLength;
2116 }else{
2117 pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int));
2119 if( pnsl!=0 ){
2120 if( ALWAYS(pGCC->nAccum>0) ){
2121 pnsl[pGCC->nAccum-1] = nSep;
2123 pGCC->pnSepLengths = pnsl;
2124 }else{
2125 sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM);
2128 #endif
2130 #ifndef SQLITE_OMIT_WINDOWFUNC
2131 else{
2132 pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]);
2134 pGCC->nAccum += 1;
2135 #endif
2136 zVal = (char*)sqlite3_value_text(argv[0]);
2137 nVal = sqlite3_value_bytes(argv[0]);
2138 if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal);
2142 #ifndef SQLITE_OMIT_WINDOWFUNC
2143 static void groupConcatInverse(
2144 sqlite3_context *context,
2145 int argc,
2146 sqlite3_value **argv
2148 GroupConcatCtx *pGCC;
2149 assert( argc==1 || argc==2 );
2150 (void)argc; /* Suppress unused parameter warning */
2151 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2152 pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
2153 /* pGCC is always non-NULL since groupConcatStep() will have always
2154 ** run first to initialize it */
2155 if( ALWAYS(pGCC) ){
2156 int nVS;
2157 /* Must call sqlite3_value_text() to convert the argument into text prior
2158 ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */
2159 (void)sqlite3_value_text(argv[0]);
2160 nVS = sqlite3_value_bytes(argv[0]);
2161 pGCC->nAccum -= 1;
2162 if( pGCC->pnSepLengths!=0 ){
2163 assert(pGCC->nAccum >= 0);
2164 if( pGCC->nAccum>0 ){
2165 nVS += *pGCC->pnSepLengths;
2166 memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1,
2167 (pGCC->nAccum-1)*sizeof(int));
2169 }else{
2170 /* If removing single accumulated string, harmlessly over-do. */
2171 nVS += pGCC->nFirstSepLength;
2173 if( nVS>=(int)pGCC->str.nChar ){
2174 pGCC->str.nChar = 0;
2175 }else{
2176 pGCC->str.nChar -= nVS;
2177 memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar);
2179 if( pGCC->str.nChar==0 ){
2180 pGCC->str.mxAlloc = 0;
2181 sqlite3_free(pGCC->pnSepLengths);
2182 pGCC->pnSepLengths = 0;
2186 #else
2187 # define groupConcatInverse 0
2188 #endif /* SQLITE_OMIT_WINDOWFUNC */
2189 static void groupConcatFinalize(sqlite3_context *context){
2190 GroupConcatCtx *pGCC
2191 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
2192 if( pGCC ){
2193 sqlite3ResultStrAccum(context, &pGCC->str);
2194 #ifndef SQLITE_OMIT_WINDOWFUNC
2195 sqlite3_free(pGCC->pnSepLengths);
2196 #endif
2199 #ifndef SQLITE_OMIT_WINDOWFUNC
2200 static void groupConcatValue(sqlite3_context *context){
2201 GroupConcatCtx *pGCC
2202 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
2203 if( pGCC ){
2204 StrAccum *pAccum = &pGCC->str;
2205 if( pAccum->accError==SQLITE_TOOBIG ){
2206 sqlite3_result_error_toobig(context);
2207 }else if( pAccum->accError==SQLITE_NOMEM ){
2208 sqlite3_result_error_nomem(context);
2209 }else{
2210 const char *zText = sqlite3_str_value(pAccum);
2211 sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
2215 #else
2216 # define groupConcatValue 0
2217 #endif /* SQLITE_OMIT_WINDOWFUNC */
2220 ** This routine does per-connection function registration. Most
2221 ** of the built-in functions above are part of the global function set.
2222 ** This routine only deals with those that are not global.
2224 void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
2225 int rc = sqlite3_overload_function(db, "MATCH", 2);
2226 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
2227 if( rc==SQLITE_NOMEM ){
2228 sqlite3OomFault(db);
2233 ** Re-register the built-in LIKE functions. The caseSensitive
2234 ** parameter determines whether or not the LIKE operator is case
2235 ** sensitive.
2237 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
2238 FuncDef *pDef;
2239 struct compareInfo *pInfo;
2240 int flags;
2241 int nArg;
2242 if( caseSensitive ){
2243 pInfo = (struct compareInfo*)&likeInfoAlt;
2244 flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE;
2245 }else{
2246 pInfo = (struct compareInfo*)&likeInfoNorm;
2247 flags = SQLITE_FUNC_LIKE;
2249 for(nArg=2; nArg<=3; nArg++){
2250 sqlite3CreateFunc(db, "like", nArg, SQLITE_UTF8, pInfo, likeFunc,
2251 0, 0, 0, 0, 0);
2252 pDef = sqlite3FindFunction(db, "like", nArg, SQLITE_UTF8, 0);
2253 pDef->funcFlags |= flags;
2254 pDef->funcFlags &= ~SQLITE_FUNC_UNSAFE;
2259 ** pExpr points to an expression which implements a function. If
2260 ** it is appropriate to apply the LIKE optimization to that function
2261 ** then set aWc[0] through aWc[2] to the wildcard characters and the
2262 ** escape character and then return TRUE. If the function is not a
2263 ** LIKE-style function then return FALSE.
2265 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
2266 ** operator if c is a string literal that is exactly one byte in length.
2267 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
2268 ** no ESCAPE clause.
2270 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
2271 ** the function (default for LIKE). If the function makes the distinction
2272 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
2273 ** false.
2275 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
2276 FuncDef *pDef;
2277 int nExpr;
2278 assert( pExpr!=0 );
2279 assert( pExpr->op==TK_FUNCTION );
2280 assert( ExprUseXList(pExpr) );
2281 if( !pExpr->x.pList ){
2282 return 0;
2284 nExpr = pExpr->x.pList->nExpr;
2285 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2286 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
2287 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
2288 if( pDef==0 ) return 0;
2289 #endif
2290 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
2291 return 0;
2294 /* The memcpy() statement assumes that the wildcard characters are
2295 ** the first three statements in the compareInfo structure. The
2296 ** asserts() that follow verify that assumption
2298 memcpy(aWc, pDef->pUserData, 3);
2299 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
2300 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
2301 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
2303 if( nExpr<3 ){
2304 aWc[3] = 0;
2305 }else{
2306 Expr *pEscape = pExpr->x.pList->a[2].pExpr;
2307 char *zEscape;
2308 if( pEscape->op!=TK_STRING ) return 0;
2309 assert( !ExprHasProperty(pEscape, EP_IntValue) );
2310 zEscape = pEscape->u.zToken;
2311 if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
2312 if( zEscape[0]==aWc[0] ) return 0;
2313 if( zEscape[0]==aWc[1] ) return 0;
2314 aWc[3] = zEscape[0];
2317 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
2318 return 1;
2321 /* Mathematical Constants */
2322 #ifndef M_PI
2323 # define M_PI 3.141592653589793238462643383279502884
2324 #endif
2325 #ifndef M_LN10
2326 # define M_LN10 2.302585092994045684017991454684364208
2327 #endif
2328 #ifndef M_LN2
2329 # define M_LN2 0.693147180559945309417232121458176568
2330 #endif
2333 /* Extra math functions that require linking with -lm
2335 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
2337 ** Implementation SQL functions:
2339 ** ceil(X)
2340 ** ceiling(X)
2341 ** floor(X)
2343 ** The sqlite3_user_data() pointer is a pointer to the libm implementation
2344 ** of the underlying C function.
2346 static void ceilingFunc(
2347 sqlite3_context *context,
2348 int argc,
2349 sqlite3_value **argv
2351 assert( argc==1 );
2352 switch( sqlite3_value_numeric_type(argv[0]) ){
2353 case SQLITE_INTEGER: {
2354 sqlite3_result_int64(context, sqlite3_value_int64(argv[0]));
2355 break;
2357 case SQLITE_FLOAT: {
2358 double (*x)(double) = (double(*)(double))sqlite3_user_data(context);
2359 sqlite3_result_double(context, x(sqlite3_value_double(argv[0])));
2360 break;
2362 default: {
2363 break;
2369 ** On some systems, ceil() and floor() are intrinsic function. You are
2370 ** unable to take a pointer to these functions. Hence, we here wrap them
2371 ** in our own actual functions.
2373 static double xCeil(double x){ return ceil(x); }
2374 static double xFloor(double x){ return floor(x); }
2377 ** Some systems do not have log2() and log10() in their standard math
2378 ** libraries.
2380 #if defined(HAVE_LOG10) && HAVE_LOG10==0
2381 # define log10(X) (0.4342944819032517867*log(X))
2382 #endif
2383 #if defined(HAVE_LOG2) && HAVE_LOG2==0
2384 # define log2(X) (1.442695040888963456*log(X))
2385 #endif
2389 ** Implementation of SQL functions:
2391 ** ln(X) - natural logarithm
2392 ** log(X) - log X base 10
2393 ** log10(X) - log X base 10
2394 ** log(B,X) - log X base B
2396 static void logFunc(
2397 sqlite3_context *context,
2398 int argc,
2399 sqlite3_value **argv
2401 double x, b, ans;
2402 assert( argc==1 || argc==2 );
2403 switch( sqlite3_value_numeric_type(argv[0]) ){
2404 case SQLITE_INTEGER:
2405 case SQLITE_FLOAT:
2406 x = sqlite3_value_double(argv[0]);
2407 if( x<=0.0 ) return;
2408 break;
2409 default:
2410 return;
2412 if( argc==2 ){
2413 switch( sqlite3_value_numeric_type(argv[0]) ){
2414 case SQLITE_INTEGER:
2415 case SQLITE_FLOAT:
2416 b = log(x);
2417 if( b<=0.0 ) return;
2418 x = sqlite3_value_double(argv[1]);
2419 if( x<=0.0 ) return;
2420 break;
2421 default:
2422 return;
2424 ans = log(x)/b;
2425 }else{
2426 switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context)) ){
2427 case 1:
2428 ans = log10(x);
2429 break;
2430 case 2:
2431 ans = log2(x);
2432 break;
2433 default:
2434 ans = log(x);
2435 break;
2438 sqlite3_result_double(context, ans);
2442 ** Functions to converts degrees to radians and radians to degrees.
2444 static double degToRad(double x){ return x*(M_PI/180.0); }
2445 static double radToDeg(double x){ return x*(180.0/M_PI); }
2448 ** Implementation of 1-argument SQL math functions:
2450 ** exp(X) - Compute e to the X-th power
2452 static void math1Func(
2453 sqlite3_context *context,
2454 int argc,
2455 sqlite3_value **argv
2457 int type0;
2458 double v0, ans;
2459 double (*x)(double);
2460 assert( argc==1 );
2461 type0 = sqlite3_value_numeric_type(argv[0]);
2462 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
2463 v0 = sqlite3_value_double(argv[0]);
2464 x = (double(*)(double))sqlite3_user_data(context);
2465 ans = x(v0);
2466 sqlite3_result_double(context, ans);
2470 ** Implementation of 2-argument SQL math functions:
2472 ** power(X,Y) - Compute X to the Y-th power
2474 static void math2Func(
2475 sqlite3_context *context,
2476 int argc,
2477 sqlite3_value **argv
2479 int type0, type1;
2480 double v0, v1, ans;
2481 double (*x)(double,double);
2482 assert( argc==2 );
2483 type0 = sqlite3_value_numeric_type(argv[0]);
2484 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
2485 type1 = sqlite3_value_numeric_type(argv[1]);
2486 if( type1!=SQLITE_INTEGER && type1!=SQLITE_FLOAT ) return;
2487 v0 = sqlite3_value_double(argv[0]);
2488 v1 = sqlite3_value_double(argv[1]);
2489 x = (double(*)(double,double))sqlite3_user_data(context);
2490 ans = x(v0, v1);
2491 sqlite3_result_double(context, ans);
2495 ** Implementation of 0-argument pi() function.
2497 static void piFunc(
2498 sqlite3_context *context,
2499 int argc,
2500 sqlite3_value **argv
2502 assert( argc==0 );
2503 (void)argv;
2504 sqlite3_result_double(context, M_PI);
2507 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
2510 ** Implementation of sign(X) function.
2512 static void signFunc(
2513 sqlite3_context *context,
2514 int argc,
2515 sqlite3_value **argv
2517 int type0;
2518 double x;
2519 UNUSED_PARAMETER(argc);
2520 assert( argc==1 );
2521 type0 = sqlite3_value_numeric_type(argv[0]);
2522 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
2523 x = sqlite3_value_double(argv[0]);
2524 sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0);
2527 #ifdef SQLITE_DEBUG
2529 ** Implementation of fpdecode(x,y,z) function.
2531 ** x is a real number that is to be decoded. y is the precision.
2532 ** z is the maximum real precision.
2534 static void fpdecodeFunc(
2535 sqlite3_context *context,
2536 int argc,
2537 sqlite3_value **argv
2539 FpDecode s;
2540 double x;
2541 int y, z;
2542 char zBuf[100];
2543 UNUSED_PARAMETER(argc);
2544 assert( argc==3 );
2545 x = sqlite3_value_double(argv[0]);
2546 y = sqlite3_value_int(argv[1]);
2547 z = sqlite3_value_int(argv[2]);
2548 sqlite3FpDecode(&s, x, y, z);
2549 if( s.isSpecial==2 ){
2550 sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN");
2551 }else{
2552 sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP);
2554 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
2556 #endif /* SQLITE_DEBUG */
2559 ** All of the FuncDef structures in the aBuiltinFunc[] array above
2560 ** to the global function hash table. This occurs at start-time (as
2561 ** a consequence of calling sqlite3_initialize()).
2563 ** After this routine runs
2565 void sqlite3RegisterBuiltinFunctions(void){
2567 ** The following array holds FuncDef structures for all of the functions
2568 ** defined in this file.
2570 ** The array cannot be constant since changes are made to the
2571 ** FuncDef.pHash elements at start-time. The elements of this array
2572 ** are read-only after initialization is complete.
2574 ** For peak efficiency, put the most frequently used function last.
2576 static FuncDef aBuiltinFunc[] = {
2577 /***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
2578 #if !defined(SQLITE_UNTESTABLE)
2579 TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),
2580 TEST_FUNC(expr_compare, 2, INLINEFUNC_expr_compare, 0),
2581 TEST_FUNC(expr_implies_expr, 2, INLINEFUNC_expr_implies_expr, 0),
2582 TEST_FUNC(affinity, 1, INLINEFUNC_affinity, 0),
2583 #endif /* !defined(SQLITE_UNTESTABLE) */
2584 /***** Regular functions *****/
2585 #ifdef SQLITE_SOUNDEX
2586 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
2587 #endif
2588 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2589 SFUNCTION(load_extension, 1, 0, 0, loadExt ),
2590 SFUNCTION(load_extension, 2, 0, 0, loadExt ),
2591 #endif
2592 #if SQLITE_USER_AUTHENTICATION
2593 FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
2594 #endif
2595 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2596 DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
2597 DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
2598 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2599 INLINE_FUNC(unlikely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
2600 INLINE_FUNC(likelihood, 2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
2601 INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
2602 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2603 INLINE_FUNC(sqlite_offset, 1, INLINEFUNC_sqlite_offset, 0 ),
2604 #endif
2605 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
2606 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
2607 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
2608 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
2609 FUNCTION(trim, 1, 3, 0, trimFunc ),
2610 FUNCTION(trim, 2, 3, 0, trimFunc ),
2611 FUNCTION(min, -1, 0, 1, minmaxFunc ),
2612 FUNCTION(min, 0, 0, 1, 0 ),
2613 WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
2614 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
2615 FUNCTION(max, -1, 1, 1, minmaxFunc ),
2616 FUNCTION(max, 0, 1, 1, 0 ),
2617 WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
2618 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
2619 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
2620 FUNCTION2(subtype, 1, 0, 0, subtypeFunc, SQLITE_FUNC_TYPEOF),
2621 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
2622 FUNCTION2(octet_length, 1, 0, 0, bytelengthFunc,SQLITE_FUNC_BYTELEN),
2623 FUNCTION(instr, 2, 0, 0, instrFunc ),
2624 FUNCTION(printf, -1, 0, 0, printfFunc ),
2625 FUNCTION(format, -1, 0, 0, printfFunc ),
2626 FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
2627 FUNCTION(char, -1, 0, 0, charFunc ),
2628 FUNCTION(abs, 1, 0, 0, absFunc ),
2629 #ifdef SQLITE_DEBUG
2630 FUNCTION(fpdecode, 3, 0, 0, fpdecodeFunc ),
2631 #endif
2632 #ifndef SQLITE_OMIT_FLOATING_POINT
2633 FUNCTION(round, 1, 0, 0, roundFunc ),
2634 FUNCTION(round, 2, 0, 0, roundFunc ),
2635 #endif
2636 FUNCTION(upper, 1, 0, 0, upperFunc ),
2637 FUNCTION(lower, 1, 0, 0, lowerFunc ),
2638 FUNCTION(hex, 1, 0, 0, hexFunc ),
2639 FUNCTION(unhex, 1, 0, 0, unhexFunc ),
2640 FUNCTION(unhex, 2, 0, 0, unhexFunc ),
2641 FUNCTION(concat, -1, 0, 0, concatFunc ),
2642 FUNCTION(concat, 0, 0, 0, 0 ),
2643 FUNCTION(concat_ws, -1, 0, 0, concatwsFunc ),
2644 FUNCTION(concat_ws, 0, 0, 0, 0 ),
2645 FUNCTION(concat_ws, 1, 0, 0, 0 ),
2646 INLINE_FUNC(ifnull, 2, INLINEFUNC_coalesce, 0 ),
2647 VFUNCTION(random, 0, 0, 0, randomFunc ),
2648 VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
2649 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
2650 DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
2651 DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
2652 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
2653 FUNCTION(quote, 1, 0, 0, quoteFunc ),
2654 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
2655 VFUNCTION(changes, 0, 0, 0, changes ),
2656 VFUNCTION(total_changes, 0, 0, 0, total_changes ),
2657 FUNCTION(replace, 3, 0, 0, replaceFunc ),
2658 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
2659 FUNCTION(substr, 2, 0, 0, substrFunc ),
2660 FUNCTION(substr, 3, 0, 0, substrFunc ),
2661 FUNCTION(substring, 2, 0, 0, substrFunc ),
2662 FUNCTION(substring, 3, 0, 0, substrFunc ),
2663 WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
2664 WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
2665 WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
2666 WAGGREGATE(count, 0,0,0, countStep,
2667 countFinalize, countFinalize, countInverse,
2668 SQLITE_FUNC_COUNT|SQLITE_FUNC_ANYORDER ),
2669 WAGGREGATE(count, 1,0,0, countStep,
2670 countFinalize, countFinalize, countInverse, SQLITE_FUNC_ANYORDER ),
2671 WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
2672 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
2673 WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
2674 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
2675 WAGGREGATE(string_agg, 2, 0, 0, groupConcatStep,
2676 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
2678 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
2679 #ifdef SQLITE_CASE_SENSITIVE_LIKE
2680 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
2681 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
2682 #else
2683 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
2684 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
2685 #endif
2686 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
2687 FUNCTION(unknown, -1, 0, 0, unknownFunc ),
2688 #endif
2689 FUNCTION(coalesce, 1, 0, 0, 0 ),
2690 FUNCTION(coalesce, 0, 0, 0, 0 ),
2691 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
2692 MFUNCTION(ceil, 1, xCeil, ceilingFunc ),
2693 MFUNCTION(ceiling, 1, xCeil, ceilingFunc ),
2694 MFUNCTION(floor, 1, xFloor, ceilingFunc ),
2695 #if SQLITE_HAVE_C99_MATH_FUNCS
2696 MFUNCTION(trunc, 1, trunc, ceilingFunc ),
2697 #endif
2698 FUNCTION(ln, 1, 0, 0, logFunc ),
2699 FUNCTION(log, 1, 1, 0, logFunc ),
2700 FUNCTION(log10, 1, 1, 0, logFunc ),
2701 FUNCTION(log2, 1, 2, 0, logFunc ),
2702 FUNCTION(log, 2, 0, 0, logFunc ),
2703 MFUNCTION(exp, 1, exp, math1Func ),
2704 MFUNCTION(pow, 2, pow, math2Func ),
2705 MFUNCTION(power, 2, pow, math2Func ),
2706 MFUNCTION(mod, 2, fmod, math2Func ),
2707 MFUNCTION(acos, 1, acos, math1Func ),
2708 MFUNCTION(asin, 1, asin, math1Func ),
2709 MFUNCTION(atan, 1, atan, math1Func ),
2710 MFUNCTION(atan2, 2, atan2, math2Func ),
2711 MFUNCTION(cos, 1, cos, math1Func ),
2712 MFUNCTION(sin, 1, sin, math1Func ),
2713 MFUNCTION(tan, 1, tan, math1Func ),
2714 MFUNCTION(cosh, 1, cosh, math1Func ),
2715 MFUNCTION(sinh, 1, sinh, math1Func ),
2716 MFUNCTION(tanh, 1, tanh, math1Func ),
2717 #if SQLITE_HAVE_C99_MATH_FUNCS
2718 MFUNCTION(acosh, 1, acosh, math1Func ),
2719 MFUNCTION(asinh, 1, asinh, math1Func ),
2720 MFUNCTION(atanh, 1, atanh, math1Func ),
2721 #endif
2722 MFUNCTION(sqrt, 1, sqrt, math1Func ),
2723 MFUNCTION(radians, 1, degToRad, math1Func ),
2724 MFUNCTION(degrees, 1, radToDeg, math1Func ),
2725 FUNCTION(pi, 0, 0, 0, piFunc ),
2726 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
2727 FUNCTION(sign, 1, 0, 0, signFunc ),
2728 INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, 0 ),
2729 INLINE_FUNC(iif, 3, INLINEFUNC_iif, 0 ),
2731 #ifndef SQLITE_OMIT_ALTERTABLE
2732 sqlite3AlterFunctions();
2733 #endif
2734 sqlite3WindowFunctions();
2735 sqlite3RegisterDateTimeFunctions();
2736 sqlite3RegisterJsonFunctions();
2737 sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
2739 #if 0 /* Enable to print out how the built-in functions are hashed */
2741 int i;
2742 FuncDef *p;
2743 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
2744 printf("FUNC-HASH %02d:", i);
2745 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
2746 int n = sqlite3Strlen30(p->zName);
2747 int h = p->zName[0] + n;
2748 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
2749 printf(" %s(%d)", p->zName, h);
2751 printf("\n");
2754 #endif