interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / test_func.c

957 lines · 28688 bytes Raw Blame History
1/*
2** 2008 March 19
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** Code for testing all sorts of SQLite interfaces. This code
13** implements new SQL functions used by the test scripts.
14*/
15#include "sqlite3.h"
16#include "tclsqlite.h"
17#include <stdlib.h>
18#include <string.h>
19#include <assert.h>
20
21#include "sqliteInt.h"
22#include "vdbeInt.h"
23
24/*
25** Allocate nByte bytes of space using sqlite3_malloc(). If the
26** allocation fails, call sqlite3_result_error_nomem() to notify
27** the database handle that malloc() has failed.
28*/
29static void *testContextMalloc(sqlite3_context *context, int nByte){
30 char *z = sqlite3_malloc(nByte);
31 if( !z && nByte>0 ){
32 sqlite3_result_error_nomem(context);
33 }
34 return z;
35}
36
37/*
38** This function generates a string of random characters. Used for
39** generating test data.
40*/
41static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
42 static const unsigned char zSrc[] =
43 "abcdefghijklmnopqrstuvwxyz"
44 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
45 "0123456789"
46 ".-!,:*^+=_|?/<> ";
47 int iMin, iMax, n, r, i;
48 unsigned char zBuf[1000];
49
50 /* It used to be possible to call randstr() with any number of arguments,
51 ** but now it is registered with SQLite as requiring exactly 2.
52 */
53 assert(argc==2);
54
55 iMin = sqlite3_value_int(argv[0]);
56 if( iMin<0 ) iMin = 0;
57 if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
58 iMax = sqlite3_value_int(argv[1]);
59 if( iMax<iMin ) iMax = iMin;
60 if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
61 n = iMin;
62 if( iMax>iMin ){
63 sqlite3_randomness(sizeof(r), &r);
64 r &= 0x7fffffff;
65 n += r%(iMax + 1 - iMin);
66 }
67 assert( n<sizeof(zBuf) );
68 sqlite3_randomness(n, zBuf);
69 for(i=0; i<n; i++){
70 zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
71 }
72 zBuf[n] = 0;
73 sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
74}
75
76/*
77** The following two SQL functions are used to test returning a text
78** result with a destructor. Function 'test_destructor' takes one argument
79** and returns the same argument interpreted as TEXT. A destructor is
80** passed with the sqlite3_result_text() call.
81**
82** SQL function 'test_destructor_count' returns the number of outstanding
83** allocations made by 'test_destructor';
84**
85** WARNING: Not threadsafe.
86*/
87static int test_destructor_count_var = 0;
88static void destructor(void *p){
89 char *zVal = (char *)p;
90 assert(zVal);
91 zVal--;
92 sqlite3_free(zVal);
93 test_destructor_count_var--;
94}
95static void test_destructor(
96 sqlite3_context *pCtx,
97 int nArg,
98 sqlite3_value **argv
99){
100 char *zVal;
101 int len;
102
103 test_destructor_count_var++;
104 assert( nArg==1 );
105 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106 len = sqlite3_value_bytes(argv[0]);
107 zVal = testContextMalloc(pCtx, len+3);
108 if( !zVal ){
109 return;
110 }
111 zVal[len+1] = 0;
112 zVal[len+2] = 0;
113 zVal++;
114 memcpy(zVal, sqlite3_value_text(argv[0]), len);
115 sqlite3_result_text(pCtx, zVal, -1, destructor);
116}
117#ifndef SQLITE_OMIT_UTF16
118static void test_destructor16(
119 sqlite3_context *pCtx,
120 int nArg,
121 sqlite3_value **argv
122){
123 char *zVal;
124 int len;
125
126 test_destructor_count_var++;
127 assert( nArg==1 );
128 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
129 len = sqlite3_value_bytes16(argv[0]);
130 zVal = testContextMalloc(pCtx, len+3);
131 if( !zVal ){
132 return;
133 }
134 zVal[len+1] = 0;
135 zVal[len+2] = 0;
136 zVal++;
137 memcpy(zVal, sqlite3_value_text16(argv[0]), len);
138 sqlite3_result_text16(pCtx, zVal, -1, destructor);
139}
140#endif
141static void test_destructor_count(
142 sqlite3_context *pCtx,
143 int nArg,
144 sqlite3_value **argv
145){
146 sqlite3_result_int(pCtx, test_destructor_count_var);
147}
148
149/*
150** The following aggregate function, test_agg_errmsg16(), takes zero
151** arguments. It returns the text value returned by the sqlite3_errmsg16()
152** API function.
153*/
154#ifndef SQLITE_UNTESTABLE
155void sqlite3BeginBenignMalloc(void);
156void sqlite3EndBenignMalloc(void);
157#else
158 #define sqlite3BeginBenignMalloc()
159 #define sqlite3EndBenignMalloc()
160#endif
161static void test_agg_errmsg16_step(sqlite3_context *a, int b,sqlite3_value **c){
162}
163static void test_agg_errmsg16_final(sqlite3_context *ctx){
164#ifndef SQLITE_OMIT_UTF16
165 const void *z;
166 sqlite3 * db = sqlite3_context_db_handle(ctx);
167 sqlite3_aggregate_context(ctx, 2048);
168 z = sqlite3_errmsg16(db);
169 sqlite3_result_text16(ctx, z, -1, SQLITE_TRANSIENT);
170#endif
171}
172
173/*
174** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
175** interface.
176**
177** The test_auxdata() SQL function attempts to register each of its arguments
178** as auxiliary data. If there are no prior registrations of aux data for
179** that argument (meaning the argument is not a constant or this is its first
180** call) then the result for that argument is 0. If there is a prior
181** registration, the result for that argument is 1. The overall result
182** is the individual argument results separated by spaces.
183*/
184static void free_test_auxdata(void *p) {sqlite3_free(p);}
185static void test_auxdata(
186 sqlite3_context *pCtx,
187 int nArg,
188 sqlite3_value **argv
189){
190 int i;
191 char *zRet = testContextMalloc(pCtx, nArg*2);
192 if( !zRet ) return;
193 memset(zRet, 0, nArg*2);
194 for(i=0; i<nArg; i++){
195 char const *z = (char*)sqlite3_value_text(argv[i]);
196 if( z ){
197 int n;
198 char *zAux = sqlite3_get_auxdata(pCtx, i);
199 if( zAux ){
200 zRet[i*2] = '1';
201 assert( strcmp(zAux,z)==0 );
202 }else {
203 zRet[i*2] = '0';
204 }
205 n = (int)strlen(z) + 1;
206 zAux = testContextMalloc(pCtx, n);
207 if( zAux ){
208 memcpy(zAux, z, n);
209 sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
210 }
211 zRet[i*2+1] = ' ';
212 }
213 }
214 sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
215}
216
217/*
218** A function to test error reporting from user functions. This function
219** returns a copy of its first argument as the error message. If the
220** second argument exists, it becomes the error code.
221*/
222static void test_error(
223 sqlite3_context *pCtx,
224 int nArg,
225 sqlite3_value **argv
226){
227 sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), -1);
228 if( nArg==2 ){
229 sqlite3_result_error_code(pCtx, sqlite3_value_int(argv[1]));
230 }
231}
232
233/*
234** Implementation of the counter(X) function. If X is an integer
235** constant, then the first invocation will return X. The second X+1.
236** and so forth. Can be used (for example) to provide a sequence number
237** in a result set.
238*/
239static void counterFunc(
240 sqlite3_context *pCtx, /* Function context */
241 int nArg, /* Number of function arguments */
242 sqlite3_value **argv /* Values for all function arguments */
243){
244 int *pCounter = (int*)sqlite3_get_auxdata(pCtx, 0);
245 if( pCounter==0 ){
246 pCounter = sqlite3_malloc( sizeof(*pCounter) );
247 if( pCounter==0 ){
248 sqlite3_result_error_nomem(pCtx);
249 return;
250 }
251 *pCounter = sqlite3_value_int(argv[0]);
252 sqlite3_set_auxdata(pCtx, 0, pCounter, sqlite3_free);
253 }else{
254 ++*pCounter;
255 }
256 sqlite3_result_int(pCtx, *pCounter);
257}
258
259
260/*
261** This function takes two arguments. It performance UTF-8/16 type
262** conversions on the first argument then returns a copy of the second
263** argument.
264**
265** This function is used in cases such as the following:
266**
267** SELECT test_isolation(x,x) FROM t1;
268**
269** We want to verify that the type conversions that occur on the
270** first argument do not invalidate the second argument.
271*/
272static void test_isolation(
273 sqlite3_context *pCtx,
274 int nArg,
275 sqlite3_value **argv
276){
277#ifndef SQLITE_OMIT_UTF16
278 sqlite3_value_text16(argv[0]);
279 sqlite3_value_text(argv[0]);
280 sqlite3_value_text16(argv[0]);
281 sqlite3_value_text(argv[0]);
282#endif
283 sqlite3_result_value(pCtx, argv[1]);
284}
285
286/*
287** Invoke an SQL statement recursively. The function result is the
288** first column of the first row of the result set.
289*/
290static void test_eval(
291 sqlite3_context *pCtx,
292 int nArg,
293 sqlite3_value **argv
294){
295 sqlite3_stmt *pStmt;
296 int rc;
297 sqlite3 *db = sqlite3_context_db_handle(pCtx);
298 const char *zSql;
299 static const char zTag[] = "test_eval()";
300
301 if( sqlite3_get_clientdata(db, zTag) ){
302 sqlite3_result_error(pCtx, "nested test_eval()", -1);
303 return;
304 }
305 zSql = (char*)sqlite3_value_text(argv[0]);
306 sqlite3_set_clientdata(db, zTag, &rc, 0);
307 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
308 if( rc==SQLITE_OK ){
309 rc = sqlite3_step(pStmt);
310 if( rc==SQLITE_ROW ){
311 sqlite3_result_value(pCtx, sqlite3_column_value(pStmt, 0));
312 }
313 rc = sqlite3_finalize(pStmt);
314 }
315 sqlite3_set_clientdata(db, zTag, 0, 0);
316 if( rc ){
317 char *zErr;
318 zErr = sqlite3_mprintf("sqlite3_prepare_v2() error: %s",sqlite3_errmsg(db));
319 sqlite3_result_text(pCtx, zErr, -1, sqlite3_free);
320 sqlite3_result_error_code(pCtx, rc);
321 }
322}
323
324
325/*
326** convert one character from hex to binary
327*/
328static int testHexChar(char c){
329 if( c>='0' && c<='9' ){
330 return c - '0';
331 }else if( c>='a' && c<='f' ){
332 return c - 'a' + 10;
333 }else if( c>='A' && c<='F' ){
334 return c - 'A' + 10;
335 }
336 return 0;
337}
338
339/*
340** Convert hex to binary.
341*/
342static void testHexToBin(const char *zIn, char *zOut){
343 while( zIn[0] && zIn[1] ){
344 *(zOut++) = (testHexChar(zIn[0])<<4) + testHexChar(zIn[1]);
345 zIn += 2;
346 }
347}
348
349/*
350** hex_to_utf16be(HEX)
351**
352** Convert the input string from HEX into binary. Then return the
353** result using sqlite3_result_text16le().
354*/
355#ifndef SQLITE_OMIT_UTF16
356static void testHexToUtf16be(
357 sqlite3_context *pCtx,
358 int nArg,
359 sqlite3_value **argv
360){
361 int n;
362 const char *zIn;
363 char *zOut;
364 assert( nArg==1 );
365 n = sqlite3_value_bytes(argv[0]);
366 zIn = (const char*)sqlite3_value_text(argv[0]);
367 zOut = sqlite3_malloc( n/2 );
368 if( zOut==0 ){
369 sqlite3_result_error_nomem(pCtx);
370 }else{
371 testHexToBin(zIn, zOut);
372 sqlite3_result_text16be(pCtx, zOut, n/2, sqlite3_free);
373 }
374}
375#endif
376
377/*
378** hex_to_utf8(HEX)
379**
380** Convert the input string from HEX into binary. Then return the
381** result using sqlite3_result_text16le().
382*/
383static void testHexToUtf8(
384 sqlite3_context *pCtx,
385 int nArg,
386 sqlite3_value **argv
387){
388 int n;
389 const char *zIn;
390 char *zOut;
391 assert( nArg==1 );
392 n = sqlite3_value_bytes(argv[0]);
393 zIn = (const char*)sqlite3_value_text(argv[0]);
394 zOut = sqlite3_malloc( n/2 );
395 if( zOut==0 ){
396 sqlite3_result_error_nomem(pCtx);
397 }else{
398 testHexToBin(zIn, zOut);
399 sqlite3_result_text(pCtx, zOut, n/2, sqlite3_free);
400 }
401}
402
403/*
404** hex_to_utf16le(HEX)
405**
406** Convert the input string from HEX into binary. Then return the
407** result using sqlite3_result_text16le().
408*/
409#ifndef SQLITE_OMIT_UTF16
410static void testHexToUtf16le(
411 sqlite3_context *pCtx,
412 int nArg,
413 sqlite3_value **argv
414){
415 int n;
416 const char *zIn;
417 char *zOut;
418 assert( nArg==1 );
419 n = sqlite3_value_bytes(argv[0]);
420 zIn = (const char*)sqlite3_value_text(argv[0]);
421 zOut = sqlite3_malloc( n/2 );
422 if( zOut==0 ){
423 sqlite3_result_error_nomem(pCtx);
424 }else{
425 testHexToBin(zIn, zOut);
426 sqlite3_result_text16le(pCtx, zOut, n/2, sqlite3_free);
427 }
428}
429#endif
430
431/*
432** SQL function: real2hex(X)
433**
434** If argument X is a real number, then convert it into a string which is
435** the big-endian hexadecimal representation of the ieee754 encoding of
436** that number. If X is not a real number, return NULL.
437*/
438static void real2hex(
439 sqlite3_context *context,
440 int argc,
441 sqlite3_value **argv
442){
443 union {
444 sqlite3_uint64 i;
445 double r;
446 unsigned char x[8];
447 } v;
448 char zOut[20];
449 int i;
450 int bigEndian;
451 v.i = 1;
452 bigEndian = v.x[0]==0;
453 v.r = sqlite3_value_double(argv[0]);
454 for(i=0; i<8; i++){
455 if( bigEndian ){
456 zOut[i*2] = "0123456789abcdef"[v.x[i]>>4];
457 zOut[i*2+1] = "0123456789abcdef"[v.x[i]&0xf];
458 }else{
459 zOut[14-i*2] = "0123456789abcdef"[v.x[i]>>4];
460 zOut[14-i*2+1] = "0123456789abcdef"[v.x[i]&0xf];
461 }
462 }
463 zOut[16] = 0;
464 sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT);
465}
466
467/*
468** test_extract(record, field)
469**
470** This function implements an SQL user-function that accepts a blob
471** containing a formatted database record as the first argument. The
472** second argument is the index of the field within that record to
473** extract and return.
474*/
475static void test_extract(
476 sqlite3_context *context,
477 int argc,
478 sqlite3_value **argv
479){
480 sqlite3 *db = sqlite3_context_db_handle(context);
481 u8 *pRec;
482 u8 *pEndHdr; /* Points to one byte past record header */
483 u8 *pHdr; /* Current point in record header */
484 u8 *pBody; /* Current point in record data */
485 u64 nHdr; /* Bytes in record header */
486 int iIdx; /* Required field */
487 int iCurrent = 0; /* Current field */
488
489 assert( argc==2 );
490 pRec = (u8*)sqlite3_value_blob(argv[0]);
491 iIdx = sqlite3_value_int(argv[1]);
492
493 pHdr = pRec + sqlite3GetVarint(pRec, &nHdr);
494 pBody = pEndHdr = &pRec[nHdr];
495
496 for(iCurrent=0; pHdr<pEndHdr && iCurrent<=iIdx; iCurrent++){
497 u64 iSerialType;
498 Mem mem;
499
500 memset(&mem, 0, sizeof(mem));
501 mem.db = db;
502 mem.enc = ENC(db);
503 pHdr += sqlite3GetVarint(pHdr, &iSerialType);
504 sqlite3VdbeSerialGet(pBody, (u32)iSerialType, &mem);
505 pBody += sqlite3VdbeSerialTypeLen((u32)iSerialType);
506
507 if( iCurrent==iIdx ){
508 sqlite3_result_value(context, &mem);
509 }
510
511 if( mem.szMalloc ) sqlite3DbFree(db, mem.zMalloc);
512 }
513}
514
515/*
516** test_decode(record)
517**
518** This function implements an SQL user-function that accepts a blob
519** containing a formatted database record as its only argument. It returns
520** a tcl list (type SQLITE_TEXT) containing each of the values stored
521** in the record.
522*/
523static void test_decode(
524 sqlite3_context *context,
525 int argc,
526 sqlite3_value **argv
527){
528 sqlite3 *db = sqlite3_context_db_handle(context);
529 u8 *pRec;
530 u8 *pEndHdr; /* Points to one byte past record header */
531 u8 *pHdr; /* Current point in record header */
532 u8 *pBody; /* Current point in record data */
533 u64 nHdr; /* Bytes in record header */
534 Tcl_Obj *pRet; /* Return value */
535
536 pRet = Tcl_NewObj();
537 Tcl_IncrRefCount(pRet);
538
539 assert( argc==1 );
540 pRec = (u8*)sqlite3_value_blob(argv[0]);
541
542 pHdr = pRec + sqlite3GetVarint(pRec, &nHdr);
543 pBody = pEndHdr = &pRec[nHdr];
544 while( pHdr<pEndHdr ){
545 Tcl_Obj *pVal = 0;
546 u64 iSerialType;
547 Mem mem;
548
549 memset(&mem, 0, sizeof(mem));
550 mem.db = db;
551 mem.enc = ENC(db);
552 pHdr += sqlite3GetVarint(pHdr, &iSerialType);
553 sqlite3VdbeSerialGet(pBody, (u32)iSerialType, &mem);
554 pBody += sqlite3VdbeSerialTypeLen((u32)iSerialType);
555
556 switch( sqlite3_value_type(&mem) ){
557 case SQLITE_TEXT:
558 pVal = Tcl_NewStringObj((const char*)sqlite3_value_text(&mem), -1);
559 break;
560
561 case SQLITE_BLOB: {
562 char hexdigit[] = {
563 '0', '1', '2', '3', '4', '5', '6', '7',
564 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
565 };
566 int n = sqlite3_value_bytes(&mem);
567 u8 *z = (u8*)sqlite3_value_blob(&mem);
568 int i;
569 pVal = Tcl_NewStringObj("x'", -1);
570 for(i=0; i<n; i++){
571 char hex[3];
572 hex[0] = hexdigit[((z[i] >> 4) & 0x0F)];
573 hex[1] = hexdigit[(z[i] & 0x0F)];
574 hex[2] = '\0';
575 Tcl_AppendStringsToObj(pVal, hex, 0);
576 }
577 Tcl_AppendStringsToObj(pVal, "'", 0);
578 break;
579 }
580
581 case SQLITE_FLOAT:
582 pVal = Tcl_NewDoubleObj(sqlite3_value_double(&mem));
583 break;
584
585 case SQLITE_INTEGER:
586 pVal = Tcl_NewWideIntObj(sqlite3_value_int64(&mem));
587 break;
588
589 case SQLITE_NULL:
590 pVal = Tcl_NewStringObj("NULL", -1);
591 break;
592
593 default:
594 assert( 0 );
595 }
596
597 Tcl_ListObjAppendElement(0, pRet, pVal);
598
599 if( mem.szMalloc ){
600 sqlite3DbFree(db, mem.zMalloc);
601 }
602 }
603
604 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
605 Tcl_DecrRefCount(pRet);
606}
607
608/*
609** test_zeroblob(N)
610**
611** The implementation of scalar SQL function "test_zeroblob()". This is
612** similar to the built-in zeroblob() function, except that it does not
613** check that the integer parameter is within range before passing it
614** to sqlite3_result_zeroblob().
615*/
616static void test_zeroblob(
617 sqlite3_context *context,
618 int argc,
619 sqlite3_value **argv
620){
621 int nZero = sqlite3_value_int(argv[0]);
622 sqlite3_result_zeroblob(context, nZero);
623}
624
625/* test_getsubtype(V)
626**
627** Return the subtype for value V.
628*/
629static void test_getsubtype(
630 sqlite3_context *context,
631 int argc,
632 sqlite3_value **argv
633){
634 sqlite3_result_int(context, (int)sqlite3_value_subtype(argv[0]));
635}
636
637/* test_frombind(A,B,C,...)
638**
639** Return an integer bitmask that has a bit set for every argument
640** (up to the first 63 arguments) that originates from a bind a parameter.
641*/
642static void test_frombind(
643 sqlite3_context *context,
644 int argc,
645 sqlite3_value **argv
646){
647 sqlite3_uint64 m = 0;
648 int i;
649 for(i=0; i<argc && i<63; i++){
650 if( sqlite3_value_frombind(argv[i]) ) m |= ((sqlite3_uint64)1)<<i;
651 }
652 sqlite3_result_int64(context, (sqlite3_int64)m);
653}
654
655/* test_setsubtype(V, T)
656**
657** Return the value V with its subtype changed to T
658*/
659static void test_setsubtype(
660 sqlite3_context *context,
661 int argc,
662 sqlite3_value **argv
663){
664 sqlite3_result_value(context, argv[0]);
665 sqlite3_result_subtype(context, (unsigned int)sqlite3_value_int(argv[1]));
666}
667
668static int registerTestFunctions(
669 sqlite3 *db,
670 char **pzErrMsg,
671 const sqlite3_api_routines *pThunk
672){
673 static const struct {
674 char *zName;
675 signed char nArg;
676 unsigned int eTextRep; /* 1: UTF-16. 0: UTF-8 */
677 void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
678 } aFuncs[] = {
679 { "randstr", 2, SQLITE_UTF8, randStr },
680 { "test_destructor", 1, SQLITE_UTF8, test_destructor},
681#ifndef SQLITE_OMIT_UTF16
682 { "test_destructor16", 1, SQLITE_UTF8, test_destructor16},
683 { "hex_to_utf16be", 1, SQLITE_UTF8, testHexToUtf16be},
684 { "hex_to_utf16le", 1, SQLITE_UTF8, testHexToUtf16le},
685#endif
686 { "hex_to_utf8", 1, SQLITE_UTF8, testHexToUtf8},
687 { "test_destructor_count", 0, SQLITE_UTF8, test_destructor_count},
688 { "test_auxdata", -1, SQLITE_UTF8, test_auxdata},
689 { "test_error", 1, SQLITE_UTF8, test_error},
690 { "test_error", 2, SQLITE_UTF8, test_error},
691 { "test_eval", 1, SQLITE_UTF8, test_eval},
692 { "test_isolation", 2, SQLITE_UTF8, test_isolation},
693 { "test_counter", 1, SQLITE_UTF8, counterFunc},
694 { "real2hex", 1, SQLITE_UTF8, real2hex},
695 { "test_decode", 1, SQLITE_UTF8, test_decode},
696 { "test_extract", 2, SQLITE_UTF8, test_extract},
697 { "test_zeroblob", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, test_zeroblob},
698 { "test_getsubtype", 1, SQLITE_UTF8, test_getsubtype},
699 { "test_setsubtype", 2, SQLITE_UTF8|SQLITE_RESULT_SUBTYPE,
700 test_setsubtype},
701 { "test_frombind", -1, SQLITE_UTF8, test_frombind},
702 };
703 int i;
704
705 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
706 sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
707 aFuncs[i].eTextRep, 0, aFuncs[i].xFunc, 0, 0);
708 }
709
710 sqlite3_create_function(db, "test_agg_errmsg16", 0, SQLITE_ANY, 0, 0,
711 test_agg_errmsg16_step, test_agg_errmsg16_final);
712
713 return SQLITE_OK;
714}
715
716/*
717** TCLCMD: autoinstall_test_functions
718**
719** Invoke this TCL command to use sqlite3_auto_extension() to cause
720** the standard set of test functions to be loaded into each new
721** database connection.
722*/
723static int SQLITE_TCLAPI autoinstall_test_funcs(
724 void * clientData,
725 Tcl_Interp *interp,
726 int objc,
727 Tcl_Obj *CONST objv[]
728){
729 extern int Md5_Register(sqlite3 *, char **, const sqlite3_api_routines *);
730 int rc = sqlite3_auto_extension((void(*)(void))registerTestFunctions);
731 if( rc==SQLITE_OK ){
732 rc = sqlite3_auto_extension((void(*)(void))Md5_Register);
733 }
734 Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
735 return TCL_OK;
736}
737
738/*
739** A bogus step function and finalizer function.
740*/
741static void tStep(sqlite3_context *a, int b, sqlite3_value **c){}
742static void tFinal(sqlite3_context *a){}
743
744
745/*
746** tclcmd: abuse_create_function
747**
748** Make various calls to sqlite3_create_function that do not have valid
749** parameters. Verify that the error condition is detected and reported.
750*/
751static int SQLITE_TCLAPI abuse_create_function(
752 void * clientData,
753 Tcl_Interp *interp,
754 int objc,
755 Tcl_Obj *CONST objv[]
756){
757 extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**);
758 sqlite3 *db;
759 int rc;
760 int mxArg;
761
762 if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
763
764 rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep,tStep,tFinal);
765 if( rc!=SQLITE_MISUSE ) goto abuse_err;
766
767 rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep, tStep, 0);
768 if( rc!=SQLITE_MISUSE ) goto abuse_err;
769
770 rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep, 0, tFinal);
771 if( rc!=SQLITE_MISUSE) goto abuse_err;
772
773 rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, 0, 0, tFinal);
774 if( rc!=SQLITE_MISUSE ) goto abuse_err;
775
776 rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, 0, tStep, 0);
777 if( rc!=SQLITE_MISUSE ) goto abuse_err;
778
779 rc = sqlite3_create_function(db, "tx", -2, SQLITE_UTF8, 0, tStep, 0, 0);
780 if( rc!=SQLITE_MISUSE ) goto abuse_err;
781
782 rc = sqlite3_create_function(db, "tx", 32768, SQLITE_UTF8, 0, tStep, 0, 0);
783 if( rc!=SQLITE_MISUSE ) goto abuse_err;
784
785 rc = sqlite3_create_function(db, "funcxx"
786 "_123456789_123456789_123456789_123456789_123456789"
787 "_123456789_123456789_123456789_123456789_123456789"
788 "_123456789_123456789_123456789_123456789_123456789"
789 "_123456789_123456789_123456789_123456789_123456789"
790 "_123456789_123456789_123456789_123456789_123456789",
791 1, SQLITE_UTF8, 0, tStep, 0, 0);
792 if( rc!=SQLITE_MISUSE ) goto abuse_err;
793
794 /* This last function registration should actually work. Generate
795 ** a no-op function (that always returns NULL) and which has the
796 ** maximum-length function name and the maximum number of parameters.
797 */
798 sqlite3_limit(db, SQLITE_LIMIT_FUNCTION_ARG, 1000000);
799 mxArg = sqlite3_limit(db, SQLITE_LIMIT_FUNCTION_ARG, -1);
800 rc = sqlite3_create_function(db, "nullx"
801 "_123456789_123456789_123456789_123456789_123456789"
802 "_123456789_123456789_123456789_123456789_123456789"
803 "_123456789_123456789_123456789_123456789_123456789"
804 "_123456789_123456789_123456789_123456789_123456789"
805 "_123456789_123456789_123456789_123456789_123456789",
806 mxArg, SQLITE_UTF8, 0, tStep, 0, 0);
807 if( rc!=SQLITE_OK ) goto abuse_err;
808
809 return TCL_OK;
810
811abuse_err:
812 Tcl_AppendResult(interp, "sqlite3_create_function abused test failed",
813 (char*)0);
814 return TCL_ERROR;
815}
816
817
818/*
819** SQLite user defined function to use with matchinfo() to calculate the
820** relevancy of an FTS match. The value returned is the relevancy score
821** (a real value greater than or equal to zero). A larger value indicates
822** a more relevant document.
823**
824** The overall relevancy returned is the sum of the relevancies of each
825** column value in the FTS table. The relevancy of a column value is the
826** sum of the following for each reportable phrase in the FTS query:
827**
828** (<hit count> / <global hit count>) * <column weight>
829**
830** where <hit count> is the number of instances of the phrase in the
831** column value of the current row and <global hit count> is the number
832** of instances of the phrase in the same column of all rows in the FTS
833** table. The <column weight> is a weighting factor assigned to each
834** column by the caller (see below).
835**
836** The first argument to this function must be the return value of the FTS
837** matchinfo() function. Following this must be one argument for each column
838** of the FTS table containing a numeric weight factor for the corresponding
839** column. Example:
840**
841** CREATE VIRTUAL TABLE documents USING fts3(title, content)
842**
843** The following query returns the docids of documents that match the full-text
844** query <query> sorted from most to least relevant. When calculating
845** relevance, query term instances in the 'title' column are given twice the
846** weighting of those in the 'content' column.
847**
848** SELECT docid FROM documents
849** WHERE documents MATCH <query>
850** ORDER BY rank(matchinfo(documents), 1.0, 0.5) DESC
851*/
852static void rankfunc(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
853 int *aMatchinfo; /* Return value of matchinfo() */
854 int nMatchinfo; /* Number of elements in aMatchinfo[] */
855 int nCol = 0; /* Number of columns in the table */
856 int nPhrase = 0; /* Number of phrases in the query */
857 int iPhrase; /* Current phrase */
858 double score = 0.0; /* Value to return */
859
860 assert( sizeof(int)==4 );
861
862 /* Check that the number of arguments passed to this function is correct.
863 ** If not, jump to wrong_number_args. Set aMatchinfo to point to the array
864 ** of unsigned integer values returned by FTS function matchinfo. Set
865 ** nPhrase to contain the number of reportable phrases in the users full-text
866 ** query, and nCol to the number of columns in the table. Then check that the
867 ** size of the matchinfo blob is as expected. Return an error if it is not.
868 */
869 if( nVal<1 ) goto wrong_number_args;
870 aMatchinfo = (int*)sqlite3_value_blob(apVal[0]);
871 nMatchinfo = sqlite3_value_bytes(apVal[0]) / sizeof(int);
872 if( nMatchinfo>=2 ){
873 nPhrase = aMatchinfo[0];
874 nCol = aMatchinfo[1];
875 }
876 if( nMatchinfo!=(2+3*nCol*nPhrase) ){
877 sqlite3_result_error(pCtx,
878 "invalid matchinfo blob passed to function rank()", -1);
879 return;
880 }
881 if( nVal!=(1+nCol) ) goto wrong_number_args;
882
883 /* Iterate through each phrase in the users query. */
884 for(iPhrase=0; iPhrase<nPhrase; iPhrase++){
885 int iCol; /* Current column */
886
887 /* Now iterate through each column in the users query. For each column,
888 ** increment the relevancy score by:
889 **
890 ** (<hit count> / <global hit count>) * <column weight>
891 **
892 ** aPhraseinfo[] points to the start of the data for phrase iPhrase. So
893 ** the hit count and global hit counts for each column are found in
894 ** aPhraseinfo[iCol*3] and aPhraseinfo[iCol*3+1], respectively.
895 */
896 int *aPhraseinfo = &aMatchinfo[2 + iPhrase*nCol*3];
897 for(iCol=0; iCol<nCol; iCol++){
898 int nHitCount = aPhraseinfo[3*iCol];
899 int nGlobalHitCount = aPhraseinfo[3*iCol+1];
900 double weight = sqlite3_value_double(apVal[iCol+1]);
901 if( nHitCount>0 ){
902 score += ((double)nHitCount / (double)nGlobalHitCount) * weight;
903 }
904 }
905 }
906
907 sqlite3_result_double(pCtx, score);
908 return;
909
910 /* Jump here if the wrong number of arguments are passed to this function */
911wrong_number_args:
912 sqlite3_result_error(pCtx, "wrong number of arguments to function rank()", -1);
913}
914
915static int SQLITE_TCLAPI install_fts3_rank_function(
916 void * clientData,
917 Tcl_Interp *interp,
918 int objc,
919 Tcl_Obj *CONST objv[]
920){
921 extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**);
922 sqlite3 *db;
923
924 if( objc!=2 ){
925 Tcl_WrongNumArgs(interp, 1, objv, "DB");
926 return TCL_ERROR;
927 }
928
929 if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
930 sqlite3_create_function(db, "rank", -1, SQLITE_UTF8, 0, rankfunc, 0, 0);
931 return TCL_OK;
932}
933
934
935/*
936** Register commands with the TCL interpreter.
937*/
938int Sqlitetest_func_Init(Tcl_Interp *interp){
939 static struct {
940 char *zName;
941 Tcl_ObjCmdProc *xProc;
942 } aObjCmd[] = {
943 { "autoinstall_test_functions", autoinstall_test_funcs },
944 { "abuse_create_function", abuse_create_function },
945 { "install_fts3_rank_function", install_fts3_rank_function },
946 };
947 int i;
948 extern int Md5_Register(sqlite3 *, char **, const sqlite3_api_routines *);
949
950 for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
951 Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, 0, 0);
952 }
953 sqlite3_initialize();
954 sqlite3_auto_extension((void(*)(void))registerTestFunctions);
955 sqlite3_auto_extension((void(*)(void))Md5_Register);
956 return TCL_OK;
957}