/ Check-in [4eccae03]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Use the new API for returning values and errors from user functions. (CVS 1453)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 4eccae03b4a7f37804fea30416579787c3584bb2
User & Date: danielk1977 2004-05-25 11:47:25
Context
2004-05-25
12:05
Change a couple of symbol names for the new user function API. (CVS 1454) check-in: 8f6b20c2 user: danielk1977 tags: trunk
11:47
Use the new API for returning values and errors from user functions. (CVS 1453) check-in: 4eccae03 user: danielk1977 tags: trunk
01:13
Add manifest type aware versions of the min() and max() aggregates. (CVS 1452) check-in: b77c268e user: danielk1977 tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to src/date.c.

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
...
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
...
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
...
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
...
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
...
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
** This file contains the C functions that implement date and time
** functions for SQLite.  
**
** There is only one exported symbol in this file - the function
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: date.c,v 1.21 2004/05/24 12:39:02 danielk1977 Exp $
**
** NOTES:
**
** SQLite processes all times and dates as Julian Day numbers.  The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system.
................................................................................
**
** Return the julian day number of the date specified in the arguments
*/
static void juliandayFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    computeJD(&x);
    sqlite3_set_result_double(context, x.rJD);
  }
}

/*
**    datetime( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD HH:MM:SS
................................................................................
static void datetimeFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
           (int)(x.s));
    sqlite3_set_result_string(context, zBuf, -1);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
................................................................................
*/
static void timeFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    sqlite3_set_result_string(context, zBuf, -1);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD
................................................................................
*/
static void dateFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
    sqlite3_set_result_string(context, zBuf, -1);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
** Return a string described by FORMAT.  Conversions as follows:
................................................................................
        case 'w':  z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
        case 'Y':  sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
        case '%':  z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;
  sqlite3_set_result_string(context, z, -1);
  if( z!=zBuf ){
    sqliteFree(z);
  }
}


#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */







|







 







|







 







|







 







|







 







|







 







|







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
...
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
...
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
...
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
...
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
...
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
** This file contains the C functions that implement date and time
** functions for SQLite.  
**
** There is only one exported symbol in this file - the function
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: date.c,v 1.22 2004/05/25 11:47:25 danielk1977 Exp $
**
** NOTES:
**
** SQLite processes all times and dates as Julian Day numbers.  The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system.
................................................................................
**
** Return the julian day number of the date specified in the arguments
*/
static void juliandayFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    computeJD(&x);
    sqlite3_result_double(context, x.rJD);
  }
}

/*
**    datetime( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD HH:MM:SS
................................................................................
static void datetimeFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
           (int)(x.s));
    sqlite3_result_text(context, zBuf, -1, 1);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
................................................................................
*/
static void timeFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    sqlite3_result_text(context, zBuf, -1, 1);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD
................................................................................
*/
static void dateFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
    sqlite3_result_text(context, zBuf, -1, 1);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
** Return a string described by FORMAT.  Conversions as follows:
................................................................................
        case 'w':  z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
        case 'Y':  sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
        case '%':  z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;
  sqlite3_result_text(context, z, -1, 1);
  if( z!=zBuf ){
    sqliteFree(z);
  }
}


#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */

Changes to src/func.c.

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
..
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
...
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

180
181
182


183
184
185
186
187
188
189

190
191
192


193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
...
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
...
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
...
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
...
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
...
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
...
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
...
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
...
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
...
548
549
550
551
552
553
554








555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
** This file contains the C functions that implement various SQL
** functions of SQLite.  
**
** There is only one exported symbol in this file - the function
** sqliteRegisterBuildinFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: func.c,v 1.53 2004/05/25 01:13:21 danielk1977 Exp $
*/
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include "sqliteInt.h"
#include "vdbeInt.h"
................................................................................
  for(i=2; i<argc; i+=2){
    zArg = sqlite3_value_data(argv[i]);
    if( zArg==0 ) return;
    if( (xCompare(zArg, zBest)^mask)<0 ){
      zBest = zArg;
    }
  }
  sqlite3_set_result_string(context, zBest, -1);
}

/*
** Return the type of the argument.
*/
static void typeofFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z = 0;
................................................................................
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE3_NULL: z = "null" ; break;
    case SQLITE3_INTEGER: z = "integer" ; break;
    case SQLITE3_TEXT: z = "text" ; break;
    case SQLITE3_FLOAT: z = "real" ; break;
    case SQLITE3_BLOB: z = "blob" ; break;
  }
  sqlite3_set_result_string(context, z, -1);
}

/*
** Implementation of the length() function
*/
static void lengthFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z;
................................................................................
  z = sqlite3_value_data(argv[0]);
  if( z==0 ) return;
#ifdef SQLITE_UTF8
  for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
#else
  len = strlen(z);
#endif
  sqlite3_set_result_int(context, len);
}

/*
** Implementation of the abs() function
*/
static void absFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z;
  assert( argc==1 );
  z = sqlite3_value_data(argv[0]);
  if( z==0 ) return;
  if( z[0]=='-' && isdigit(z[1]) ) z++;
  sqlite3_set_result_string(context, z, -1);
}

/*
** Implementation of the substr() function
*/
static void substrFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z;
................................................................................
  while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
  for(; i<p1+p2 && z[i]; i++){
    if( (z[i]&0xc0)==0x80 ) p2++;
  }
  while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
#endif
  if( p2<0 ) p2 = 0;
  sqlite3_set_result_string(context, &z[p1], p2);
}

/*
** Implementation of the round() function
*/
static void roundFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int n = 0;
................................................................................
    n = sqlite3_value_int(argv[1]);
    if( n>30 ) n = 30;
    if( n<0 ) n = 0;
  }
  if( SQLITE3_NULL==sqlite3_value_type(argv[0]) ) return;
  r = sqlite3_value_float(argv[0]);
  sprintf(zBuf,"%.*f",n,r);
  sqlite3_set_result_string(context, zBuf, -1);
}

/*
** Implementation of the upper() and lower() SQL functions.
*/
static void upperFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  char *z;
  int i;
  if( argc<1 ) return;
  z = sqlite3_set_result_string(context, sqlite3_value_data(argv[0]), -1);
  if( z==0 ) return;

  for(i=0; z[i]; i++){
    if( islower(z[i]) ) z[i] = toupper(z[i]);
  }


}
static void lowerFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  char *z;
  int i;
  if( argc<1 ) return;
  z = sqlite3_set_result_string(context, sqlite3_value_data(argv[0]), -1);
  if( z==0 ) return;

  for(i=0; z[i]; i++){
    if( isupper(z[i]) ) z[i] = tolower(z[i]);
  }


}

/*
** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
** All three do the same thing.  They return the first non-NULL
** argument.
*/
static void ifnullFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE3_NULL!=sqlite3_value_type(argv[i]) ){
      sqlite3_set_result_string(context, sqlite3_value_data(argv[i]), -1);
      break;
    }
  }
}

/*
** Implementation of random().  Return a random integer.  
*/
static void randomFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int r;
  sqlite3Randomness(sizeof(r), &r);
  sqlite3_set_result_int(context, r);
}

/*
** Implementation of the last_insert_rowid() SQL function.  The return
** value is the same as the sqlite3_last_insert_rowid() API function.
*/
static void last_insert_rowid(
  sqlite_func *context, 
  int arg, 
  sqlite3_value **argv
){
  sqlite *db = sqlite3_user_data(context);
  sqlite3_set_result_int(context, sqlite3_last_insert_rowid(db));
}

/*
** Implementation of the change_count() SQL function.  The return
** value is the same as the sqlite3_changes() API function.
*/
static void change_count(sqlite_func *context, int arg, sqlite3_value **argv){
  sqlite *db = sqlite3_user_data(context);
  sqlite3_set_result_int(context, sqlite3_changes(db));
}

/*
** Implementation of the last_statement_change_count() SQL function.  The
** return value is the same as the sqlite3_last_statement_changes() API
** function.
*/
static void last_statement_change_count(
  sqlite_func *context, 
  int arg,
  sqlite3_value **argv
){
  sqlite *db = sqlite3_user_data(context);
  sqlite3_set_result_int(context, sqlite3_last_statement_changes(db));
}

/*
** Implementation of the like() SQL function.  This function implements
** the build-in LIKE operator.  The first argument to the function is the
** string and the second argument is the pattern.  So, the SQL statements:
**
................................................................................
  sqlite_func *context, 
  int argc, 
  sqlite3_value **argv
){
  const unsigned char *zA = sqlite3_value_data(argv[0]);
  const unsigned char *zB = sqlite3_value_data(argv[1]);
  if( zA && zB ){
    sqlite3_set_result_int(context, sqlite3LikeCompare(zA, zB));
  }
}

/*
** Implementation of the glob() SQL function.  This function implements
** the build-in GLOB operator.  The first argument to the function is the
** string and the second argument is the pattern.  So, the SQL statements:
................................................................................
**
** is implemented as glob(A,B).
*/
static void globFunc(sqlite_func *context, int arg, sqlite3_value **argv){
  const unsigned char *zA = sqlite3_value_data(argv[0]);
  const unsigned char *zB = sqlite3_value_data(argv[1]);
  if( zA && zB ){
    sqlite3_set_result_int(context, sqlite3GlobCompare(zA, zB));
  }
}

/*
** Implementation of the NULLIF(x,y) function.  The result is the first
** argument if the arguments are different.  The result is NULL if the
** arguments are equal to each other.
*/
static void nullifFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const unsigned char *zX = sqlite3_value_data(argv[0]);
  const unsigned char *zY = sqlite3_value_data(argv[1]);
  if( zX!=0 && sqlite3Compare(zX, zY)!=0 ){
    sqlite3_set_result_string(context, zX, -1);
  }
}

/*
** Implementation of the VERSION(*) function.  The result is the version
** of the SQLite library that is running.
*/
static void versionFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  sqlite3_set_result_string(context, sqlite3_version, -1);
}

/*
** EXPERIMENTAL - This is not an official function.  The interface may
** change.  This function may disappear.  Do not write code that depends
** on this function.
**
................................................................................
** "NULL".  Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *zArg = sqlite3_value_data(argv[0]);
  if( argc<1 ) return;
  if( zArg==0 ){
    sqlite3_set_result_string(context, "NULL", 4);
  }else if( sqlite3IsNumber(zArg, 0, TEXT_Utf8) ){
    sqlite3_set_result_string(context, zArg, -1);
  }else{
    int i,j,n;
    char *z;
    for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
    z = sqliteMalloc( i+n+3 );
    if( z==0 ) return;
    z[0] = '\'';
................................................................................
      z[j++] = zArg[i];
      if( zArg[i]=='\'' ){
        z[j++] = '\'';
      }
    }
    z[j++] = '\'';
    z[j] = 0;
    sqlite3_set_result_string(context, z, j);
    sqliteFree(z);
  }
}

#ifdef SQLITE_SOUNDEX
/*
** Compute the soundex encoding of a word.
................................................................................
        zResult[j++] = code + '0';
      }
    }
    while( j<4 ){
      zResult[j++] = '0';
    }
    zResult[j] = 0;
    sqlite3_set_result_string(context, zResult, 4);
  }else{
    sqlite3_set_result_string(context, "?000", 4);
  }
}
#endif

#ifdef SQLITE_TEST
/*
** This function generates a string of random characters.  Used for
................................................................................
  }
  assert( n<sizeof(zBuf) );
  sqlite3Randomness(n, zBuf);
  for(i=0; i<n; i++){
    zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  }
  zBuf[n] = 0;
  sqlite3_set_result_string(context, zBuf, n);
}
#endif

/*
** An instance of the following structure holds the context of a
** sum() or avg() aggregate computation.
*/
................................................................................
    p->sum += sqlite3_value_float(argv[0]);
    p->cnt++;
  }
}
static void sumFinalize(sqlite_func *context){
  SumCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  sqlite3_set_result_double(context, p ? p->sum : 0.0);
}
static void avgFinalize(sqlite_func *context){
  SumCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  if( p && p->cnt>0 ){
    sqlite3_set_result_double(context, p->sum/(double)p->cnt);
  }
}

/*
** An instance of the following structure holds the context of a
** variance or standard deviation computation.
*/
................................................................................
  if( (argc==0 || SQLITE3_NULL!=sqlite3_value_type(argv[0])) && p ){
    p->n++;
  }
}   
static void countFinalize(sqlite_func *context){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  sqlite3_set_result_int(context, p ? p->n : 0);
}

/*
** This function tracks state information for the min() and max()
** aggregate functions.
*/
typedef struct MinMaxCtx MinMaxCtx;
................................................................................
  int cmp = 0;
  Mem *pArg  = (Mem *)argv[0];
  Mem *pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));

  if( SQLITE3_NULL==sqlite3_value_type(argv[0]) ) return;

  if( pBest->flags ){








    max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
    cmp = sqlite3MemCompare(pBest, pArg, 0);
    if( (max && cmp<0) || (!max && cmp>0) ){
      sqlite3MemCopy(pBest, pArg);
    }
  }else{
    sqlite3MemCopy(pBest, pArg);
  }
}
static void minMaxFinalize(sqlite_func *context){
  sqlite3_value *pRes;
  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, sizeof(Mem));
  
  if( pRes->flags ){
    switch( sqlite3_value_type(pRes) ){
      case SQLITE3_INTEGER: 
        sqlite3_set_result_int(context, sqlite3_value_int(pRes));
        break;
      case SQLITE3_FLOAT: 
        sqlite3_set_result_double(context, sqlite3_value_float(pRes));
      case SQLITE3_TEXT: 
      case SQLITE3_BLOB: 
        sqlite3_set_result_string(context,
            sqlite3_value_data(pRes),
            sqlite3_value_bytes(pRes));
        break;
      case SQLITE3_NULL: 
      default:
        assert(0);
    }
  }
}







|







 







|







 







|







 







|











|







 







|







 







|








|
|

>



>
>




|
|

>



>
>











|











|












|








|













|







 







|







 







|












|








|







 







|

|







 







|







 







|

|







 







|







 







|





|







 







|







 







>
>
>
>
>
>
>
>



|


|









|


|


|
|
<







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
..
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
...
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
...
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
...
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
...
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
...
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
...
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
...
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
...
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
...
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
...
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592

593
594
595
596
597
598
599
** This file contains the C functions that implement various SQL
** functions of SQLite.  
**
** There is only one exported symbol in this file - the function
** sqliteRegisterBuildinFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: func.c,v 1.54 2004/05/25 11:47:25 danielk1977 Exp $
*/
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include "sqliteInt.h"
#include "vdbeInt.h"
................................................................................
  for(i=2; i<argc; i+=2){
    zArg = sqlite3_value_data(argv[i]);
    if( zArg==0 ) return;
    if( (xCompare(zArg, zBest)^mask)<0 ){
      zBest = zArg;
    }
  }
  sqlite3_result_text(context, zBest, -1, 1);
}

/*
** Return the type of the argument.
*/
static void typeofFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z = 0;
................................................................................
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE3_NULL: z = "null" ; break;
    case SQLITE3_INTEGER: z = "integer" ; break;
    case SQLITE3_TEXT: z = "text" ; break;
    case SQLITE3_FLOAT: z = "real" ; break;
    case SQLITE3_BLOB: z = "blob" ; break;
  }
  sqlite3_result_text(context, z, -1, 0);
}

/*
** Implementation of the length() function
*/
static void lengthFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z;
................................................................................
  z = sqlite3_value_data(argv[0]);
  if( z==0 ) return;
#ifdef SQLITE_UTF8
  for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
#else
  len = strlen(z);
#endif
  sqlite3_result_int32(context, len);
}

/*
** Implementation of the abs() function
*/
static void absFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z;
  assert( argc==1 );
  z = sqlite3_value_data(argv[0]);
  if( z==0 ) return;
  if( z[0]=='-' && isdigit(z[1]) ) z++;
  sqlite3_result_text(context, z, -1, 1);
}

/*
** Implementation of the substr() function
*/
static void substrFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *z;
................................................................................
  while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
  for(; i<p1+p2 && z[i]; i++){
    if( (z[i]&0xc0)==0x80 ) p2++;
  }
  while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
#endif
  if( p2<0 ) p2 = 0;
  sqlite3_result_text(context, &z[p1], p2, 1);
}

/*
** Implementation of the round() function
*/
static void roundFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int n = 0;
................................................................................
    n = sqlite3_value_int(argv[1]);
    if( n>30 ) n = 30;
    if( n<0 ) n = 0;
  }
  if( SQLITE3_NULL==sqlite3_value_type(argv[0]) ) return;
  r = sqlite3_value_float(argv[0]);
  sprintf(zBuf,"%.*f",n,r);
  sqlite3_result_text(context, zBuf, -1, 1);
}

/*
** Implementation of the upper() and lower() SQL functions.
*/
static void upperFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  char *z;
  int i;
  if( argc<1 || SQLITE3_NULL==sqlite3_value_type(argv[0]) ) return;
  z = sqliteMalloc(sqlite3_value_bytes(argv[0]));
  if( z==0 ) return;
  strcpy(z, sqlite3_value_data(argv[0]));
  for(i=0; z[i]; i++){
    if( islower(z[i]) ) z[i] = toupper(z[i]);
  }
  sqlite3_result_text(context, z, -1, 1);
  sqliteFree(z);
}
static void lowerFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  char *z;
  int i;
  if( argc<1 || SQLITE3_NULL==sqlite3_value_type(argv[0]) ) return;
  z = sqliteMalloc(sqlite3_value_bytes(argv[0]));
  if( z==0 ) return;
  strcpy(z, sqlite3_value_data(argv[0]));
  for(i=0; z[i]; i++){
    if( isupper(z[i]) ) z[i] = tolower(z[i]);
  }
  sqlite3_result_text(context, z, -1, 1);
  sqliteFree(z);
}

/*
** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
** All three do the same thing.  They return the first non-NULL
** argument.
*/
static void ifnullFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE3_NULL!=sqlite3_value_type(argv[i]) ){
      sqlite3_result_text(context, sqlite3_value_data(argv[i]), -1, 1);
      break;
    }
  }
}

/*
** Implementation of random().  Return a random integer.  
*/
static void randomFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int r;
  sqlite3Randomness(sizeof(r), &r);
  sqlite3_result_int32(context, r);
}

/*
** Implementation of the last_insert_rowid() SQL function.  The return
** value is the same as the sqlite3_last_insert_rowid() API function.
*/
static void last_insert_rowid(
  sqlite_func *context, 
  int arg, 
  sqlite3_value **argv
){
  sqlite *db = sqlite3_user_data(context);
  sqlite3_result_int32(context, sqlite3_last_insert_rowid(db));
}

/*
** Implementation of the change_count() SQL function.  The return
** value is the same as the sqlite3_changes() API function.
*/
static void change_count(sqlite_func *context, int arg, sqlite3_value **argv){
  sqlite *db = sqlite3_user_data(context);
  sqlite3_result_int32(context, sqlite3_changes(db));
}

/*
** Implementation of the last_statement_change_count() SQL function.  The
** return value is the same as the sqlite3_last_statement_changes() API
** function.
*/
static void last_statement_change_count(
  sqlite_func *context, 
  int arg,
  sqlite3_value **argv
){
  sqlite *db = sqlite3_user_data(context);
  sqlite3_result_int32(context, sqlite3_last_statement_changes(db));
}

/*
** Implementation of the like() SQL function.  This function implements
** the build-in LIKE operator.  The first argument to the function is the
** string and the second argument is the pattern.  So, the SQL statements:
**
................................................................................
  sqlite_func *context, 
  int argc, 
  sqlite3_value **argv
){
  const unsigned char *zA = sqlite3_value_data(argv[0]);
  const unsigned char *zB = sqlite3_value_data(argv[1]);
  if( zA && zB ){
    sqlite3_result_int32(context, sqlite3LikeCompare(zA, zB));
  }
}

/*
** Implementation of the glob() SQL function.  This function implements
** the build-in GLOB operator.  The first argument to the function is the
** string and the second argument is the pattern.  So, the SQL statements:
................................................................................
**
** is implemented as glob(A,B).
*/
static void globFunc(sqlite_func *context, int arg, sqlite3_value **argv){
  const unsigned char *zA = sqlite3_value_data(argv[0]);
  const unsigned char *zB = sqlite3_value_data(argv[1]);
  if( zA && zB ){
    sqlite3_result_int32(context, sqlite3GlobCompare(zA, zB));
  }
}

/*
** Implementation of the NULLIF(x,y) function.  The result is the first
** argument if the arguments are different.  The result is NULL if the
** arguments are equal to each other.
*/
static void nullifFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const unsigned char *zX = sqlite3_value_data(argv[0]);
  const unsigned char *zY = sqlite3_value_data(argv[1]);
  if( zX!=0 && sqlite3Compare(zX, zY)!=0 ){
    sqlite3_result_text(context, zX, -1, 1);
  }
}

/*
** Implementation of the VERSION(*) function.  The result is the version
** of the SQLite library that is running.
*/
static void versionFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  sqlite3_result_text(context, sqlite3_version, -1, 0);
}

/*
** EXPERIMENTAL - This is not an official function.  The interface may
** change.  This function may disappear.  Do not write code that depends
** on this function.
**
................................................................................
** "NULL".  Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  const char *zArg = sqlite3_value_data(argv[0]);
  if( argc<1 ) return;
  if( zArg==0 ){
    sqlite3_result_text(context, "NULL", 4, 0);
  }else if( sqlite3IsNumber(zArg, 0, TEXT_Utf8) ){
    sqlite3_result_text(context, zArg, -1, 1);
  }else{
    int i,j,n;
    char *z;
    for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
    z = sqliteMalloc( i+n+3 );
    if( z==0 ) return;
    z[0] = '\'';
................................................................................
      z[j++] = zArg[i];
      if( zArg[i]=='\'' ){
        z[j++] = '\'';
      }
    }
    z[j++] = '\'';
    z[j] = 0;
    sqlite3_result_text(context, z, j, 1);
    sqliteFree(z);
  }
}

#ifdef SQLITE_SOUNDEX
/*
** Compute the soundex encoding of a word.
................................................................................
        zResult[j++] = code + '0';
      }
    }
    while( j<4 ){
      zResult[j++] = '0';
    }
    zResult[j] = 0;
    sqlite3_result_text(context, zResult, 4, 1);
  }else{
    sqlite3_result_text(context, "?000", 4, 0);
  }
}
#endif

#ifdef SQLITE_TEST
/*
** This function generates a string of random characters.  Used for
................................................................................
  }
  assert( n<sizeof(zBuf) );
  sqlite3Randomness(n, zBuf);
  for(i=0; i<n; i++){
    zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  }
  zBuf[n] = 0;
  sqlite3_result_text(context, zBuf, n, 1);
}
#endif

/*
** An instance of the following structure holds the context of a
** sum() or avg() aggregate computation.
*/
................................................................................
    p->sum += sqlite3_value_float(argv[0]);
    p->cnt++;
  }
}
static void sumFinalize(sqlite_func *context){
  SumCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  sqlite3_result_double(context, p ? p->sum : 0.0);
}
static void avgFinalize(sqlite_func *context){
  SumCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  if( p && p->cnt>0 ){
    sqlite3_result_double(context, p->sum/(double)p->cnt);
  }
}

/*
** An instance of the following structure holds the context of a
** variance or standard deviation computation.
*/
................................................................................
  if( (argc==0 || SQLITE3_NULL!=sqlite3_value_type(argv[0])) && p ){
    p->n++;
  }
}   
static void countFinalize(sqlite_func *context){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  sqlite3_result_int32(context, p ? p->n : 0);
}

/*
** This function tracks state information for the min() and max()
** aggregate functions.
*/
typedef struct MinMaxCtx MinMaxCtx;
................................................................................
  int cmp = 0;
  Mem *pArg  = (Mem *)argv[0];
  Mem *pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));

  if( SQLITE3_NULL==sqlite3_value_type(argv[0]) ) return;

  if( pBest->flags ){
    /* This step function is used for both the min() and max() aggregates,
    ** the only difference between the two being that the sense of the
    ** comparison is inverted. For the max() aggregate, the
    ** sqlite3_user_data() function returns (void *)-1. For min() it
    ** returns (void *)db, where db is the sqlite3* database pointer.
    ** Therefore the next statement sets variable 'max' to 1 for the max()
    ** aggregate, or 0 for min().
    */
    max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
    cmp = sqlite3MemCompare(pBest, pArg, 0);
    if( (max && cmp<0) || (!max && cmp>0) ){
      sqlite3VdbeMemCopy(pBest, pArg);
    }
  }else{
    sqlite3VdbeMemCopy(pBest, pArg);
  }
}
static void minMaxFinalize(sqlite_func *context){
  sqlite3_value *pRes;
  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, sizeof(Mem));
  
  if( pRes->flags ){
    switch( sqlite3_value_type(pRes) ){
      case SQLITE3_INTEGER: 
        sqlite3_result_int32(context, sqlite3_value_int(pRes));
        break;
      case SQLITE3_FLOAT: 
        sqlite3_result_double(context, sqlite3_value_float(pRes));
      case SQLITE3_TEXT: 
      case SQLITE3_BLOB: 
        sqlite3_result_text(context,
            sqlite3_value_data(pRes), sqlite3_value_bytes(pRes), 1);

        break;
      case SQLITE3_NULL: 
      default:
        assert(0);
    }
  }
}

Changes to src/md5.c.

375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
static void md5finalize(sqlite_func *context){
  MD5Context *p;
  unsigned char digest[16];
  char zBuf[33];
  p = sqlite3_aggregate_context(context, sizeof(*p));
  MD5Final(digest,p);
  DigestToBase16(digest, zBuf);
  sqlite3_set_result_string(context, zBuf, strlen(zBuf));
}
void Md5_Register(sqlite *db){
  sqlite3_create_aggregate(db, "md5sum", -1, md5step, md5finalize, 0);
}










|







375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
static void md5finalize(sqlite_func *context){
  MD5Context *p;
  unsigned char digest[16];
  char zBuf[33];
  p = sqlite3_aggregate_context(context, sizeof(*p));
  MD5Final(digest,p);
  DigestToBase16(digest, zBuf);
  sqlite3_result_text(context, zBuf, -1, 1);
}
void Md5_Register(sqlite *db){
  sqlite3_create_aggregate(db, "md5sum", -1, md5step, md5finalize, 0);
}



Changes to src/sqlite.h.in.

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
...
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
....
1408
1409
1410
1411
1412
1413
1414




























































































1415
1416
1417
1418
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the SQLite library
** presents to client programs.
**
** @(#) $Id: sqlite.h.in,v 1.74 2004/05/24 23:48:27 danielk1977 Exp $
*/
#ifndef _SQLITE_H_
#define _SQLITE_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.
................................................................................
  const char *zName,        /* Name of the function */
  int datatype              /* The datatype for this function */
);
#define SQLITE_NUMERIC     (-1)
#define SQLITE_TEXT        (-2)
#define SQLITE_ARGS        (-3)

/*
** The user function implementations call one of the following four routines
** in order to return their results.  The first parameter to each of these
** routines is a copy of the first argument to xFunc() or xFinialize().
** The second parameter to these routines is the result to be returned.
** A NULL can be passed as the second parameter to sqlite3_set_result_string()
** in order to return a NULL result.
**
** The 3rd argument to _string and _error is the number of characters to
** take from the string.  If this argument is negative, then all characters
** up to and including the first '\000' are used.
**
** The sqlite3_set_result_string() function allocates a buffer to hold the
** result and returns a pointer to this buffer.  The calling routine
** (that is, the implmentation of a user function) can alter the content
** of this buffer if desired.
*/
char *sqlite3_set_result_string(sqlite_func*,const char*,int);
void sqlite3_set_result_int(sqlite_func*,int);
void sqlite3_set_result_double(sqlite_func*,double);
void sqlite3_set_result_error(sqlite_func*,const char*,int);

/*
** The pUserData parameter to the sqlite3_create_function() and
** sqlite3_create_aggregate() routines used to register user functions
** is available to the implementation of the function using this
** call.
*/
void *sqlite3_user_data(sqlite_func*);

/*
** Aggregate functions use the following routine to allocate
** a structure for storing their state.  The first time this routine
** is called for a particular aggregate, a new structure of size nBytes
** is allocated, zeroed, and returned.  On subsequent calls (for the
** same aggregate instance) the same buffer is returned.  The implementation
** of the aggregate can use the returned buffer to accumulate data.
................................................................................
** SQLITE3_INTEGER   The value of the integer. Some rounding may occur.
** SQLITE3_FLOAT     The value of the float.
** SQLITE3_TEXT      Real number conversion of string, or 0.0
** SQLITE3_BLOB      0.0
*/
double sqlite3_value_float(sqlite3_value*);





























































































#ifdef __cplusplus
}  /* End of the 'extern "C"' block */
#endif
#endif







|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
...
460
461
462
463
464
465
466






























467
468
469
470
471
472
473
....
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the SQLite library
** presents to client programs.
**
** @(#) $Id: sqlite.h.in,v 1.75 2004/05/25 11:47:26 danielk1977 Exp $
*/
#ifndef _SQLITE_H_
#define _SQLITE_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.
................................................................................
  const char *zName,        /* Name of the function */
  int datatype              /* The datatype for this function */
);
#define SQLITE_NUMERIC     (-1)
#define SQLITE_TEXT        (-2)
#define SQLITE_ARGS        (-3)































/*
** Aggregate functions use the following routine to allocate
** a structure for storing their state.  The first time this routine
** is called for a particular aggregate, a new structure of size nBytes
** is allocated, zeroed, and returned.  On subsequent calls (for the
** same aggregate instance) the same buffer is returned.  The implementation
** of the aggregate can use the returned buffer to accumulate data.
................................................................................
** SQLITE3_INTEGER   The value of the integer. Some rounding may occur.
** SQLITE3_FLOAT     The value of the float.
** SQLITE3_TEXT      Real number conversion of string, or 0.0
** SQLITE3_BLOB      0.0
*/
double sqlite3_value_float(sqlite3_value*);

typedef sqlite_func sqlite3_context;

void *sqlite3_get_context(sqlite3_context*, int nbyte);

/*
** The pUserData parameter to the sqlite3_create_function() and
** sqlite3_create_aggregate() routines used to register user functions
** is available to the implementation of the function using this
** call.
*/
void *sqlite3_user_data(sqlite3_context*);

/*
** The following three functions may be called from within a user-defined
** function callback or a user-defined aggregate finalizer callback. The
** result of the user-defined function or aggregate is set to the value of
** the second parameter. Any value previously set as the return value via
** an sqlite3_result_*() call is overwritten.
**
** The first parameter to each of these routines must be a copy of the
** sqlite3_context* pointer passed to the user-defined function or
** aggregate finalizer function.
*/
void sqlite3_result_int32(sqlite3_context*, int);
void sqlite3_result_int64(sqlite3_context*, long long int);
void sqlite3_result_double(sqlite3_context*, double);

/*
** This function may be called from within a user-defined function callback
** or a user-defined aggregate finalizer callback. The result of the
** user-defined function or aggregate is set to NULL.  Any value previously
** set as the return value via an sqlite3_result_*() call is overwritten.
**
** The parameter to this routine must be a copy of the sqlite3_context*
** pointer passed to the user-defined function or aggregate finalizer
** function.
*/
void sqlite3_result_null(sqlite3_context*);

/*
** The following two functions may be called from within a user-defined or
** a user-defined aggregate finalizer callback to return a text value. 
** The second parameter is a pointer to the string, encoded in UTF-8 
** for sqlite3_result_text() and UTF-16 (machine byte order) for
** sqlite3_result_text16(). 
**
** If the third parameter, n,  is positive, it is the number of bytes (not
** characters) in the string data. A negative n value indicates that the
** string may be read up to the nul terminator character.
**
** If the fourth parameter is non-zero, then a copy is made of the string.
** Otherwise, SQLite stores a pointer to the original string data.
**
** The first parameter to this routine must be a copy of the
** sqlite3_context* pointer passed to the user-defined function or
** aggregate finalizer function.
*/
void sqlite3_result_text(sqlite3_context*, const char*, int n, int eCopy);
void sqlite3_result_text16(sqlite3_context*, const void*, int n, int eCopy);

/*
** The following function may be called from within a user-defined or a
** user-defined aggregate finalizer callback to return a blob value.  The
** second parameter is a pointer to the blob of data. The third parameter
** is the number of bytes of data in the blob.
**
** If the fourth parameter is non-zero, then a copy is made of the blob.
** Otherwise, SQLite stores a pointer to the original blob data.
**
** The first parameter to this routine must be a copy of the
** sqlite3_context* pointer passed to the user-defined function or
** aggregate finalizer function.
*/
void sqlite3_result_blob(sqlite3_context*, const void*, int n, int eCopy);

/*
** These routines are used from within a user-defined or a user-defined
** aggregate finalizer callback to return an error. The second parameter
** is a pointer to a string describing the error, or NULL if no explanation
** is provided.
**
** The string should be encoded in UTF-8 for sqlite3_result_error() and
** UTF-16 (machine byte order) for sqlite3_result_error16().
**
** If not negative, the third parameter is the number of bytes (not
** characters) in the string passed as the second argument. If the third
** parameter is negative, then the string is read up to the first nul
** terminator character.
*/
void sqlite3_result_error(sqlite3_context*, const char*, int);
void sqlite3_result_error16(sqlite3_context*, const void*, int);

#ifdef __cplusplus
}  /* End of the 'extern "C"' block */
#endif
#endif

Changes to src/tclsqlite.c.

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** A TCL Interface to SQLite
**
** $Id: tclsqlite.c,v 1.67 2004/05/24 12:39:02 danielk1977 Exp $
*/
#ifndef NO_TCL     /* Omit this whole file if TCL is unavailable */

#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>
................................................................................
      Tcl_DStringAppendElement(&cmd, "");
    }else{
      Tcl_DStringAppendElement(&cmd, sqlite3_value_data(argv[i]));
    }
  }
  rc = Tcl_Eval(p->interp, Tcl_DStringValue(&cmd));
  if( rc ){
    sqlite3_set_result_error(context, Tcl_GetStringResult(p->interp), -1); 
  }else{
    sqlite3_set_result_string(context, Tcl_GetStringResult(p->interp), -1);
  }
}
#ifndef SQLITE_OMIT_AUTHORIZATION
/*
** This is the authentication function.  It appends the authentication
** type code and the two arguments to zCmd[] then invokes the result
** on the interpreter.  The reply is examined to determine if the







|







 







|

|







7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** A TCL Interface to SQLite
**
** $Id: tclsqlite.c,v 1.68 2004/05/25 11:47:26 danielk1977 Exp $
*/
#ifndef NO_TCL     /* Omit this whole file if TCL is unavailable */

#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>
................................................................................
      Tcl_DStringAppendElement(&cmd, "");
    }else{
      Tcl_DStringAppendElement(&cmd, sqlite3_value_data(argv[i]));
    }
  }
  rc = Tcl_Eval(p->interp, Tcl_DStringValue(&cmd));
  if( rc ){
    sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); 
  }else{
    sqlite3_result_text(context, Tcl_GetStringResult(p->interp), -1, 1);
  }
}
#ifndef SQLITE_OMIT_AUTHORIZATION
/*
** This is the authentication function.  It appends the authentication
** type code and the two arguments to zCmd[] then invokes the result
** on the interpreter.  The reply is examined to determine if the

Changes to src/test1.c.

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
...
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
...
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
...
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
...
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the printf() interface to SQLite.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test1.c,v 1.49 2004/05/24 23:48:27 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include "os.h"
#include <stdlib.h>
#include <string.h>

................................................................................
** Implementation of the x_coalesce() function.
** Return the first argument non-NULL argument.
*/
static void ifnullFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE3_NULL!=sqlite3_value_type(argv[i]) ){
      sqlite3_set_result_string(context, sqlite3_value_data(argv[i]), -1);
      break;
    }
  }
}

/*
** A structure into which to accumulate text.
................................................................................
  sqlite3_value **argv
){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  sqlite3_exec((sqlite*)sqlite3_user_data(context),
      sqlite3_value_data(argv[0]),
      execFuncCallback, &x, 0);
  sqlite3_set_result_string(context, x.z, x.nUsed);
  sqliteFree(x.z);
}

/*
** Usage:  sqlite_test_create_function DB
**
** Call the sqlite3_create_function API on the given database in order
................................................................................
  if( (argc==0 || SQLITE3_NULL!=sqlite3_value_type(argv[0]) ) && p ){
    p->n++;
  }
}   
static void countFinalize(sqlite_func *context){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  sqlite3_set_result_int(context, p ? p->n : 0);
}

/*
** Usage:  sqlite_test_create_aggregate DB
**
** Call the sqlite3_create_function API on the given database in order
** to create a function named "x_count".  This function does the same thing
................................................................................
** is to test the sqlite_set_result() API.
*/
static void testFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  while( argc>=2 ){
    const char *zArg0 = sqlite3_value_data(argv[0]);
    const char *zArg1 = sqlite3_value_data(argv[1]);
    if( zArg0==0 ){
      sqlite3_set_result_error(context, "first argument to test function "
         "may not be NULL", -1);
    }else if( sqlite3StrICmp(zArg0,"string")==0 ){
      sqlite3_set_result_string(context, zArg1, -1);
    }else if( zArg1==0 ){
      sqlite3_set_result_error(context, "2nd argument may not be NULL if the "
         "first argument is not \"string\"", -1);
    }else if( sqlite3StrICmp(zArg0,"int")==0 ){
      sqlite3_set_result_int(context, atoi(zArg1));
    }else if( sqlite3StrICmp(zArg0,"double")==0 ){
      sqlite3_set_result_double(context, sqlite3AtoF(zArg1, 0));
    }else{
      sqlite3_set_result_error(context,"first argument should be one of: "
          "string int double", -1);
    }
    argc -= 2;
    argv += 2;
  }
}








|







 







|







 







|







 







|







 







|


|

|


|

|

|







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
...
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
...
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
...
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
...
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the printf() interface to SQLite.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test1.c,v 1.50 2004/05/25 11:47:26 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include "os.h"
#include <stdlib.h>
#include <string.h>

................................................................................
** Implementation of the x_coalesce() function.
** Return the first argument non-NULL argument.
*/
static void ifnullFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE3_NULL!=sqlite3_value_type(argv[i]) ){
      sqlite3_result_text(context, sqlite3_value_data(argv[i]), -1, 1);
      break;
    }
  }
}

/*
** A structure into which to accumulate text.
................................................................................
  sqlite3_value **argv
){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  sqlite3_exec((sqlite*)sqlite3_user_data(context),
      sqlite3_value_data(argv[0]),
      execFuncCallback, &x, 0);
  sqlite3_result_text(context, x.z, x.nUsed, 1);
  sqliteFree(x.z);
}

/*
** Usage:  sqlite_test_create_function DB
**
** Call the sqlite3_create_function API on the given database in order
................................................................................
  if( (argc==0 || SQLITE3_NULL!=sqlite3_value_type(argv[0]) ) && p ){
    p->n++;
  }
}   
static void countFinalize(sqlite_func *context){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  sqlite3_result_int32(context, p ? p->n : 0);
}

/*
** Usage:  sqlite_test_create_aggregate DB
**
** Call the sqlite3_create_function API on the given database in order
** to create a function named "x_count".  This function does the same thing
................................................................................
** is to test the sqlite_set_result() API.
*/
static void testFunc(sqlite_func *context, int argc, sqlite3_value **argv){
  while( argc>=2 ){
    const char *zArg0 = sqlite3_value_data(argv[0]);
    const char *zArg1 = sqlite3_value_data(argv[1]);
    if( zArg0==0 ){
      sqlite3_result_error(context, "first argument to test function "
         "may not be NULL", -1);
    }else if( sqlite3StrICmp(zArg0,"string")==0 ){
      sqlite3_result_text(context, zArg1, -1, 1);
    }else if( zArg1==0 ){
      sqlite3_result_error(context, "2nd argument may not be NULL if the "
         "first argument is not \"string\"", -1);
    }else if( sqlite3StrICmp(zArg0,"int")==0 ){
      sqlite3_result_int32(context, atoi(zArg1));
    }else if( sqlite3StrICmp(zArg0,"double")==0 ){
      sqlite3_result_double(context, sqlite3AtoF(zArg1, 0));
    }else{
      sqlite3_result_error(context,"first argument should be one of: "
          "string int double", -1);
    }
    argc -= 2;
    argv += 2;
  }
}

Changes to src/vdbe.c.

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
64
65
66
67
68
69
70
71
























































































72
73
74
75
76
77









78
79



80
81
82
83
84
85
86
....
2008
2009
2010
2011
2012
2013
2014

2015
2016
2017
2018
2019
2020
2021
....
2270
2271
2272
2273
2274
2275
2276


2277
2278
2279
2280
2281
2282
2283
2284

2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
**
** Various scripts scan this source file in order to generate HTML
** documentation, headers files, or other derived files.  The formatting
** of the code in this file is, therefore, important.  See other comments
** in this file for details.  If in doubt, do not deviate from existing
** commenting and indentation practices when changing or adding code.
**
** $Id: vdbe.c,v 1.327 2004/05/24 23:48:27 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>
#include "vdbeInt.h"

/*
................................................................................
** each instruction in the VDBE.  When reaches zero, the SQLITE_Interrupt
** of the db.flags field is set in order to simulate and interrupt.
**
** This facility is used for testing purposes only.  It does not function
** in an ordinary build.
*/
int sqlite3_interrupt_count = 0;

























































































#if 0
/*
** NulTermify
** Stringify
** Integerify
** Realify









** SetEncoding
** Release



*/
struct MemRecord {
  char *zData;    /* Serialized record */
  int nField;     /* Number of fields in the header */
  int nHeader;    /* Number of bytes in the entire header */
  u64 *aType;     /* Type values for all entries in the record */
};
................................................................................
case OP_Callback: {
  int i;
  assert( p->nResColumn==pOp->p1 );

  for(i=0; i<pOp->p1; i++){
    Mem *pVal = &pTos[0-i];
    SetEncodingFlags(pVal, db->enc);

  }

  p->resOnStack = 1;
  p->nCallback++;
  p->popStack = pOp->p1;
  p->pc = pc + 1;
  p->pTos = pTos;
................................................................................
  ctx.s.z = 0;
  ctx.isError = 0;
  ctx.isStep = 0;
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  popStack(&pTos, n);


  pTos++;
  *pTos = ctx.s;
  if( pTos->flags & MEM_Str ){
    pTos->flags |= MEM_Term;
  }
  if( pTos->flags & MEM_Short ){
    pTos->z = pTos->zShort;
  }

  if( ctx.isError ){
    sqlite3SetString(&p->zErrMsg, 
       (pTos->flags & MEM_Str)!=0 ? pTos->z : "user function error", (char*)0);
    rc = SQLITE_ERROR;
  }

  if( pTos->flags&MEM_Str ){
    SetEncodingFlags(pTos, TEXT_Utf8);
    SetEncoding(pTos, encToFlags(db->enc)|MEM_Term);
  }

  break;
}

/* Opcode: BitAnd * * *







|







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


<
<
<
<
>
>
>
>
>
>
>
>
>
|
<
>
>
>







 







>







 







>
>


<
<
<



>







<







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161




162
163
164
165
166
167
168
169
170
171

172
173
174
175
176
177
178
179
180
181
....
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
....
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376



2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387

2388
2389
2390
2391
2392
2393
2394
**
** Various scripts scan this source file in order to generate HTML
** documentation, headers files, or other derived files.  The formatting
** of the code in this file is, therefore, important.  See other comments
** in this file for details.  If in doubt, do not deviate from existing
** commenting and indentation practices when changing or adding code.
**
** $Id: vdbe.c,v 1.328 2004/05/25 11:47:26 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>
#include "vdbeInt.h"

/*
................................................................................
** each instruction in the VDBE.  When reaches zero, the SQLITE_Interrupt
** of the db.flags field is set in order to simulate and interrupt.
**
** This facility is used for testing purposes only.  It does not function
** in an ordinary build.
*/
int sqlite3_interrupt_count = 0;

/*
** This macro takes a single parameter, a pointer to a Mem structure.
** It returns the string encoding for the Mem structure, one of TEXT_Utf8
** TEXT_Utf16le or TEXT_Utf16be.
*/
#define MemEnc(p) ( \
   p->flags&MEM_Utf16le?TEXT_Utf16le: \
  (p->flags&MEM_Utf16le?TEXT_Utf16be:TEXT_Utf8) )

/*
** The following macros each take one parameter, a pointer to a Mem
** structure. The value returned is non-zero if the value stored in 
** the Mem structure is of or can be losslessly converted to the
** type implicit in the macro name.
** 
** MemIsNull     # NULL values
** MemIsInt      # Ints and reals and strings that can be converted to ints.
** MemIsReal     # Reals, ints and strings that look like numbers
** MemIsStr      # Strings, reals and ints.
** MemIsBlob     # Blobs.
**
** These macros do not alter the contents of the Mem structure.
*/
#define MemIsNull(p) ((p)->flags&Mem_Null)
#define MemIsBlob(p) ((p)->flags&Mem_Blob)
#define MemIsStr(p) ((p)->flags&(MEM_Int|MEM_Real|MEM_Str))
#define MemIsInt(p) ((p)->flags&MEM_Int || hardMemIsInt(p))
#define MemIsReal(p) ((p)->flags&(MEM_Int|MEM_Real) || hardMemIsReal(p))
static int hardMemIsInt(Mem *p){
  assert( !(p->flags&(MEM_Int|MEM_Real)) );
  if( p->flags&MEM_Str ){
    int realnum = 0;
    if( sqlite3IsNumber(p->z, &realnum, MemEnc(p)) && !realnum ){
      return 1;
    }
  }
  return 0;
}
static int hardMemIsReal(Mem *p){
  assert( !(p->flags&(MEM_Int|MEM_Real)) );
  if( p->flags&MEM_Str && sqlite3IsNumber(p->z, 0, MemEnc(p)) ){
    return 1;
  }
  return 0;
}

/*
** The following two macros each take one parameter, a pointer to a Mem
** structure. They return the value stored in the Mem structure coerced
** to a 64-bit integer or real, respectively.
**
** MemInt
** MemReal
**
** These macros do not alter the contents of the Mem structure, although
** they may cache the integer or real value cast of the value.
*/
#define MemInt(p) (((p)->flags&MEM_Int)?(p)->i:hardMemInt(p))
#define MemReal(p) (((p)->flags&MEM_Real)?(p)->i:hardMemReal(p))
static i64 hardMemInt(Mem *p){
  assert( !(p->flags&MEM_Int) );
  if( !MemIsInt(p) ) return 0;

  if( p->flags&MEM_Real ){
    p->i = p->r;
  }else{
    assert( p->flags&MEM_Str );
    sqlite3atoi64(p->z, &(p->i), MemEnc(p));
  }
  p->flags |= MEM_Int;
  return p->i;
}
static double hardMemReal(Mem *p){
  assert( !(p->flags&MEM_Real) );
  if( !MemIsReal(p) ) return 0.0;

  if( p->flags&MEM_Int ){
    p->r = p->i;
  }else{
    assert( p->flags&MEM_Str );
    /* p->r = sqlite3AtoF(p->z, 0, MemEnc(p)); */
    p->r = sqlite3AtoF(p->z, 0);
  }
  p->flags |= MEM_Real;
  return p->r;
}


#if 0
/*




** MemStr(Mem *pMem)
** MemBlob(Mem *pMem)
** MemBloblen(Mem *pMem)
**
** MemType(Mem *pMem)
**
** MemSetBlob
** MemSetStr
**
** MemSetEnc

** MemSetType
**
** MemCopy
*/
struct MemRecord {
  char *zData;    /* Serialized record */
  int nField;     /* Number of fields in the header */
  int nHeader;    /* Number of bytes in the entire header */
  u64 *aType;     /* Type values for all entries in the record */
};
................................................................................
case OP_Callback: {
  int i;
  assert( p->nResColumn==pOp->p1 );

  for(i=0; i<pOp->p1; i++){
    Mem *pVal = &pTos[0-i];
    SetEncodingFlags(pVal, db->enc);
    MemNulTerminate(pVal);
  }

  p->resOnStack = 1;
  p->nCallback++;
  p->popStack = pOp->p1;
  p->pc = pc + 1;
  p->pTos = pTos;
................................................................................
  ctx.s.z = 0;
  ctx.isError = 0;
  ctx.isStep = 0;
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  popStack(&pTos, n);

  /* Copy the result of the function to the top of the stack */
  pTos++;
  *pTos = ctx.s;



  if( pTos->flags & MEM_Short ){
    pTos->z = pTos->zShort;
  }
  /* If the function returned an error, throw an exception */
  if( ctx.isError ){
    sqlite3SetString(&p->zErrMsg, 
       (pTos->flags & MEM_Str)!=0 ? pTos->z : "user function error", (char*)0);
    rc = SQLITE_ERROR;
  }

  if( pTos->flags&MEM_Str ){

    SetEncoding(pTos, encToFlags(db->enc)|MEM_Term);
  }

  break;
}

/* Opcode: BitAnd * * *

Changes to src/vdbeInt.h.

113
114
115
116
117
118
119
120


121





122
123
124
125
126
127
128
129
130
131
132



























133
134
135
136
137
138
139
...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
...
357
358
359
360
361
362
363
364
365
366
367
368
369


** Number of bytes of string storage space available to each stack
** layer without having to malloc.  NBFS is short for Number of Bytes
** For Strings.
*/
#define NBFS 32

/*
** A single level of the stack or a single memory cell


** is an instance of the following structure. 





*/
struct Mem {
  i64 i;              /* Integer value */
  int n;              /* Number of characters in string value, including '\0' */
  int flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  double r;           /* Real value */
  char *z;            /* String or BLOB value */
  char zShort[NBFS];  /* Space for short strings */
};
typedef struct Mem Mem;




























/*
** Allowed values for Mem.flags.
**
** The first 5 values determine the data type(s).  Null and Blob must
** occur alone.  But Str, Int, and Real can occur together.
**
** The next 3 utf entries determine the text representation for strings.
................................................................................
** These valus are only meaningful if the Str or Blob types are used.
*/
#define MEM_Null      0x0001   /* Value is NULL */
#define MEM_Str       0x0002   /* Value is a string */
#define MEM_Int       0x0004   /* Value is an integer */
#define MEM_Real      0x0008   /* Value is a real number */
#define MEM_Blob      0x0010   /* Value is a BLOB */
#define MEM_Struct    0x0020   /* Value is some kind of struct */

#define MEM_Term      0x0200   /* String has a nul terminator character */

#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
#define MEM_Static    0x0800   /* Mem.z points to a static string */
#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
#define MEM_Short     0x2000   /* Mem.z points to Mem.zShort */
................................................................................
int sqlite3VdbeSerialPut(unsigned char *, Mem *);
int sqlite3VdbeSerialGet(const unsigned char *, u64, Mem *, u8 enc);

int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
int sqlite3VdbeIdxKeyCompare(Cursor*, int , const unsigned char*, int*);
int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
int sqlite3MemCopy(Mem*, const Mem*);
int sqlite3VdbeKeyCompare(void*,int,const void*,int, const void*);
int sqlite3VdbeRowCompare(void*,int,const void*,int, const void*);
int sqlite3VdbeExec(Vdbe*);
int sqlite3VdbeList(Vdbe*);
int sqlite3VdbeSetEncoding(Mem *, u8);









|
>
>
|
>
>
>
>
>











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<







 







<





>
>
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
...
177
178
179
180
181
182
183

184
185
186
187
188
189
190
...
390
391
392
393
394
395
396

397
398
399
400
401
402
403
** Number of bytes of string storage space available to each stack
** layer without having to malloc.  NBFS is short for Number of Bytes
** For Strings.
*/
#define NBFS 32

/*
** Internally, the vdbe manipulates nearly all SQL values as Mem
** structures. Each Mem struct may cache multiple representations (string,
** integer etc.) of the same value.  A value (and therefore Mem structure)
** has the following properties:
**
** Each value has a manifest type. The manifest type of the value stored
** in a Mem struct is returned by the MemType(Mem*) macro. The type is
** one of SQLITE3_NULL, SQLITE3_INTEGER, SQLITE3_REAL, SQLITE3_TEXT or
** SQLITE3_BLOB.
*/
struct Mem {
  i64 i;              /* Integer value */
  int n;              /* Number of characters in string value, including '\0' */
  int flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  double r;           /* Real value */
  char *z;            /* String or BLOB value */
  char zShort[NBFS];  /* Space for short strings */
};
typedef struct Mem Mem;

/*
** The following three macros are used to set the value and manifest type
** stored by a Mem structure.
**
** MemSetNull - Set the value to NULL.
** MemSetInt  - Set the value to an integer.
** MemSetReal - Set the value to a real.
** MemSetStr - Set the value to a string.
*/
#define MemSetNull(p) sqlite3VdbeMemSetNull(p)
#define MemSetInt(p,v) sqlite3VdbeMemSetInt(p,v)
#define MemSetReal(p,v) sqlite3VdbeMemSetReal(p,v)
#define MemSetStr(p,z,n,enc,eCopy) sqlite3VdbeMemSetStr(p,z,n,enc,eCopy)

/*
** This macro is used to ensure a string stored in a Mem struct is NULL
** terminated. When used on an object that is not a string or is a nul
** terminated string this is a no-op. When used on a non-nul-terminated
** string a nul terminator character is appended.
**
** Non-zero is returned if a malloc() fails.
*/
#define MemNulTerminate(p) ( \
  ((p)->flags&MEM_Str) && \
  !((p)->flags&MEM_Term) && \
  sqlite3VdbeMemNulTerminate(p) )

/*
** Allowed values for Mem.flags.
**
** The first 5 values determine the data type(s).  Null and Blob must
** occur alone.  But Str, Int, and Real can occur together.
**
** The next 3 utf entries determine the text representation for strings.
................................................................................
** These valus are only meaningful if the Str or Blob types are used.
*/
#define MEM_Null      0x0001   /* Value is NULL */
#define MEM_Str       0x0002   /* Value is a string */
#define MEM_Int       0x0004   /* Value is an integer */
#define MEM_Real      0x0008   /* Value is a real number */
#define MEM_Blob      0x0010   /* Value is a BLOB */


#define MEM_Term      0x0200   /* String has a nul terminator character */

#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
#define MEM_Static    0x0800   /* Mem.z points to a static string */
#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
#define MEM_Short     0x2000   /* Mem.z points to Mem.zShort */
................................................................................
int sqlite3VdbeSerialPut(unsigned char *, Mem *);
int sqlite3VdbeSerialGet(const unsigned char *, u64, Mem *, u8 enc);

int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
int sqlite3VdbeIdxKeyCompare(Cursor*, int , const unsigned char*, int*);
int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);

int sqlite3VdbeKeyCompare(void*,int,const void*,int, const void*);
int sqlite3VdbeRowCompare(void*,int,const void*,int, const void*);
int sqlite3VdbeExec(Vdbe*);
int sqlite3VdbeList(Vdbe*);
int sqlite3VdbeSetEncoding(Mem *, u8);
int sqlite3VdbeMemCopy(Mem*, const Mem*);
int sqlite3VdbeMemNulTerminate(Mem *);

Changes to src/vdbeaux.c.

420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
....
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
....
1749
1750
1751
1752
1753
1754
1755



































































































































































































































*/
VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  assert( p->magic==VDBE_MAGIC_INIT );
  assert( addr>=0 && addr<p->nOp );
  return &p->aOp[addr];
}

/*
** The following group or routines are employed by installable functions
** to return their results.
**
** The sqlite3_set_result_string() routine can be used to return a string
** value or to return a NULL.  To return a NULL, pass in NULL for zResult.
** A copy is made of the string before this routine returns so it is safe
** to pass in an ephemeral string.
**
** sqlite3_set_result_error() works like sqlite3_set_result_string() except
** that it signals a fatal error.  The string argument, if any, is the
** error message.  If the argument is NULL a generic substitute error message
** is used.
**
** The sqlite3_set_result_int() and sqlite3_set_result_double() set the return
** value of the user function to an integer or a double.
**
** These routines are defined here in vdbe.c because they depend on knowing
** the internals of the sqlite_func structure which is only defined in 
** this source file.
*/
char *sqlite3_set_result_string(sqlite_func *p, const char *zResult, int n){
  assert( !p->isStep );
  if( p->s.flags & MEM_Dyn ){
    sqliteFree(p->s.z);
  }
  if( zResult==0 ){
    p->s.flags = MEM_Null;
    n = 0;
    p->s.z = 0;
    p->s.n = 0;
  }else{
    if( n<0 ) n = strlen(zResult);
    if( n<NBFS-1 ){
      memcpy(p->s.zShort, zResult, n);
      p->s.zShort[n] = 0;
      p->s.flags = MEM_Utf8 | MEM_Str | MEM_Short;
      p->s.z = p->s.zShort;
    }else{
      p->s.z = sqliteMallocRaw( n+1 );
      if( p->s.z ){
        memcpy(p->s.z, zResult, n);
        p->s.z[n] = 0;
      }
      p->s.flags = MEM_Utf8 | MEM_Str | MEM_Dyn;
    }
    p->s.n = n+1;
  }
  return p->s.z;
}
void sqlite3_set_result_int(sqlite_func *p, int iResult){
  assert( !p->isStep );
  if( p->s.flags & MEM_Dyn ){
    sqliteFree(p->s.z);
  }
  p->s.i = iResult;
  p->s.flags = MEM_Int;
}
void sqlite3_set_result_double(sqlite_func *p, double rResult){
  assert( !p->isStep );
  if( p->s.flags & MEM_Dyn ){
    sqliteFree(p->s.z);
  }
  p->s.r = rResult;
  p->s.flags = MEM_Real;
}
void sqlite3_set_result_error(sqlite_func *p, const char *zMsg, int n){
  assert( !p->isStep );
  sqlite3_set_result_string(p, zMsg, n);
  p->isError = 1;
}

/*
** Extract the user data from a sqlite_func structure and return a
** pointer to it.
*/
void *sqlite3_user_data(sqlite_func *p){
  assert( p && p->pFunc );
  return p->pFunc->pUserData;
}

/*
** Allocate or return the aggregate context for a user function.  A new
** context is allocated on the first call.  Subsequent calls return the
................................................................................
  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  if( rc==0 ){
    rc = pMem1->n - pMem2->n;
  }
  return rc;
}

/*
** Copy the contents of memory cell pFrom into pTo.
*/
int sqlite3MemCopy(Mem *pTo, const Mem *pFrom){
  if( pTo->flags&MEM_Dyn ){
    sqliteFree(pTo->z);
  }

  memcpy(pTo, pFrom, sizeof(*pFrom));
  if( pTo->flags&MEM_Short ){
    pTo->z = pTo->zShort;
  }
  else if( pTo->flags&(MEM_Ephem|MEM_Dyn) ){
    pTo->flags = pTo->flags&(~(MEM_Static|MEM_Ephem|MEM_Short|MEM_Dyn));
    if( pTo->n>NBFS ){
      pTo->z = sqliteMalloc(pTo->n);
      if( !pTo->z ) return SQLITE_NOMEM;
      pTo->flags |= MEM_Dyn;
    }else{
      pTo->z = pTo->zShort;
      pTo->flags |= MEM_Short;
    }
    memcpy(pTo->z, pFrom->z, pTo->n);
  }
  return SQLITE_OK;
}

/*
** The following is the comparison function for (non-integer)
** keys in the btrees.  This function returns negative, zero, or
** positive if the first key is less than, equal to, or greater than
** the second.
**
** This function assumes that each key consists of one or more type/blob
................................................................................
  *res = sqlite3VdbeKeyCompare(pC->pKeyInfo, len, pCellKey, nKey, pKey);
  
  if( freeCellKey ){
    sqliteFree(pCellKey);
  }
  return SQLITE_OK;
}











































































































































































































































<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
420
421
422
423
424
425
426
427








































































428
429
430
431
432
433
434
435
436
437
438
....
1385
1386
1387
1388
1389
1390
1391



























1392
1393
1394
1395
1396
1397
1398
....
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
*/
VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  assert( p->magic==VDBE_MAGIC_INIT );
  assert( addr>=0 && addr<p->nOp );
  return &p->aOp[addr];
}

/*








































































** Extract the user data from a sqlite_func structure and return a
** pointer to it.
*/
void *sqlite3_user_data(sqlite3_context *p){
  assert( p && p->pFunc );
  return p->pFunc->pUserData;
}

/*
** Allocate or return the aggregate context for a user function.  A new
** context is allocated on the first call.  Subsequent calls return the
................................................................................
  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  if( rc==0 ){
    rc = pMem1->n - pMem2->n;
  }
  return rc;
}




























/*
** The following is the comparison function for (non-integer)
** keys in the btrees.  This function returns negative, zero, or
** positive if the first key is less than, equal to, or greater than
** the second.
**
** This function assumes that each key consists of one or more type/blob
................................................................................
  *res = sqlite3VdbeKeyCompare(pC->pKeyInfo, len, pCellKey, nKey, pKey);
  
  if( freeCellKey ){
    sqliteFree(pCellKey);
  }
  return SQLITE_OK;
}

/*
** Parameter "enc" is one of TEXT_Utf8, TEXT_Utf16le or TEXT_Utf16be.
** Return the corresponding MEM_Utf* value.
*/
static int encToFlags(u8 enc){
  switch( enc ){
    case TEXT_Utf8: return MEM_Utf8;
    case TEXT_Utf16be: return MEM_Utf16be;
    case TEXT_Utf16le: return MEM_Utf16le;
  }
  assert(0);
}
static u8 flagsToEnc(int flags){
  switch( flags&(MEM_Utf8|MEM_Utf16be|MEM_Utf16le) ){
    case MEM_Utf8: return TEXT_Utf8;
    case MEM_Utf16le: return TEXT_Utf16le;
    case MEM_Utf16be: return TEXT_Utf16be;
  }
  return 0;
}

/*
** Delete any previous value and set the value stored in *pMem to NULL.
*/
void sqlite3VdbeMemSetNull(Mem *pMem){
  if( pMem->flags&MEM_Dyn ){
    sqliteFree(pMem->z);
  }
  pMem->flags = MEM_Null;
}

/*
** Delete any previous value and set the value stored in *pMem to val,
** manifest type INTEGER.
*/
void sqlite3VdbeMemSetInt(Mem *pMem, i64 val){
  MemSetNull(pMem);
  pMem->i = val;
  pMem->flags = MEM_Int;
}

/*
** Delete any previous value and set the value stored in *pMem to val,
** manifest type REAL.
*/
void sqlite3VdbeMemSetReal(Mem *pMem, double val){
  MemSetNull(pMem);
  pMem->r = val;
  pMem->flags = MEM_Real;
}

/*
** Copy the contents of memory cell pFrom into pTo.
*/
int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  if( pTo->flags&MEM_Dyn ){
    sqliteFree(pTo->z);
  }

  memcpy(pTo, pFrom, sizeof(*pFrom));
  if( pTo->flags&MEM_Short ){
    pTo->z = pTo->zShort;
  }
  else if( pTo->flags&(MEM_Ephem|MEM_Dyn) ){
    pTo->flags = pTo->flags&(~(MEM_Static|MEM_Ephem|MEM_Short|MEM_Dyn));
    if( pTo->n>NBFS ){
      pTo->z = sqliteMalloc(pTo->n);
      if( !pTo->z ) return SQLITE_NOMEM;
      pTo->flags |= MEM_Dyn;
    }else{
      pTo->z = pTo->zShort;
      pTo->flags |= MEM_Short;
    }
    memcpy(pTo->z, pFrom->z, pTo->n);
  }
  return SQLITE_OK;
}

int sqlite3VdbeMemSetStr(
  Mem *pMem,          /* Memory cell to set to string value */
  const char *z,      /* String pointer */
  int n,              /* Bytes in string, or negative */
  u8 enc,             /* Encoding of z */
  int eCopy           /* True if this function should make a copy of z */
){
  Mem tmp;

  if( !z ){
    /* If z is NULL, just set *pMem to contain NULL. */
    MemSetNull(pMem);
    return SQLITE_OK;
  }

  tmp.z = (char *)z;
  if( eCopy ){
    tmp.flags = MEM_Ephem|MEM_Str;
  }else{
    tmp.flags = MEM_Static|MEM_Str;
  }
  tmp.flags |= encToFlags(enc);
  tmp.n = n;
  switch( enc ){
    case 0:
      tmp.flags |= MEM_Blob;
      break;

    case TEXT_Utf8:
      tmp.flags |= MEM_Utf8;
      if( n<0 ) tmp.n = strlen(z)+1;
      tmp.flags |= ((tmp.z[tmp.n-1])?0:MEM_Term);
      break;

    case TEXT_Utf16le:
    case TEXT_Utf16be:
      tmp.flags |= (enc==TEXT_Utf16le?MEM_Utf16le:MEM_Utf16be);
      if( n<0 ) tmp.n = sqlite3utf16ByteLen(z,-1)+1;
      tmp.flags |= ((tmp.z[tmp.n-1]||tmp.z[tmp.n-2])?0:MEM_Term);
      break;

    default:
      assert(0);
  }
  return sqlite3VdbeMemCopy(pMem, &tmp);
}

int sqlite3VdbeMemNulTerminate(Mem *pMem){
  int nulTermLen;
  int f = pMem->flags;

  assert( pMem->flags&MEM_Str && !pMem->flags&MEM_Term );
  assert( flagsToEnc(pMem->flags) );

  nulTermLen = (flagsToEnc(f)==TEXT_Utf8?1:2);

  if( pMem->n+nulTermLen<=NBFS ){
    /* If the string plus the nul terminator will fit in the Mem.zShort
    ** buffer, and it is not already stored there, copy it there.
    */
    if( !(f&MEM_Short) ){
      memcpy(pMem->z, pMem->zShort, pMem->n);
      if( f&MEM_Dyn ){
        sqliteFree(pMem->z);
      }
      pMem->z = pMem->zShort;
      pMem->flags &= ~(MEM_Static|MEM_Ephem|MEM_Dyn);
      pMem->flags |= MEM_Short;
    }
  }else{
    /* Otherwise we have to malloc for memory. If the string is already
    ** dynamic, use sqliteRealloc(). Otherwise sqliteMalloc() enough
    ** space for the string and the nul terminator, and copy the string
    ** data there.
    */
    if( f&MEM_Dyn ){
      pMem->z = (char *)sqliteRealloc(pMem->z, pMem->n+nulTermLen);
      if( !pMem->z ){
        return SQLITE_NOMEM;
      }
    }else{
      char *z = (char *)sqliteMalloc(pMem->n+nulTermLen);
      memcpy(z, pMem->z, pMem->n);
      pMem->z = z;
      pMem->flags &= ~(MEM_Static|MEM_Ephem|MEM_Short);
      pMem->flags |= MEM_Dyn;
    }
  }

  /* pMem->z now points at the string data, with enough space at the end
  ** to insert the nul nul terminator. pMem->n has not yet been updated.
  */
  memcpy(&pMem->z[pMem->n], "\0\0", nulTermLen);
  pMem->n += nulTermLen;
  pMem->flags |= MEM_Term;
}

/*
** The following nine routines, named sqlite3_result_*(), are used to
** return values or errors from user-defined functions and aggregate
** operations. They are commented in the header file sqlite.h (sqlite.h.in)
*/
void sqlite3_result_int32(sqlite3_context *pCtx, int iVal){
  MemSetInt(&pCtx->s, iVal);
}
void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  MemSetInt(&pCtx->s, iVal);
}
void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  MemSetReal(&pCtx->s, rVal);
}
void sqlite3_result_null(sqlite3_context *pCtx){
  MemSetNull(&pCtx->s);
}
void sqlite3_result_text(
  sqlite3_context *pCtx, 
  const char *z, 
  int n,
  int eCopy
){
  MemSetStr(&pCtx->s, z, n, TEXT_Utf8, eCopy);
}
void sqlite3_result_text16(
  sqlite3_context *pCtx, 
  const void *z, 
  int n, 
  int eCopy
){
  MemSetStr(&pCtx->s, z, n, TEXT_Utf16, eCopy);
}
void sqlite3_result_blob(
  sqlite3_context *pCtx, 
  const void *z, 
  int n, 
  int eCopy
){
  assert( n>0 );
  MemSetStr(&pCtx->s, z, n, 0, eCopy);
}
void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  pCtx->isError = 1;
  MemSetStr(&pCtx->s, z, n, TEXT_Utf8, 1);
}
void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  pCtx->isError = 1;
  MemSetStr(&pCtx->s, z, n, TEXT_Utf16, 1);
}