PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/ext/pdo_sqlite/sqlite/src/func.c

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