xref: /sqlite-3.40.0/src/test_func.c (revision d5578433)
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 "tcl.h"
17 #include <stdlib.h>
18 #include <string.h>
19 #include <assert.h>
20 
21 
22 /*
23 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
24 ** allocation fails, call sqlite3_result_error_nomem() to notify
25 ** the database handle that malloc() has failed.
26 */
27 static void *testContextMalloc(sqlite3_context *context, int nByte){
28   char *z = sqlite3_malloc(nByte);
29   if( !z && nByte>0 ){
30     sqlite3_result_error_nomem(context);
31   }
32   return z;
33 }
34 
35 /*
36 ** This function generates a string of random characters.  Used for
37 ** generating test data.
38 */
39 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
40   static const unsigned char zSrc[] =
41      "abcdefghijklmnopqrstuvwxyz"
42      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
43      "0123456789"
44      ".-!,:*^+=_|?/<> ";
45   int iMin, iMax, n, r, i;
46   unsigned char zBuf[1000];
47 
48   /* It used to be possible to call randstr() with any number of arguments,
49   ** but now it is registered with SQLite as requiring exactly 2.
50   */
51   assert(argc==2);
52 
53   iMin = sqlite3_value_int(argv[0]);
54   if( iMin<0 ) iMin = 0;
55   if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
56   iMax = sqlite3_value_int(argv[1]);
57   if( iMax<iMin ) iMax = iMin;
58   if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
59   n = iMin;
60   if( iMax>iMin ){
61     sqlite3_randomness(sizeof(r), &r);
62     r &= 0x7fffffff;
63     n += r%(iMax + 1 - iMin);
64   }
65   assert( n<sizeof(zBuf) );
66   sqlite3_randomness(n, zBuf);
67   for(i=0; i<n; i++){
68     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
69   }
70   zBuf[n] = 0;
71   sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
72 }
73 
74 /*
75 ** The following two SQL functions are used to test returning a text
76 ** result with a destructor. Function 'test_destructor' takes one argument
77 ** and returns the same argument interpreted as TEXT. A destructor is
78 ** passed with the sqlite3_result_text() call.
79 **
80 ** SQL function 'test_destructor_count' returns the number of outstanding
81 ** allocations made by 'test_destructor';
82 **
83 ** WARNING: Not threadsafe.
84 */
85 static int test_destructor_count_var = 0;
86 static void destructor(void *p){
87   char *zVal = (char *)p;
88   assert(zVal);
89   zVal--;
90   sqlite3_free(zVal);
91   test_destructor_count_var--;
92 }
93 static void test_destructor(
94   sqlite3_context *pCtx,
95   int nArg,
96   sqlite3_value **argv
97 ){
98   char *zVal;
99   int len;
100 
101   test_destructor_count_var++;
102   assert( nArg==1 );
103   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104   len = sqlite3_value_bytes(argv[0]);
105   zVal = testContextMalloc(pCtx, len+3);
106   if( !zVal ){
107     return;
108   }
109   zVal[len+1] = 0;
110   zVal[len+2] = 0;
111   zVal++;
112   memcpy(zVal, sqlite3_value_text(argv[0]), len);
113   sqlite3_result_text(pCtx, zVal, -1, destructor);
114 }
115 #ifndef SQLITE_OMIT_UTF16
116 static void test_destructor16(
117   sqlite3_context *pCtx,
118   int nArg,
119   sqlite3_value **argv
120 ){
121   char *zVal;
122   int len;
123 
124   test_destructor_count_var++;
125   assert( nArg==1 );
126   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
127   len = sqlite3_value_bytes16(argv[0]);
128   zVal = testContextMalloc(pCtx, len+3);
129   if( !zVal ){
130     return;
131   }
132   zVal[len+1] = 0;
133   zVal[len+2] = 0;
134   zVal++;
135   memcpy(zVal, sqlite3_value_text16(argv[0]), len);
136   sqlite3_result_text16(pCtx, zVal, -1, destructor);
137 }
138 #endif
139 static void test_destructor_count(
140   sqlite3_context *pCtx,
141   int nArg,
142   sqlite3_value **argv
143 ){
144   sqlite3_result_int(pCtx, test_destructor_count_var);
145 }
146 
147 /*
148 ** The following aggregate function, test_agg_errmsg16(), takes zero
149 ** arguments. It returns the text value returned by the sqlite3_errmsg16()
150 ** API function.
151 */
152 #ifndef SQLITE_OMIT_BUILTIN_TEST
153 void sqlite3BeginBenignMalloc(void);
154 void sqlite3EndBenignMalloc(void);
155 #else
156   #define sqlite3BeginBenignMalloc()
157   #define sqlite3EndBenignMalloc()
158 #endif
159 static void test_agg_errmsg16_step(sqlite3_context *a, int b,sqlite3_value **c){
160 }
161 static void test_agg_errmsg16_final(sqlite3_context *ctx){
162 #ifndef SQLITE_OMIT_UTF16
163   const void *z;
164   sqlite3 * db = sqlite3_context_db_handle(ctx);
165   sqlite3_aggregate_context(ctx, 2048);
166   sqlite3BeginBenignMalloc();
167   z = sqlite3_errmsg16(db);
168   sqlite3EndBenignMalloc();
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 */
184 static void free_test_auxdata(void *p) {sqlite3_free(p);}
185 static 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 */
222 static 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 */
239 static 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 */
272 static 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 */
290 static 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 
300   zSql = (char*)sqlite3_value_text(argv[0]);
301   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
302   if( rc==SQLITE_OK ){
303     rc = sqlite3_step(pStmt);
304     if( rc==SQLITE_ROW ){
305       sqlite3_result_value(pCtx, sqlite3_column_value(pStmt, 0));
306     }
307     rc = sqlite3_finalize(pStmt);
308   }
309   if( rc ){
310     char *zErr;
311     assert( pStmt==0 );
312     zErr = sqlite3_mprintf("sqlite3_prepare_v2() error: %s",sqlite3_errmsg(db));
313     sqlite3_result_text(pCtx, zErr, -1, sqlite3_free);
314     sqlite3_result_error_code(pCtx, rc);
315   }
316 }
317 
318 
319 /*
320 ** convert one character from hex to binary
321 */
322 static int testHexChar(char c){
323   if( c>='0' && c<='9' ){
324     return c - '0';
325   }else if( c>='a' && c<='f' ){
326     return c - 'a' + 10;
327   }else if( c>='A' && c<='F' ){
328     return c - 'A' + 10;
329   }
330   return 0;
331 }
332 
333 /*
334 ** Convert hex to binary.
335 */
336 static void testHexToBin(const char *zIn, char *zOut){
337   while( zIn[0] && zIn[1] ){
338     *(zOut++) = (testHexChar(zIn[0])<<4) + testHexChar(zIn[1]);
339     zIn += 2;
340   }
341 }
342 
343 /*
344 **      hex_to_utf16be(HEX)
345 **
346 ** Convert the input string from HEX into binary.  Then return the
347 ** result using sqlite3_result_text16le().
348 */
349 #ifndef SQLITE_OMIT_UTF16
350 static void testHexToUtf16be(
351   sqlite3_context *pCtx,
352   int nArg,
353   sqlite3_value **argv
354 ){
355   int n;
356   const char *zIn;
357   char *zOut;
358   assert( nArg==1 );
359   n = sqlite3_value_bytes(argv[0]);
360   zIn = (const char*)sqlite3_value_text(argv[0]);
361   zOut = sqlite3_malloc( n/2 );
362   if( zOut==0 ){
363     sqlite3_result_error_nomem(pCtx);
364   }else{
365     testHexToBin(zIn, zOut);
366     sqlite3_result_text16be(pCtx, zOut, n/2, sqlite3_free);
367   }
368 }
369 #endif
370 
371 /*
372 **      hex_to_utf8(HEX)
373 **
374 ** Convert the input string from HEX into binary.  Then return the
375 ** result using sqlite3_result_text16le().
376 */
377 static void testHexToUtf8(
378   sqlite3_context *pCtx,
379   int nArg,
380   sqlite3_value **argv
381 ){
382   int n;
383   const char *zIn;
384   char *zOut;
385   assert( nArg==1 );
386   n = sqlite3_value_bytes(argv[0]);
387   zIn = (const char*)sqlite3_value_text(argv[0]);
388   zOut = sqlite3_malloc( n/2 );
389   if( zOut==0 ){
390     sqlite3_result_error_nomem(pCtx);
391   }else{
392     testHexToBin(zIn, zOut);
393     sqlite3_result_text(pCtx, zOut, n/2, sqlite3_free);
394   }
395 }
396 
397 /*
398 **      hex_to_utf16le(HEX)
399 **
400 ** Convert the input string from HEX into binary.  Then return the
401 ** result using sqlite3_result_text16le().
402 */
403 #ifndef SQLITE_OMIT_UTF16
404 static void testHexToUtf16le(
405   sqlite3_context *pCtx,
406   int nArg,
407   sqlite3_value **argv
408 ){
409   int n;
410   const char *zIn;
411   char *zOut;
412   assert( nArg==1 );
413   n = sqlite3_value_bytes(argv[0]);
414   zIn = (const char*)sqlite3_value_text(argv[0]);
415   zOut = sqlite3_malloc( n/2 );
416   if( zOut==0 ){
417     sqlite3_result_error_nomem(pCtx);
418   }else{
419     testHexToBin(zIn, zOut);
420     sqlite3_result_text16le(pCtx, zOut, n/2, sqlite3_free);
421   }
422 }
423 #endif
424 
425 /*
426 ** SQL function:   real2hex(X)
427 **
428 ** If argument X is a real number, then convert it into a string which is
429 ** the big-endian hexadecimal representation of the ieee754 encoding of
430 ** that number.  If X is not a real number, return NULL.
431 */
432 static void real2hex(
433   sqlite3_context *context,
434   int argc,
435   sqlite3_value **argv
436 ){
437   union {
438     sqlite3_uint64 i;
439     double r;
440     unsigned char x[8];
441   } v;
442   char zOut[20];
443   int i;
444   int bigEndian;
445   v.i = 1;
446   bigEndian = v.x[0]==0;
447   v.r = sqlite3_value_double(argv[0]);
448   for(i=0; i<8; i++){
449     if( bigEndian ){
450       zOut[i*2]   = "0123456789abcdef"[v.x[i]>>4];
451       zOut[i*2+1] = "0123456789abcdef"[v.x[i]&0xf];
452     }else{
453       zOut[14-i*2]   = "0123456789abcdef"[v.x[i]>>4];
454       zOut[14-i*2+1] = "0123456789abcdef"[v.x[i]&0xf];
455     }
456   }
457   zOut[16] = 0;
458   sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT);
459 }
460 
461 
462 static int registerTestFunctions(sqlite3 *db){
463   static const struct {
464      char *zName;
465      signed char nArg;
466      unsigned char eTextRep; /* 1: UTF-16.  0: UTF-8 */
467      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
468   } aFuncs[] = {
469     { "randstr",               2, SQLITE_UTF8, randStr    },
470     { "test_destructor",       1, SQLITE_UTF8, test_destructor},
471 #ifndef SQLITE_OMIT_UTF16
472     { "test_destructor16",     1, SQLITE_UTF8, test_destructor16},
473     { "hex_to_utf16be",        1, SQLITE_UTF8, testHexToUtf16be},
474     { "hex_to_utf16le",        1, SQLITE_UTF8, testHexToUtf16le},
475 #endif
476     { "hex_to_utf8",           1, SQLITE_UTF8, testHexToUtf8},
477     { "test_destructor_count", 0, SQLITE_UTF8, test_destructor_count},
478     { "test_auxdata",         -1, SQLITE_UTF8, test_auxdata},
479     { "test_error",            1, SQLITE_UTF8, test_error},
480     { "test_error",            2, SQLITE_UTF8, test_error},
481     { "test_eval",             1, SQLITE_UTF8, test_eval},
482     { "test_isolation",        2, SQLITE_UTF8, test_isolation},
483     { "test_counter",          1, SQLITE_UTF8, counterFunc},
484     { "real2hex",              1, SQLITE_UTF8, real2hex},
485   };
486   int i;
487 
488   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
489     sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
490         aFuncs[i].eTextRep, 0, aFuncs[i].xFunc, 0, 0);
491   }
492 
493   sqlite3_create_function(db, "test_agg_errmsg16", 0, SQLITE_ANY, 0, 0,
494       test_agg_errmsg16_step, test_agg_errmsg16_final);
495 
496   return SQLITE_OK;
497 }
498 
499 /*
500 ** TCLCMD:  autoinstall_test_functions
501 **
502 ** Invoke this TCL command to use sqlite3_auto_extension() to cause
503 ** the standard set of test functions to be loaded into each new
504 ** database connection.
505 */
506 static int autoinstall_test_funcs(
507   void * clientData,
508   Tcl_Interp *interp,
509   int objc,
510   Tcl_Obj *CONST objv[]
511 ){
512   extern int Md5_Register(sqlite3*);
513   int rc = sqlite3_auto_extension((void*)registerTestFunctions);
514   if( rc==SQLITE_OK ){
515     rc = sqlite3_auto_extension((void*)Md5_Register);
516   }
517   Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
518   return TCL_OK;
519 }
520 
521 /*
522 ** A bogus step function and finalizer function.
523 */
524 static void tStep(sqlite3_context *a, int b, sqlite3_value **c){}
525 static void tFinal(sqlite3_context *a){}
526 
527 
528 /*
529 ** tclcmd:  abuse_create_function
530 **
531 ** Make various calls to sqlite3_create_function that do not have valid
532 ** parameters.  Verify that the error condition is detected and reported.
533 */
534 static int abuse_create_function(
535   void * clientData,
536   Tcl_Interp *interp,
537   int objc,
538   Tcl_Obj *CONST objv[]
539 ){
540   extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**);
541   sqlite3 *db;
542   int rc;
543   int mxArg;
544 
545   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
546 
547   rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep,tStep,tFinal);
548   if( rc!=SQLITE_MISUSE ) goto abuse_err;
549 
550   rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep, tStep, 0);
551   if( rc!=SQLITE_MISUSE ) goto abuse_err;
552 
553   rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep, 0, tFinal);
554   if( rc!=SQLITE_MISUSE) goto abuse_err;
555 
556   rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, 0, 0, tFinal);
557   if( rc!=SQLITE_MISUSE ) goto abuse_err;
558 
559   rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, 0, tStep, 0);
560   if( rc!=SQLITE_MISUSE ) goto abuse_err;
561 
562   rc = sqlite3_create_function(db, "tx", -2, SQLITE_UTF8, 0, tStep, 0, 0);
563   if( rc!=SQLITE_MISUSE ) goto abuse_err;
564 
565   rc = sqlite3_create_function(db, "tx", 128, SQLITE_UTF8, 0, tStep, 0, 0);
566   if( rc!=SQLITE_MISUSE ) goto abuse_err;
567 
568   rc = sqlite3_create_function(db, "funcxx"
569        "_123456789_123456789_123456789_123456789_123456789"
570        "_123456789_123456789_123456789_123456789_123456789"
571        "_123456789_123456789_123456789_123456789_123456789"
572        "_123456789_123456789_123456789_123456789_123456789"
573        "_123456789_123456789_123456789_123456789_123456789",
574        1, SQLITE_UTF8, 0, tStep, 0, 0);
575   if( rc!=SQLITE_MISUSE ) goto abuse_err;
576 
577   /* This last function registration should actually work.  Generate
578   ** a no-op function (that always returns NULL) and which has the
579   ** maximum-length function name and the maximum number of parameters.
580   */
581   sqlite3_limit(db, SQLITE_LIMIT_FUNCTION_ARG, 10000);
582   mxArg = sqlite3_limit(db, SQLITE_LIMIT_FUNCTION_ARG, -1);
583   rc = sqlite3_create_function(db, "nullx"
584        "_123456789_123456789_123456789_123456789_123456789"
585        "_123456789_123456789_123456789_123456789_123456789"
586        "_123456789_123456789_123456789_123456789_123456789"
587        "_123456789_123456789_123456789_123456789_123456789"
588        "_123456789_123456789_123456789_123456789_123456789",
589        mxArg, SQLITE_UTF8, 0, tStep, 0, 0);
590   if( rc!=SQLITE_OK ) goto abuse_err;
591 
592   return TCL_OK;
593 
594 abuse_err:
595   Tcl_AppendResult(interp, "sqlite3_create_function abused test failed",
596                    (char*)0);
597   return TCL_ERROR;
598 }
599 
600 /*
601 ** Register commands with the TCL interpreter.
602 */
603 int Sqlitetest_func_Init(Tcl_Interp *interp){
604   static struct {
605      char *zName;
606      Tcl_ObjCmdProc *xProc;
607   } aObjCmd[] = {
608      { "autoinstall_test_functions",    autoinstall_test_funcs },
609      { "abuse_create_function",         abuse_create_function  },
610   };
611   int i;
612   extern int Md5_Register(sqlite3*);
613 
614   for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
615     Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, 0, 0);
616   }
617   sqlite3_initialize();
618   sqlite3_auto_extension((void*)registerTestFunctions);
619   sqlite3_auto_extension((void*)Md5_Register);
620   return TCL_OK;
621 }
622