/ Check-in [b7155db2]
Login

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

Overview
Comment:Have the vdbe handle strings in the same encoding as the database. (CVS 1445)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: b7155db2b13aa3ca5f6c68e948d9e8740ebcac47
User & Date: danielk1977 2004-05-24 07:04:26
Context
2004-05-24
07:34
Fix for retrieving UTF-16 little-endian text from a big-endian database. (CVS 1446) check-in: 8104baf2 user: danielk1977 tags: trunk
07:04
Have the vdbe handle strings in the same encoding as the database. (CVS 1445) check-in: b7155db2 user: danielk1977 tags: trunk
2004-05-23
13:30
Begin changing the vdbe so all stack values use the database encoding. (CVS 1444) check-in: f47de3a9 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
...
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
** 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.19 2004/05/14 11:00:53 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.
................................................................................
    double r;
    if( sqlite3OsCurrentTime(&r)==0 ){
      p->rJD = r;
      p->validJD = 1;
      return 0;
    }
    return 1;
  }else if( sqlite3IsNumber(zDate, 0) ){
    p->rJD = sqlite3AtoF(zDate, 0);
    p->validJD = 1;
    return 0;
  }
  return 1;
}








|







 







|







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
...
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
** 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.20 2004/05/24 07:04:26 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.
................................................................................
    double r;
    if( sqlite3OsCurrentTime(&r)==0 ){
      p->rJD = r;
      p->validJD = 1;
      return 0;
    }
    return 1;
  }else if( sqlite3IsNumber(zDate, 0, TEXT_Utf8) ){
    p->rJD = sqlite3AtoF(zDate, 0);
    p->validJD = 1;
    return 0;
  }
  return 1;
}

Changes to src/func.c.

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
...
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
** 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.48 2004/05/16 11:15:38 danielk1977 Exp $
*/
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include "sqliteInt.h"
#include "os.h"
................................................................................
** "NULL".  Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite_func *context, int argc, const char **argv){
  if( argc<1 ) return;
  if( argv[0]==0 ){
    sqlite3_set_result_string(context, "NULL", 4);
  }else if( sqlite3IsNumber(argv[0], 0) ){
    sqlite3_set_result_string(context, argv[0], -1);
  }else{
    int i,j,n;
    char *z;
    for(i=n=0; argv[0][i]; i++){ if( argv[0][i]=='\'' ) n++; }
    z = sqliteMalloc( i+n+3 );
    if( z==0 ) return;







|







 







|







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
...
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
** 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.49 2004/05/24 07:04:26 danielk1977 Exp $
*/
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include "sqliteInt.h"
#include "os.h"
................................................................................
** "NULL".  Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite_func *context, int argc, const char **argv){
  if( argc<1 ) return;
  if( argv[0]==0 ){
    sqlite3_set_result_string(context, "NULL", 4);
  }else if( sqlite3IsNumber(argv[0], 0, TEXT_Utf8) ){
    sqlite3_set_result_string(context, argv[0], -1);
  }else{
    int i,j,n;
    char *z;
    for(i=n=0; argv[0][i]; i++){ if( argv[0][i]=='\'' ) n++; }
    z = sqliteMalloc( i+n+3 );
    if( z==0 ) return;

Changes to src/shell.c.

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
..
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
...
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement the "sqlite" command line
** utility for accessing SQLite databases.
**
** $Id: shell.c,v 1.97 2004/05/22 09:21:21 danielk1977 Exp $
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "sqlite.h"
#include <ctype.h>

................................................................................
static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */


/*
** Determines if a string is a number of not.
*/
extern int sqlite3IsNumber(const char*, int*);

/*
** This routine reads a line of text from standard input, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text.  NULL is returned at end of file, or if malloc()
** fails.
**
................................................................................
    case MODE_Insert: {
      if( azArg==0 ) break;
      fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
      for(i=0; i<nArg; i++){
        char *zSep = i>0 ? ",": "";
        if( azArg[i]==0 ){
          fprintf(p->out,"%sNULL",zSep);
        }else if( sqlite3IsNumber(azArg[i], 0) ){
          fprintf(p->out,"%s%s",zSep, azArg[i]);
        }else{
          if( zSep[0] ) fprintf(p->out,"%s",zSep);
          output_quoted_string(p->out, azArg[i]);
        }
      }
      fprintf(p->out,");\n");







|







 







|







 







|







8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
..
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
...
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement the "sqlite" command line
** utility for accessing SQLite databases.
**
** $Id: shell.c,v 1.98 2004/05/24 07:04:26 danielk1977 Exp $
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "sqlite.h"
#include <ctype.h>

................................................................................
static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */


/*
** Determines if a string is a number of not.
*/
extern int sqlite3IsNumber(const char*, int*, unsigned char);

/*
** This routine reads a line of text from standard input, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text.  NULL is returned at end of file, or if malloc()
** fails.
**
................................................................................
    case MODE_Insert: {
      if( azArg==0 ) break;
      fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
      for(i=0; i<nArg; i++){
        char *zSep = i>0 ? ",": "";
        if( azArg[i]==0 ){
          fprintf(p->out,"%sNULL",zSep);
        }else if( sqlite3IsNumber(azArg[i], 0, 1) ){
          fprintf(p->out,"%s%s",zSep, azArg[i]);
        }else{
          if( zSep[0] ) fprintf(p->out,"%s",zSep);
          output_quoted_string(p->out, azArg[i]);
        }
      }
      fprintf(p->out,");\n");

Changes to src/sqliteInt.h.

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
....
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
....
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
**    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.
**
*************************************************************************
** Internal interface definitions for SQLite.
**
** @(#) $Id: sqliteInt.h,v 1.247 2004/05/23 13:30:58 danielk1977 Exp $
*/
#include "config.h"
#include "sqlite.h"
#include "hash.h"
#include "parse.h"
#include <stdio.h>
#include <stdlib.h>
................................................................................
#define DB_Cookie          0x0002  /* OP_VerifyCookie opcode has been emiited */
#define DB_SchemaLoaded    0x0004  /* The schema has been loaded */
#define DB_UnresetViews    0x0008  /* Some views have defined column names */

/*
** Possible values for the Db.textEnc field.
*/
#define TEXT_Utf8             1
#define TEXT_Utf16le          2
#define TEXT_Utf16be          3
/* #define TEXT_Utf16            4 */

/*
** Each database is an instance of the following structure.
**
** The sqlite.file_format is initialized by the database file
** and helps determines how the data in the database file is
** represented.  This field allows newer versions of the library
................................................................................

/*
** Internal function prototypes
*/
int sqlite3StrICmp(const char *, const char *);
int sqlite3StrNICmp(const char *, const char *, int);
int sqlite3HashNoCase(const char *, int);
int sqlite3IsNumber(const char*, int*);
int sqlite3Compare(const char *, const char *);
int sqlite3SortCompare(const char *, const char *);
void sqlite3RealToSortable(double r, char *);
#ifdef MEMORY_DEBUG
  void *sqlite3Malloc_(int,int,char*,int);
  void sqlite3Free_(void*,char*,int);
  void *sqlite3Realloc_(void*,int,char*,int);
................................................................................
char sqlite3AffinityType(const char *, int);
void sqlite3IndexAffinityStr(Vdbe *, Index *);
void sqlite3TableAffinityStr(Vdbe *, Table *);
char sqlite3CompareAffinity(Expr *pExpr, char aff2);
char const *sqlite3AffinityString(char affinity);
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
char sqlite3ExprAffinity(Expr *pExpr);
int sqlite3atoi64(const char*, i64*);
void sqlite3Error(sqlite *, int, const char*,...);
int sqlite3utfTranslate(const void *, int , u8 , void **, int *, u8);
u8 sqlite3UtfReadBom(const void *zData, int nData);







|







 







|
|
|
|







 







|







 







|



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
....
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
....
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
**    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.
**
*************************************************************************
** Internal interface definitions for SQLite.
**
** @(#) $Id: sqliteInt.h,v 1.248 2004/05/24 07:04:26 danielk1977 Exp $
*/
#include "config.h"
#include "sqlite.h"
#include "hash.h"
#include "parse.h"
#include <stdio.h>
#include <stdlib.h>
................................................................................
#define DB_Cookie          0x0002  /* OP_VerifyCookie opcode has been emiited */
#define DB_SchemaLoaded    0x0004  /* The schema has been loaded */
#define DB_UnresetViews    0x0008  /* Some views have defined column names */

/*
** Possible values for the Db.textEnc field.
*/
#define TEXT_Utf8          1
#define TEXT_Utf16le       2
#define TEXT_Utf16be       3
#define TEXT_Utf16         (SQLITE3_BIGENDIAN?TEXT_Utf16be:TEXT_Utf16le)

/*
** Each database is an instance of the following structure.
**
** The sqlite.file_format is initialized by the database file
** and helps determines how the data in the database file is
** represented.  This field allows newer versions of the library
................................................................................

/*
** Internal function prototypes
*/
int sqlite3StrICmp(const char *, const char *);
int sqlite3StrNICmp(const char *, const char *, int);
int sqlite3HashNoCase(const char *, int);
int sqlite3IsNumber(const char*, int*, u8);
int sqlite3Compare(const char *, const char *);
int sqlite3SortCompare(const char *, const char *);
void sqlite3RealToSortable(double r, char *);
#ifdef MEMORY_DEBUG
  void *sqlite3Malloc_(int,int,char*,int);
  void sqlite3Free_(void*,char*,int);
  void *sqlite3Realloc_(void*,int,char*,int);
................................................................................
char sqlite3AffinityType(const char *, int);
void sqlite3IndexAffinityStr(Vdbe *, Index *);
void sqlite3TableAffinityStr(Vdbe *, Table *);
char sqlite3CompareAffinity(Expr *pExpr, char aff2);
char const *sqlite3AffinityString(char affinity);
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
char sqlite3ExprAffinity(Expr *pExpr);
int sqlite3atoi64(const char*, i64*, u8);
void sqlite3Error(sqlite *, int, const char*,...);
int sqlite3utfTranslate(const void *, int , u8 , void **, int *, u8);
u8 sqlite3UtfReadBom(const void *zData, int nData);

Changes to src/util.c.

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
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
...
659
660
661
662
663
664
665
666
667
668
669


670
671
672
673
674
675
676
677
678
679
680
681
682


683
684
685
686
687
688
689
...
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
...
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
...
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
** $Id: util.c,v 1.87 2004/05/20 11:00:52 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include <stdarg.h>
#include <ctype.h>

/*
** If malloc() ever fails, this global variable gets set to 1.
................................................................................
** Return TRUE if z is a pure numeric string.  Return FALSE if the
** string contains any character which is not part of a number. If
** the string is numeric and contains the '.' character, set *realnum
** to TRUE (otherwise FALSE).
**
** Am empty string is considered non-numeric.
*/
int sqlite3IsNumber(const char *z, int *realnum){


  if( *z=='-' || *z=='+' ) z++;
  if( !isdigit(*z) ){
    return 0;
  }
  z++;
  if( realnum ) *realnum = 0;
  while( isdigit(*z) ){ z++; }
  if( *z=='.' ){
    z++;
    if( !isdigit(*z) ) return 0;
    while( isdigit(*z) ){ z++; }
    if( realnum ) *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z++;
    if( *z=='+' || *z=='-' ) z++;
    if( !isdigit(*z) ) return 0;
    while( isdigit(*z) ){ z++; }
    if( realnum ) *realnum = 1;
  }
  return *z==0;
}

/*
** The string z[] is an ascii representation of a real number.
................................................................................
** then return false.  If n>0 and the integer is string is not
** exactly n bytes long, return false.
**
** When this routine was originally written it dealt with only
** 32-bit numbers.  At that time, it was much faster than the
** atoi() library routine in RedHat 7.2.
*/
int sqlite3atoi64(const char *zNum, i64 *pNum){
  i64 v = 0;
  int neg;
  int i, c;


  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    neg = 0;
    zNum++;
  }else{
    neg = 0;
  }
  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
    v = v*10 + c - '0';
  }
  *pNum = neg ? -v : v;


  return c==0 && i>0 && 
      (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
}

/*
** The string zNum represents an integer.  There might be some other
** information following the integer too, but that part is ignored.
................................................................................

/*
** If zNum represents an integer that will fit in 64-bits, then set
** *pValue to that integer and return true.  Otherwise return false.
*/
int sqlite3GetInt64(const char *zNum, i64 *pValue){
  if( sqlite3FitsIn64Bits(zNum) ){
    sqlite3atoi64(zNum, pValue);
    return 1;
  }
  return 0;
}

/* This comparison routine is what we use for comparison operations
** between numeric values in an SQL expression.  "Numeric" is a little
................................................................................
  int result;
  int isNumA, isNumB;
  if( atext==0 ){
    return -1;
  }else if( btext==0 ){
    return 1;
  }
  isNumA = sqlite3IsNumber(atext, 0);
  isNumB = sqlite3IsNumber(btext, 0);
  if( isNumA ){
    if( !isNumB ){
      result = -1;
    }else{
      double rA, rB;
      rA = sqlite3AtoF(atext, 0);
      rB = sqlite3AtoF(btext, 0);
................................................................................
      break;
    }
    assert( a[0]==b[0] );
    if( (dir=a[0])=='A' || a[0]=='D' ){
      res = strcmp(&a[1],&b[1]);
      if( res ) break;
    }else{
      isNumA = sqlite3IsNumber(&a[1], 0);
      isNumB = sqlite3IsNumber(&b[1], 0);
      if( isNumA ){
        double rA, rB;
        if( !isNumB ){
          res = -1;
          break;
        }
        rA = sqlite3AtoF(&a[1], 0);







|







 







|
>
>
|



|

|

|

|



|
|

|







 







|



>
>


|


|



|



>
>







 







|







 







|
|







 







|
|







10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
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
...
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
...
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
...
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
...
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
** $Id: util.c,v 1.88 2004/05/24 07:04:26 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include <stdarg.h>
#include <ctype.h>

/*
** If malloc() ever fails, this global variable gets set to 1.
................................................................................
** Return TRUE if z is a pure numeric string.  Return FALSE if the
** string contains any character which is not part of a number. If
** the string is numeric and contains the '.' character, set *realnum
** to TRUE (otherwise FALSE).
**
** Am empty string is considered non-numeric.
*/
int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
  int incr = (enc==TEXT_Utf8?1:2);
  if( enc==TEXT_Utf16be ) z++;
  if( *z=='-' || *z=='+' ) z += incr;
  if( !isdigit(*z) ){
    return 0;
  }
  z += incr;
  if( realnum ) *realnum = 0;
  while( isdigit(*z) ){ z += incr; }
  if( *z=='.' ){
    z += incr;
    if( !isdigit(*z) ) return 0;
    while( isdigit(*z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z += incr;
    if( *z=='+' || *z=='-' ) z += incr;
    if( !isdigit(*z) ) return 0;
    while( isdigit(*z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  return *z==0;
}

/*
** The string z[] is an ascii representation of a real number.
................................................................................
** then return false.  If n>0 and the integer is string is not
** exactly n bytes long, return false.
**
** When this routine was originally written it dealt with only
** 32-bit numbers.  At that time, it was much faster than the
** atoi() library routine in RedHat 7.2.
*/
int sqlite3atoi64(const char *zNum, i64 *pNum, u8 enc){
  i64 v = 0;
  int neg;
  int i, c;
  int incr = (enc==TEXT_Utf8?1:2);
  if( enc==TEXT_Utf16be ) zNum++;
  if( *zNum=='-' ){
    neg = 1;
    zNum += incr;
  }else if( *zNum=='+' ){
    neg = 0;
    zNum += incr;
  }else{
    neg = 0;
  }
  for(i=0; (c=zNum[i])>='0' && c<='9'; i += incr){
    v = v*10 + c - '0';
  }
  *pNum = neg ? -v : v;

  /* FIX ME: Handle overflow of strings in UTF-16 here */
  return c==0 && i>0 && 
      (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
}

/*
** The string zNum represents an integer.  There might be some other
** information following the integer too, but that part is ignored.
................................................................................

/*
** If zNum represents an integer that will fit in 64-bits, then set
** *pValue to that integer and return true.  Otherwise return false.
*/
int sqlite3GetInt64(const char *zNum, i64 *pValue){
  if( sqlite3FitsIn64Bits(zNum) ){
    sqlite3atoi64(zNum, pValue, TEXT_Utf8);
    return 1;
  }
  return 0;
}

/* This comparison routine is what we use for comparison operations
** between numeric values in an SQL expression.  "Numeric" is a little
................................................................................
  int result;
  int isNumA, isNumB;
  if( atext==0 ){
    return -1;
  }else if( btext==0 ){
    return 1;
  }
  isNumA = sqlite3IsNumber(atext, 0, TEXT_Utf8);
  isNumB = sqlite3IsNumber(btext, 0, TEXT_Utf8);
  if( isNumA ){
    if( !isNumB ){
      result = -1;
    }else{
      double rA, rB;
      rA = sqlite3AtoF(atext, 0);
      rB = sqlite3AtoF(btext, 0);
................................................................................
      break;
    }
    assert( a[0]==b[0] );
    if( (dir=a[0])=='A' || a[0]=='D' ){
      res = strcmp(&a[1],&b[1]);
      if( res ) break;
    }else{
      isNumA = sqlite3IsNumber(&a[1], 0, TEXT_Utf8);
      isNumB = sqlite3IsNumber(&b[1], 0, TEXT_Utf8);
      if( isNumA ){
        double rA, rB;
        if( !isNumB ){
          res = -1;
          break;
        }
        rA = sqlite3AtoF(&a[1], 0);

Changes to src/vdbe.c.

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
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
...
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
...
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
...
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
325
326
327
328
329

























330
331
332
333
334
335
336
...
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
...
509
510
511
512
513
514
515





















516

517
518
519





520

521
522
523
524
525
526
527
528
529

530
531
532
533
534
535
536
...
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
...
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
...
712
713
714
715
716
717
718











































































































































































































































































719
720
721
722
723
724
725
...
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
...
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
...
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
...
993
994
995
996
997
998
999
1000
1001

1002
1003
1004
1005
1006
1007
1008
....
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
....
1596
1597
1598
1599
1600
1601
1602

1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621


1622








1623
1624
1625
1626
1627
1628
1629
....
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648


1649






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
....
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
....
1832
1833
1834
1835
1836
1837
1838



1839
1840


1841
1842
1843
1844
1845
1846
1847
....
1859
1860
1861
1862
1863
1864
1865






1866
1867
1868
1869
1870
1871
1872
....
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921




1922
1923


1924
1925
1926
1927
1928
1929
1930
....
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
....
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
....
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
....
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
....
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
....
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
....
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
....
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
....
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308




2309


2310
2311
2312
2313
2314
2315
2316
....
2365
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
2395
2396
2397
....
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
....
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
....
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
....
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
....
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
....
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
....
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
....
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
....
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
....
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
....
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
....
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565




4566
4567
4568
4569
4570
4571
4572
....
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
....
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
....
4983
4984
4985
4986
4987
4988
4989

4990
4991
4992
4993
4994
4995
4996
....
5139
5140
5141
5142
5143
5144
5145
5146


5147
5148
5149
5150
5151
5152
5153
....
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
....
5219
5220
5221
5222
5223
5224
5225


5226
5227
5228
5229
5230
5231
5232
....
5243
5244
5245
5246
5247
5248
5249




5250
5251
5252
5253
5254
5255
5256
**
** 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.321 2004/05/23 13:30:58 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>
#include "vdbeInt.h"

/*
................................................................................
** Mem.z points at a MemRecord struct
*/
static int Recordify(Mem *pMem){
  return 0;
}
#endif

/*
** Convert the given stack entity into a string if it isn't one
** already.
*/
#define Stringify(P) if(!((P)->flags&(MEM_Str|MEM_Blob))){hardStringify(P);}
static int hardStringify(Mem *pStack){
  int fg = pStack->flags;
  if( fg & MEM_Real ){
    sqlite3_snprintf(sizeof(pStack->zShort),pStack->zShort,"%.15g",pStack->r);
  }else if( fg & MEM_Int ){
    sqlite3_snprintf(sizeof(pStack->zShort),pStack->zShort,"%lld",pStack->i);
  }else{
    pStack->zShort[0] = 0;
  }
  pStack->z = pStack->zShort;
  pStack->n = strlen(pStack->zShort)+1;
  pStack->flags = MEM_Str | MEM_Short | MEM_Term | MEM_Utf8;
  return 0;
}

/*
** Release the memory associated with the given stack level.  This
** leaves the Mem.flags field in an inconsistent state.
*/
#define Release(P) if((P)->flags&MEM_Dyn){ sqliteFree((P)->z); }

/*
** Convert the given stack entity into a integer if it isn't one
** already.
**
** Any prior string or real representation is invalidated.  
** NULLs are converted into 0.
*/
#define Integerify(P) if(((P)->flags&MEM_Int)==0){ hardIntegerify(P); }
static void hardIntegerify(Mem *pStack){
  if( pStack->flags & MEM_Real ){
    pStack->i = (int)pStack->r;
    Release(pStack);
  }else if( pStack->flags & MEM_Str ){
    sqlite3atoi64(pStack->z, &pStack->i);
    Release(pStack);
  }else{
    pStack->i = 0;
  }
  pStack->flags = MEM_Int;
}

/*
** Get a valid Real representation for the given stack element.
**
** Any prior string or integer representation is retained.
** NULLs are converted into 0.0.
*/
#define Realify(P) if(((P)->flags&MEM_Real)==0){ hardRealify(P); }
static void hardRealify(Mem *pStack){
  if( pStack->flags & MEM_Str ){
    pStack->r = sqlite3AtoF(pStack->z, 0);
  }else if( pStack->flags & MEM_Int ){
    pStack->r = pStack->i;
  }else{
    pStack->r = 0.0;
  }
  pStack->flags |= MEM_Real;
}

/*
** Parmameter "flags" is the value of the flags for a string Mem object.
** Return one of TEXT_Utf8, TEXT_Utf16le or TEXT_Utf16be, depending
** on the encoding indicated by the flags value.
*/
static u8 flagsToEnc(int flags){
  if( flags&MEM_Utf8 ){
................................................................................
}

/*
** Set the encoding flags of memory cell "pMem" to the correct values
** for the database encoding "enc" (one of TEXT_Utf8, TEXT_Utf16le or
** TEXT_Utf16be).
*/
#define SetEncodingFlags(pMem, enc) (pMem->flags = \
(pMem->flags & ~(MEM_Utf8|MEM_Utf16le|MEM_Utf16be)) | encToFlags(enc))

/*
** If pMem is a string object, this routine sets the encoding of the string
** (to one of UTF-8 or UTF16) and whether or not the string is
** nul-terminated. If pMem is not a string object, then this routine is
** a no-op.
**
................................................................................
** between formats.
*/
int SetEncoding(Mem *pMem, int flags){
  u8 enc1;    /* Current string encoding (TEXT_Utf* value) */
  u8 enc2;    /* Required string encoding (TEXT_Utf* value) */

  /* If this is not a string, do nothing. */
  if( !(pMem->flags&MEM_Str) || pMem->flags&MEM_Int || pMem->flags&MEM_Real ){
    return SQLITE_OK;
  }

  enc1 = flagsToEnc(pMem->flags);
  enc2 = flagsToEnc(flags);

  if( enc1!=enc2 ){
    /* If the current encoding does not match the desired encoding, then
    ** we will need to do some translation between encodings.
    */
    char *z;
    int n;
    int rc = sqlite3utfTranslate(pMem->z, pMem->n, enc1, (void **)&z, &n, enc2);
    if( rc!=SQLITE_OK ){
      return rc;
    }

    /* Result of sqlite3utfTranslate is currently always dynamically
    ** allocated and nul terminated. This might be altered as a performance
    ** enhancement later.
................................................................................
    */
    memcpy(&pMem->z[pMem->n], "\0\0", nulTermLen);
    pMem->n += nulTermLen;
    pMem->flags |= MEM_Term;
  }
  return SQLITE_OK;
}

/*

























































































** Convert the given stack entity into a string that has been obtained
** from sqliteMalloc().  This is different from Stringify() above in that
** Stringify() will use the NBFS bytes of static string space if the string
** will fit but this routine always mallocs for space.
** Return non-zero if we run out of memory.
*/

#define Dynamicify(P) (((P)->flags & MEM_Dyn)==0 ? hardDynamicify(P):0)
static int hardDynamicify(Mem *pStack){
  int fg = pStack->flags;
  char *z;
  if( (fg & MEM_Str)==0 ){
    hardStringify(pStack);
  }
  assert( (fg & MEM_Dyn)==0 );
  z = sqliteMallocRaw( pStack->n );
  if( z==0 ) return 1;
  memcpy(z, pStack->z, pStack->n);
  pStack->z = z;
  pStack->flags |= MEM_Dyn;
  return 0;
}


























/*
** Advance the virtual machine to the next output row.
**
** The return vale will be either SQLITE_BUSY, SQLITE_DONE, 
** SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
**
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];
  SetEncodingFlags(pVal, pVm->db->enc);
  return sqlite3_value_data((sqlite3_value *)pVal);
}















const unsigned char *sqlite3_value_data(sqlite3_value* pVal){
  if( pVal->flags&MEM_Null ){

    return 0;
  }
  if( !(pVal->flags&MEM_Blob) ){
    if( pVal->flags&MEM_Str && !(pVal->flags&MEM_Utf8) ){
      char *z = 0;
      int n;
      u8 enc = flagsToEnc(pVal->flags);
      if( sqlite3utfTranslate(pVal->z,pVal->n,enc,(void **)&z,&n,TEXT_Utf8) ){
        return 0;
      }
      Release(pVal);
      pVal->z = z;
      pVal->n = n;
      SetEncodingFlags(pVal, TEXT_Utf8);
    }else{







      Stringify(pVal);
    }
  }
  return pVal->z;
}

/*
** Return the value of the 'i'th column of the current row of the currently
** executing statement pStmt.
*/
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];





















  if( pVal->flags&MEM_Null ){

    return 0;
  }






  if( !(pVal->flags&MEM_Blob) ){

    Stringify(pVal);
    if( SQLITE3_BIGENDIAN ){
      /* SetEncoding(pVal, MEM_Utf16be|MEM_Term); */
    }else{
  /*    SetEncoding(pVal, MEM_Utf16le|MEM_Term); */
    }
  }

  return pVal->z;

}

/*
** Return the number of bytes of data that will be returned by the
** equivalent sqlite3_column_data() call.
*/
int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];
  Integerify(pVal);
  return pVal->i;
}

/*
** Return the value of the 'i'th column of the current row of the currently
** executing statement pStmt.
*/
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];
  Realify(pVal);
  return pVal->r;
}

/*
** Return the name of the Nth column of the result set returned by SQL
** statement pStmt.
*/
................................................................................
/*
** Return the column declaration type (if applicable) of the 'i'th column
** of the result set of SQL statement pStmt, encoded as UTF-16.
*/
const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int i){
  return columnName16(pStmt, i, 1);
}












































































































































































































































































/*
** Insert a new aggregate element and make it the element that
** has focus.
**
** Return 0 on success and 1 if memory is exhausted.
*/
................................................................................
  if( pElem==0 ){
    AggInsert(p,"",1);
    pElem = sqliteHashFirst(&p->hash);
  }
  return pElem ? sqliteHashData(pElem) : 0;
}

/*
** An ephemeral string value (signified by the MEM_Ephem flag) contains
** a pointer to a dynamically allocated string where some other entity
** is responsible for deallocating that string.  Because the stack entry
** does not control the string, it might be deleted without the stack
** entry knowing it.
**
** This routine converts an ephemeral string into a dynamically allocated
** string that the stack entry itself controls.  In other words, it
** converts an MEM_Ephem string into an MEM_Dyn string.
*/
#define Deephemeralize(P) \
   if( ((P)->flags&MEM_Ephem)!=0 && hardDeephem(P) ){ goto no_mem;}
static int hardDeephem(Mem *pStack){
  char *z;
  assert( (pStack->flags & MEM_Ephem)!=0 );
  z = sqliteMallocRaw( pStack->n );
  if( z==0 ) return 1;
  memcpy(z, pStack->z, pStack->n);
  pStack->z = z;
  pStack->flags &= ~MEM_Ephem;
  pStack->flags |= MEM_Dyn;
  return 0;
}

/*
** Pop the stack N times.
*/
static void popStack(Mem **ppTos, int N){
  Mem *pTos = *ppTos;
  while( N>0 ){
    N--;
................................................................................
**
** SQLITE_AFF_NUMERIC
** SQLITE_AFF_TEXT
** SQLITE_AFF_NONE
** SQLITE_AFF_INTEGER
**
*/
static void applyAffinity(Mem *pRec, char affinity){
  switch( affinity ){
    case SQLITE_AFF_INTEGER:
    case SQLITE_AFF_NUMERIC:
      if( 0==(pRec->flags&(MEM_Real|MEM_Int)) ){
        /* pRec does not have a valid integer or real representation. 
        ** Attempt a conversion if pRec has a string representation and
        ** it looks like a number.
        */
        int realnum;
        if( pRec->flags&MEM_Str && sqlite3IsNumber(pRec->z, &realnum) ){
          if( realnum ){
            Realify(pRec);
          }else{
            Integerify(pRec);
          }
        }
      }

      if( affinity==SQLITE_AFF_INTEGER ){
        /* For INTEGER affinity, try to convert a real value to an int */
        if( pRec->flags&MEM_Real ){
................................................................................

    case SQLITE_AFF_TEXT:
      /* Only attempt the conversion if there is an integer or real
      ** representation (blob and NULL do not get converted) but no string
      ** representation.
      */
      if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
        Stringify(pRec);
      }
      pRec->flags &= ~(MEM_Real|MEM_Int);

      break;

    case SQLITE_AFF_NONE:
      /* Affinity NONE. Do nothing. */
................................................................................
      zBuf[1] = 's';
    }
    k = 2;
    k += sprintf(&zBuf[k], "%d", pMem->n);
    zBuf[k++] = '[';
    for(j=0; j<15 && j<pMem->n; j++){
      u8 c = pMem->z[j];
      if( c==0 && j==pMem->n-1 ) break;
/*

            zBuf[k++] = "0123456789ABCDEF"[c>>4];
            zBuf[k++] = "0123456789ABCDEF"[c&0xf];
*/
      if( c>=0x20 && c<0x7f ){
        zBuf[k++] = c;
      }else{
        zBuf[k++] = '.';
................................................................................
  pTos->flags = 0;
 
  /* If this is an OP_Real or OP_Integer opcode, set the pTos->r or pTos->i
  ** values respectively.
  */
  if( op==OP_Real ){
    assert( z );
    assert( sqlite3IsNumber(z, 0) );
    pTos->r = sqlite3AtoF(z, 0);
    pTos->flags = MEM_Real;
  }else if( op==OP_Integer ){
    pTos->flags = MEM_Int;
    pTos->i = pOp->p1;
    if( pTos->i==0 && pOp->p3 ){
      sqlite3GetInt64(pOp->p3, &pTos->i);
................................................................................
/* Opcode: Callback P1 * *
**
** Pop P1 values off the stack and form them into an array.  Then
** invoke the callback function using the newly formed array as the
** 3rd parameter.
*/
case OP_Callback: {

  int i;
  char **azArgv = p->zArgv;
  Mem *pCol;

  pCol = &pTos[1-pOp->p1];
  assert( pCol>=p->aStack );
  for(i=0; i<pOp->p1; i++, pCol++){
    if( pCol->flags & MEM_Null ){
      azArgv[i] = 0;
    }else{
      Stringify(pCol);
      azArgv[i] = pCol->z;
    }
  }
  p->resOnStack = 1;

  azArgv[i] = 0;
  p->azResColumn = azArgv;
  p->nCallback++;


  assert( p->nResColumn==pOp->p1 );








  p->popStack = pOp->p1;
  p->pc = pc + 1;
  p->pTos = pTos;
  return SQLITE_ROW;
}

/* Opcode: Concat P1 P2 P3
................................................................................
** from sqliteMalloc().
*/
case OP_Concat: {
  char *zNew;
  int nByte;
  int nField;
  int i, j;
  char *zSep;
  int nSep;
  Mem *pTerm;









  nField = pOp->p1;
  zSep = pOp->p3;
  if( zSep==0 ) zSep = "";
  nSep = strlen(zSep);
  assert( &pTos[1-nField] >= p->aStack );
  nByte = 1 - nSep;









  pTerm = &pTos[1-nField];

  for(i=0; i<nField; i++, pTerm++){

    if( pTerm->flags & MEM_Null ){
      nByte = -1;
      break;
    }else{

      Stringify(pTerm);
      nByte += pTerm->n - 1 + nSep;

    }
  }
  if( nByte<0 ){




    if( pOp->p2==0 ){
      popStack(&pTos, nField);
    }
    pTos++;
    pTos->flags = MEM_Null;
    break;
  }




  zNew = sqliteMallocRaw( nByte );
  if( zNew==0 ) goto no_mem;
  j = 0;
  pTerm = &pTos[1-nField];
  for(i=j=0; i<nField; i++, pTerm++){

    assert( pTerm->flags & MEM_Str );
    memcpy(&zNew[j], pTerm->z, pTerm->n-1);
    j += pTerm->n-1;
    if( nSep>0 && i<nField-1 ){


      memcpy(&zNew[j], zSep, nSep);
      j += nSep;
    }
  }
  zNew[j] = 0;





  if( pOp->p2==0 ){
    popStack(&pTos, nField);
  }
  pTos++;
  pTos->n = nByte;
  pTos->flags = MEM_Str|MEM_Dyn|MEM_Utf8|MEM_Term;
  pTos->z = zNew;

  break;
}

/* Opcode: Add * * *
**
** Pop the top two elements from the stack, add them together,
** and push the result back onto the stack.  If either element
................................................................................
    Release(pTos);
    pTos--;
    Release(pTos);
    pTos->i = b;
    pTos->flags = MEM_Int;
  }else{
    double a, b;
    Realify(pTos);
    Realify(pNos);
    a = pTos->r;
    b = pNos->r;
    switch( pOp->opcode ){
      case OP_Add:         b += a;       break;
      case OP_Subtract:    b -= a;       break;
      case OP_Multiply:    b *= a;       break;
      case OP_Divide: {
................................................................................

  n = pOp->p1;
  pArg = &pTos[1-n];
  azArgv = p->zArgv;
  for(i=0; i<n; i++, pArg++){
    if( pArg->flags & MEM_Null ){
      azArgv[i] = 0;



    }else{
      Stringify(pArg);


      azArgv[i] = pArg->z;
    }
  }
  ctx.pFunc = (FuncDef*)pOp->p3;
  ctx.s.flags = MEM_Null;
  ctx.s.z = 0;
  ctx.isError = 0;
................................................................................
    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;
  }






  break;
}

/* Opcode: BitAnd * * *
**
** Pop the top two elements from the stack.  Convert both elements
** to integers.  Push back onto the stack the bit-wise AND of the
................................................................................
  assert( pNos>=p->aStack );
  if( (pTos->flags | pNos->flags) & MEM_Null ){
    popStack(&pTos, 2);
    pTos++;
    pTos->flags = MEM_Null;
    break;
  }
  Integerify(pTos);
  Integerify(pNos);
  a = pTos->i;
  b = pNos->i;
  switch( pOp->opcode ){
    case OP_BitAnd:      a &= b;     break;
    case OP_BitOr:       a |= b;     break;
    case OP_ShiftLeft:   a <<= b;    break;
    case OP_ShiftRight:  a >>= b;    break;
    default:   /* CANT HAPPEN */     break;
  }




  assert( (pTos->flags & MEM_Dyn)==0 );
  assert( (pNos->flags & MEM_Dyn)==0 );


  pTos--;
  Release(pTos);
  pTos->i = a;
  pTos->flags = MEM_Int;
  break;
}

................................................................................
** Add the value P1 to whatever is on top of the stack.  The result
** is always an integer.
**
** To force the top of the stack to be an integer, just add 0.
*/
case OP_AddImm: {
  assert( pTos>=p->aStack );
  Integerify(pTos);
  pTos->i += pOp->p1;
  break;
}

/* Opcode: ForceInt P1 P2 *
**
** Convert the top of the stack into an integer.  If the current top of
................................................................................
** convert it into the least integer that is greater than or equal to its
** current value if P1==0, or to the least integer that is strictly
** greater than its current value if P1==1.
*/
case OP_ForceInt: {
  int v;
  assert( pTos>=p->aStack );
  if( (pTos->flags & (MEM_Int|MEM_Real))==0
         && ((pTos->flags & MEM_Str)==0 || sqlite3IsNumber(pTos->z, 0)==0) ){
    Release(pTos);
    pTos--;
    pc = pOp->p2 - 1;
    break;
  }
  if( pTos->flags & MEM_Int ){
    v = pTos->i + (pOp->p1!=0);
  }else{
    Realify(pTos);
    v = (int)pTos->r;
    if( pTos->r>(double)v ) v++;
    if( pOp->p1 && pTos->r==(double)v ) v++;
  }
  Release(pTos);
  pTos->i = v;
  pTos->flags = MEM_Int;
................................................................................
    double r = (double)i;
    if( r!=pTos->r ){
      goto mismatch;
    }
    pTos->i = i;
  }else if( pTos->flags & MEM_Str ){
    i64 v;
    if( !sqlite3atoi64(pTos->z, &v) ){
      double r;
      if( !sqlite3IsNumber(pTos->z, 0) ){
        goto mismatch;
      }
      Realify(pTos);
      v = (int)pTos->r;
      r = (double)v;
      if( r!=pTos->r ){
        goto mismatch;
      }
    }
    pTos->i = v;
................................................................................
      pTos->flags = MEM_Null;
    }
    break;
  }

  affinity = (pOp->p1>>8)&0xFF;
  if( affinity=='\0' ) affinity = 'n';
  applyAffinity(pNos, affinity);
  applyAffinity(pTos, affinity);

  assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
  res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
  switch( pOp->opcode ){
    case OP_Eq:    res = res==0;     break;
    case OP_Ne:    res = res!=0;     break;
    case OP_Lt:    res = res<0;      break;
................................................................................
  Mem *pNos = &pTos[-1];
  int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */

  assert( pNos>=p->aStack );
  if( pTos->flags & MEM_Null ){
    v1 = 2;
  }else{
    Integerify(pTos);
    v1 = pTos->i==0;
  }
  if( pNos->flags & MEM_Null ){
    v2 = 2;
  }else{
    Integerify(pNos);
    v2 = pNos->i==0;
  }
  if( pOp->opcode==OP_And ){
    static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
    v1 = and_logic[v1*3+v2];
  }else{
    static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
................................................................................
    if( pOp->opcode==OP_Negative || pTos->i<0 ){
      pTos->i = -pTos->i;
    }
    pTos->flags = MEM_Int;
  }else if( pTos->flags & MEM_Null ){
    /* Do nothing */
  }else{
    Realify(pTos);
    Release(pTos);
    if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
      pTos->r = -pTos->r;
    }
    pTos->flags = MEM_Real;
  }
  break;
................................................................................
** Interpret the top of the stack as a boolean value.  Replace it
** with its complement.  If the top of the stack is NULL its value
** is unchanged.
*/
case OP_Not: {
  assert( pTos>=p->aStack );
  if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
  Integerify(pTos);
  Release(pTos);
  pTos->i = !pTos->i;
  pTos->flags = MEM_Int;
  break;
}

/* Opcode: BitNot * * *
................................................................................
** Interpret the top of the stack as an value.  Replace it
** with its ones-complement.  If the top of the stack is NULL its
** value is unchanged.
*/
case OP_BitNot: {
  assert( pTos>=p->aStack );
  if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
  Integerify(pTos);
  Release(pTos);
  pTos->i = ~pTos->i;
  pTos->flags = MEM_Int;
  break;
}

/* Opcode: Noop * * *
................................................................................
case OP_If:
case OP_IfNot: {
  int c;
  assert( pTos>=p->aStack );
  if( pTos->flags & MEM_Null ){
    c = pOp->p1;
  }else{
    Integerify(pTos);
    c = pTos->i;
    if( pOp->opcode==OP_IfNot ) c = !c;
  }




  assert( (pTos->flags & MEM_Dyn)==0 );


  pTos--;
  if( c ) pc = pOp->p2-1;
  break;
}

/* Opcode: IsNull P1 P2 *
**
................................................................................
case OP_Class: {
  int flags = pTos->flags;
  int i;

  struct {
    int mask;
    char * zClass;

  } classes[] = {
    {MEM_Null, "NULL"},
    {MEM_Int, "INTEGER"},
    {MEM_Real, "REAL"},
    {MEM_Str, "TEXT"},
    {MEM_Blob, "BLOB"}
  };

  Release(pTos);
  pTos->flags = MEM_Str|MEM_Static|MEM_Utf8|MEM_Term;

  for(i=0; i<5; i++){
    if( classes[i].mask&flags ){


      pTos->z = classes[i].zClass;










      break;
    }
  }
  assert( i<5 );


  pTos->n = strlen(classes[i].zClass);




  break;
}

/* Opcode: SetNumColumns P1 P2 *
**
** Before the OP_Column opcode can be executed on a cursor, this
** opcode must be called to set the number of fields in the table.
................................................................................

  /* Loop through the elements that will make up the record to figure
  ** out how much space is required for the new record.
  */
  for(pRec=pData0; pRec<=pTos; pRec++){
    u64 serial_type;
    if( zAffinity ){
      applyAffinity(pRec, zAffinity[pRec-pData0]);
    }
    serial_type = sqlite3VdbeSerialType(pRec);
    nBytes += sqlite3VdbeSerialTypeLen(serial_type);
    nBytes += sqlite3VarintLen(serial_type);
  }

  if( nBytes>MAX_BYTES_PER_ROW ){
................................................................................
  **
  ** TODO: Figure out if the in-place coercion causes a problem for
  ** OP_MakeKey when P2 is 0 (used by DISTINCT).
  */
  for(pRec=pData0; pRec<=pTos; pRec++){
    u64 serial_type;
    if( zAffinity ){
      applyAffinity(pRec, zAffinity[pRec-pData0]);
    }
    if( pRec->flags&MEM_Null ){
      containsNull = 1;
    }
    serial_type = sqlite3VdbeSerialType(pRec);
    nByte += sqlite3VarintLen(serial_type);
    nByte += sqlite3VdbeSerialTypeLen(serial_type);
................................................................................
  /* If we have to append a varint rowid to this record, set 'rowid'
  ** to the value of the rowid and increase nByte by the amount of space
  ** required to store it and the 0x00 seperator byte.
  */
  if( addRowid ){
    pRec = &pTos[0-nField];
    assert( pRec>=p->aStack );
    Integerify(pRec);
    rowid = pRec->i;
    nByte += sqlite3VarintLen(rowid);
    nByte++;
  }
  
  if( nByte>MAX_BYTES_PER_ROW ){
    rc = SQLITE_TOOBIG;
................................................................................
** A transaction must be started before executing this opcode.
*/
case OP_SetCookie: {
  assert( pOp->p2<SQLITE_N_BTREE_META );
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( db->aDb[pOp->p1].pBt!=0 );
  assert( pTos>=p->aStack );
  Integerify(pTos);
  /* See note about index shifting on OP_ReadCookie */
  rc = sqlite3BtreeUpdateMeta(db->aDb[pOp->p1].pBt, 1+pOp->p2, (int)pTos->i);
  Release(pTos);
  pTos--;
  break;
}

................................................................................
  int p2 = pOp->p2;
  int wrFlag;
  Btree *pX;
  int iDb;
  Cursor *pCur;
  
  assert( pTos>=p->aStack );
  Integerify(pTos);
  iDb = pTos->i;
  pTos--;
  assert( iDb>=0 && iDb<db->nDb );
  pX = db->aDb[iDb].pBt;
  assert( pX!=0 );
  wrFlag = pOp->opcode==OP_OpenWrite;
  if( p2<=0 ){
    assert( pTos>=p->aStack );
    Integerify(pTos);
    p2 = pTos->i;
    pTos--;
    if( p2<2 ){
      sqlite3SetString(&p->zErrMsg, "root page number less than 2", (char*)0);
      rc = SQLITE_INTERNAL;
      break;
    }
................................................................................
    int res, oc;
    oc = pOp->opcode;
    pC->nullRow = 0;
    *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
    if( pC->intKey ){
      i64 iKey;
      assert( !pOp->p3 );
      Integerify(pTos);
      iKey = intToKey(pTos->i);
      if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
        pC->movetoTarget = iKey;
        pC->deferredMoveto = 1;
        Release(pTos);
        pTos--;
        break;
      }
      sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, &res);
      pC->lastRecno = pTos->i;
      pC->recnoIsValid = res==0;
    }else{
      Stringify(pTos);
      sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
      pC->recnoIsValid = 0;
    }
    pC->deferredMoveto = 0;
    pC->cacheValid = 0;
    *pC->pIncrKey = 0;
    sqlite3_search_count++;
................................................................................
  int alreadyExists = 0;
  Cursor *pC;
  assert( pTos>=p->aStack );
  assert( i>=0 && i<p->nCursor );
  if( (pC = p->apCsr[i])->pCursor!=0 ){
    int res, rx;
    assert( pC->intKey==0 );
    Stringify(pTos);
    rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
    alreadyExists = rx==SQLITE_OK && res==0;
    pC->deferredMoveto = 0;
    pC->cacheValid = 0;
  }
  if( pOp->opcode==OP_Found ){
    if( alreadyExists ) pc = pOp->p2 - 1;
................................................................................
  Cursor *pCx;
  BtCursor *pCrsr;
  i64 R;

  /* Pop the value R off the top of the stack
  */
  assert( pNos>=p->aStack );
  Integerify(pTos);
  R = pTos->i;
  pTos--;
  assert( i>=0 && i<=p->nCursor );
  pCx = p->apCsr[i];
  pCrsr = pCx->pCursor;
  if( pCrsr!=0 ){
    int res, rc;
................................................................................
    i64 v;         /* The record number on the P1 entry that matches K */
    char *zKey;    /* The value of K */
    int nKey;      /* Number of bytes in K */
    int len;       /* Number of bytes in K without the rowid at the end */

    /* Make sure K is a string and make zKey point to K
    */
    Stringify(pNos);
    zKey = pNos->z;
    nKey = pNos->n;

    assert( nKey >= 2 );
    len = nKey-2;
    while( zKey[len] && --len );

................................................................................
  assert( pNos>=p->aStack );
  assert( i>=0 && i<p->nCursor );
  if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
    char *zKey;
    i64 nKey; 
    i64 iKey;
    if( pOp->opcode==OP_PutStrKey ){
      Stringify(pNos);
      nKey = pNos->n;
      zKey = pNos->z;
    }else{
      assert( pNos->flags & MEM_Int );

      /* If the table is an INTKEY table, set nKey to the value of
      ** the integer key, and zKey to NULL. Otherwise, set nKey to
................................................................................
  Cursor *pC;

  assert( i>=0 && i<p->nCursor );
  assert( pTos>=p->aStack );
  if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
    int res, rc;
 
    Stringify(pTos);
    assert( pC->deferredMoveto==0 );
    *pC->pIncrKey = pOp->p3!=0;
    assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
    rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, pTos->z, &res);
    *pC->pIncrKey = 0;
    if( rc!=SQLITE_OK ){
      break;
................................................................................
  popStack(&pTos, nRoot);
  pTos++;
  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
  if( z==0 || z[0]==0 ){
    if( z ) sqliteFree(z);
    pTos->z = "ok";
    pTos->n = 3;
    pTos->flags = MEM_Utf8 | MEM_Str | MEM_Static;
  }else{
    pTos->z = z;
    pTos->n = strlen(z) + 1;
    pTos->flags = MEM_Utf8 | MEM_Str | MEM_Dyn;




  }
  sqliteFree(aRoot);
  break;
}

/* Opcode: ListWrite * * *
**
................................................................................
    if( pKeylist==0 ) goto no_mem;
    pKeylist->nKey = 1000;
    pKeylist->nRead = 0;
    pKeylist->nUsed = 0;
    pKeylist->pNext = p->pList;
    p->pList = pKeylist;
  }
  Integerify(pTos);
  pKeylist->aKey[pKeylist->nUsed++] = pTos->i;
  Release(pTos);
  pTos--;
  break;
}

/* Opcode: ListRewind * * *
................................................................................
** and put them on the sorter.  The key and data should have been
** made using SortMakeKey and SortMakeRec, respectively.
*/
case OP_SortPut: {
  Mem *pNos = &pTos[-1];
  Sorter *pSorter;
  assert( pNos>=p->aStack );
  if( Dynamicify(pTos) || Dynamicify(pNos) ) goto no_mem;
  pSorter = sqliteMallocRaw( sizeof(Sorter) );
  if( pSorter==0 ) goto no_mem;
  pSorter->pNext = p->pSort;
  p->pSort = pSorter;
  assert( pTos->flags & MEM_Dyn );
  pSorter->nKey = pTos->n;
  pSorter->zKey = pTos->z;
................................................................................
    z = 0;
  }
  pTos++;
  if( z ){
    pTos->n = strlen(z) + 1;
    pTos->z = z;
    pTos->flags = MEM_Utf8 | MEM_Str | MEM_Ephem | MEM_Term;

  }else{
    pTos->flags = MEM_Null;
  }
  break;
}

/* Opcode: MemStore P1 P2 *
................................................................................
  assert( pTos->flags==MEM_Int );
  pRec = &pTos[-n];
  assert( pRec>=p->aStack );
  for(i=0; i<n; i++, pRec++){
    if( pRec->flags & MEM_Null ){
      azArgv[i] = 0;
    }else{
      Stringify(pRec);


      azArgv[i] = pRec->z;
    }
  }
  i = pTos->i;
  assert( i>=0 && i<p->agg.nMem );
  ctx.pFunc = (FuncDef*)pOp->p3;
  pMem = &p->agg.pCurrent->aMem[i];
................................................................................
*/
case OP_AggFocus: {
  AggElem *pElem;
  char *zKey;
  int nKey;

  assert( pTos>=p->aStack );
  Stringify(pTos);
  zKey = pTos->z;
  nKey = pTos->n;
  pElem = sqlite3HashFind(&p->agg.hash, zKey, nKey);
  if( pElem ){
    p->agg.pCurrent = pElem;
    pc = pOp->p2 - 1;
  }else{
................................................................................
  Release(pMem);
  *pMem = *pTos;
  if( pMem->flags & MEM_Dyn ){
    pTos->flags = MEM_Null;
  }else if( pMem->flags & MEM_Short ){
    pMem->z = pMem->zShort;
  }


  Release(pTos);
  pTos--;
  break;
}

/* Opcode: AggGet * P2 *
**
................................................................................
  pTos++;
  pMem = &pFocus->aMem[i];
  *pTos = *pMem;
  if( pTos->flags & (MEM_Str|MEM_Blob) ){
    pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
    pTos->flags |= MEM_Ephem;
  }




  break;
}

/* Opcode: AggNext * P2 *
**
** Make the next aggregate value the current aggregate.  The prior
** aggregate is deleted.  If all aggregate values have been consumed,







|







 








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





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







 







|
|







 







|












|







 









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






>
|
|



|









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







 







<



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


>


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







 







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

>



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







 







|







 







|







 







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







 







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







 







|









|

|

|







 







|







 







<

>







 







|







 







>










|



<



|
>
>

>
>
>
>
>
>
>
>







 







<
<

>
>

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

>

>
|


<
>
|
<
>
|
|

>
>
>
>





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







 







|
|







 







>
>
>

<
>
>







 







>
>
>
>
>
>







 







|
|









>
>
>
>


>
>







 







|







 







|
|








|







 







|

|


|







 







|
|







 







|





|







 







|







 







|







 







|







 







|



>
>
>
>
|
>
>







 







>

|
|
|
|
|



|



>
>
|
>
>
>
>
>
>
>
>
>
>




>
>
|
>
>
>
>







 







|







 







|







 







|







 







|







 







|








|







 







|












|







 







|







 







|







 







|







 







|







 







|







 







|



|
>
>
>
>







 







|







 







|







 







>







 







|
>
>







 







|







 







>
>







 







>
>
>
>







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
93
94
95
96
97
98
99
100




















101
102
103
104
105







































106
107
108
109
110
111
112
...
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
...
159
160
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
...
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
...
522
523
524
525
526
527
528

529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550







551





552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
...
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614




615
616


617
618
619
620
621
622
623
624
...
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
...
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
...
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
....
1110
1111
1112
1113
1114
1115
1116

























1117
1118
1119
1120
1121
1122
1123
....
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
....
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
....
1323
1324
1325
1326
1327
1328
1329

1330
1331
1332
1333
1334
1335
1336
1337
1338
....
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
....
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947

1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
....
1979
1980
1981
1982
1983
1984
1985


1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997

1998


1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014

2015
2016

2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029


2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042

2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
....
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
....
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210

2211
2212
2213
2214
2215
2216
2217
2218
2219
....
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
....
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
....
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
....
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
....
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
....
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
....
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
....
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
....
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
....
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
....
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
....
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
....
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
....
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
....
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
....
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
....
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
....
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
....
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
....
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
....
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
....
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
....
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
....
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
....
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
....
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
....
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
....
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
....
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
....
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
....
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
**
** 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.322 2004/05/24 07:04:27 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>
#include "vdbeInt.h"

/*
................................................................................
** Mem.z points at a MemRecord struct
*/
static int Recordify(Mem *pMem){
  return 0;
}
#endif

/*




















** Release the memory associated with the given stack level.  This
** leaves the Mem.flags field in an inconsistent state.
*/
#define Release(P) if((P)->flags&MEM_Dyn){ sqliteFree((P)->z); }








































/*
** Parmameter "flags" is the value of the flags for a string Mem object.
** Return one of TEXT_Utf8, TEXT_Utf16le or TEXT_Utf16be, depending
** on the encoding indicated by the flags value.
*/
static u8 flagsToEnc(int flags){
  if( flags&MEM_Utf8 ){
................................................................................
}

/*
** Set the encoding flags of memory cell "pMem" to the correct values
** for the database encoding "enc" (one of TEXT_Utf8, TEXT_Utf16le or
** TEXT_Utf16be).
*/
#define SetEncodingFlags(pMem, enc) ((pMem)->flags = \
((pMem->flags & ~(MEM_Utf8|MEM_Utf16le|MEM_Utf16be))) | encToFlags(enc))

/*
** If pMem is a string object, this routine sets the encoding of the string
** (to one of UTF-8 or UTF16) and whether or not the string is
** nul-terminated. If pMem is not a string object, then this routine is
** a no-op.
**
................................................................................
** between formats.
*/
int SetEncoding(Mem *pMem, int flags){
  u8 enc1;    /* Current string encoding (TEXT_Utf* value) */
  u8 enc2;    /* Required string encoding (TEXT_Utf* value) */

  /* If this is not a string, do nothing. */
  if( !(pMem->flags&MEM_Str) ){
    return SQLITE_OK;
  }

  enc1 = flagsToEnc(pMem->flags);
  enc2 = flagsToEnc(flags);

  if( enc1!=enc2 ){
    /* If the current encoding does not match the desired encoding, then
    ** we will need to do some translation between encodings.
    */
    char *z;
    int n;
    int rc = sqlite3utfTranslate(pMem->z,pMem->n,enc1,(void **)&z,&n,enc2);
    if( rc!=SQLITE_OK ){
      return rc;
    }

    /* Result of sqlite3utfTranslate is currently always dynamically
    ** allocated and nul terminated. This might be altered as a performance
    ** enhancement later.
................................................................................
    */
    memcpy(&pMem->z[pMem->n], "\0\0", nulTermLen);
    pMem->n += nulTermLen;
    pMem->flags |= MEM_Term;
  }
  return SQLITE_OK;
}

/*
** Convert the given stack entity into a integer if it isn't one
** already.
**
** Any prior string or real representation is invalidated.  
** NULLs are converted into 0.
*/
#define Integerify(P, enc) \
if(((P)->flags&MEM_Int)==0){ hardIntegerify(P, enc); }
static void hardIntegerify(Mem *pStack, u8 enc){
  pStack->i = 0;
  if( pStack->flags & MEM_Real ){
    pStack->i = (int)pStack->r;
    Release(pStack);
  }else if( pStack->flags & MEM_Str ){
    if( pStack->z ){
      sqlite3atoi64(pStack->z, &pStack->i, enc);
    }
  }
  pStack->flags = MEM_Int;
}

/*
** Get a valid Real representation for the given stack element.
**
** Any prior string or integer representation is retained.
** NULLs are converted into 0.0.
*/
#define Realify(P,enc) if(((P)->flags&MEM_Real)==0){ hardRealify(P,enc); }
static void hardRealify(Mem *pStack, u8 enc){
  if( pStack->flags & MEM_Str ){
    SetEncodingFlags(pStack, enc);
    SetEncoding(pStack, MEM_Utf8|MEM_Term);
    pStack->r = sqlite3AtoF(pStack->z, 0);
  }else if( pStack->flags & MEM_Int ){
    pStack->r = pStack->i;
  }else{
    pStack->r = 0.0;
  }
/*  pStack->flags |= MEM_Real; */
  pStack->flags = MEM_Real;
}


/*
** Convert the given stack entity into a string if it isn't one
** already. Return non-zero if a malloc() fails.
*/
#define Stringify(P, enc) \
(!((P)->flags&(MEM_Str|MEM_Blob)) && hardStringify(P, enc))
static int hardStringify(Mem *pStack, u8 enc){
  int rc = SQLITE_OK;
  int fg = pStack->flags;

  assert( !(fg&(MEM_Str|MEM_Blob)) );
  assert( fg&(MEM_Int|MEM_Real|MEM_Null) );

  if( fg & MEM_Null ){      
    /* A NULL value is converted to a zero length string */
    pStack->zShort[0] = 0;
    pStack->zShort[1] = 0;
    pStack->flags = MEM_Str | MEM_Short | MEM_Term;
    pStack->z = pStack->zShort;
    pStack->n = (enc==TEXT_Utf8?1:2);
  }else{
    /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
    ** string representation of the value. Then, if the required encoding
    ** is UTF-16le or UTF-16be do a translation.
    ** 
    ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
    */
    if( fg & MEM_Real ){
      sqlite3_snprintf(NBFS, pStack->zShort, "%.15g", pStack->r);
    }else if( fg & MEM_Int ){
      sqlite3_snprintf(NBFS, pStack->zShort, "%lld", pStack->i);
    }
    pStack->n = strlen(pStack->zShort) + 1;
    pStack->z = pStack->zShort;
    pStack->flags = MEM_Str | MEM_Short | MEM_Term;

    /* Flip the string to UTF-16 if required */
    SetEncodingFlags(pStack, TEXT_Utf8);
    rc = SetEncoding(pStack, encToFlags(enc)|MEM_Term);
  }

  return rc;
}


/*
** Convert the given stack entity into a string that has been obtained
** from sqliteMalloc().  This is different from Stringify() above in that
** Stringify() will use the NBFS bytes of static string space if the string
** will fit but this routine always mallocs for space.
** Return non-zero if we run out of memory.
*/
#define Dynamicify(P, enc) \
(((P)->flags & MEM_Dyn)==0 ? hardDynamicify(P, enc):0)
static int hardDynamicify(Mem *pStack, u8 enc){
  int fg = pStack->flags;
  char *z;
  if( (fg & MEM_Str)==0 ){
    hardStringify(pStack, enc);
  }
  assert( (fg & MEM_Dyn)==0 );
  z = sqliteMallocRaw( pStack->n );
  if( z==0 ) return 1;
  memcpy(z, pStack->z, pStack->n);
  pStack->z = z;
  pStack->flags |= MEM_Dyn;
  return 0;
}

/*
** An ephemeral string value (signified by the MEM_Ephem flag) contains
** a pointer to a dynamically allocated string where some other entity
** is responsible for deallocating that string.  Because the stack entry
** does not control the string, it might be deleted without the stack
** entry knowing it.
**
** This routine converts an ephemeral string into a dynamically allocated
** string that the stack entry itself controls.  In other words, it
** converts an MEM_Ephem string into an MEM_Dyn string.
*/
#define Deephemeralize(P) \
   if( ((P)->flags&MEM_Ephem)!=0 && hardDeephem(P) ){ goto no_mem;}
static int hardDeephem(Mem *pStack){
  char *z;
  assert( (pStack->flags & MEM_Ephem)!=0 );
  z = sqliteMallocRaw( pStack->n );
  if( z==0 ) return 1;
  memcpy(z, pStack->z, pStack->n);
  pStack->z = z;
  pStack->flags &= ~MEM_Ephem;
  pStack->flags |= MEM_Dyn;
  return 0;
}

/*
** Advance the virtual machine to the next output row.
**
** The return vale will be either SQLITE_BUSY, SQLITE_DONE, 
** SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
**
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];

  return sqlite3_value_data((sqlite3_value *)pVal);
}

/*
** pVal is a Mem* cast to an sqlite_value* value. Return a pointer to
** the nul terminated UTF-8 string representation if the value is 
** not a blob or NULL. If the value is a blob, then just return a pointer
** to the blob of data. If it is a NULL, return a NULL pointer.
**
** This function may translate the encoding of the string stored by
** pVal. The MEM_Utf8, MEM_Utf16le and MEM_Utf16be flags must be set
** correctly when this function is called. If a translation occurs,
** the flags are set to reflect the new encoding of the string.
**
** If a translation fails because of a malloc() failure, a NULL pointer
** is returned.
*/
const unsigned char *sqlite3_value_data(sqlite3_value* pVal){
  if( pVal->flags&MEM_Null ){
    /* For a NULL return a NULL Pointer */
    return 0;
  }













  if( pVal->flags&MEM_Str ){
    /* If there is already a string representation, make sure it is in
    ** encoded in UTF-8.
    */
    SetEncoding(pVal, MEM_Utf8|MEM_Term);
  }else if( !(pVal->flags&MEM_Blob) ){
    /* Otherwise, unless this is a blob, convert it to a UTF-8 string */
    Stringify(pVal, TEXT_Utf8);
  }

  return pVal->z;
}

/*
** Return the value of the 'i'th column of the current row of the currently
** executing statement pStmt.
*/
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];
  return sqlite3_value_data16((sqlite3_value *)pVal);
}

/*
** pVal is a Mem* cast to an sqlite_value* value. Return a pointer to
** the nul terminated UTF-16 string representation if the value is 
** not a blob or NULL. If the value is a blob, then just return a pointer
** to the blob of data. If it is a NULL, return a NULL pointer.
**
** The byte-order of the returned string data is the machines native byte
** order.
**
** This function may translate the encoding of the string stored by
** pVal. The MEM_Utf8, MEM_Utf16le and MEM_Utf16be flags must be set
** correctly when this function is called. If a translation occurs,
** the flags are set to reflect the new encoding of the string.
**
** If a translation fails because of a malloc() failure, a NULL pointer
** is returned.
*/
const void *sqlite3_value_data16(sqlite3_value* pVal){
  if( pVal->flags&MEM_Null ){
    /* For a NULL return a NULL Pointer */
    return 0;
  }

  if( pVal->flags&MEM_Str ){
    /* If there is already a string representation, make sure it is in
    ** encoded in UTF-16 machine byte order.
    */
    SetEncoding(pVal, encToFlags(TEXT_Utf16)|MEM_Term);
  }else if( !(pVal->flags&MEM_Blob) ){
    /* Otherwise, unless this is a blob, convert it to a UTF-16 string */
    Stringify(pVal, TEXT_Utf16);




  }



  return (const void *)(pVal->z);
}

/*
** Return the number of bytes of data that will be returned by the
** equivalent sqlite3_column_data() call.
*/
int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];
  Integerify(pVal, pVm->db->enc);
  return pVal->i;
}

/*
** Return the value of the 'i'th column of the current row of the currently
** executing statement pStmt.
*/
................................................................................
  vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return 0;
  }

  pVal = &pVm->pTos[(1-vals)+i];
  Realify(pVal, pVm->db->enc);
  return pVal->r;
}

/*
** Return the name of the Nth column of the result set returned by SQL
** statement pStmt.
*/
................................................................................
/*
** Return the column declaration type (if applicable) of the 'i'th column
** of the result set of SQL statement pStmt, encoded as UTF-16.
*/
const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int i){
  return columnName16(pStmt, i, 1);
}

/*
** Unbind the value bound to variable $i in virtual machine p. This is the 
** the same as binding a NULL value to the column. If the "i" parameter is
** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
**
** The error code stored in database p->db is overwritten with the return
** value in any case.
*/
static int vdbeUnbind(Vdbe *p, int i){
  Mem *pVar;
  if( p->magic!=VDBE_MAGIC_RUN || p->pc!=0 ){
    sqlite3Error(p->db, SQLITE_MISUSE, 0);
    return SQLITE_MISUSE;
  }
  if( i<1 || i>p->nVar ){
    sqlite3Error(p->db, SQLITE_RANGE, 0);
    return SQLITE_RANGE;
  }
  i--;
  pVar = &p->apVar[i];
  if( pVar->flags&MEM_Dyn ){
    sqliteFree(pVar->z);
  }
  pVar->flags = MEM_Null;
  sqlite3Error(p->db, SQLITE_OK, 0);
  return SQLITE_OK;
}

/*
** This routine is used to bind text or blob data to an SQL variable (a ?).
** It may also be used to bind a NULL value, by setting zVal to 0. Any
** existing value is unbound.
**
** The error code stored in p->db is overwritten with the return value in
** all cases.
*/
static int vdbeBindBlob(
  Vdbe *p,           /* Virtual machine */
  int i,             /* Var number to bind (numbered from 1 upward) */
  const char *zVal,  /* Pointer to blob of data */
  int bytes,         /* Number of bytes to copy */
  int copy,          /* True to copy the memory, false to copy a pointer */
  int flags          /* Valid combination of MEM_Blob, MEM_Str, MEM_Term */
){
  Mem *pVar;
  int rc;

  rc = vdbeUnbind(p, i);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pVar = &p->apVar[i-1];

  if( zVal ){
    pVar->n = bytes;
    pVar->flags = flags;
    if( !copy ){
      pVar->z = (char *)zVal;
      pVar->flags |= MEM_Static;
    }else{
      if( bytes>NBFS ){
        pVar->z = (char *)sqliteMalloc(bytes);
        if( !pVar->z ){
          sqlite3Error(p->db, SQLITE_NOMEM, 0);
          return SQLITE_NOMEM;
        }
        pVar->flags |= MEM_Dyn;
      }else{
        pVar->z = pVar->zShort;
        pVar->flags |= MEM_Short;
      }
      memcpy(pVar->z, zVal, bytes);
    }
  }

  return SQLITE_OK;
}

/*
** Bind a 64 bit integer to an SQL statement variable.
*/
int sqlite3_bind_int64(sqlite3_stmt *p, int i, long long int iValue){
  int rc;
  Vdbe *v = (Vdbe *)p;
  rc = vdbeUnbind(v, i);
  if( rc==SQLITE_OK ){
    Mem *pVar = &v->apVar[i-1];
    pVar->flags = MEM_Int;
    pVar->i = iValue;
  }
  return rc;
}

/*
** Bind a 32 bit integer to an SQL statement variable.
*/
int sqlite3_bind_int32(sqlite3_stmt *p, int i, int iValue){
  return sqlite3_bind_int64(p, i, (long long int)iValue);
}

/*
** Bind a double (real) to an SQL statement variable.
*/
int sqlite3_bind_double(sqlite3_stmt *p, int i, double iValue){
  int rc;
  Vdbe *v = (Vdbe *)p;
  rc = vdbeUnbind(v, i);
  if( rc==SQLITE_OK ){
    Mem *pVar = &v->apVar[i-1];
    pVar->flags = MEM_Real;
    pVar->r = iValue;
  }
  return SQLITE_OK;
}

/*
** Bind a NULL value to an SQL statement variable.
*/
int sqlite3_bind_null(sqlite3_stmt* p, int i){
  return vdbeUnbind((Vdbe *)p, i);
}

/*
** Bind a UTF-8 text value to an SQL statement variable.
*/
int sqlite3_bind_text( 
  sqlite3_stmt *pStmt, 
  int i, 
  const char *zData, 
  int nData, 
  int eCopy
){
  Mem *pVar;
  Vdbe *p = (Vdbe *)pStmt;
  int rc = SQLITE_OK;
  u8 db_enc = p->db->enc;            /* Text encoding of the database */

  /* Unbind any previous variable value */
  rc = vdbeUnbind(p, i);
  if( rc==SQLITE_OK ){
    pVar = &p->apVar[i-1];

    if( !zData ){
      /* If zData is NULL, then bind an SQL NULL value */
      pVar->flags = MEM_Null;
    }else{
      if( zData && nData<0 ){
        nData = strlen(zData) + 1;
      }
      pVar->z = (char *)zData;
      pVar->n = nData;
      pVar->flags = MEM_Utf8|MEM_Str|(zData[nData-1]?0:MEM_Term);
      if( !eCopy || db_enc!=TEXT_Utf8 ){
        pVar->flags |= MEM_Static;
        rc = SetEncoding(pVar, encToFlags(db_enc)|MEM_Term);
      }else{
        pVar->flags |= MEM_Ephem;
        Deephemeralize(pVar);
      }
    }
  }

  sqlite3Error(p->db, rc, 0);
  return rc;

no_mem:
  sqlite3Error(p->db, SQLITE_NOMEM, 0);
  return SQLITE_NOMEM;
}

/*
** Bind a UTF-16 text value to an SQL statement variable.
*/
int sqlite3_bind_text16(
  sqlite3_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  int eCopy
){
  Vdbe *p = (Vdbe *)pStmt;
  Mem *pVar;
  u8 db_enc = p->db->enc;            /* Text encoding of the database */
  u8 txt_enc;
  int null_term = 0;
  int rc;

  rc = vdbeUnbind(p, i);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pVar = &p->apVar[i-1];

  /* If zData is NULL, then bind an SQL NULL value */
  if( !zData ){
    pVar->flags = MEM_Null;
    return SQLITE_OK;
  }

  if( db_enc==TEXT_Utf8 ){
    /* If the database encoding is UTF-8, then do a translation. */
    pVar->z = sqlite3utf16to8(zData, nData, SQLITE3_BIGENDIAN);
    if( !pVar->z ) return SQLITE_NOMEM;
    pVar->n = strlen(pVar->z)+1;
    pVar->flags = MEM_Str|MEM_Term|MEM_Dyn;
    return SQLITE_OK;
  }
 
  /* There may or may not be a byte order mark at the start of the UTF-16.
  ** Either way set 'txt_enc' to the TEXT_Utf16* value indicating the 
  ** actual byte order used by this string. If the string does happen
  ** to contain a BOM, then move zData so that it points to the first
  ** byte after the BOM.
  */
  txt_enc = sqlite3UtfReadBom(zData, nData);
  if( txt_enc ){
    zData = (void *)(((u8 *)zData) + 2);
  }else{
    txt_enc = SQLITE3_BIGENDIAN?TEXT_Utf16be:TEXT_Utf16le;
  }

  if( nData<0 ){
    nData = sqlite3utf16ByteLen(zData, -1) + 2;
    null_term = 1;
  }else if( nData>1 && !((u8*)zData)[nData-1] && !((u8*)zData)[nData-2] ){
    null_term = 1;
  }

  if( db_enc==txt_enc && !eCopy ){
    /* If the byte order of the string matches the byte order of the
    ** database and the eCopy parameter is not set, then the string can
    ** be used without making a copy.
    */
    pVar->z = (char *)zData;
    pVar->n = nData;
    pVar->flags = MEM_Str|MEM_Static|(null_term?MEM_Term:0);
  }else{
    /* Make a copy. Swap the byte order if required */
    pVar->n = nData + (null_term?0:2);
    pVar->z = sqliteMalloc(pVar->n);
    pVar->flags = MEM_Str|MEM_Dyn|MEM_Term;
    if( db_enc==txt_enc ){
      memcpy(pVar->z, zData, nData);
    }else{
      swab(zData, pVar->z, nData);
    }
    pVar->z[pVar->n-1] = '\0';
    pVar->z[pVar->n-2] = '\0';
  }

  return SQLITE_OK;
}

/*
** Bind a blob value to an SQL statement variable.
*/
int sqlite3_bind_blob(
  sqlite3_stmt *p, 
  int i, 
  const void *zData, 
  int nData, 
  int eCopy
){
  return vdbeBindBlob((Vdbe *)p, i, zData, nData, eCopy, MEM_Blob);
}


/*
** Insert a new aggregate element and make it the element that
** has focus.
**
** Return 0 on success and 1 if memory is exhausted.
*/
................................................................................
  if( pElem==0 ){
    AggInsert(p,"",1);
    pElem = sqliteHashFirst(&p->hash);
  }
  return pElem ? sqliteHashData(pElem) : 0;
}


























/*
** Pop the stack N times.
*/
static void popStack(Mem **ppTos, int N){
  Mem *pTos = *ppTos;
  while( N>0 ){
    N--;
................................................................................
**
** SQLITE_AFF_NUMERIC
** SQLITE_AFF_TEXT
** SQLITE_AFF_NONE
** SQLITE_AFF_INTEGER
**
*/
static void applyAffinity(Mem *pRec, char affinity, u8 enc){
  switch( affinity ){
    case SQLITE_AFF_INTEGER:
    case SQLITE_AFF_NUMERIC:
      if( 0==(pRec->flags&(MEM_Real|MEM_Int)) ){
        /* pRec does not have a valid integer or real representation. 
        ** Attempt a conversion if pRec has a string representation and
        ** it looks like a number.
        */
        int realnum;
        if( pRec->flags&MEM_Str && sqlite3IsNumber(pRec->z, &realnum, enc) ){
          if( realnum ){
            Realify(pRec, enc);
          }else{
            Integerify(pRec, enc);
          }
        }
      }

      if( affinity==SQLITE_AFF_INTEGER ){
        /* For INTEGER affinity, try to convert a real value to an int */
        if( pRec->flags&MEM_Real ){
................................................................................

    case SQLITE_AFF_TEXT:
      /* Only attempt the conversion if there is an integer or real
      ** representation (blob and NULL do not get converted) but no string
      ** representation.
      */
      if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
        Stringify(pRec, enc);
      }
      pRec->flags &= ~(MEM_Real|MEM_Int);

      break;

    case SQLITE_AFF_NONE:
      /* Affinity NONE. Do nothing. */
................................................................................
      zBuf[1] = 's';
    }
    k = 2;
    k += sprintf(&zBuf[k], "%d", pMem->n);
    zBuf[k++] = '[';
    for(j=0; j<15 && j<pMem->n; j++){
      u8 c = pMem->z[j];

/*
      if( c==0 && j==pMem->n-1 ) break;
            zBuf[k++] = "0123456789ABCDEF"[c>>4];
            zBuf[k++] = "0123456789ABCDEF"[c&0xf];
*/
      if( c>=0x20 && c<0x7f ){
        zBuf[k++] = c;
      }else{
        zBuf[k++] = '.';
................................................................................
  pTos->flags = 0;
 
  /* If this is an OP_Real or OP_Integer opcode, set the pTos->r or pTos->i
  ** values respectively.
  */
  if( op==OP_Real ){
    assert( z );
    assert( sqlite3IsNumber(z, 0, TEXT_Utf8) );
    pTos->r = sqlite3AtoF(z, 0);
    pTos->flags = MEM_Real;
  }else if( op==OP_Integer ){
    pTos->flags = MEM_Int;
    pTos->i = pOp->p1;
    if( pTos->i==0 && pOp->p3 ){
      sqlite3GetInt64(pOp->p3, &pTos->i);
................................................................................
/* Opcode: Callback P1 * *
**
** Pop P1 values off the stack and form them into an array.  Then
** invoke the callback function using the newly formed array as the
** 3rd parameter.
*/
case OP_Callback: {
#if 0
  int i;
  char **azArgv = p->zArgv;
  Mem *pCol;

  pCol = &pTos[1-pOp->p1];
  assert( pCol>=p->aStack );
  for(i=0; i<pOp->p1; i++, pCol++){
    if( pCol->flags & MEM_Null ){
      azArgv[i] = 0;
    }else{
      Stringify(pCol, db->enc);
      azArgv[i] = pCol->z;
    }
  }


  azArgv[i] = 0;
  p->azResColumn = azArgv;
#endif

  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;
  return SQLITE_ROW;
}

/* Opcode: Concat P1 P2 P3
................................................................................
** from sqliteMalloc().
*/
case OP_Concat: {
  char *zNew;
  int nByte;
  int nField;
  int i, j;


  Mem *pTerm;
  Mem zSep; /* Memory cell containing the seperator string, if any */
  int termLen;  /* Bytes in the terminator character for this encoding */

  termLen = (db->enc==TEXT_Utf8?1:2);

  /* FIX ME: Eventually, P3 will be in database native encoding. But for
  ** now it is always UTF-8. So set up zSep to hold the native encoding of
  ** P3.
  */
  if( pOp->p3 ){
    zSep.z = pOp->p3;

    zSep.n = strlen(zSep.z)+1;


    zSep.flags = MEM_Str|MEM_Static|MEM_Utf8|MEM_Term;
    SetEncoding(&zSep, encToFlags(db->enc)|MEM_Term);
  }else{
    zSep.flags = MEM_Null;
    zSep.n = 0;
  }

  /* Loop through the stack elements to see how long the result will be. */
  nField = pOp->p1;
  pTerm = &pTos[1-nField];
  nByte = termLen + (nField-1)*(zSep.n - ((zSep.flags&MEM_Term)?termLen:0));
  for(i=0; i<nField; i++, pTerm++){
    assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
    if( pTerm->flags&MEM_Null ){
      nByte = -1;
      break;

    }
    Stringify(pTerm, db->enc);

    nByte += (pTerm->n - ((pTerm->flags&MEM_Term)?termLen:0));
  }

  if( nByte<0 ){
    /* If nByte is less than zero, then there is a NULL value on the stack.
    ** In this case just pop the values off the stack (if required) and
    ** push on a NULL.
    */
    if( pOp->p2==0 ){
      popStack(&pTos, nField);
    }
    pTos++;
    pTos->flags = MEM_Null;


  }else{
    /* Otherwise malloc() space for the result and concatenate all the
    ** stack values.
    */
    zNew = sqliteMallocRaw( nByte );
    if( zNew==0 ) goto no_mem;
    j = 0;
    pTerm = &pTos[1-nField];
    for(i=j=0; i<nField; i++, pTerm++){
      int n = pTerm->n-((pTerm->flags&MEM_Term)?termLen:0);
      assert( pTerm->flags & MEM_Str );
      memcpy(&zNew[j], pTerm->z, n);
      j += n;

      if( i<nField-1 && !(zSep.flags|MEM_Null) ){
        n = zSep.n-((zSep.flags&MEM_Term)?termLen:0);
        memcpy(&zNew[j], zSep.z, n);
        j += n;
      }
    }
    zNew[j++] = 0;
    if( termLen==2 ){
      zNew[j++] = 0;
    }
    assert( j==nByte );

    if( pOp->p2==0 ){
      popStack(&pTos, nField);
    }
    pTos++;
    pTos->n = nByte;
    pTos->flags = MEM_Str|MEM_Dyn|MEM_Term|encToFlags(db->enc);
    pTos->z = zNew;
  }
  break;
}

/* Opcode: Add * * *
**
** Pop the top two elements from the stack, add them together,
** and push the result back onto the stack.  If either element
................................................................................
    Release(pTos);
    pTos--;
    Release(pTos);
    pTos->i = b;
    pTos->flags = MEM_Int;
  }else{
    double a, b;
    Realify(pTos, db->enc);
    Realify(pNos, db->enc);
    a = pTos->r;
    b = pNos->r;
    switch( pOp->opcode ){
      case OP_Add:         b += a;       break;
      case OP_Subtract:    b -= a;       break;
      case OP_Multiply:    b *= a;       break;
      case OP_Divide: {
................................................................................

  n = pOp->p1;
  pArg = &pTos[1-n];
  azArgv = p->zArgv;
  for(i=0; i<n; i++, pArg++){
    if( pArg->flags & MEM_Null ){
      azArgv[i] = 0;
    }else if( !(pArg->flags&MEM_Str) ){
      Stringify(pArg, TEXT_Utf8);
      azArgv[i] = pArg->z;
    }else{

      SetEncodingFlags(pArg, db->enc);
      SetEncoding(pArg, MEM_Utf8|MEM_Term);
      azArgv[i] = pArg->z;
    }
  }
  ctx.pFunc = (FuncDef*)pOp->p3;
  ctx.s.flags = MEM_Null;
  ctx.s.z = 0;
  ctx.isError = 0;
................................................................................
    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 * * *
**
** Pop the top two elements from the stack.  Convert both elements
** to integers.  Push back onto the stack the bit-wise AND of the
................................................................................
  assert( pNos>=p->aStack );
  if( (pTos->flags | pNos->flags) & MEM_Null ){
    popStack(&pTos, 2);
    pTos++;
    pTos->flags = MEM_Null;
    break;
  }
  Integerify(pTos, db->enc);
  Integerify(pNos, db->enc);
  a = pTos->i;
  b = pNos->i;
  switch( pOp->opcode ){
    case OP_BitAnd:      a &= b;     break;
    case OP_BitOr:       a |= b;     break;
    case OP_ShiftLeft:   a <<= b;    break;
    case OP_ShiftRight:  a >>= b;    break;
    default:   /* CANT HAPPEN */     break;
  }
  /* FIX ME: Because constant P3 values sometimes need to be translated,
  ** the following assert() can fail. When P3 is always in the native text
  ** encoding, this assert() will be valid again. Until then, the Release()
  ** is neeed instead.
  assert( (pTos->flags & MEM_Dyn)==0 );
  assert( (pNos->flags & MEM_Dyn)==0 );
  */
  Release(pTos);
  pTos--;
  Release(pTos);
  pTos->i = a;
  pTos->flags = MEM_Int;
  break;
}

................................................................................
** Add the value P1 to whatever is on top of the stack.  The result
** is always an integer.
**
** To force the top of the stack to be an integer, just add 0.
*/
case OP_AddImm: {
  assert( pTos>=p->aStack );
  Integerify(pTos, db->enc);
  pTos->i += pOp->p1;
  break;
}

/* Opcode: ForceInt P1 P2 *
**
** Convert the top of the stack into an integer.  If the current top of
................................................................................
** convert it into the least integer that is greater than or equal to its
** current value if P1==0, or to the least integer that is strictly
** greater than its current value if P1==1.
*/
case OP_ForceInt: {
  int v;
  assert( pTos>=p->aStack );
  if( (pTos->flags & (MEM_Int|MEM_Real))==0 && ((pTos->flags & MEM_Str)==0 
      || sqlite3IsNumber(pTos->z, 0, db->enc)==0) ){
    Release(pTos);
    pTos--;
    pc = pOp->p2 - 1;
    break;
  }
  if( pTos->flags & MEM_Int ){
    v = pTos->i + (pOp->p1!=0);
  }else{
    Realify(pTos, db->enc);
    v = (int)pTos->r;
    if( pTos->r>(double)v ) v++;
    if( pOp->p1 && pTos->r==(double)v ) v++;
  }
  Release(pTos);
  pTos->i = v;
  pTos->flags = MEM_Int;
................................................................................
    double r = (double)i;
    if( r!=pTos->r ){
      goto mismatch;
    }
    pTos->i = i;
  }else if( pTos->flags & MEM_Str ){
    i64 v;
    if( !sqlite3atoi64(pTos->z, &v, db->enc) ){
      double r;
      if( !sqlite3IsNumber(pTos->z, 0, db->enc) ){
        goto mismatch;
      }
      Realify(pTos, db->enc);
      v = (int)pTos->r;
      r = (double)v;
      if( r!=pTos->r ){
        goto mismatch;
      }
    }
    pTos->i = v;
................................................................................
      pTos->flags = MEM_Null;
    }
    break;
  }

  affinity = (pOp->p1>>8)&0xFF;
  if( affinity=='\0' ) affinity = 'n';
  applyAffinity(pNos, affinity, db->enc);
  applyAffinity(pTos, affinity, db->enc);

  assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
  res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
  switch( pOp->opcode ){
    case OP_Eq:    res = res==0;     break;
    case OP_Ne:    res = res!=0;     break;
    case OP_Lt:    res = res<0;      break;
................................................................................
  Mem *pNos = &pTos[-1];
  int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */

  assert( pNos>=p->aStack );
  if( pTos->flags & MEM_Null ){
    v1 = 2;
  }else{
    Integerify(pTos, db->enc);
    v1 = pTos->i==0;
  }
  if( pNos->flags & MEM_Null ){
    v2 = 2;
  }else{
    Integerify(pNos, db->enc);
    v2 = pNos->i==0;
  }
  if( pOp->opcode==OP_And ){
    static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
    v1 = and_logic[v1*3+v2];
  }else{
    static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
................................................................................
    if( pOp->opcode==OP_Negative || pTos->i<0 ){
      pTos->i = -pTos->i;
    }
    pTos->flags = MEM_Int;
  }else if( pTos->flags & MEM_Null ){
    /* Do nothing */
  }else{
    Realify(pTos, db->enc);
    Release(pTos);
    if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
      pTos->r = -pTos->r;
    }
    pTos->flags = MEM_Real;
  }
  break;
................................................................................
** Interpret the top of the stack as a boolean value.  Replace it
** with its complement.  If the top of the stack is NULL its value
** is unchanged.
*/
case OP_Not: {
  assert( pTos>=p->aStack );
  if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
  Integerify(pTos, db->enc);
  Release(pTos);
  pTos->i = !pTos->i;
  pTos->flags = MEM_Int;
  break;
}

/* Opcode: BitNot * * *
................................................................................
** Interpret the top of the stack as an value.  Replace it
** with its ones-complement.  If the top of the stack is NULL its
** value is unchanged.
*/
case OP_BitNot: {
  assert( pTos>=p->aStack );
  if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
  Integerify(pTos, db->enc);
  Release(pTos);
  pTos->i = ~pTos->i;
  pTos->flags = MEM_Int;
  break;
}

/* Opcode: Noop * * *
................................................................................
case OP_If:
case OP_IfNot: {
  int c;
  assert( pTos>=p->aStack );
  if( pTos->flags & MEM_Null ){
    c = pOp->p1;
  }else{
    Integerify(pTos, db->enc);
    c = pTos->i;
    if( pOp->opcode==OP_IfNot ) c = !c;
  }
  /* FIX ME: Because constant P3 values sometimes need to be translated,
  ** the following assert() can fail. When P3 is always in the native text
  ** encoding, this assert() will be valid again. Until then, the Release()
  ** is neeed instead.
  assert( (pTos->flags & MEM_Dyn)==0 ); 
  */
  Release(pTos);
  pTos--;
  if( c ) pc = pOp->p2-1;
  break;
}

/* Opcode: IsNull P1 P2 *
**
................................................................................
case OP_Class: {
  int flags = pTos->flags;
  int i;

  struct {
    int mask;
    char * zClass;
    char * zClass16;
  } classes[] = {
    {MEM_Null, "NULL", "\0N\0U\0L\0L\0\0\0"},
    {MEM_Int, "INTEGER", "\0I\0N\0T\0E\0G\0E\0R\0\0\0"},
    {MEM_Real, "REAL", "\0R\0E\0A\0L\0\0\0"},
    {MEM_Str, "TEXT", "\0T\0E\0X\0T\0\0\0"},
    {MEM_Blob, "BLOB", "\0B\0L\0O\0B\0\0\0"}
  };

  Release(pTos);
  pTos->flags = MEM_Str|MEM_Static|MEM_Term;

  for(i=0; i<5; i++){
    if( classes[i].mask&flags ){
      switch( db->enc ){
        case TEXT_Utf8: 
          pTos->z = classes[i].zClass;
          break;
        case TEXT_Utf16be: 
          pTos->z = classes[i].zClass16;
          break;
        case TEXT_Utf16le: 
          pTos->z = &(classes[i].zClass16[1]);
          break;
        default:
          assert(0);
      }
      break;
    }
  }
  assert( i<5 );

  if( db->enc==TEXT_Utf8 ){
    pTos->n = strlen(pTos->z) + 1;
  }else{
    pTos->n = sqlite3utf16ByteLen(pTos->z, -1) + 2;
  }

  break;
}

/* Opcode: SetNumColumns P1 P2 *
**
** Before the OP_Column opcode can be executed on a cursor, this
** opcode must be called to set the number of fields in the table.
................................................................................

  /* Loop through the elements that will make up the record to figure
  ** out how much space is required for the new record.
  */
  for(pRec=pData0; pRec<=pTos; pRec++){
    u64 serial_type;
    if( zAffinity ){
      applyAffinity(pRec, zAffinity[pRec-pData0], db->enc);
    }
    serial_type = sqlite3VdbeSerialType(pRec);
    nBytes += sqlite3VdbeSerialTypeLen(serial_type);
    nBytes += sqlite3VarintLen(serial_type);
  }

  if( nBytes>MAX_BYTES_PER_ROW ){
................................................................................
  **
  ** TODO: Figure out if the in-place coercion causes a problem for
  ** OP_MakeKey when P2 is 0 (used by DISTINCT).
  */
  for(pRec=pData0; pRec<=pTos; pRec++){
    u64 serial_type;
    if( zAffinity ){
      applyAffinity(pRec, zAffinity[pRec-pData0], db->enc);
    }
    if( pRec->flags&MEM_Null ){
      containsNull = 1;
    }
    serial_type = sqlite3VdbeSerialType(pRec);
    nByte += sqlite3VarintLen(serial_type);
    nByte += sqlite3VdbeSerialTypeLen(serial_type);
................................................................................
  /* If we have to append a varint rowid to this record, set 'rowid'
  ** to the value of the rowid and increase nByte by the amount of space
  ** required to store it and the 0x00 seperator byte.
  */
  if( addRowid ){
    pRec = &pTos[0-nField];
    assert( pRec>=p->aStack );
    Integerify(pRec, db->enc);
    rowid = pRec->i;
    nByte += sqlite3VarintLen(rowid);
    nByte++;
  }
  
  if( nByte>MAX_BYTES_PER_ROW ){
    rc = SQLITE_TOOBIG;
................................................................................
** A transaction must be started before executing this opcode.
*/
case OP_SetCookie: {
  assert( pOp->p2<SQLITE_N_BTREE_META );
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( db->aDb[pOp->p1].pBt!=0 );
  assert( pTos>=p->aStack );
  Integerify(pTos, db->enc);
  /* See note about index shifting on OP_ReadCookie */
  rc = sqlite3BtreeUpdateMeta(db->aDb[pOp->p1].pBt, 1+pOp->p2, (int)pTos->i);
  Release(pTos);
  pTos--;
  break;
}

................................................................................
  int p2 = pOp->p2;
  int wrFlag;
  Btree *pX;
  int iDb;
  Cursor *pCur;
  
  assert( pTos>=p->aStack );
  Integerify(pTos, db->enc);
  iDb = pTos->i;
  pTos--;
  assert( iDb>=0 && iDb<db->nDb );
  pX = db->aDb[iDb].pBt;
  assert( pX!=0 );
  wrFlag = pOp->opcode==OP_OpenWrite;
  if( p2<=0 ){
    assert( pTos>=p->aStack );
    Integerify(pTos, db->enc);
    p2 = pTos->i;
    pTos--;
    if( p2<2 ){
      sqlite3SetString(&p->zErrMsg, "root page number less than 2", (char*)0);
      rc = SQLITE_INTERNAL;
      break;
    }
................................................................................
    int res, oc;
    oc = pOp->opcode;
    pC->nullRow = 0;
    *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
    if( pC->intKey ){
      i64 iKey;
      assert( !pOp->p3 );
      Integerify(pTos, db->enc);
      iKey = intToKey(pTos->i);
      if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
        pC->movetoTarget = iKey;
        pC->deferredMoveto = 1;
        Release(pTos);
        pTos--;
        break;
      }
      sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, &res);
      pC->lastRecno = pTos->i;
      pC->recnoIsValid = res==0;
    }else{
      Stringify(pTos, db->enc);
      sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
      pC->recnoIsValid = 0;
    }
    pC->deferredMoveto = 0;
    pC->cacheValid = 0;
    *pC->pIncrKey = 0;
    sqlite3_search_count++;
................................................................................
  int alreadyExists = 0;
  Cursor *pC;
  assert( pTos>=p->aStack );
  assert( i>=0 && i<p->nCursor );
  if( (pC = p->apCsr[i])->pCursor!=0 ){
    int res, rx;
    assert( pC->intKey==0 );
    Stringify(pTos, db->enc);
    rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
    alreadyExists = rx==SQLITE_OK && res==0;
    pC->deferredMoveto = 0;
    pC->cacheValid = 0;
  }
  if( pOp->opcode==OP_Found ){
    if( alreadyExists ) pc = pOp->p2 - 1;
................................................................................
  Cursor *pCx;
  BtCursor *pCrsr;
  i64 R;

  /* Pop the value R off the top of the stack
  */
  assert( pNos>=p->aStack );
  Integerify(pTos, db->enc);
  R = pTos->i;
  pTos--;
  assert( i>=0 && i<=p->nCursor );
  pCx = p->apCsr[i];
  pCrsr = pCx->pCursor;
  if( pCrsr!=0 ){
    int res, rc;
................................................................................
    i64 v;         /* The record number on the P1 entry that matches K */
    char *zKey;    /* The value of K */
    int nKey;      /* Number of bytes in K */
    int len;       /* Number of bytes in K without the rowid at the end */

    /* Make sure K is a string and make zKey point to K
    */
    Stringify(pNos, db->enc);
    zKey = pNos->z;
    nKey = pNos->n;

    assert( nKey >= 2 );
    len = nKey-2;
    while( zKey[len] && --len );

................................................................................
  assert( pNos>=p->aStack );
  assert( i>=0 && i<p->nCursor );
  if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
    char *zKey;
    i64 nKey; 
    i64 iKey;
    if( pOp->opcode==OP_PutStrKey ){
      Stringify(pNos, db->enc);
      nKey = pNos->n;
      zKey = pNos->z;
    }else{
      assert( pNos->flags & MEM_Int );

      /* If the table is an INTKEY table, set nKey to the value of
      ** the integer key, and zKey to NULL. Otherwise, set nKey to
................................................................................
  Cursor *pC;

  assert( i>=0 && i<p->nCursor );
  assert( pTos>=p->aStack );
  if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
    int res, rc;
 
    Stringify(pTos, db->enc);
    assert( pC->deferredMoveto==0 );
    *pC->pIncrKey = pOp->p3!=0;
    assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
    rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, pTos->z, &res);
    *pC->pIncrKey = 0;
    if( rc!=SQLITE_OK ){
      break;
................................................................................
  popStack(&pTos, nRoot);
  pTos++;
  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
  if( z==0 || z[0]==0 ){
    if( z ) sqliteFree(z);
    pTos->z = "ok";
    pTos->n = 3;
    pTos->flags = MEM_Str | MEM_Static;
  }else{
    pTos->z = z;
    pTos->n = strlen(z) + 1;
    pTos->flags = MEM_Str | MEM_Dyn;
  }
  if( db->enc!=TEXT_Utf8 ){
    SetEncodingFlags(pTos, TEXT_Utf8);
    SetEncoding(pTos, encToFlags(db->enc)|MEM_Term);
  }
  sqliteFree(aRoot);
  break;
}

/* Opcode: ListWrite * * *
**
................................................................................
    if( pKeylist==0 ) goto no_mem;
    pKeylist->nKey = 1000;
    pKeylist->nRead = 0;
    pKeylist->nUsed = 0;
    pKeylist->pNext = p->pList;
    p->pList = pKeylist;
  }
  Integerify(pTos, db->enc);
  pKeylist->aKey[pKeylist->nUsed++] = pTos->i;
  Release(pTos);
  pTos--;
  break;
}

/* Opcode: ListRewind * * *
................................................................................
** and put them on the sorter.  The key and data should have been
** made using SortMakeKey and SortMakeRec, respectively.
*/
case OP_SortPut: {
  Mem *pNos = &pTos[-1];
  Sorter *pSorter;
  assert( pNos>=p->aStack );
  if( Dynamicify(pTos, db->enc) || Dynamicify(pNos, db->enc) ) goto no_mem;
  pSorter = sqliteMallocRaw( sizeof(Sorter) );
  if( pSorter==0 ) goto no_mem;
  pSorter->pNext = p->pSort;
  p->pSort = pSorter;
  assert( pTos->flags & MEM_Dyn );
  pSorter->nKey = pTos->n;
  pSorter->zKey = pTos->z;
................................................................................
    z = 0;
  }
  pTos++;
  if( z ){
    pTos->n = strlen(z) + 1;
    pTos->z = z;
    pTos->flags = MEM_Utf8 | MEM_Str | MEM_Ephem | MEM_Term;
    SetEncoding(pTos, encToFlags(db->enc)|MEM_Term);
  }else{
    pTos->flags = MEM_Null;
  }
  break;
}

/* Opcode: MemStore P1 P2 *
................................................................................
  assert( pTos->flags==MEM_Int );
  pRec = &pTos[-n];
  assert( pRec>=p->aStack );
  for(i=0; i<n; i++, pRec++){
    if( pRec->flags & MEM_Null ){
      azArgv[i] = 0;
    }else{
      Stringify(pRec, db->enc);
      SetEncodingFlags(pRec, db->enc);
      SetEncoding(pRec, MEM_Utf8|MEM_Term);
      azArgv[i] = pRec->z;
    }
  }
  i = pTos->i;
  assert( i>=0 && i<p->agg.nMem );
  ctx.pFunc = (FuncDef*)pOp->p3;
  pMem = &p->agg.pCurrent->aMem[i];
................................................................................
*/
case OP_AggFocus: {
  AggElem *pElem;
  char *zKey;
  int nKey;

  assert( pTos>=p->aStack );
  Stringify(pTos, db->enc);
  zKey = pTos->z;
  nKey = pTos->n;
  pElem = sqlite3HashFind(&p->agg.hash, zKey, nKey);
  if( pElem ){
    p->agg.pCurrent = pElem;
    pc = pOp->p2 - 1;
  }else{
................................................................................
  Release(pMem);
  *pMem = *pTos;
  if( pMem->flags & MEM_Dyn ){
    pTos->flags = MEM_Null;
  }else if( pMem->flags & MEM_Short ){
    pMem->z = pMem->zShort;
  }
  SetEncodingFlags(pMem, db->enc);
  SetEncoding(pMem, MEM_Utf8|MEM_Term);
  Release(pTos);
  pTos--;
  break;
}

/* Opcode: AggGet * P2 *
**
................................................................................
  pTos++;
  pMem = &pFocus->aMem[i];
  *pTos = *pMem;
  if( pTos->flags & (MEM_Str|MEM_Blob) ){
    pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
    pTos->flags |= MEM_Ephem;
  }
  if( pTos->flags&MEM_Str ){
    SetEncodingFlags(pTos, TEXT_Utf8);
    SetEncoding(pTos, encToFlags(db->enc)|MEM_Term);
  }
  break;
}

/* Opcode: AggNext * P2 *
**
** Make the next aggregate value the current aggregate.  The prior
** aggregate is deleted.  If all aggregate values have been consumed,

Changes to src/vdbeaux.c.

1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
  }
  if( rc==SQLITE_SCHEMA ){
    sqlite3ResetInternalSchema(db, 0);
  }
  return rc;
}

/*
** Unbind the value bound to variable $i in virtual machine p. This is the 
** the same as binding a NULL value to the column. If the "i" parameter is
** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
**
** The error code stored in database p->db is overwritten with the return
** value in any case.
*/
static int vdbeUnbind(Vdbe *p, int i){
  Mem *pVar;
  if( p->magic!=VDBE_MAGIC_RUN || p->pc!=0 ){
    sqlite3Error(p->db, SQLITE_MISUSE, 0);
    return SQLITE_MISUSE;
  }
  if( i<1 || i>p->nVar ){
    sqlite3Error(p->db, SQLITE_RANGE, 0);
    return SQLITE_RANGE;
  }
  i--;
  pVar = &p->apVar[i];
  if( pVar->flags&MEM_Dyn ){
    sqliteFree(pVar->z);
  }
  pVar->flags = MEM_Null;
  sqlite3Error(p->db, SQLITE_OK, 0);
  return SQLITE_OK;
}

/*
** This routine is used to bind text or blob data to an SQL variable (a ?).
** It may also be used to bind a NULL value, by setting zVal to 0. Any
** existing value is unbound.
**
** The error code stored in p->db is overwritten with the return value in
** all cases.
*/
static int vdbeBindBlob(
  Vdbe *p,           /* Virtual machine */
  int i,             /* Var number to bind (numbered from 1 upward) */
  const char *zVal,  /* Pointer to blob of data */
  int bytes,         /* Number of bytes to copy */
  int copy,          /* True to copy the memory, false to copy a pointer */
  int flags          /* Valid combination of MEM_Blob, MEM_Str, MEM_Term */
){
  Mem *pVar;
  int rc;

  rc = vdbeUnbind(p, i);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pVar = &p->apVar[i-1];

  if( zVal ){
    pVar->n = bytes;
    pVar->flags = flags;
    if( !copy ){
      pVar->z = (char *)zVal;
      pVar->flags |= MEM_Static;
    }else{
      if( bytes>NBFS ){
        pVar->z = (char *)sqliteMalloc(bytes);
        if( !pVar->z ){
          sqlite3Error(p->db, SQLITE_NOMEM, 0);
          return SQLITE_NOMEM;
        }
        pVar->flags |= MEM_Dyn;
      }else{
        pVar->z = pVar->zShort;
        pVar->flags |= MEM_Short;
      }
      memcpy(pVar->z, zVal, bytes);
    }
  }

  return SQLITE_OK;
}

/*
** Bind a 64 bit integer to an SQL statement variable.
*/
int sqlite3_bind_int64(sqlite3_stmt *p, int i, long long int iValue){
  int rc;
  Vdbe *v = (Vdbe *)p;
  rc = vdbeUnbind(v, i);
  if( rc==SQLITE_OK ){
    Mem *pVar = &v->apVar[i-1];
    pVar->flags = MEM_Int;
    pVar->i = iValue;
  }
  return rc;
}

/*
** Bind a 32 bit integer to an SQL statement variable.
*/
int sqlite3_bind_int32(sqlite3_stmt *p, int i, int iValue){
  return sqlite3_bind_int64(p, i, (long long int)iValue);
}

/*
** Bind a double (real) to an SQL statement variable.
*/
int sqlite3_bind_double(sqlite3_stmt *p, int i, double iValue){
  int rc;
  Vdbe *v = (Vdbe *)p;
  rc = vdbeUnbind(v, i);
  if( rc==SQLITE_OK ){
    Mem *pVar = &v->apVar[i-1];
    pVar->flags = MEM_Real;
    pVar->r = iValue;
  }
  return SQLITE_OK;
}

/*
** Bind a NULL value to an SQL statement variable.
*/
int sqlite3_bind_null(sqlite3_stmt* p, int i){
  return vdbeUnbind((Vdbe *)p, i);
}

/*
** Bind a UTF-8 text value to an SQL statement variable.
*/
int sqlite3_bind_text( 
  sqlite3_stmt *p, 
  int i, 
  const char *zData, 
  int nData, 
  int eCopy
){
  int flags = MEM_Str|MEM_Utf8;
  if( zData ){
    if( nData<0 ){
      nData = strlen(zData)+1;
      flags |= MEM_Term;
    }else if( !zData[nData-1] ){
      flags |= MEM_Term;
    }
  }
  return vdbeBindBlob((Vdbe *)p, i, zData, nData, eCopy, flags);
}

/*
** Bind a UTF-16 text value to an SQL statement variable.
*/
int sqlite3_bind_text16(
  sqlite3_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  int eCopy
){
  Vdbe *p = (Vdbe *)pStmt;
  Mem *pVar;
  u8 db_enc = p->db->enc;            /* Text encoding of the database */
  u8 txt_enc;
  int null_term = 0;

  int flags;
  int rc;

  rc = vdbeUnbind(p, i);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pVar = &p->apVar[i-1];

  if( db_enc==TEXT_Utf8 ){
    /* If the database encoding is UTF-8, then do a translation. */
    pVar->z = sqlite3utf16to8(zData, nData, SQLITE3_BIGENDIAN);
    if( !pVar->z ) return SQLITE_NOMEM;
    pVar->n = strlen(pVar->z)+1;
    pVar->flags = MEM_Str|MEM_Term|MEM_Dyn;
    return SQLITE_OK;
  }
 
  /* There may or may not be a byte order mark at the start of the UTF-16.
  ** Either way set 'txt_enc' to the TEXT_Utf16* value indicating the 
  ** actual byte order used by this string. If the string does happen
  ** to contain a BOM, then move zData so that it points to the first
  ** byte after the BOM.
  */
  txt_enc = sqlite3UtfReadBom(zData, nData);
  if( txt_enc ){
    zData = (void *)(((u8 *)zData) + 2);
  }else{
    txt_enc = SQLITE3_BIGENDIAN?TEXT_Utf16be:TEXT_Utf16le;
  }

  if( nData<0 ){
    nData = sqlite3utf16ByteLen(zData, -1) + 2;
    null_term = 1;
  }else if( nData>1 && !((u8*)zData)[nData-1] && !((u8*)zData)[nData-2] ){
    null_term = 1;
  }

  if( db_enc==txt_enc && !eCopy ){
    /* If the byte order of the string matches the byte order of the
    ** database and the eCopy parameter is not set, then the string can
    ** be used without making a copy.
    */
    pVar->z = (char *)zData;
    pVar->n = nData;
    pVar->flags = MEM_Str|MEM_Static|(null_term?MEM_Term:0);
  }else{
    /* Make a copy. Swap the byte order if required */
    pVar->n = nData + (null_term?0:2);
    pVar->z = sqliteMalloc(pVar->n);
    pVar->flags = MEM_Str|MEM_Dyn|MEM_Term;
    if( db_enc==txt_enc ){
      memcpy(pVar->z, zData, nData);
    }else{
      swab(zData, pVar->z, nData);
    }
    pVar->z[pVar->n-1] = '\0';
    pVar->z[pVar->n-2] = '\0';
  }

  return SQLITE_OK;
}

/*
** Bind a blob value to an SQL statement variable.
*/
int sqlite3_bind_blob(
  sqlite3_stmt *p, 
  int i, 
  const void *zData, 
  int nData, 
  int eCopy
){
  return vdbeBindBlob((Vdbe *)p, i, zData, nData, eCopy, MEM_Blob);
}

/*
** Set the values of all variables.  Variable $1 in the original SQL will
** be the string azValue[0].  $2 will have the value azValue[1].  And
** so forth.  If a value is out of range (for example $3 when nValue==2)
** then its value will be NULL.
**
** This routine overrides any prior call.







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







1055
1056
1057
1058
1059
1060
1061












































































































































































































































1062
1063
1064
1065
1066
1067
1068
  }
  if( rc==SQLITE_SCHEMA ){
    sqlite3ResetInternalSchema(db, 0);
  }
  return rc;
}













































































































































































































































/*
** Set the values of all variables.  Variable $1 in the original SQL will
** be the string azValue[0].  $2 will have the value azValue[1].  And
** so forth.  If a value is out of range (for example $3 when nValue==2)
** then its value will be NULL.
**
** This routine overrides any prior call.