func.c 46 KB

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