4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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"
19 #ifndef SQLITE_OMIT_FLOATING_POINT
25 ** Return the collating function associated with a function.
27 static CollSeq
*sqlite3GetFuncCollSeq(sqlite3_context
*context
){
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
);
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
,
55 int mask
; /* 0 for min() or 0xffffffff for max() */
60 mask
= sqlite3_user_data(context
)==0 ? 0 : -1;
61 pColl
= sqlite3GetFuncCollSeq(context
);
63 assert( mask
==-1 || mask
==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 ){
73 sqlite3_result_value(context
, argv
[iBest
]);
77 ** Return the type of the argument.
79 static void typeofFunc(
80 sqlite3_context
*context
,
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
);
102 ** Return the subtype of X
104 static void subtypeFunc(
105 sqlite3_context
*context
,
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
,
122 UNUSED_PARAMETER(argc
);
123 switch( sqlite3_value_type(argv
[0]) ){
127 sqlite3_result_int(context
, sqlite3_value_bytes(argv
[0]));
131 const unsigned char *z
= sqlite3_value_text(argv
[0]);
132 const unsigned char *z0
;
136 while( (c
= *z
)!=0 ){
139 while( (*z
& 0xc0)==0x80 ){ z
++; z0
++; }
142 sqlite3_result_int(context
, (int)(z
-z0
));
146 sqlite3_result_null(context
);
153 ** Implementation of the octet_length() function
155 static void bytelengthFunc(
156 sqlite3_context
*context
,
161 UNUSED_PARAMETER(argc
);
162 switch( sqlite3_value_type(argv
[0]) ){
164 sqlite3_result_int(context
, sqlite3_value_bytes(argv
[0]));
169 i64 m
= sqlite3_context_db_handle(context
)->enc
<=SQLITE_UTF8
? 1 : 2;
170 sqlite3_result_int64(context
, sqlite3_value_bytes(argv
[0])*m
);
174 if( sqlite3_value_encoding(argv
[0])<=SQLITE_UTF8
){
175 sqlite3_result_int(context
, sqlite3_value_bytes(argv
[0]));
177 sqlite3_result_int(context
, sqlite3_value_bytes16(argv
[0]));
182 sqlite3_result_null(context
);
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
){
196 UNUSED_PARAMETER(argc
);
197 switch( sqlite3_value_type(argv
[0]) ){
198 case SQLITE_INTEGER
: {
199 i64 iVal
= sqlite3_value_int64(argv
[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);
210 sqlite3_result_int64(context
, iVal
);
214 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
215 sqlite3_result_null(context
);
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
);
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
,
248 const unsigned char *zHaystack
;
249 const unsigned char *zNeedle
;
252 int typeHaystack
, typeNeedle
;
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]);
266 if( typeHaystack
==SQLITE_BLOB
&& typeNeedle
==SQLITE_BLOB
){
267 zHaystack
= sqlite3_value_blob(argv
[0]);
268 zNeedle
= sqlite3_value_blob(argv
[1]);
270 }else if( typeHaystack
!=SQLITE_BLOB
&& typeNeedle
!=SQLITE_BLOB
){
271 zHaystack
= sqlite3_value_text(argv
[0]);
272 zNeedle
= sqlite3_value_text(argv
[1]);
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
);
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)
294 }while( isText
&& (zHaystack
[0]&0xc0)==0x80 );
296 if( nNeedle
>nHaystack
) N
= 0;
298 sqlite3_result_int(context
, N
);
300 sqlite3_value_free(pC1
);
301 sqlite3_value_free(pC2
);
304 sqlite3_result_error_nomem(context
);
309 ** Implementation of the printf() (a.k.a. format()) SQL function.
311 static void printfFunc(
312 sqlite3_context
*context
,
320 sqlite3
*db
= sqlite3_context_db_handle(context
);
322 if( argc
>=1 && (zFormat
= (const char*)sqlite3_value_text(argv
[0]))!=0 ){
326 sqlite3StrAccumInit(&str
, db
, 0, 0, db
->aLimit
[SQLITE_LIMIT_LENGTH
]);
327 str
.printfFlags
= SQLITE_PRINTF_SQLFUNC
;
328 sqlite3_str_appendf(&str
, zFormat
, &x
);
330 sqlite3_result_text(context
, sqlite3StrAccumFinish(&str
), n
,
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
,
352 const unsigned char *z
;
353 const unsigned char *z2
;
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
)
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]);
371 assert( len
==sqlite3_value_bytes(argv
[0]) );
373 z
= sqlite3_value_text(argv
[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> */
391 p2
= sqlite3_value_int(argv
[2]);
397 p2
= sqlite3_context_db_handle(context
)->aLimit
[SQLITE_LIMIT_LENGTH
];
418 assert( p1
>=0 && p2
>=0 );
419 if( p0type
!=SQLITE_BLOB
){
424 for(z2
=z
; *z2
&& p2
; p2
--){
425 SQLITE_SKIP_UTF8(z2
);
427 sqlite3_result_text64(context
, (char*)z
, z2
-z
, SQLITE_TRANSIENT
,
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
){
446 assert( argc
==1 || argc
==2 );
448 if( SQLITE_NULL
==sqlite3_value_type(argv
[1]) ) return;
449 n
= sqlite3_value_int(argv
[1]);
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 */
462 r
= (double)((sqlite_int64
)(r
+(r
<0?-0.5:+0.5)));
464 zBuf
= sqlite3_mprintf("%!.*f",n
,r
);
466 sqlite3_result_error_nomem(context
);
469 sqlite3AtoF(zBuf
, &r
, sqlite3Strlen30(zBuf
), SQLITE_UTF8
);
472 sqlite3_result_double(context
, r
);
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
){
485 sqlite3
*db
= sqlite3_context_db_handle(context
);
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
);
493 z
= sqlite3Malloc(nByte
);
495 sqlite3_result_error_nomem(context
);
502 ** Implementation of the upper() and lower() SQL functions.
504 static void upperFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
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]) );
514 z1
= contextMalloc(context
, ((i64
)n
)+1);
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
){
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]) );
533 z1
= contextMalloc(context
, ((i64
)n
)+1);
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
,
559 sqlite3_value
**NotUsed2
562 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
563 sqlite3_randomness(sizeof(r
), &r
);
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
,
590 UNUSED_PARAMETER(argc
);
591 n
= sqlite3_value_int64(argv
[0]);
595 p
= contextMalloc(context
, n
);
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
,
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
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.
627 sqlite3_context
*context
,
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
,
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.
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++))
672 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
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.
700 ** '*' Matches any sequence of zero or more characters.
702 ** '?' Matches exactly one character.
704 ** [...] Matches one character from the enclosed list of
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
;
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
;
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 */
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
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
783 zStop
[0] = sqlite3Toupper(c
);
784 zStop
[1] = sqlite3Tolower(c
);
791 zString
+= strcspn((const char*)zString
, zStop
);
792 if( zString
[0]==0 ) break;
794 bMatch
= patternCompare(zPattern
,zString
,pInfo
,matchOther
);
795 if( bMatch
!=SQLITE_NOMATCH
) return 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
;
808 if( pInfo
->matchSet
==0 ){
809 c
= sqlite3Utf8Read(&zPattern
);
810 if( c
==0 ) return SQLITE_NOMATCH
;
816 c
= sqlite3Utf8Read(&zString
);
817 if( c
==0 ) return SQLITE_NOMATCH
;
818 c2
= sqlite3Utf8Read(&zPattern
);
821 c2
= sqlite3Utf8Read(&zPattern
);
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;
838 c2
= sqlite3Utf8Read(&zPattern
);
840 if( c2
==0 || (seen
^ invert
)==0 ){
841 return SQLITE_NOMATCH
;
846 c2
= Utf8Read(zString
);
847 if( c
==c2
) continue;
848 if( noCase
&& sqlite3Tolower(c
)==sqlite3Tolower(c2
) && c
<0x80 && c2
<0x80 ){
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
){
863 return zGlobPattern
!=0;
864 }else if( zGlobPattern
==0 ){
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
){
878 }else if( zPattern
==0 ){
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
891 int sqlite3_like_count
= 0;
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:
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
,
912 const unsigned char *zA
, *zB
;
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
924 sqlite3_like_count
++;
926 sqlite3_result_int(context
, 0);
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);
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);
952 escape
= sqlite3Utf8Read(&zEsc
);
953 if( escape
==pInfo
->matchAll
|| escape
==pInfo
->matchOne
){
954 memcpy(&backupInfo
, pInfo
, sizeof(backupInfo
));
956 if( escape
==pInfo
->matchAll
) pInfo
->matchAll
= 0;
957 if( escape
==pInfo
->matchOne
) pInfo
->matchOne
= 0;
960 escape
= pInfo
->matchSet
;
962 zB
= sqlite3_value_text(argv
[0]);
963 zA
= sqlite3_value_text(argv
[1]);
966 sqlite3_like_count
++;
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
,
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
,
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
1010 static void sourceidFunc(
1011 sqlite3_context
*context
,
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
,
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
,
1045 sqlite3_value
**argv
1047 const char *zOptName
;
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++
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
,
1069 sqlite3_value
**argv
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
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
: {
1103 r1
= sqlite3_value_double(pValue
);
1104 sqlite3_str_appendf(pStr
, "%!.15g", r1
);
1105 zVal
= sqlite3_str_value(pStr
);
1107 sqlite3AtoF(zVal
, &r2
, pStr
->nChar
, SQLITE_UTF8
);
1109 sqlite3_str_reset(pStr
);
1110 sqlite3_str_appendf(pStr
, "%!.20e", r1
);
1115 case SQLITE_INTEGER
: {
1116 sqlite3_str_appendf(pStr
, "%lld", sqlite3_value_int64(pValue
));
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
;
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';
1135 pStr
->nChar
= nBlob
*2 + 3;
1140 const unsigned char *zArg
= sqlite3_value_text(pValue
);
1141 sqlite3_str_appendf(pStr
, "%Q", zArg
);
1145 assert( sqlite3_value_type(pValue
)==SQLITE_NULL
);
1146 sqlite3_str_append(pStr
, "NULL", 4);
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
){
1164 sqlite3
*db
= sqlite3_context_db_handle(context
);
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
,
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
,
1184 sqlite3_value
**argv
1186 const unsigned char *z
= sqlite3_value_text(argv
[0]);
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
,
1199 sqlite3_value
**argv
1201 unsigned char *z
, *zOut
;
1203 zOut
= z
= sqlite3_malloc64( argc
*4+1 );
1205 sqlite3_result_error_nomem(context
);
1208 for(i
=0; i
<argc
; i
++){
1211 x
= sqlite3_value_int64(argv
[i
]);
1212 if( x
<0 || x
>0x10ffff ) x
= 0xfffd;
1213 c
= (unsigned)(x
& 0x1fffff);
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);
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);
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
,
1241 sqlite3_value
**argv
1244 const unsigned char *pBlob
;
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);
1253 for(i
=0; i
<n
; i
++, pBlob
++){
1254 unsigned char c
= *pBlob
;
1255 *(z
++) = hexdigits
[(c
>>4)&0xf];
1256 *(z
++) = hexdigits
[c
&0xf];
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
];
1272 u32 tst
= Utf8Read(z
);
1273 if( tst
==ch
) return 1;
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
,
1303 sqlite3_value
**argv
1305 const u8
*zPass
= (const u8
*)"";
1307 const u8
*zHex
= sqlite3_value_text(argv
[0]);
1308 int nHex
= sqlite3_value_bytes(argv
[0]);
1310 const u8
*zEnd
= zHex
? &zHex
[nHex
] : 0;
1315 assert( argc
==1 || 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);
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
;
1333 if( c
==0x00 ) goto unhex_done
;
1336 assert( *zEnd
==0x00 );
1337 assert( zHex
<=zEnd
);
1339 if( !sqlite3Isxdigit(d
) ) goto unhex_null
;
1340 *(p
++) = (sqlite3HexToInt(c
)<<4) | sqlite3HexToInt(d
);
1345 sqlite3_result_blob(pCtx
, pBlob
, (p
- pBlob
), sqlite3_free
);
1349 sqlite3_free(pBlob
);
1355 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
1357 static void zeroblobFunc(
1358 sqlite3_context
*context
,
1360 sqlite3_value
**argv
1365 UNUSED_PARAMETER(argc
);
1366 n
= sqlite3_value_int64(argv
[0]);
1368 rc
= sqlite3_result_zeroblob64(context
, n
); /* IMP: R-00293-64994 */
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
,
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
);
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]);
1406 assert( sqlite3_value_type(argv
[1])==SQLITE_NULL
1407 || sqlite3_context_db_handle(context
)->mallocFailed
);
1410 if( zPattern
[0]==0 ){
1411 assert( sqlite3_value_type(argv
[1])!=SQLITE_NULL
);
1412 sqlite3_result_value(context
, argv
[0]);
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]) );
1422 assert( nOut
<SQLITE_MAX_LENGTH
);
1423 zOut
= contextMalloc(context
, (i64
)nOut
);
1427 loopLimit
= nStr
- nPattern
;
1429 for(i
=j
=0; i
<=loopLimit
; i
++){
1430 if( zStr
[i
]!=zPattern
[0] || memcmp(&zStr
[i
], zPattern
, nPattern
) ){
1431 zOut
[j
++] = zStr
[i
];
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
);
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, ... */
1448 zOut
= sqlite3Realloc(zOut
, (int)nOut
+ (nOut
- nStr
- 1));
1450 sqlite3_result_error_nomem(context
);
1456 memcpy(&zOut
[j
], zRep
, nRep
);
1461 assert( j
+nStr
-i
+1<=nOut
);
1462 memcpy(&zOut
[j
], &zStr
[i
], nStr
-i
);
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
,
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
){
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]) );
1495 static const unsigned lenOne
[] = { 1 };
1496 static unsigned char * const azOne
[] = { (u8
*)" " };
1498 aLen
= (unsigned*)lenOne
;
1499 azChar
= (unsigned char **)azOne
;
1501 }else if( (zCharSet
= sqlite3_value_text(argv
[1]))==0 ){
1504 const unsigned char *z
;
1505 for(z
=zCharSet
, nChar
=0; *z
; nChar
++){
1506 SQLITE_SKIP_UTF8(z
);
1509 azChar
= contextMalloc(context
,
1510 ((i64
)nChar
)*(sizeof(char*)+sizeof(unsigned)));
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
]);
1523 flags
= SQLITE_PTR_TO_INT(sqlite3_user_data(context
));
1526 unsigned int len
= 0;
1527 for(i
=0; i
<nChar
; i
++){
1529 if( len
<=nIn
&& memcmp(zIn
, azChar
[i
], len
)==0 ) break;
1531 if( i
>=nChar
) break;
1538 unsigned int len
= 0;
1539 for(i
=0; i
<nChar
; i
++){
1541 if( len
<=nIn
&& memcmp(&zIn
[nIn
-len
],azChar
[i
],len
)==0 ) break;
1543 if( i
>=nChar
) break;
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,...)
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
,
1563 sqlite3_value
**argv
,
1570 for(i
=0; i
<argc
; i
++){
1571 n
+= sqlite3_value_bytes(argv
[i
]);
1574 z
= sqlite3_malloc64(n
+1);
1576 sqlite3_result_error_nomem(context
);
1580 for(i
=0; i
<argc
; i
++){
1581 k
= sqlite3_value_bytes(argv
[i
]);
1583 const char *v
= (const char*)sqlite3_value_text(argv
[i
]);
1585 if( j
>0 && nSep
>0 ){
1586 memcpy(&z
[j
], zSep
, nSep
);
1589 memcpy(&z
[j
], v
, k
);
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
,
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
1618 static void concatwsFunc(
1619 sqlite3_context
*context
,
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
1640 static void unknownFunc(
1641 sqlite3_context
*context
,
1643 sqlite3_value
**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
,
1667 sqlite3_value
**argv
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,
1683 zIn
= (u8
*)sqlite3_value_text(argv
[0]);
1684 if( zIn
==0 ) zIn
= (u8
*)"";
1685 for(i
=0; zIn
[i
] && !sqlite3Isalpha(zIn
[i
]); 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];
1692 if( code
!=prevcode
){
1694 zResult
[j
++] = code
+ '0';
1704 sqlite3_result_text(context
, zResult
, 4, SQLITE_TRANSIENT
);
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]);
1720 sqlite3
*db
= sqlite3_context_db_handle(context
);
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);
1732 zProc
= (const char *)sqlite3_value_text(argv
[1]);
1736 if( zFile
&& sqlite3_load_extension(db
, zFile
, zProc
, &zErrMsg
) ){
1737 sqlite3_result_error(context
, zErrMsg
, -1);
1738 sqlite3_free(zErrMsg
);
1745 ** An instance of the following structure holds the context of a
1746 ** sum() or avg() aggregate computation.
1748 typedef struct SumCtx 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
,
1770 volatile double s
= pSum
->rSum
;
1771 volatile double t
= s
+ r
;
1772 if( fabs(s
) > fabs(r
) ){
1773 pSum
->rErr
+= (s
- t
) + r
;
1775 pSum
->rErr
+= (r
- t
) + s
;
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 ){
1788 kahanBabuskaNeumaierStep(pSum
, iBig
);
1789 kahanBabuskaNeumaierStep(pSum
, iSm
);
1791 kahanBabuskaNeumaierStep(pSum
, (double)iVal
);
1796 ** Initialize the Kahan-Babaska-Neumaier sum from a 64-bit integer
1798 static void kahanBabuskaNeumaierInit(
1802 if( iVal
<=-4503599627370496LL || iVal
>=+4503599627370496LL ){
1803 i64 iSm
= iVal
% 16384;
1804 p
->rSum
= (double)(iVal
- iSm
);
1805 p
->rErr
= (double)iSm
;
1807 p
->rSum
= (double)iVal
;
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
){
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
){
1832 if( type
!=SQLITE_INTEGER
){
1833 kahanBabuskaNeumaierInit(p
, p
->iSum
);
1835 kahanBabuskaNeumaierStep(p
, sqlite3_value_double(argv
[0]));
1838 if( sqlite3AddInt64(&x
, sqlite3_value_int64(argv
[0]))==0 ){
1842 kahanBabuskaNeumaierInit(p
, p
->iSum
);
1844 kahanBabuskaNeumaierStepInt64(p
, sqlite3_value_int64(argv
[0]));
1848 if( type
==SQLITE_INTEGER
){
1849 kahanBabuskaNeumaierStepInt64(p
, sqlite3_value_int64(argv
[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
){
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
){
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
);
1877 kahanBabuskaNeumaierStepInt64(p
, LARGEST_INT64
);
1878 kahanBabuskaNeumaierStepInt64(p
, 1);
1881 kahanBabuskaNeumaierStep(p
, -sqlite3_value_double(argv
[0]));
1886 # define sumInverse 0
1887 #endif /* SQLITE_OMIT_WINDOWFUNC */
1888 static void sumFinalize(sqlite3_context
*context
){
1890 p
= sqlite3_aggregate_context(context
, 0);
1891 if( p
&& p
->cnt
>0 ){
1894 sqlite3_result_error(context
,"integer overflow",-1);
1895 }else if( !sqlite3IsNaN(p
->rErr
) ){
1896 sqlite3_result_double(context
, p
->rSum
+p
->rErr
);
1898 sqlite3_result_double(context
, p
->rSum
);
1901 sqlite3_result_int64(context
, p
->iSum
);
1905 static void avgFinalize(sqlite3_context
*context
){
1907 p
= sqlite3_aggregate_context(context
, 0);
1908 if( p
&& p
->cnt
>0 ){
1912 if( !sqlite3IsNaN(p
->rErr
) ) r
+= p
->rErr
;
1914 r
= (double)(p
->iSum
);
1916 sqlite3_result_double(context
, r
/(double)p
->cnt
);
1919 static void totalFinalize(sqlite3_context
*context
){
1922 p
= sqlite3_aggregate_context(context
, 0);
1926 if( !sqlite3IsNaN(p
->rErr
) ) r
+= p
->rErr
;
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
;
1942 int bInverse
; /* True if xInverse() ever called */
1947 ** Routines to implement the count() aggregate function.
1949 static void countStep(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
1951 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
1952 if( (argc
==0 || SQLITE_NULL
!=sqlite3_value_type(argv
[0])) && p
){
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
) );
1965 static void countFinalize(sqlite3_context
*context
){
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
){
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
) ){
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
,
1992 sqlite3_value
**argv
1994 Mem
*pArg
= (Mem
*)argv
[0];
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
){
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
);
2020 sqlite3SkipAccumulatorLoad(context
);
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);
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);
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.
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.
2072 static void groupConcatStep(
2073 sqlite3_context
*context
,
2075 sqlite3_value
**argv
2078 GroupConcatCtx
*pGCC
;
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
));
2085 sqlite3
*db
= sqlite3_context_db_handle(context
);
2086 int firstTerm
= pGCC
->str
.mxAlloc
==0;
2087 pGCC
->str
.mxAlloc
= db
->aLimit
[SQLITE_LIMIT_LENGTH
];
2090 sqlite3_str_appendchar(&pGCC
->str
, 1, ',');
2092 #ifndef SQLITE_OMIT_WINDOWFUNC
2094 pGCC
->nFirstSepLength
= 1;
2097 }else if( !firstTerm
){
2098 zSep
= (char*)sqlite3_value_text(argv
[1]);
2099 nSep
= sqlite3_value_bytes(argv
[1]);
2101 sqlite3_str_append(&pGCC
->str
, zSep
, nSep
);
2103 #ifndef SQLITE_OMIT_WINDOWFUNC
2107 if( nSep
!= pGCC
->nFirstSepLength
|| pGCC
->pnSepLengths
!= 0 ){
2108 int *pnsl
= pGCC
->pnSepLengths
;
2110 /* First separator length variation seen, start tracking them. */
2111 pnsl
= (int*)sqlite3_malloc64((pGCC
->nAccum
+1) * sizeof(int));
2113 int i
= 0, nA
= pGCC
->nAccum
-1;
2114 while( i
<nA
) pnsl
[i
++] = pGCC
->nFirstSepLength
;
2117 pnsl
= (int*)sqlite3_realloc64(pnsl
, pGCC
->nAccum
* sizeof(int));
2120 if( ALWAYS(pGCC
->nAccum
>0) ){
2121 pnsl
[pGCC
->nAccum
-1] = nSep
;
2123 pGCC
->pnSepLengths
= pnsl
;
2125 sqlite3StrAccumSetError(&pGCC
->str
, SQLITE_NOMEM
);
2130 #ifndef SQLITE_OMIT_WINDOWFUNC
2132 pGCC
->nFirstSepLength
= sqlite3_value_bytes(argv
[1]);
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
,
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 */
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]);
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));
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;
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;
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);
2193 sqlite3ResultStrAccum(context
, &pGCC
->str
);
2194 #ifndef SQLITE_OMIT_WINDOWFUNC
2195 sqlite3_free(pGCC
->pnSepLengths
);
2199 #ifndef SQLITE_OMIT_WINDOWFUNC
2200 static void groupConcatValue(sqlite3_context
*context
){
2201 GroupConcatCtx
*pGCC
2202 = (GroupConcatCtx
*)sqlite3_aggregate_context(context
, 0);
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
);
2210 const char *zText
= sqlite3_str_value(pAccum
);
2211 sqlite3_result_text(context
, zText
, pAccum
->nChar
, SQLITE_TRANSIENT
);
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
);
2230 /* BEGIN SQLCIPHER */
2231 #ifdef SQLITE_HAS_CODEC
2233 extern void sqlcipher_exportFunc(sqlite3_context
*, int, sqlite3_value
**);
2234 sqlite3CreateFunc(db
, "sqlcipher_export", -1, SQLITE_TEXT
, 0, sqlcipher_exportFunc
, 0, 0, 0, 0, 0);
2236 #ifdef SQLCIPHER_EXT
2237 #include "sqlcipher_funcs_init.h"
2244 ** Re-register the built-in LIKE functions. The caseSensitive
2245 ** parameter determines whether or not the LIKE operator is case
2248 void sqlite3RegisterLikeFunctions(sqlite3
*db
, int caseSensitive
){
2250 struct compareInfo
*pInfo
;
2253 if( caseSensitive
){
2254 pInfo
= (struct compareInfo
*)&likeInfoAlt
;
2255 flags
= SQLITE_FUNC_LIKE
| SQLITE_FUNC_CASE
;
2257 pInfo
= (struct compareInfo
*)&likeInfoNorm
;
2258 flags
= SQLITE_FUNC_LIKE
;
2260 for(nArg
=2; nArg
<=3; nArg
++){
2261 sqlite3CreateFunc(db
, "like", nArg
, SQLITE_UTF8
, pInfo
, likeFunc
,
2263 pDef
= sqlite3FindFunction(db
, "like", nArg
, SQLITE_UTF8
, 0);
2264 pDef
->funcFlags
|= flags
;
2265 pDef
->funcFlags
&= ~SQLITE_FUNC_UNSAFE
;
2270 ** pExpr points to an expression which implements a function. If
2271 ** it is appropriate to apply the LIKE optimization to that function
2272 ** then set aWc[0] through aWc[2] to the wildcard characters and the
2273 ** escape character and then return TRUE. If the function is not a
2274 ** LIKE-style function then return FALSE.
2276 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
2277 ** operator if c is a string literal that is exactly one byte in length.
2278 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
2279 ** no ESCAPE clause.
2281 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
2282 ** the function (default for LIKE). If the function makes the distinction
2283 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
2286 int sqlite3IsLikeFunction(sqlite3
*db
, Expr
*pExpr
, int *pIsNocase
, char *aWc
){
2290 assert( pExpr
->op
==TK_FUNCTION
);
2291 assert( ExprUseXList(pExpr
) );
2292 if( !pExpr
->x
.pList
){
2295 nExpr
= pExpr
->x
.pList
->nExpr
;
2296 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2297 pDef
= sqlite3FindFunction(db
, pExpr
->u
.zToken
, nExpr
, SQLITE_UTF8
, 0);
2298 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
2299 if( pDef
==0 ) return 0;
2301 if( NEVER(pDef
==0) || (pDef
->funcFlags
& SQLITE_FUNC_LIKE
)==0 ){
2305 /* The memcpy() statement assumes that the wildcard characters are
2306 ** the first three statements in the compareInfo structure. The
2307 ** asserts() that follow verify that assumption
2309 memcpy(aWc
, pDef
->pUserData
, 3);
2310 assert( (char*)&likeInfoAlt
== (char*)&likeInfoAlt
.matchAll
);
2311 assert( &((char*)&likeInfoAlt
)[1] == (char*)&likeInfoAlt
.matchOne
);
2312 assert( &((char*)&likeInfoAlt
)[2] == (char*)&likeInfoAlt
.matchSet
);
2317 Expr
*pEscape
= pExpr
->x
.pList
->a
[2].pExpr
;
2319 if( pEscape
->op
!=TK_STRING
) return 0;
2320 assert( !ExprHasProperty(pEscape
, EP_IntValue
) );
2321 zEscape
= pEscape
->u
.zToken
;
2322 if( zEscape
[0]==0 || zEscape
[1]!=0 ) return 0;
2323 if( zEscape
[0]==aWc
[0] ) return 0;
2324 if( zEscape
[0]==aWc
[1] ) return 0;
2325 aWc
[3] = zEscape
[0];
2328 *pIsNocase
= (pDef
->funcFlags
& SQLITE_FUNC_CASE
)==0;
2332 /* Mathematical Constants */
2334 # define M_PI 3.141592653589793238462643383279502884
2337 # define M_LN10 2.302585092994045684017991454684364208
2340 # define M_LN2 0.693147180559945309417232121458176568
2344 /* Extra math functions that require linking with -lm
2346 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
2348 ** Implementation SQL functions:
2354 ** The sqlite3_user_data() pointer is a pointer to the libm implementation
2355 ** of the underlying C function.
2357 static void ceilingFunc(
2358 sqlite3_context
*context
,
2360 sqlite3_value
**argv
2363 switch( sqlite3_value_numeric_type(argv
[0]) ){
2364 case SQLITE_INTEGER
: {
2365 sqlite3_result_int64(context
, sqlite3_value_int64(argv
[0]));
2368 case SQLITE_FLOAT
: {
2369 double (*x
)(double) = (double(*)(double))sqlite3_user_data(context
);
2370 sqlite3_result_double(context
, x(sqlite3_value_double(argv
[0])));
2380 ** On some systems, ceil() and floor() are intrinsic function. You are
2381 ** unable to take a pointer to these functions. Hence, we here wrap them
2382 ** in our own actual functions.
2384 static double xCeil(double x
){ return ceil(x
); }
2385 static double xFloor(double x
){ return floor(x
); }
2388 ** Some systems do not have log2() and log10() in their standard math
2391 #if defined(HAVE_LOG10) && HAVE_LOG10==0
2392 # define log10(X) (0.4342944819032517867*log(X))
2394 #if defined(HAVE_LOG2) && HAVE_LOG2==0
2395 # define log2(X) (1.442695040888963456*log(X))
2400 ** Implementation of SQL functions:
2402 ** ln(X) - natural logarithm
2403 ** log(X) - log X base 10
2404 ** log10(X) - log X base 10
2405 ** log(B,X) - log X base B
2407 static void logFunc(
2408 sqlite3_context
*context
,
2410 sqlite3_value
**argv
2413 assert( argc
==1 || argc
==2 );
2414 switch( sqlite3_value_numeric_type(argv
[0]) ){
2415 case SQLITE_INTEGER
:
2417 x
= sqlite3_value_double(argv
[0]);
2418 if( x
<=0.0 ) return;
2424 switch( sqlite3_value_numeric_type(argv
[0]) ){
2425 case SQLITE_INTEGER
:
2428 if( b
<=0.0 ) return;
2429 x
= sqlite3_value_double(argv
[1]);
2430 if( x
<=0.0 ) return;
2437 switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context
)) ){
2449 sqlite3_result_double(context
, ans
);
2453 ** Functions to converts degrees to radians and radians to degrees.
2455 static double degToRad(double x
){ return x
*(M_PI
/180.0); }
2456 static double radToDeg(double x
){ return x
*(180.0/M_PI
); }
2459 ** Implementation of 1-argument SQL math functions:
2461 ** exp(X) - Compute e to the X-th power
2463 static void math1Func(
2464 sqlite3_context
*context
,
2466 sqlite3_value
**argv
2470 double (*x
)(double);
2472 type0
= sqlite3_value_numeric_type(argv
[0]);
2473 if( type0
!=SQLITE_INTEGER
&& type0
!=SQLITE_FLOAT
) return;
2474 v0
= sqlite3_value_double(argv
[0]);
2475 x
= (double(*)(double))sqlite3_user_data(context
);
2477 sqlite3_result_double(context
, ans
);
2481 ** Implementation of 2-argument SQL math functions:
2483 ** power(X,Y) - Compute X to the Y-th power
2485 static void math2Func(
2486 sqlite3_context
*context
,
2488 sqlite3_value
**argv
2492 double (*x
)(double,double);
2494 type0
= sqlite3_value_numeric_type(argv
[0]);
2495 if( type0
!=SQLITE_INTEGER
&& type0
!=SQLITE_FLOAT
) return;
2496 type1
= sqlite3_value_numeric_type(argv
[1]);
2497 if( type1
!=SQLITE_INTEGER
&& type1
!=SQLITE_FLOAT
) return;
2498 v0
= sqlite3_value_double(argv
[0]);
2499 v1
= sqlite3_value_double(argv
[1]);
2500 x
= (double(*)(double,double))sqlite3_user_data(context
);
2502 sqlite3_result_double(context
, ans
);
2506 ** Implementation of 0-argument pi() function.
2509 sqlite3_context
*context
,
2511 sqlite3_value
**argv
2515 sqlite3_result_double(context
, M_PI
);
2518 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
2521 ** Implementation of sign(X) function.
2523 static void signFunc(
2524 sqlite3_context
*context
,
2526 sqlite3_value
**argv
2530 UNUSED_PARAMETER(argc
);
2532 type0
= sqlite3_value_numeric_type(argv
[0]);
2533 if( type0
!=SQLITE_INTEGER
&& type0
!=SQLITE_FLOAT
) return;
2534 x
= sqlite3_value_double(argv
[0]);
2535 sqlite3_result_int(context
, x
<0.0 ? -1 : x
>0.0 ? +1 : 0);
2540 ** Implementation of fpdecode(x,y,z) function.
2542 ** x is a real number that is to be decoded. y is the precision.
2543 ** z is the maximum real precision.
2545 static void fpdecodeFunc(
2546 sqlite3_context
*context
,
2548 sqlite3_value
**argv
2554 UNUSED_PARAMETER(argc
);
2556 x
= sqlite3_value_double(argv
[0]);
2557 y
= sqlite3_value_int(argv
[1]);
2558 z
= sqlite3_value_int(argv
[2]);
2559 sqlite3FpDecode(&s
, x
, y
, z
);
2560 if( s
.isSpecial
==2 ){
2561 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "NaN");
2563 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%c%.*s/%d", s
.sign
, s
.n
, s
.z
, s
.iDP
);
2565 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
2567 #endif /* SQLITE_DEBUG */
2570 ** All of the FuncDef structures in the aBuiltinFunc[] array above
2571 ** to the global function hash table. This occurs at start-time (as
2572 ** a consequence of calling sqlite3_initialize()).
2574 ** After this routine runs
2576 void sqlite3RegisterBuiltinFunctions(void){
2578 ** The following array holds FuncDef structures for all of the functions
2579 ** defined in this file.
2581 ** The array cannot be constant since changes are made to the
2582 ** FuncDef.pHash elements at start-time. The elements of this array
2583 ** are read-only after initialization is complete.
2585 ** For peak efficiency, put the most frequently used function last.
2587 static FuncDef aBuiltinFunc
[] = {
2588 /***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
2589 #if !defined(SQLITE_UNTESTABLE)
2590 TEST_FUNC(implies_nonnull_row
, 2, INLINEFUNC_implies_nonnull_row
, 0),
2591 TEST_FUNC(expr_compare
, 2, INLINEFUNC_expr_compare
, 0),
2592 TEST_FUNC(expr_implies_expr
, 2, INLINEFUNC_expr_implies_expr
, 0),
2593 TEST_FUNC(affinity
, 1, INLINEFUNC_affinity
, 0),
2594 #endif /* !defined(SQLITE_UNTESTABLE) */
2595 /***** Regular functions *****/
2596 #ifdef SQLITE_SOUNDEX
2597 FUNCTION(soundex
, 1, 0, 0, soundexFunc
),
2599 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2600 SFUNCTION(load_extension
, 1, 0, 0, loadExt
),
2601 SFUNCTION(load_extension
, 2, 0, 0, loadExt
),
2603 #if SQLITE_USER_AUTHENTICATION
2604 FUNCTION(sqlite_crypt
, 2, 0, 0, sqlite3CryptFunc
),
2606 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2607 DFUNCTION(sqlite_compileoption_used
,1, 0, 0, compileoptionusedFunc
),
2608 DFUNCTION(sqlite_compileoption_get
, 1, 0, 0, compileoptiongetFunc
),
2609 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2610 INLINE_FUNC(unlikely
, 1, INLINEFUNC_unlikely
, SQLITE_FUNC_UNLIKELY
),
2611 INLINE_FUNC(likelihood
, 2, INLINEFUNC_unlikely
, SQLITE_FUNC_UNLIKELY
),
2612 INLINE_FUNC(likely
, 1, INLINEFUNC_unlikely
, SQLITE_FUNC_UNLIKELY
),
2613 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2614 INLINE_FUNC(sqlite_offset
, 1, INLINEFUNC_sqlite_offset
, 0 ),
2616 FUNCTION(ltrim
, 1, 1, 0, trimFunc
),
2617 FUNCTION(ltrim
, 2, 1, 0, trimFunc
),
2618 FUNCTION(rtrim
, 1, 2, 0, trimFunc
),
2619 FUNCTION(rtrim
, 2, 2, 0, trimFunc
),
2620 FUNCTION(trim
, 1, 3, 0, trimFunc
),
2621 FUNCTION(trim
, 2, 3, 0, trimFunc
),
2622 FUNCTION(min
, -1, 0, 1, minmaxFunc
),
2623 FUNCTION(min
, 0, 0, 1, 0 ),
2624 WAGGREGATE(min
, 1, 0, 1, minmaxStep
, minMaxFinalize
, minMaxValue
, 0,
2625 SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
),
2626 FUNCTION(max
, -1, 1, 1, minmaxFunc
),
2627 FUNCTION(max
, 0, 1, 1, 0 ),
2628 WAGGREGATE(max
, 1, 1, 1, minmaxStep
, minMaxFinalize
, minMaxValue
, 0,
2629 SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
),
2630 FUNCTION2(typeof, 1, 0, 0, typeofFunc
, SQLITE_FUNC_TYPEOF
),
2631 FUNCTION2(subtype
, 1, 0, 0, subtypeFunc
, SQLITE_FUNC_TYPEOF
),
2632 FUNCTION2(length
, 1, 0, 0, lengthFunc
, SQLITE_FUNC_LENGTH
),
2633 FUNCTION2(octet_length
, 1, 0, 0, bytelengthFunc
,SQLITE_FUNC_BYTELEN
),
2634 FUNCTION(instr
, 2, 0, 0, instrFunc
),
2635 FUNCTION(printf
, -1, 0, 0, printfFunc
),
2636 FUNCTION(format
, -1, 0, 0, printfFunc
),
2637 FUNCTION(unicode
, 1, 0, 0, unicodeFunc
),
2638 FUNCTION(char, -1, 0, 0, charFunc
),
2639 FUNCTION(abs
, 1, 0, 0, absFunc
),
2641 FUNCTION(fpdecode
, 3, 0, 0, fpdecodeFunc
),
2643 #ifndef SQLITE_OMIT_FLOATING_POINT
2644 FUNCTION(round
, 1, 0, 0, roundFunc
),
2645 FUNCTION(round
, 2, 0, 0, roundFunc
),
2647 FUNCTION(upper
, 1, 0, 0, upperFunc
),
2648 FUNCTION(lower
, 1, 0, 0, lowerFunc
),
2649 FUNCTION(hex
, 1, 0, 0, hexFunc
),
2650 FUNCTION(unhex
, 1, 0, 0, unhexFunc
),
2651 FUNCTION(unhex
, 2, 0, 0, unhexFunc
),
2652 FUNCTION(concat
, -1, 0, 0, concatFunc
),
2653 FUNCTION(concat
, 0, 0, 0, 0 ),
2654 FUNCTION(concat_ws
, -1, 0, 0, concatwsFunc
),
2655 FUNCTION(concat_ws
, 0, 0, 0, 0 ),
2656 FUNCTION(concat_ws
, 1, 0, 0, 0 ),
2657 INLINE_FUNC(ifnull
, 2, INLINEFUNC_coalesce
, 0 ),
2658 VFUNCTION(random
, 0, 0, 0, randomFunc
),
2659 VFUNCTION(randomblob
, 1, 0, 0, randomBlob
),
2660 FUNCTION(nullif
, 2, 0, 1, nullifFunc
),
2661 DFUNCTION(sqlite_version
, 0, 0, 0, versionFunc
),
2662 DFUNCTION(sqlite_source_id
, 0, 0, 0, sourceidFunc
),
2663 FUNCTION(sqlite_log
, 2, 0, 0, errlogFunc
),
2664 FUNCTION(quote
, 1, 0, 0, quoteFunc
),
2665 VFUNCTION(last_insert_rowid
, 0, 0, 0, last_insert_rowid
),
2666 VFUNCTION(changes
, 0, 0, 0, changes
),
2667 VFUNCTION(total_changes
, 0, 0, 0, total_changes
),
2668 FUNCTION(replace
, 3, 0, 0, replaceFunc
),
2669 FUNCTION(zeroblob
, 1, 0, 0, zeroblobFunc
),
2670 FUNCTION(substr
, 2, 0, 0, substrFunc
),
2671 FUNCTION(substr
, 3, 0, 0, substrFunc
),
2672 FUNCTION(substring
, 2, 0, 0, substrFunc
),
2673 FUNCTION(substring
, 3, 0, 0, substrFunc
),
2674 WAGGREGATE(sum
, 1,0,0, sumStep
, sumFinalize
, sumFinalize
, sumInverse
, 0),
2675 WAGGREGATE(total
, 1,0,0, sumStep
,totalFinalize
,totalFinalize
,sumInverse
, 0),
2676 WAGGREGATE(avg
, 1,0,0, sumStep
, avgFinalize
, avgFinalize
, sumInverse
, 0),
2677 WAGGREGATE(count
, 0,0,0, countStep
,
2678 countFinalize
, countFinalize
, countInverse
,
2679 SQLITE_FUNC_COUNT
|SQLITE_FUNC_ANYORDER
),
2680 WAGGREGATE(count
, 1,0,0, countStep
,
2681 countFinalize
, countFinalize
, countInverse
, SQLITE_FUNC_ANYORDER
),
2682 WAGGREGATE(group_concat
, 1, 0, 0, groupConcatStep
,
2683 groupConcatFinalize
, groupConcatValue
, groupConcatInverse
, 0),
2684 WAGGREGATE(group_concat
, 2, 0, 0, groupConcatStep
,
2685 groupConcatFinalize
, groupConcatValue
, groupConcatInverse
, 0),
2686 WAGGREGATE(string_agg
, 2, 0, 0, groupConcatStep
,
2687 groupConcatFinalize
, groupConcatValue
, groupConcatInverse
, 0),
2689 LIKEFUNC(glob
, 2, &globInfo
, SQLITE_FUNC_LIKE
|SQLITE_FUNC_CASE
),
2690 #ifdef SQLITE_CASE_SENSITIVE_LIKE
2691 LIKEFUNC(like
, 2, &likeInfoAlt
, SQLITE_FUNC_LIKE
|SQLITE_FUNC_CASE
),
2692 LIKEFUNC(like
, 3, &likeInfoAlt
, SQLITE_FUNC_LIKE
|SQLITE_FUNC_CASE
),
2694 LIKEFUNC(like
, 2, &likeInfoNorm
, SQLITE_FUNC_LIKE
),
2695 LIKEFUNC(like
, 3, &likeInfoNorm
, SQLITE_FUNC_LIKE
),
2697 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
2698 FUNCTION(unknown
, -1, 0, 0, unknownFunc
),
2700 FUNCTION(coalesce
, 1, 0, 0, 0 ),
2701 FUNCTION(coalesce
, 0, 0, 0, 0 ),
2702 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
2703 MFUNCTION(ceil
, 1, xCeil
, ceilingFunc
),
2704 MFUNCTION(ceiling
, 1, xCeil
, ceilingFunc
),
2705 MFUNCTION(floor
, 1, xFloor
, ceilingFunc
),
2706 #if SQLITE_HAVE_C99_MATH_FUNCS
2707 MFUNCTION(trunc
, 1, trunc
, ceilingFunc
),
2709 FUNCTION(ln
, 1, 0, 0, logFunc
),
2710 FUNCTION(log
, 1, 1, 0, logFunc
),
2711 FUNCTION(log10
, 1, 1, 0, logFunc
),
2712 FUNCTION(log2
, 1, 2, 0, logFunc
),
2713 FUNCTION(log
, 2, 0, 0, logFunc
),
2714 MFUNCTION(exp
, 1, exp
, math1Func
),
2715 MFUNCTION(pow
, 2, pow
, math2Func
),
2716 MFUNCTION(power
, 2, pow
, math2Func
),
2717 MFUNCTION(mod
, 2, fmod
, math2Func
),
2718 MFUNCTION(acos
, 1, acos
, math1Func
),
2719 MFUNCTION(asin
, 1, asin
, math1Func
),
2720 MFUNCTION(atan
, 1, atan
, math1Func
),
2721 MFUNCTION(atan2
, 2, atan2
, math2Func
),
2722 MFUNCTION(cos
, 1, cos
, math1Func
),
2723 MFUNCTION(sin
, 1, sin
, math1Func
),
2724 MFUNCTION(tan
, 1, tan
, math1Func
),
2725 MFUNCTION(cosh
, 1, cosh
, math1Func
),
2726 MFUNCTION(sinh
, 1, sinh
, math1Func
),
2727 MFUNCTION(tanh
, 1, tanh
, math1Func
),
2728 #if SQLITE_HAVE_C99_MATH_FUNCS
2729 MFUNCTION(acosh
, 1, acosh
, math1Func
),
2730 MFUNCTION(asinh
, 1, asinh
, math1Func
),
2731 MFUNCTION(atanh
, 1, atanh
, math1Func
),
2733 MFUNCTION(sqrt
, 1, sqrt
, math1Func
),
2734 MFUNCTION(radians
, 1, degToRad
, math1Func
),
2735 MFUNCTION(degrees
, 1, radToDeg
, math1Func
),
2736 FUNCTION(pi
, 0, 0, 0, piFunc
),
2737 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
2738 FUNCTION(sign
, 1, 0, 0, signFunc
),
2739 INLINE_FUNC(coalesce
, -1, INLINEFUNC_coalesce
, 0 ),
2740 INLINE_FUNC(iif
, 3, INLINEFUNC_iif
, 0 ),
2742 #ifndef SQLITE_OMIT_ALTERTABLE
2743 sqlite3AlterFunctions();
2745 sqlite3WindowFunctions();
2746 sqlite3RegisterDateTimeFunctions();
2747 sqlite3RegisterJsonFunctions();
2748 sqlite3InsertBuiltinFuncs(aBuiltinFunc
, ArraySize(aBuiltinFunc
));
2750 #if 0 /* Enable to print out how the built-in functions are hashed */
2754 for(i
=0; i
<SQLITE_FUNC_HASH_SZ
; i
++){
2755 printf("FUNC-HASH %02d:", i
);
2756 for(p
=sqlite3BuiltinFunctions
.a
[i
]; p
; p
=p
->u
.pHash
){
2757 int n
= sqlite3Strlen30(p
->zName
);
2758 int h
= p
->zName
[0] + n
;
2759 assert( p
->funcFlags
& SQLITE_FUNC_BUILTIN
);
2760 printf(" %s(%d)", p
->zName
, h
);