You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

573 lines
15 KiB

  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 <ctype.h>
  22. #include <math.h>
  23. #include <stdlib.h>
  24. #include <assert.h>
  25. #include "sqliteInt.h"
  26. /*
  27. ** Implementation of the non-aggregate min() and max() functions
  28. */
  29. static void minFunc(sqlite_func *context, int argc, const char **argv){
  30. const char *zBest;
  31. int i;
  32. if( argc==0 ) return;
  33. zBest = argv[0];
  34. if( zBest==0 ) return;
  35. for(i=1; i<argc; i++){
  36. if( argv[i]==0 ) return;
  37. if( sqliteCompare(argv[i], zBest)<0 ){
  38. zBest = argv[i];
  39. }
  40. }
  41. sqlite_set_result_string(context, zBest, -1);
  42. }
  43. static void maxFunc(sqlite_func *context, int argc, const char **argv){
  44. const char *zBest;
  45. int i;
  46. if( argc==0 ) return;
  47. zBest = argv[0];
  48. if( zBest==0 ) return;
  49. for(i=1; i<argc; i++){
  50. if( argv[i]==0 ) return;
  51. if( sqliteCompare(argv[i], zBest)>0 ){
  52. zBest = argv[i];
  53. }
  54. }
  55. sqlite_set_result_string(context, zBest, -1);
  56. }
  57. /*
  58. ** Implementation of the length() function
  59. */
  60. static void lengthFunc(sqlite_func *context, int argc, const char **argv){
  61. const char *z;
  62. int len;
  63. assert( argc==1 );
  64. z = argv[0];
  65. if( z==0 ) return;
  66. #ifdef SQLITE_UTF8
  67. for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
  68. #else
  69. len = strlen(z);
  70. #endif
  71. sqlite_set_result_int(context, len);
  72. }
  73. /*
  74. ** Implementation of the abs() function
  75. */
  76. static void absFunc(sqlite_func *context, int argc, const char **argv){
  77. const char *z;
  78. assert( argc==1 );
  79. z = argv[0];
  80. if( z==0 ) return;
  81. if( z[0]=='-' && isdigit(z[1]) ) z++;
  82. sqlite_set_result_string(context, z, -1);
  83. }
  84. /*
  85. ** Implementation of the substr() function
  86. */
  87. static void substrFunc(sqlite_func *context, int argc, const char **argv){
  88. const char *z;
  89. #ifdef SQLITE_UTF8
  90. const char *z2;
  91. int i;
  92. #endif
  93. int p1, p2, len;
  94. assert( argc==3 );
  95. z = argv[0];
  96. if( z==0 ) return;
  97. p1 = atoi(argv[1]?argv[1]:0);
  98. p2 = atoi(argv[2]?argv[2]:0);
  99. #ifdef SQLITE_UTF8
  100. for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
  101. #else
  102. len = strlen(z);
  103. #endif
  104. if( p1<0 ){
  105. p1 += len;
  106. if( p1<0 ){
  107. p2 += p1;
  108. p1 = 0;
  109. }
  110. }else if( p1>0 ){
  111. p1--;
  112. }
  113. if( p1+p2>len ){
  114. p2 = len-p1;
  115. }
  116. #ifdef SQLITE_UTF8
  117. for(i=0; i<p1; i++){
  118. assert( z[i] );
  119. if( (z[i]&0xc0)==0x80 ) p1++;
  120. }
  121. while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
  122. for(; i<p1+p2; i++){
  123. assert( z[i] );
  124. if( (z[i]&0xc0)==0x80 ) p2++;
  125. }
  126. while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
  127. #endif
  128. if( p2<0 ) p2 = 0;
  129. sqlite_set_result_string(context, &z[p1], p2);
  130. }
  131. /*
  132. ** Implementation of the round() function
  133. */
  134. static void roundFunc(sqlite_func *context, int argc, const char **argv){
  135. int n;
  136. double r;
  137. char zBuf[100];
  138. assert( argc==1 || argc==2 );
  139. if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
  140. n = argc==2 ? atoi(argv[1]) : 0;
  141. if( n>30 ) n = 30;
  142. if( n<0 ) n = 0;
  143. r = atof(argv[0]);
  144. sprintf(zBuf,"%.*f",n,r);
  145. sqlite_set_result_string(context, zBuf, -1);
  146. }
  147. /*
  148. ** Implementation of the upper() and lower() SQL functions.
  149. */
  150. static void upperFunc(sqlite_func *context, int argc, const char **argv){
  151. char *z;
  152. int i;
  153. if( argc<1 || argv[0]==0 ) return;
  154. z = sqlite_set_result_string(context, argv[0], -1);
  155. if( z==0 ) return;
  156. for(i=0; z[i]; i++){
  157. if( islower(z[i]) ) z[i] = toupper(z[i]);
  158. }
  159. }
  160. static void lowerFunc(sqlite_func *context, int argc, const char **argv){
  161. char *z;
  162. int i;
  163. if( argc<1 || argv[0]==0 ) return;
  164. z = sqlite_set_result_string(context, argv[0], -1);
  165. if( z==0 ) return;
  166. for(i=0; z[i]; i++){
  167. if( isupper(z[i]) ) z[i] = tolower(z[i]);
  168. }
  169. }
  170. /*
  171. ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
  172. ** All three do the same thing. They return the first argument
  173. ** non-NULL argument.
  174. */
  175. static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
  176. int i;
  177. for(i=0; i<argc; i++){
  178. if( argv[i] ){
  179. sqlite_set_result_string(context, argv[i], -1);
  180. break;
  181. }
  182. }
  183. }
  184. /*
  185. ** Implementation of random(). Return a random integer.
  186. */
  187. static void randomFunc(sqlite_func *context, int argc, const char **argv){
  188. sqlite_set_result_int(context, sqliteRandomInteger());
  189. }
  190. /*
  191. ** Implementation of the last_insert_rowid() SQL function. The return
  192. ** value is the same as the sqlite_last_insert_rowid() API function.
  193. */
  194. static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
  195. sqlite *db = sqlite_user_data(context);
  196. sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
  197. }
  198. /*
  199. ** Implementation of the like() SQL function. This function implements
  200. ** the build-in LIKE operator. The first argument to the function is the
  201. ** string and the second argument is the pattern. So, the SQL statements:
  202. **
  203. ** A LIKE B
  204. **
  205. ** is implemented as like(A,B).
  206. */
  207. static void likeFunc(sqlite_func *context, int arg, const char **argv){
  208. if( argv[0]==0 || argv[1]==0 ) return;
  209. sqlite_set_result_int(context, sqliteLikeCompare(argv[0], argv[1]));
  210. }
  211. /*
  212. ** Implementation of the glob() SQL function. This function implements
  213. ** the build-in GLOB operator. The first argument to the function is the
  214. ** string and the second argument is the pattern. So, the SQL statements:
  215. **
  216. ** A GLOB B
  217. **
  218. ** is implemented as glob(A,B).
  219. */
  220. static void globFunc(sqlite_func *context, int arg, const char **argv){
  221. if( argv[0]==0 || argv[1]==0 ) return;
  222. sqlite_set_result_int(context, sqliteGlobCompare(argv[0], argv[1]));
  223. }
  224. /*
  225. ** Implementation of the NULLIF(x,y) function. The result is the first
  226. ** argument if the arguments are different. The result is NULL if the
  227. ** arguments are equal to each other.
  228. */
  229. static void nullifFunc(sqlite_func *context, int argc, const char **argv){
  230. if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
  231. sqlite_set_result_string(context, argv[0], -1);
  232. }
  233. }
  234. /*
  235. ** Implementation of the VERSION(*) function. The result is the version
  236. ** of the SQLite library that is running.
  237. */
  238. static void versionFunc(sqlite_func *context, int argc, const char **argv){
  239. sqlite_set_result_string(context, sqlite_version, -1);
  240. }
  241. #ifdef SQLITE_SOUNDEX
  242. /*
  243. ** Compute the soundex encoding of a word.
  244. */
  245. static void soundexFunc(sqlite_func *context, int argc, const char **argv){
  246. char zResult[8];
  247. const char *zIn;
  248. int i, j;
  249. static const unsigned char iCode[] = {
  250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  254. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  255. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  256. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  257. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  258. };
  259. assert( argc==1 );
  260. zIn = argv[0];
  261. for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
  262. if( zIn[i] ){
  263. zResult[0] = toupper(zIn[i]);
  264. for(j=1; j<4 && zIn[i]; i++){
  265. int code = iCode[zIn[i]&0x7f];
  266. if( code>0 ){
  267. zResult[j++] = code + '0';
  268. }
  269. }
  270. while( j<4 ){
  271. zResult[j++] = '0';
  272. }
  273. zResult[j] = 0;
  274. sqlite_set_result_string(context, zResult, 4);
  275. }else{
  276. sqlite_set_result_string(context, zResult, "?000", 4);
  277. }
  278. }
  279. #endif
  280. #ifdef SQLITE_TEST
  281. /*
  282. ** This function generates a string of random characters. Used for
  283. ** generating test data.
  284. */
  285. static void randStr(sqlite_func *context, int argc, const char **argv){
  286. static const char zSrc[] =
  287. "abcdefghijklmnopqrstuvwxyz"
  288. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  289. "0123456789"
  290. ".-!,:*^+=_|?/<> ";
  291. int iMin, iMax, n, r, i;
  292. char zBuf[1000];
  293. if( argc>=1 ){
  294. iMin = atoi(argv[0]);
  295. if( iMin<0 ) iMin = 0;
  296. if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
  297. }else{
  298. iMin = 1;
  299. }
  300. if( argc>=2 ){
  301. iMax = atoi(argv[1]);
  302. if( iMax<iMin ) iMax = iMin;
  303. if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf);
  304. }else{
  305. iMax = 50;
  306. }
  307. n = iMin;
  308. if( iMax>iMin ){
  309. r = sqliteRandomInteger() & 0x7fffffff;
  310. n += r%(iMax + 1 - iMin);
  311. }
  312. r = 0;
  313. for(i=0; i<n; i++){
  314. r = (r + sqliteRandomByte())% (sizeof(zSrc)-1);
  315. zBuf[i] = zSrc[r];
  316. }
  317. zBuf[n] = 0;
  318. sqlite_set_result_string(context, zBuf, n);
  319. }
  320. #endif
  321. /*
  322. ** An instance of the following structure holds the context of a
  323. ** sum() or avg() aggregate computation.
  324. */
  325. typedef struct SumCtx SumCtx;
  326. struct SumCtx {
  327. double sum; /* Sum of terms */
  328. int cnt; /* Number of elements summed */
  329. };
  330. /*
  331. ** Routines used to compute the sum or average.
  332. */
  333. static void sumStep(sqlite_func *context, int argc, const char **argv){
  334. SumCtx *p;
  335. if( argc<1 ) return;
  336. p = sqlite_aggregate_context(context, sizeof(*p));
  337. if( p && argv[0] ){
  338. p->sum += atof(argv[0]);
  339. p->cnt++;
  340. }
  341. }
  342. static void sumFinalize(sqlite_func *context){
  343. SumCtx *p;
  344. p = sqlite_aggregate_context(context, sizeof(*p));
  345. sqlite_set_result_double(context, p ? p->sum : 0.0);
  346. }
  347. static void avgFinalize(sqlite_func *context){
  348. SumCtx *p;
  349. p = sqlite_aggregate_context(context, sizeof(*p));
  350. if( p && p->cnt>0 ){
  351. sqlite_set_result_double(context, p->sum/(double)p->cnt);
  352. }
  353. }
  354. /*
  355. ** An instance of the following structure holds the context of a
  356. ** variance or standard deviation computation.
  357. */
  358. typedef struct StdDevCtx StdDevCtx;
  359. struct StdDevCtx {
  360. double sum; /* Sum of terms */
  361. double sum2; /* Sum of the squares of terms */
  362. int cnt; /* Number of terms counted */
  363. };
  364. #if 0 /* Omit because math library is required */
  365. /*
  366. ** Routines used to compute the standard deviation as an aggregate.
  367. */
  368. static void stdDevStep(sqlite_func *context, int argc, const char **argv){
  369. StdDevCtx *p;
  370. double x;
  371. if( argc<1 ) return;
  372. p = sqlite_aggregate_context(context, sizeof(*p));
  373. if( p && argv[0] ){
  374. x = atof(argv[0]);
  375. p->sum += x;
  376. p->sum2 += x*x;
  377. p->cnt++;
  378. }
  379. }
  380. static void stdDevFinalize(sqlite_func *context){
  381. double rN = sqlite_aggregate_count(context);
  382. StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
  383. if( p && p->cnt>1 ){
  384. double rCnt = cnt;
  385. sqlite_set_result_double(context,
  386. sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
  387. }
  388. }
  389. #endif
  390. /*
  391. ** The following structure keeps track of state information for the
  392. ** count() aggregate function.
  393. */
  394. typedef struct CountCtx CountCtx;
  395. struct CountCtx {
  396. int n;
  397. };
  398. /*
  399. ** Routines to implement the count() aggregate function.
  400. */
  401. static void countStep(sqlite_func *context, int argc, const char **argv){
  402. CountCtx *p;
  403. p = sqlite_aggregate_context(context, sizeof(*p));
  404. if( (argc==0 || argv[0]) && p ){
  405. p->n++;
  406. }
  407. }
  408. static void countFinalize(sqlite_func *context){
  409. CountCtx *p;
  410. p = sqlite_aggregate_context(context, sizeof(*p));
  411. sqlite_set_result_int(context, p ? p->n : 0);
  412. }
  413. /*
  414. ** This function tracks state information for the min() and max()
  415. ** aggregate functions.
  416. */
  417. typedef struct MinMaxCtx MinMaxCtx;
  418. struct MinMaxCtx {
  419. char *z; /* The best so far */
  420. char zBuf[28]; /* Space that can be used for storage */
  421. };
  422. /*
  423. ** Routines to implement min() and max() aggregate functions.
  424. */
  425. static void minStep(sqlite_func *context, int argc, const char **argv){
  426. MinMaxCtx *p;
  427. p = sqlite_aggregate_context(context, sizeof(*p));
  428. if( p==0 || argc<1 || argv[0]==0 ) return;
  429. if( p->z==0 || sqliteCompare(argv[0],p->z)<0 ){
  430. int len;
  431. if( p->z && p->z!=p->zBuf ){
  432. sqliteFree(p->z);
  433. }
  434. len = strlen(argv[0]);
  435. if( len < sizeof(p->zBuf) ){
  436. p->z = p->zBuf;
  437. }else{
  438. p->z = sqliteMalloc( len+1 );
  439. if( p->z==0 ) return;
  440. }
  441. strcpy(p->z, argv[0]);
  442. }
  443. }
  444. static void maxStep(sqlite_func *context, int argc, const char **argv){
  445. MinMaxCtx *p;
  446. p = sqlite_aggregate_context(context, sizeof(*p));
  447. if( p==0 || argc<1 || argv[0]==0 ) return;
  448. if( p->z==0 || sqliteCompare(argv[0],p->z)>0 ){
  449. int len;
  450. if( p->z && p->z!=p->zBuf ){
  451. sqliteFree(p->z);
  452. }
  453. len = strlen(argv[0]);
  454. if( len < sizeof(p->zBuf) ){
  455. p->z = p->zBuf;
  456. }else{
  457. p->z = sqliteMalloc( len+1 );
  458. if( p->z==0 ) return;
  459. }
  460. strcpy(p->z, argv[0]);
  461. }
  462. }
  463. static void minMaxFinalize(sqlite_func *context){
  464. MinMaxCtx *p;
  465. p = sqlite_aggregate_context(context, sizeof(*p));
  466. if( p && p->z ){
  467. sqlite_set_result_string(context, p->z, strlen(p->z));
  468. }
  469. if( p && p->z && p->z!=p->zBuf ){
  470. sqliteFree(p->z);
  471. }
  472. }
  473. /*
  474. ** This function registered all of the above C functions as SQL
  475. ** functions. This should be the only routine in this file with
  476. ** external linkage.
  477. */
  478. void sqliteRegisterBuiltinFunctions(sqlite *db){
  479. static struct {
  480. char *zName;
  481. int nArg;
  482. int dataType;
  483. void (*xFunc)(sqlite_func*,int,const char**);
  484. } aFuncs[] = {
  485. { "min", -1, SQLITE_ARGS, minFunc },
  486. { "min", 0, 0, 0 },
  487. { "max", -1, SQLITE_ARGS, maxFunc },
  488. { "max", 0, 0, 0 },
  489. { "length", 1, SQLITE_NUMERIC, lengthFunc },
  490. { "substr", 3, SQLITE_TEXT, substrFunc },
  491. { "abs", 1, SQLITE_NUMERIC, absFunc },
  492. { "round", 1, SQLITE_NUMERIC, roundFunc },
  493. { "round", 2, SQLITE_NUMERIC, roundFunc },
  494. { "upper", 1, SQLITE_TEXT, upperFunc },
  495. { "lower", 1, SQLITE_TEXT, lowerFunc },
  496. { "coalesce", -1, SQLITE_ARGS, ifnullFunc },
  497. { "coalesce", 0, 0, 0 },
  498. { "coalesce", 1, 0, 0 },
  499. { "ifnull", 2, SQLITE_ARGS, ifnullFunc },
  500. { "random", -1, SQLITE_NUMERIC, randomFunc },
  501. { "like", 2, SQLITE_NUMERIC, likeFunc },
  502. { "glob", 2, SQLITE_NUMERIC, globFunc },
  503. { "nullif", 2, SQLITE_ARGS, nullifFunc },
  504. { "sqlite_version",0,SQLITE_TEXT, versionFunc},
  505. #ifdef SQLITE_SOUNDEX
  506. { "soundex", 1, SQLITE_TEXT, soundexFunc},
  507. #endif
  508. #ifdef SQLITE_TEST
  509. { "randstr", 2, SQLITE_TEXT, randStr },
  510. #endif
  511. };
  512. static struct {
  513. char *zName;
  514. int nArg;
  515. int dataType;
  516. void (*xStep)(sqlite_func*,int,const char**);
  517. void (*xFinalize)(sqlite_func*);
  518. } aAggs[] = {
  519. { "min", 1, 0, minStep, minMaxFinalize },
  520. { "max", 1, 0, maxStep, minMaxFinalize },
  521. { "sum", 1, SQLITE_NUMERIC, sumStep, sumFinalize },
  522. { "avg", 1, SQLITE_NUMERIC, sumStep, avgFinalize },
  523. { "count", 0, SQLITE_NUMERIC, countStep, countFinalize },
  524. { "count", 1, SQLITE_NUMERIC, countStep, countFinalize },
  525. #if 0
  526. { "stddev", 1, SQLITE_NUMERIC, stdDevStep, stdDevFinalize },
  527. #endif
  528. };
  529. int i;
  530. for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
  531. sqlite_create_function(db, aFuncs[i].zName,
  532. aFuncs[i].nArg, aFuncs[i].xFunc, 0);
  533. if( aFuncs[i].xFunc ){
  534. sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
  535. }
  536. }
  537. sqlite_create_function(db, "last_insert_rowid", 0,
  538. last_insert_rowid, db);
  539. sqlite_function_type(db, "last_insert_rowid", SQLITE_NUMERIC);
  540. for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
  541. sqlite_create_aggregate(db, aAggs[i].zName,
  542. aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, 0);
  543. sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
  544. }
  545. }