extensions/sqlite/sqlite-source/vdbeaux.c
author Scott Ehlert <ds@alliedmods.net>
Sun Mar 30 07:00:22 2008 +0000 (2008-03-30)
changeset 1952 b7aa2b626807
permissions -rw-r--r--
Spring Cleaning, Part Ichi (1)
Various minor things done to project files
Updated sample extension project file and updated makefile to the new unified version (more changes likely on the way)
Updated regex project file and makefile
ds@1952
     1
/*
ds@1952
     2
** 2003 September 6
ds@1952
     3
**
ds@1952
     4
** The author disclaims copyright to this source code.  In place of
ds@1952
     5
** a legal notice, here is a blessing:
ds@1952
     6
**
ds@1952
     7
**    May you do good and not evil.
ds@1952
     8
**    May you find forgiveness for yourself and forgive others.
ds@1952
     9
**    May you share freely, never taking more than you give.
ds@1952
    10
**
ds@1952
    11
*************************************************************************
ds@1952
    12
** This file contains code used for creating, destroying, and populating
ds@1952
    13
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
ds@1952
    14
** to version 2.8.7, all this code was combined into the vdbe.c source file.
ds@1952
    15
** But that file was getting too big so this subroutines were split out.
ds@1952
    16
*/
ds@1952
    17
#include "sqliteInt.h"
ds@1952
    18
#include <ctype.h>
ds@1952
    19
#include "vdbeInt.h"
ds@1952
    20
ds@1952
    21
ds@1952
    22
ds@1952
    23
/*
ds@1952
    24
** When debugging the code generator in a symbolic debugger, one can
ds@1952
    25
** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
ds@1952
    26
** as they are added to the instruction stream.
ds@1952
    27
*/
ds@1952
    28
#ifdef SQLITE_DEBUG
ds@1952
    29
int sqlite3_vdbe_addop_trace = 0;
ds@1952
    30
#endif
ds@1952
    31
ds@1952
    32
ds@1952
    33
/*
ds@1952
    34
** Create a new virtual database engine.
ds@1952
    35
*/
ds@1952
    36
Vdbe *sqlite3VdbeCreate(sqlite3 *db){
ds@1952
    37
  Vdbe *p;
ds@1952
    38
  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
ds@1952
    39
  if( p==0 ) return 0;
ds@1952
    40
  p->db = db;
ds@1952
    41
  if( db->pVdbe ){
ds@1952
    42
    db->pVdbe->pPrev = p;
ds@1952
    43
  }
ds@1952
    44
  p->pNext = db->pVdbe;
ds@1952
    45
  p->pPrev = 0;
ds@1952
    46
  db->pVdbe = p;
ds@1952
    47
  p->magic = VDBE_MAGIC_INIT;
ds@1952
    48
  return p;
ds@1952
    49
}
ds@1952
    50
ds@1952
    51
/*
ds@1952
    52
** Remember the SQL string for a prepared statement.
ds@1952
    53
*/
ds@1952
    54
void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
ds@1952
    55
  if( p==0 ) return;
ds@1952
    56
  assert( p->zSql==0 );
ds@1952
    57
  p->zSql = sqlite3DbStrNDup(p->db, z, n);
ds@1952
    58
}
ds@1952
    59
ds@1952
    60
/*
ds@1952
    61
** Return the SQL associated with a prepared statement
ds@1952
    62
*/
ds@1952
    63
const char *sqlite3VdbeGetSql(Vdbe *p){
ds@1952
    64
  return p->zSql;
ds@1952
    65
}
ds@1952
    66
ds@1952
    67
/*
ds@1952
    68
** Swap all content between two VDBE structures.
ds@1952
    69
*/
ds@1952
    70
void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
ds@1952
    71
  Vdbe tmp, *pTmp;
ds@1952
    72
  char *zTmp;
ds@1952
    73
  int nTmp;
ds@1952
    74
  tmp = *pA;
ds@1952
    75
  *pA = *pB;
ds@1952
    76
  *pB = tmp;
ds@1952
    77
  pTmp = pA->pNext;
ds@1952
    78
  pA->pNext = pB->pNext;
ds@1952
    79
  pB->pNext = pTmp;
ds@1952
    80
  pTmp = pA->pPrev;
ds@1952
    81
  pA->pPrev = pB->pPrev;
ds@1952
    82
  pB->pPrev = pTmp;
ds@1952
    83
  zTmp = pA->zSql;
ds@1952
    84
  pA->zSql = pB->zSql;
ds@1952
    85
  pB->zSql = zTmp;
ds@1952
    86
  nTmp = pA->nSql;
ds@1952
    87
  pA->nSql = pB->nSql;
ds@1952
    88
  pB->nSql = nTmp;
ds@1952
    89
}
ds@1952
    90
ds@1952
    91
#ifdef SQLITE_DEBUG
ds@1952
    92
/*
ds@1952
    93
** Turn tracing on or off
ds@1952
    94
*/
ds@1952
    95
void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
ds@1952
    96
  p->trace = trace;
ds@1952
    97
}
ds@1952
    98
#endif
ds@1952
    99
ds@1952
   100
/*
ds@1952
   101
** Resize the Vdbe.aOp array so that it contains at least N
ds@1952
   102
** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
ds@1952
   103
** the Vdbe.aOp array will be sized to contain exactly N
ds@1952
   104
** elements. Vdbe.nOpAlloc is set to reflect the new size of
ds@1952
   105
** the array.
ds@1952
   106
**
ds@1952
   107
** If an out-of-memory error occurs while resizing the array,
ds@1952
   108
** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
ds@1952
   109
** any opcodes already allocated can be correctly deallocated
ds@1952
   110
** along with the rest of the Vdbe).
ds@1952
   111
*/
ds@1952
   112
static void resizeOpArray(Vdbe *p, int N){
ds@1952
   113
  int runMode = p->magic==VDBE_MAGIC_RUN;
ds@1952
   114
  if( runMode || p->nOpAlloc<N ){
ds@1952
   115
    VdbeOp *pNew;
ds@1952
   116
    int nNew = N + 100*(!runMode);
ds@1952
   117
    int oldSize = p->nOpAlloc;
ds@1952
   118
    pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
ds@1952
   119
    if( pNew ){
ds@1952
   120
      p->nOpAlloc = nNew;
ds@1952
   121
      p->aOp = pNew;
ds@1952
   122
      if( nNew>oldSize ){
ds@1952
   123
        memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
ds@1952
   124
      }
ds@1952
   125
    }
ds@1952
   126
  }
ds@1952
   127
}
ds@1952
   128
ds@1952
   129
/*
ds@1952
   130
** Add a new instruction to the list of instructions current in the
ds@1952
   131
** VDBE.  Return the address of the new instruction.
ds@1952
   132
**
ds@1952
   133
** Parameters:
ds@1952
   134
**
ds@1952
   135
**    p               Pointer to the VDBE
ds@1952
   136
**
ds@1952
   137
**    op              The opcode for this instruction
ds@1952
   138
**
ds@1952
   139
**    p1, p2          First two of the three possible operands.
ds@1952
   140
**
ds@1952
   141
** Use the sqlite3VdbeResolveLabel() function to fix an address and
ds@1952
   142
** the sqlite3VdbeChangeP3() function to change the value of the P3
ds@1952
   143
** operand.
ds@1952
   144
*/
ds@1952
   145
int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
ds@1952
   146
  int i;
ds@1952
   147
  VdbeOp *pOp;
ds@1952
   148
ds@1952
   149
  i = p->nOp;
ds@1952
   150
  assert( p->magic==VDBE_MAGIC_INIT );
ds@1952
   151
  if( p->nOpAlloc<=i ){
ds@1952
   152
    resizeOpArray(p, i+1);
ds@1952
   153
    if( p->db->mallocFailed ){
ds@1952
   154
      return 0;
ds@1952
   155
    }
ds@1952
   156
  }
ds@1952
   157
  p->nOp++;
ds@1952
   158
  pOp = &p->aOp[i];
ds@1952
   159
  pOp->opcode = op;
ds@1952
   160
  pOp->p1 = p1;
ds@1952
   161
  pOp->p2 = p2;
ds@1952
   162
  pOp->p3 = 0;
ds@1952
   163
  pOp->p3type = P3_NOTUSED;
ds@1952
   164
  p->expired = 0;
ds@1952
   165
#ifdef SQLITE_DEBUG
ds@1952
   166
  if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
ds@1952
   167
#endif
ds@1952
   168
  return i;
ds@1952
   169
}
ds@1952
   170
ds@1952
   171
/*
ds@1952
   172
** Add an opcode that includes the p3 value.
ds@1952
   173
*/
ds@1952
   174
int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
ds@1952
   175
  int addr = sqlite3VdbeAddOp(p, op, p1, p2);
ds@1952
   176
  sqlite3VdbeChangeP3(p, addr, zP3, p3type);
ds@1952
   177
  return addr;
ds@1952
   178
}
ds@1952
   179
ds@1952
   180
/*
ds@1952
   181
** Create a new symbolic label for an instruction that has yet to be
ds@1952
   182
** coded.  The symbolic label is really just a negative number.  The
ds@1952
   183
** label can be used as the P2 value of an operation.  Later, when
ds@1952
   184
** the label is resolved to a specific address, the VDBE will scan
ds@1952
   185
** through its operation list and change all values of P2 which match
ds@1952
   186
** the label into the resolved address.
ds@1952
   187
**
ds@1952
   188
** The VDBE knows that a P2 value is a label because labels are
ds@1952
   189
** always negative and P2 values are suppose to be non-negative.
ds@1952
   190
** Hence, a negative P2 value is a label that has yet to be resolved.
ds@1952
   191
**
ds@1952
   192
** Zero is returned if a malloc() fails.
ds@1952
   193
*/
ds@1952
   194
int sqlite3VdbeMakeLabel(Vdbe *p){
ds@1952
   195
  int i;
ds@1952
   196
  i = p->nLabel++;
ds@1952
   197
  assert( p->magic==VDBE_MAGIC_INIT );
ds@1952
   198
  if( i>=p->nLabelAlloc ){
ds@1952
   199
    p->nLabelAlloc = p->nLabelAlloc*2 + 10;
ds@1952
   200
    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
ds@1952
   201
                                    p->nLabelAlloc*sizeof(p->aLabel[0]));
ds@1952
   202
  }
ds@1952
   203
  if( p->aLabel ){
ds@1952
   204
    p->aLabel[i] = -1;
ds@1952
   205
  }
ds@1952
   206
  return -1-i;
ds@1952
   207
}
ds@1952
   208
ds@1952
   209
/*
ds@1952
   210
** Resolve label "x" to be the address of the next instruction to
ds@1952
   211
** be inserted.  The parameter "x" must have been obtained from
ds@1952
   212
** a prior call to sqlite3VdbeMakeLabel().
ds@1952
   213
*/
ds@1952
   214
void sqlite3VdbeResolveLabel(Vdbe *p, int x){
ds@1952
   215
  int j = -1-x;
ds@1952
   216
  assert( p->magic==VDBE_MAGIC_INIT );
ds@1952
   217
  assert( j>=0 && j<p->nLabel );
ds@1952
   218
  if( p->aLabel ){
ds@1952
   219
    p->aLabel[j] = p->nOp;
ds@1952
   220
  }
ds@1952
   221
}
ds@1952
   222
ds@1952
   223
/*
ds@1952
   224
** Return non-zero if opcode 'op' is guarenteed not to push more values
ds@1952
   225
** onto the VDBE stack than it pops off.
ds@1952
   226
*/
ds@1952
   227
static int opcodeNoPush(u8 op){
ds@1952
   228
  /* The 10 NOPUSH_MASK_n constants are defined in the automatically
ds@1952
   229
  ** generated header file opcodes.h. Each is a 16-bit bitmask, one
ds@1952
   230
  ** bit corresponding to each opcode implemented by the virtual
ds@1952
   231
  ** machine in vdbe.c. The bit is true if the word "no-push" appears
ds@1952
   232
  ** in a comment on the same line as the "case OP_XXX:" in 
ds@1952
   233
  ** sqlite3VdbeExec() in vdbe.c.
ds@1952
   234
  **
ds@1952
   235
  ** If the bit is true, then the corresponding opcode is guarenteed not
ds@1952
   236
  ** to grow the stack when it is executed. Otherwise, it may grow the
ds@1952
   237
  ** stack by at most one entry.
ds@1952
   238
  **
ds@1952
   239
  ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
ds@1952
   240
  ** one bit for opcodes 16 to 31, and so on.
ds@1952
   241
  **
ds@1952
   242
  ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h 
ds@1952
   243
  ** because the file is generated by an awk program. Awk manipulates
ds@1952
   244
  ** all numbers as floating-point and we don't want to risk a rounding
ds@1952
   245
  ** error if someone builds with an awk that uses (for example) 32-bit 
ds@1952
   246
  ** IEEE floats.
ds@1952
   247
  */ 
ds@1952
   248
  static const u32 masks[5] = {
ds@1952
   249
    NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
ds@1952
   250
    NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
ds@1952
   251
    NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
ds@1952
   252
    NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
ds@1952
   253
    NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
ds@1952
   254
  };
ds@1952
   255
  assert( op<32*5 );
ds@1952
   256
  return (masks[op>>5] & (1<<(op&0x1F)));
ds@1952
   257
}
ds@1952
   258
ds@1952
   259
#ifndef NDEBUG
ds@1952
   260
int sqlite3VdbeOpcodeNoPush(u8 op){
ds@1952
   261
  return opcodeNoPush(op);
ds@1952
   262
}
ds@1952
   263
#endif
ds@1952
   264
ds@1952
   265
/*
ds@1952
   266
** Loop through the program looking for P2 values that are negative.
ds@1952
   267
** Each such value is a label.  Resolve the label by setting the P2
ds@1952
   268
** value to its correct non-zero value.
ds@1952
   269
**
ds@1952
   270
** This routine is called once after all opcodes have been inserted.
ds@1952
   271
**
ds@1952
   272
** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
ds@1952
   273
** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
ds@1952
   274
** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
ds@1952
   275
**
ds@1952
   276
** The integer *pMaxStack is set to the maximum number of vdbe stack
ds@1952
   277
** entries that static analysis reveals this program might need.
ds@1952
   278
**
ds@1952
   279
** This routine also does the following optimization:  It scans for
ds@1952
   280
** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
ds@1952
   281
** IdxInsert instructions where P2!=0.  If no such instruction is
ds@1952
   282
** found, then every Statement instruction is changed to a Noop.  In
ds@1952
   283
** this way, we avoid creating the statement journal file unnecessarily.
ds@1952
   284
*/
ds@1952
   285
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
ds@1952
   286
  int i;
ds@1952
   287
  int nMaxArgs = 0;
ds@1952
   288
  int nMaxStack = p->nOp;
ds@1952
   289
  Op *pOp;
ds@1952
   290
  int *aLabel = p->aLabel;
ds@1952
   291
  int doesStatementRollback = 0;
ds@1952
   292
  int hasStatementBegin = 0;
ds@1952
   293
  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
ds@1952
   294
    u8 opcode = pOp->opcode;
ds@1952
   295
ds@1952
   296
    if( opcode==OP_Function || opcode==OP_AggStep 
ds@1952
   297
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
   298
        || opcode==OP_VUpdate
ds@1952
   299
#endif
ds@1952
   300
    ){
ds@1952
   301
      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
ds@1952
   302
    }
ds@1952
   303
    if( opcode==OP_Halt ){
ds@1952
   304
      if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
ds@1952
   305
        doesStatementRollback = 1;
ds@1952
   306
      }
ds@1952
   307
    }else if( opcode==OP_Statement ){
ds@1952
   308
      hasStatementBegin = 1;
ds@1952
   309
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
   310
    }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
ds@1952
   311
      doesStatementRollback = 1;
ds@1952
   312
    }else if( opcode==OP_VFilter ){
ds@1952
   313
      int n;
ds@1952
   314
      assert( p->nOp - i >= 3 );
ds@1952
   315
      assert( pOp[-2].opcode==OP_Integer );
ds@1952
   316
      n = pOp[-2].p1;
ds@1952
   317
      if( n>nMaxArgs ) nMaxArgs = n;
ds@1952
   318
#endif
ds@1952
   319
    }
ds@1952
   320
    if( opcodeNoPush(opcode) ){
ds@1952
   321
      nMaxStack--;
ds@1952
   322
    }
ds@1952
   323
ds@1952
   324
    if( pOp->p2>=0 ) continue;
ds@1952
   325
    assert( -1-pOp->p2<p->nLabel );
ds@1952
   326
    pOp->p2 = aLabel[-1-pOp->p2];
ds@1952
   327
  }
ds@1952
   328
  sqlite3_free(p->aLabel);
ds@1952
   329
  p->aLabel = 0;
ds@1952
   330
ds@1952
   331
  *pMaxFuncArgs = nMaxArgs;
ds@1952
   332
  *pMaxStack = nMaxStack;
ds@1952
   333
ds@1952
   334
  /* If we never rollback a statement transaction, then statement
ds@1952
   335
  ** transactions are not needed.  So change every OP_Statement
ds@1952
   336
  ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
ds@1952
   337
  ** which can be expensive on some platforms.
ds@1952
   338
  */
ds@1952
   339
  if( hasStatementBegin && !doesStatementRollback ){
ds@1952
   340
    for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
ds@1952
   341
      if( pOp->opcode==OP_Statement ){
ds@1952
   342
        pOp->opcode = OP_Noop;
ds@1952
   343
      }
ds@1952
   344
    }
ds@1952
   345
  }
ds@1952
   346
}
ds@1952
   347
ds@1952
   348
/*
ds@1952
   349
** Return the address of the next instruction to be inserted.
ds@1952
   350
*/
ds@1952
   351
int sqlite3VdbeCurrentAddr(Vdbe *p){
ds@1952
   352
  assert( p->magic==VDBE_MAGIC_INIT );
ds@1952
   353
  return p->nOp;
ds@1952
   354
}
ds@1952
   355
ds@1952
   356
/*
ds@1952
   357
** Add a whole list of operations to the operation stack.  Return the
ds@1952
   358
** address of the first operation added.
ds@1952
   359
*/
ds@1952
   360
int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
ds@1952
   361
  int addr;
ds@1952
   362
  assert( p->magic==VDBE_MAGIC_INIT );
ds@1952
   363
  resizeOpArray(p, p->nOp + nOp);
ds@1952
   364
  if( p->db->mallocFailed ){
ds@1952
   365
    return 0;
ds@1952
   366
  }
ds@1952
   367
  addr = p->nOp;
ds@1952
   368
  if( nOp>0 ){
ds@1952
   369
    int i;
ds@1952
   370
    VdbeOpList const *pIn = aOp;
ds@1952
   371
    for(i=0; i<nOp; i++, pIn++){
ds@1952
   372
      int p2 = pIn->p2;
ds@1952
   373
      VdbeOp *pOut = &p->aOp[i+addr];
ds@1952
   374
      pOut->opcode = pIn->opcode;
ds@1952
   375
      pOut->p1 = pIn->p1;
ds@1952
   376
      pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
ds@1952
   377
      pOut->p3 = pIn->p3;
ds@1952
   378
      pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
ds@1952
   379
#ifdef SQLITE_DEBUG
ds@1952
   380
      if( sqlite3_vdbe_addop_trace ){
ds@1952
   381
        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
ds@1952
   382
      }
ds@1952
   383
#endif
ds@1952
   384
    }
ds@1952
   385
    p->nOp += nOp;
ds@1952
   386
  }
ds@1952
   387
  return addr;
ds@1952
   388
}
ds@1952
   389
ds@1952
   390
/*
ds@1952
   391
** Change the value of the P1 operand for a specific instruction.
ds@1952
   392
** This routine is useful when a large program is loaded from a
ds@1952
   393
** static array using sqlite3VdbeAddOpList but we want to make a
ds@1952
   394
** few minor changes to the program.
ds@1952
   395
*/
ds@1952
   396
void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
ds@1952
   397
  assert( p==0 || p->magic==VDBE_MAGIC_INIT );
ds@1952
   398
  if( p && addr>=0 && p->nOp>addr && p->aOp ){
ds@1952
   399
    p->aOp[addr].p1 = val;
ds@1952
   400
  }
ds@1952
   401
}
ds@1952
   402
ds@1952
   403
/*
ds@1952
   404
** Change the value of the P2 operand for a specific instruction.
ds@1952
   405
** This routine is useful for setting a jump destination.
ds@1952
   406
*/
ds@1952
   407
void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
ds@1952
   408
  assert( val>=0 );
ds@1952
   409
  assert( p==0 || p->magic==VDBE_MAGIC_INIT );
ds@1952
   410
  if( p && addr>=0 && p->nOp>addr && p->aOp ){
ds@1952
   411
    p->aOp[addr].p2 = val;
ds@1952
   412
  }
ds@1952
   413
}
ds@1952
   414
ds@1952
   415
/*
ds@1952
   416
** Change the P2 operand of instruction addr so that it points to
ds@1952
   417
** the address of the next instruction to be coded.
ds@1952
   418
*/
ds@1952
   419
void sqlite3VdbeJumpHere(Vdbe *p, int addr){
ds@1952
   420
  sqlite3VdbeChangeP2(p, addr, p->nOp);
ds@1952
   421
}
ds@1952
   422
ds@1952
   423
ds@1952
   424
/*
ds@1952
   425
** If the input FuncDef structure is ephemeral, then free it.  If
ds@1952
   426
** the FuncDef is not ephermal, then do nothing.
ds@1952
   427
*/
ds@1952
   428
static void freeEphemeralFunction(FuncDef *pDef){
ds@1952
   429
  if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
ds@1952
   430
    sqlite3_free(pDef);
ds@1952
   431
  }
ds@1952
   432
}
ds@1952
   433
ds@1952
   434
/*
ds@1952
   435
** Delete a P3 value if necessary.
ds@1952
   436
*/
ds@1952
   437
static void freeP3(int p3type, void *p3){
ds@1952
   438
  if( p3 ){
ds@1952
   439
    switch( p3type ){
ds@1952
   440
      case P3_DYNAMIC:
ds@1952
   441
      case P3_KEYINFO:
ds@1952
   442
      case P3_KEYINFO_HANDOFF: {
ds@1952
   443
        sqlite3_free(p3);
ds@1952
   444
        break;
ds@1952
   445
      }
ds@1952
   446
      case P3_MPRINTF: {
ds@1952
   447
        sqlite3_free(p3);
ds@1952
   448
        break;
ds@1952
   449
      }
ds@1952
   450
      case P3_VDBEFUNC: {
ds@1952
   451
        VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
ds@1952
   452
        freeEphemeralFunction(pVdbeFunc->pFunc);
ds@1952
   453
        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
ds@1952
   454
        sqlite3_free(pVdbeFunc);
ds@1952
   455
        break;
ds@1952
   456
      }
ds@1952
   457
      case P3_FUNCDEF: {
ds@1952
   458
        freeEphemeralFunction((FuncDef*)p3);
ds@1952
   459
        break;
ds@1952
   460
      }
ds@1952
   461
      case P3_MEM: {
ds@1952
   462
        sqlite3ValueFree((sqlite3_value*)p3);
ds@1952
   463
        break;
ds@1952
   464
      }
ds@1952
   465
    }
ds@1952
   466
  }
ds@1952
   467
}
ds@1952
   468
ds@1952
   469
ds@1952
   470
/*
ds@1952
   471
** Change N opcodes starting at addr to No-ops.
ds@1952
   472
*/
ds@1952
   473
void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
ds@1952
   474
  if( p && p->aOp ){
ds@1952
   475
    VdbeOp *pOp = &p->aOp[addr];
ds@1952
   476
    while( N-- ){
ds@1952
   477
      freeP3(pOp->p3type, pOp->p3);
ds@1952
   478
      memset(pOp, 0, sizeof(pOp[0]));
ds@1952
   479
      pOp->opcode = OP_Noop;
ds@1952
   480
      pOp++;
ds@1952
   481
    }
ds@1952
   482
  }
ds@1952
   483
}
ds@1952
   484
ds@1952
   485
/*
ds@1952
   486
** Change the value of the P3 operand for a specific instruction.
ds@1952
   487
** This routine is useful when a large program is loaded from a
ds@1952
   488
** static array using sqlite3VdbeAddOpList but we want to make a
ds@1952
   489
** few minor changes to the program.
ds@1952
   490
**
ds@1952
   491
** If n>=0 then the P3 operand is dynamic, meaning that a copy of
ds@1952
   492
** the string is made into memory obtained from sqlite3_malloc().
ds@1952
   493
** A value of n==0 means copy bytes of zP3 up to and including the
ds@1952
   494
** first null byte.  If n>0 then copy n+1 bytes of zP3.
ds@1952
   495
**
ds@1952
   496
** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
ds@1952
   497
** A copy is made of the KeyInfo structure into memory obtained from
ds@1952
   498
** sqlite3_malloc, to be freed when the Vdbe is finalized.
ds@1952
   499
** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
ds@1952
   500
** stored in memory that the caller has obtained from sqlite3_malloc. The 
ds@1952
   501
** caller should not free the allocation, it will be freed when the Vdbe is
ds@1952
   502
** finalized.
ds@1952
   503
** 
ds@1952
   504
** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
ds@1952
   505
** to a string or structure that is guaranteed to exist for the lifetime of
ds@1952
   506
** the Vdbe. In these cases we can just copy the pointer.
ds@1952
   507
**
ds@1952
   508
** If addr<0 then change P3 on the most recently inserted instruction.
ds@1952
   509
*/
ds@1952
   510
void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
ds@1952
   511
  Op *pOp;
ds@1952
   512
  assert( p==0 || p->magic==VDBE_MAGIC_INIT );
ds@1952
   513
  if( p==0 || p->aOp==0 || p->db->mallocFailed ){
ds@1952
   514
    if (n != P3_KEYINFO) {
ds@1952
   515
      freeP3(n, (void*)*(char**)&zP3);
ds@1952
   516
    }
ds@1952
   517
    return;
ds@1952
   518
  }
ds@1952
   519
  if( addr<0 || addr>=p->nOp ){
ds@1952
   520
    addr = p->nOp - 1;
ds@1952
   521
    if( addr<0 ) return;
ds@1952
   522
  }
ds@1952
   523
  pOp = &p->aOp[addr];
ds@1952
   524
  freeP3(pOp->p3type, pOp->p3);
ds@1952
   525
  pOp->p3 = 0;
ds@1952
   526
  if( zP3==0 ){
ds@1952
   527
    pOp->p3 = 0;
ds@1952
   528
    pOp->p3type = P3_NOTUSED;
ds@1952
   529
  }else if( n==P3_KEYINFO ){
ds@1952
   530
    KeyInfo *pKeyInfo;
ds@1952
   531
    int nField, nByte;
ds@1952
   532
ds@1952
   533
    nField = ((KeyInfo*)zP3)->nField;
ds@1952
   534
    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
ds@1952
   535
    pKeyInfo = sqlite3_malloc( nByte );
ds@1952
   536
    pOp->p3 = (char*)pKeyInfo;
ds@1952
   537
    if( pKeyInfo ){
ds@1952
   538
      unsigned char *aSortOrder;
ds@1952
   539
      memcpy(pKeyInfo, zP3, nByte);
ds@1952
   540
      aSortOrder = pKeyInfo->aSortOrder;
ds@1952
   541
      if( aSortOrder ){
ds@1952
   542
        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
ds@1952
   543
        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
ds@1952
   544
      }
ds@1952
   545
      pOp->p3type = P3_KEYINFO;
ds@1952
   546
    }else{
ds@1952
   547
      p->db->mallocFailed = 1;
ds@1952
   548
      pOp->p3type = P3_NOTUSED;
ds@1952
   549
    }
ds@1952
   550
  }else if( n==P3_KEYINFO_HANDOFF ){
ds@1952
   551
    pOp->p3 = (char*)zP3;
ds@1952
   552
    pOp->p3type = P3_KEYINFO;
ds@1952
   553
  }else if( n<0 ){
ds@1952
   554
    pOp->p3 = (char*)zP3;
ds@1952
   555
    pOp->p3type = n;
ds@1952
   556
  }else{
ds@1952
   557
    if( n==0 ) n = strlen(zP3);
ds@1952
   558
    pOp->p3 = sqlite3DbStrNDup(p->db, zP3, n);
ds@1952
   559
    pOp->p3type = P3_DYNAMIC;
ds@1952
   560
  }
ds@1952
   561
}
ds@1952
   562
ds@1952
   563
#ifndef NDEBUG
ds@1952
   564
/*
ds@1952
   565
** Replace the P3 field of the most recently coded instruction with
ds@1952
   566
** comment text.
ds@1952
   567
*/
ds@1952
   568
void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
ds@1952
   569
  va_list ap;
ds@1952
   570
  assert( p->nOp>0 || p->aOp==0 );
ds@1952
   571
  assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || p->db->mallocFailed );
ds@1952
   572
  va_start(ap, zFormat);
ds@1952
   573
  sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(p->db, zFormat, ap), P3_DYNAMIC);
ds@1952
   574
  va_end(ap);
ds@1952
   575
}
ds@1952
   576
#endif
ds@1952
   577
ds@1952
   578
/*
ds@1952
   579
** Return the opcode for a given address.
ds@1952
   580
*/
ds@1952
   581
VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
ds@1952
   582
  assert( p->magic==VDBE_MAGIC_INIT );
ds@1952
   583
  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
ds@1952
   584
  return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
ds@1952
   585
}
ds@1952
   586
ds@1952
   587
#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
ds@1952
   588
     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
ds@1952
   589
/*
ds@1952
   590
** Compute a string that describes the P3 parameter for an opcode.
ds@1952
   591
** Use zTemp for any required temporary buffer space.
ds@1952
   592
*/
ds@1952
   593
static char *displayP3(Op *pOp, char *zTemp, int nTemp){
ds@1952
   594
  char *zP3;
ds@1952
   595
  assert( nTemp>=20 );
ds@1952
   596
  switch( pOp->p3type ){
ds@1952
   597
    case P3_KEYINFO: {
ds@1952
   598
      int i, j;
ds@1952
   599
      KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
ds@1952
   600
      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
ds@1952
   601
      i = strlen(zTemp);
ds@1952
   602
      for(j=0; j<pKeyInfo->nField; j++){
ds@1952
   603
        CollSeq *pColl = pKeyInfo->aColl[j];
ds@1952
   604
        if( pColl ){
ds@1952
   605
          int n = strlen(pColl->zName);
ds@1952
   606
          if( i+n>nTemp-6 ){
ds@1952
   607
            memcpy(&zTemp[i],",...",4);
ds@1952
   608
            break;
ds@1952
   609
          }
ds@1952
   610
          zTemp[i++] = ',';
ds@1952
   611
          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
ds@1952
   612
            zTemp[i++] = '-';
ds@1952
   613
          }
ds@1952
   614
          memcpy(&zTemp[i], pColl->zName,n+1);
ds@1952
   615
          i += n;
ds@1952
   616
        }else if( i+4<nTemp-6 ){
ds@1952
   617
          memcpy(&zTemp[i],",nil",4);
ds@1952
   618
          i += 4;
ds@1952
   619
        }
ds@1952
   620
      }
ds@1952
   621
      zTemp[i++] = ')';
ds@1952
   622
      zTemp[i] = 0;
ds@1952
   623
      assert( i<nTemp );
ds@1952
   624
      zP3 = zTemp;
ds@1952
   625
      break;
ds@1952
   626
    }
ds@1952
   627
    case P3_COLLSEQ: {
ds@1952
   628
      CollSeq *pColl = (CollSeq*)pOp->p3;
ds@1952
   629
      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
ds@1952
   630
      zP3 = zTemp;
ds@1952
   631
      break;
ds@1952
   632
    }
ds@1952
   633
    case P3_FUNCDEF: {
ds@1952
   634
      FuncDef *pDef = (FuncDef*)pOp->p3;
ds@1952
   635
      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
ds@1952
   636
      zP3 = zTemp;
ds@1952
   637
      break;
ds@1952
   638
    }
ds@1952
   639
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
   640
    case P3_VTAB: {
ds@1952
   641
      sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
ds@1952
   642
      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
ds@1952
   643
      zP3 = zTemp;
ds@1952
   644
      break;
ds@1952
   645
    }
ds@1952
   646
#endif
ds@1952
   647
    default: {
ds@1952
   648
      zP3 = pOp->p3;
ds@1952
   649
      if( zP3==0 || pOp->opcode==OP_Noop ){
ds@1952
   650
        zP3 = "";
ds@1952
   651
      }
ds@1952
   652
    }
ds@1952
   653
  }
ds@1952
   654
  assert( zP3!=0 );
ds@1952
   655
  return zP3;
ds@1952
   656
}
ds@1952
   657
#endif
ds@1952
   658
ds@1952
   659
/*
ds@1952
   660
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
ds@1952
   661
**
ds@1952
   662
*/
ds@1952
   663
void sqlite3VdbeUsesBtree(Vdbe *p, int i){
ds@1952
   664
  int mask;
ds@1952
   665
  assert( i>=0 && i<p->db->nDb );
ds@1952
   666
  assert( i<sizeof(p->btreeMask)*8 );
ds@1952
   667
  mask = 1<<i;
ds@1952
   668
  if( (p->btreeMask & mask)==0 ){
ds@1952
   669
    p->btreeMask |= mask;
ds@1952
   670
    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
ds@1952
   671
  }
ds@1952
   672
}
ds@1952
   673
ds@1952
   674
ds@1952
   675
#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
ds@1952
   676
/*
ds@1952
   677
** Print a single opcode.  This routine is used for debugging only.
ds@1952
   678
*/
ds@1952
   679
void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
ds@1952
   680
  char *zP3;
ds@1952
   681
  char zPtr[50];
ds@1952
   682
  static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
ds@1952
   683
  if( pOut==0 ) pOut = stdout;
ds@1952
   684
  zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
ds@1952
   685
  fprintf(pOut, zFormat1,
ds@1952
   686
      pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, zP3);
ds@1952
   687
  fflush(pOut);
ds@1952
   688
}
ds@1952
   689
#endif
ds@1952
   690
ds@1952
   691
/*
ds@1952
   692
** Release an array of N Mem elements
ds@1952
   693
*/
ds@1952
   694
static void releaseMemArray(Mem *p, int N){
ds@1952
   695
  if( p ){
ds@1952
   696
    while( N-->0 ){
ds@1952
   697
      assert( N<2 || p[0].db==p[1].db );
ds@1952
   698
      sqlite3VdbeMemRelease(p++);
ds@1952
   699
    }
ds@1952
   700
  }
ds@1952
   701
}
ds@1952
   702
ds@1952
   703
#ifndef SQLITE_OMIT_EXPLAIN
ds@1952
   704
/*
ds@1952
   705
** Give a listing of the program in the virtual machine.
ds@1952
   706
**
ds@1952
   707
** The interface is the same as sqlite3VdbeExec().  But instead of
ds@1952
   708
** running the code, it invokes the callback once for each instruction.
ds@1952
   709
** This feature is used to implement "EXPLAIN".
ds@1952
   710
*/
ds@1952
   711
int sqlite3VdbeList(
ds@1952
   712
  Vdbe *p                   /* The VDBE */
ds@1952
   713
){
ds@1952
   714
  sqlite3 *db = p->db;
ds@1952
   715
  int i;
ds@1952
   716
  int rc = SQLITE_OK;
ds@1952
   717
ds@1952
   718
  assert( p->explain );
ds@1952
   719
  if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
ds@1952
   720
  assert( db->magic==SQLITE_MAGIC_BUSY );
ds@1952
   721
  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
ds@1952
   722
ds@1952
   723
  /* Even though this opcode does not put dynamic strings onto the
ds@1952
   724
  ** the stack, they may become dynamic if the user calls
ds@1952
   725
  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
ds@1952
   726
  */
ds@1952
   727
  if( p->pTos==&p->aStack[4] ){
ds@1952
   728
    releaseMemArray(p->aStack, 5);
ds@1952
   729
  }
ds@1952
   730
  p->resOnStack = 0;
ds@1952
   731
ds@1952
   732
  do{
ds@1952
   733
    i = p->pc++;
ds@1952
   734
  }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
ds@1952
   735
  if( i>=p->nOp ){
ds@1952
   736
    p->rc = SQLITE_OK;
ds@1952
   737
    rc = SQLITE_DONE;
ds@1952
   738
  }else if( db->u1.isInterrupted ){
ds@1952
   739
    p->rc = SQLITE_INTERRUPT;
ds@1952
   740
    rc = SQLITE_ERROR;
ds@1952
   741
    sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
ds@1952
   742
  }else{
ds@1952
   743
    Op *pOp = &p->aOp[i];
ds@1952
   744
    Mem *pMem = p->aStack;
ds@1952
   745
    pMem->flags = MEM_Int;
ds@1952
   746
    pMem->type = SQLITE_INTEGER;
ds@1952
   747
    pMem->u.i = i;                                /* Program counter */
ds@1952
   748
    pMem++;
ds@1952
   749
ds@1952
   750
    pMem->flags = MEM_Static|MEM_Str|MEM_Term;
ds@1952
   751
    pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
ds@1952
   752
    assert( pMem->z!=0 );
ds@1952
   753
    pMem->n = strlen(pMem->z);
ds@1952
   754
    pMem->type = SQLITE_TEXT;
ds@1952
   755
    pMem->enc = SQLITE_UTF8;
ds@1952
   756
    pMem++;
ds@1952
   757
ds@1952
   758
    pMem->flags = MEM_Int;
ds@1952
   759
    pMem->u.i = pOp->p1;                          /* P1 */
ds@1952
   760
    pMem->type = SQLITE_INTEGER;
ds@1952
   761
    pMem++;
ds@1952
   762
ds@1952
   763
    pMem->flags = MEM_Int;
ds@1952
   764
    pMem->u.i = pOp->p2;                          /* P2 */
ds@1952
   765
    pMem->type = SQLITE_INTEGER;
ds@1952
   766
    pMem++;
ds@1952
   767
ds@1952
   768
    pMem->flags = MEM_Ephem|MEM_Str|MEM_Term;   /* P3 */
ds@1952
   769
    pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
ds@1952
   770
    assert( pMem->z!=0 );
ds@1952
   771
    pMem->n = strlen(pMem->z);
ds@1952
   772
    pMem->type = SQLITE_TEXT;
ds@1952
   773
    pMem->enc = SQLITE_UTF8;
ds@1952
   774
ds@1952
   775
    p->nResColumn = 5 - 2*(p->explain-1);
ds@1952
   776
    p->pTos = pMem;
ds@1952
   777
    p->rc = SQLITE_OK;
ds@1952
   778
    p->resOnStack = 1;
ds@1952
   779
    rc = SQLITE_ROW;
ds@1952
   780
  }
ds@1952
   781
  return rc;
ds@1952
   782
}
ds@1952
   783
#endif /* SQLITE_OMIT_EXPLAIN */
ds@1952
   784
ds@1952
   785
#ifdef SQLITE_DEBUG
ds@1952
   786
/*
ds@1952
   787
** Print the SQL that was used to generate a VDBE program.
ds@1952
   788
*/
ds@1952
   789
void sqlite3VdbePrintSql(Vdbe *p){
ds@1952
   790
  int nOp = p->nOp;
ds@1952
   791
  VdbeOp *pOp;
ds@1952
   792
  if( nOp<1 ) return;
ds@1952
   793
  pOp = &p->aOp[nOp-1];
ds@1952
   794
  if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
ds@1952
   795
    const char *z = pOp->p3;
ds@1952
   796
    while( isspace(*(u8*)z) ) z++;
ds@1952
   797
    printf("SQL: [%s]\n", z);
ds@1952
   798
  }
ds@1952
   799
}
ds@1952
   800
#endif
ds@1952
   801
ds@1952
   802
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
ds@1952
   803
/*
ds@1952
   804
** Print an IOTRACE message showing SQL content.
ds@1952
   805
*/
ds@1952
   806
void sqlite3VdbeIOTraceSql(Vdbe *p){
ds@1952
   807
  int nOp = p->nOp;
ds@1952
   808
  VdbeOp *pOp;
ds@1952
   809
  if( sqlite3_io_trace==0 ) return;
ds@1952
   810
  if( nOp<1 ) return;
ds@1952
   811
  pOp = &p->aOp[nOp-1];
ds@1952
   812
  if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
ds@1952
   813
    int i, j;
ds@1952
   814
    char z[1000];
ds@1952
   815
    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p3);
ds@1952
   816
    for(i=0; isspace((unsigned char)z[i]); i++){}
ds@1952
   817
    for(j=0; z[i]; i++){
ds@1952
   818
      if( isspace((unsigned char)z[i]) ){
ds@1952
   819
        if( z[i-1]!=' ' ){
ds@1952
   820
          z[j++] = ' ';
ds@1952
   821
        }
ds@1952
   822
      }else{
ds@1952
   823
        z[j++] = z[i];
ds@1952
   824
      }
ds@1952
   825
    }
ds@1952
   826
    z[j] = 0;
ds@1952
   827
    sqlite3_io_trace("SQL %s\n", z);
ds@1952
   828
  }
ds@1952
   829
}
ds@1952
   830
#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
ds@1952
   831
ds@1952
   832
ds@1952
   833
/*
ds@1952
   834
** Prepare a virtual machine for execution.  This involves things such
ds@1952
   835
** as allocating stack space and initializing the program counter.
ds@1952
   836
** After the VDBE has be prepped, it can be executed by one or more
ds@1952
   837
** calls to sqlite3VdbeExec().  
ds@1952
   838
**
ds@1952
   839
** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
ds@1952
   840
** VDBE_MAGIC_RUN.
ds@1952
   841
*/
ds@1952
   842
void sqlite3VdbeMakeReady(
ds@1952
   843
  Vdbe *p,                       /* The VDBE */
ds@1952
   844
  int nVar,                      /* Number of '?' see in the SQL statement */
ds@1952
   845
  int nMem,                      /* Number of memory cells to allocate */
ds@1952
   846
  int nCursor,                   /* Number of cursors to allocate */
ds@1952
   847
  int isExplain                  /* True if the EXPLAIN keywords is present */
ds@1952
   848
){
ds@1952
   849
  int n;
ds@1952
   850
  sqlite3 *db = p->db;
ds@1952
   851
ds@1952
   852
  assert( p!=0 );
ds@1952
   853
  assert( p->magic==VDBE_MAGIC_INIT );
ds@1952
   854
ds@1952
   855
  /* There should be at least one opcode.
ds@1952
   856
  */
ds@1952
   857
  assert( p->nOp>0 );
ds@1952
   858
ds@1952
   859
  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
ds@1952
   860
   * is because the call to resizeOpArray() below may shrink the
ds@1952
   861
   * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
ds@1952
   862
   * state.
ds@1952
   863
   */
ds@1952
   864
  p->magic = VDBE_MAGIC_RUN;
ds@1952
   865
ds@1952
   866
  /* No instruction ever pushes more than a single element onto the
ds@1952
   867
  ** stack.  And the stack never grows on successive executions of the
ds@1952
   868
  ** same loop.  So the total number of instructions is an upper bound
ds@1952
   869
  ** on the maximum stack depth required.  (Added later:)  The
ds@1952
   870
  ** resolveP2Values() call computes a tighter upper bound on the
ds@1952
   871
  ** stack size.
ds@1952
   872
  **
ds@1952
   873
  ** Allocation all the stack space we will ever need.
ds@1952
   874
  */
ds@1952
   875
  if( p->aStack==0 ){
ds@1952
   876
    int nArg;       /* Maximum number of args passed to a user function. */
ds@1952
   877
    int nStack;     /* Maximum number of stack entries required */
ds@1952
   878
    resolveP2Values(p, &nArg, &nStack);
ds@1952
   879
    resizeOpArray(p, p->nOp);
ds@1952
   880
    assert( nVar>=0 );
ds@1952
   881
    assert( nStack<p->nOp );
ds@1952
   882
    if( isExplain ){
ds@1952
   883
      nStack = 10;
ds@1952
   884
    }
ds@1952
   885
    p->aStack = sqlite3DbMallocZero(db,
ds@1952
   886
        nStack*sizeof(p->aStack[0])    /* aStack */
ds@1952
   887
      + nArg*sizeof(Mem*)              /* apArg */
ds@1952
   888
      + nVar*sizeof(Mem)               /* aVar */
ds@1952
   889
      + nVar*sizeof(char*)             /* azVar */
ds@1952
   890
      + nMem*sizeof(Mem)               /* aMem */
ds@1952
   891
      + nCursor*sizeof(Cursor*)        /* apCsr */
ds@1952
   892
    );
ds@1952
   893
    if( !db->mallocFailed ){
ds@1952
   894
      p->aMem = &p->aStack[nStack];
ds@1952
   895
      p->nMem = nMem;
ds@1952
   896
      p->aVar = &p->aMem[nMem];
ds@1952
   897
      p->nVar = nVar;
ds@1952
   898
      p->okVar = 0;
ds@1952
   899
      p->apArg = (Mem**)&p->aVar[nVar];
ds@1952
   900
      p->azVar = (char**)&p->apArg[nArg];
ds@1952
   901
      p->apCsr = (Cursor**)&p->azVar[nVar];
ds@1952
   902
      p->nCursor = nCursor;
ds@1952
   903
      for(n=0; n<nVar; n++){
ds@1952
   904
        p->aVar[n].flags = MEM_Null;
ds@1952
   905
        p->aVar[n].db = db;
ds@1952
   906
      }
ds@1952
   907
      for(n=0; n<nStack; n++){
ds@1952
   908
        p->aStack[n].db = db;
ds@1952
   909
      }
ds@1952
   910
    }
ds@1952
   911
  }
ds@1952
   912
  for(n=0; n<p->nMem; n++){
ds@1952
   913
    p->aMem[n].flags = MEM_Null;
ds@1952
   914
    p->aMem[n].db = db;
ds@1952
   915
  }
ds@1952
   916
ds@1952
   917
  p->pTos = &p->aStack[-1];
ds@1952
   918
  p->pc = -1;
ds@1952
   919
  p->rc = SQLITE_OK;
ds@1952
   920
  p->uniqueCnt = 0;
ds@1952
   921
  p->returnDepth = 0;
ds@1952
   922
  p->errorAction = OE_Abort;
ds@1952
   923
  p->popStack =  0;
ds@1952
   924
  p->explain |= isExplain;
ds@1952
   925
  p->magic = VDBE_MAGIC_RUN;
ds@1952
   926
  p->nChange = 0;
ds@1952
   927
  p->cacheCtr = 1;
ds@1952
   928
  p->minWriteFileFormat = 255;
ds@1952
   929
  p->openedStatement = 0;
ds@1952
   930
#ifdef VDBE_PROFILE
ds@1952
   931
  {
ds@1952
   932
    int i;
ds@1952
   933
    for(i=0; i<p->nOp; i++){
ds@1952
   934
      p->aOp[i].cnt = 0;
ds@1952
   935
      p->aOp[i].cycles = 0;
ds@1952
   936
    }
ds@1952
   937
  }
ds@1952
   938
#endif
ds@1952
   939
}
ds@1952
   940
ds@1952
   941
/*
ds@1952
   942
** Close a VDBE cursor and release all the resources that cursor happens
ds@1952
   943
** to hold.
ds@1952
   944
*/
ds@1952
   945
void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
ds@1952
   946
  if( pCx==0 ){
ds@1952
   947
    return;
ds@1952
   948
  }
ds@1952
   949
  if( pCx->pCursor ){
ds@1952
   950
    sqlite3BtreeCloseCursor(pCx->pCursor);
ds@1952
   951
  }
ds@1952
   952
  if( pCx->pBt ){
ds@1952
   953
    sqlite3BtreeClose(pCx->pBt);
ds@1952
   954
  }
ds@1952
   955
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
   956
  if( pCx->pVtabCursor ){
ds@1952
   957
    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
ds@1952
   958
    const sqlite3_module *pModule = pCx->pModule;
ds@1952
   959
    p->inVtabMethod = 1;
ds@1952
   960
    sqlite3SafetyOff(p->db);
ds@1952
   961
    pModule->xClose(pVtabCursor);
ds@1952
   962
    sqlite3SafetyOn(p->db);
ds@1952
   963
    p->inVtabMethod = 0;
ds@1952
   964
  }
ds@1952
   965
#endif
ds@1952
   966
  sqlite3_free(pCx->pData);
ds@1952
   967
  sqlite3_free(pCx->aType);
ds@1952
   968
  sqlite3_free(pCx);
ds@1952
   969
}
ds@1952
   970
ds@1952
   971
/*
ds@1952
   972
** Close all cursors except for VTab cursors that are currently
ds@1952
   973
** in use.
ds@1952
   974
*/
ds@1952
   975
static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
ds@1952
   976
  int i;
ds@1952
   977
  if( p->apCsr==0 ) return;
ds@1952
   978
  for(i=0; i<p->nCursor; i++){
ds@1952
   979
    Cursor *pC = p->apCsr[i];
ds@1952
   980
    if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
ds@1952
   981
      sqlite3VdbeFreeCursor(p, pC);
ds@1952
   982
      p->apCsr[i] = 0;
ds@1952
   983
    }
ds@1952
   984
  }
ds@1952
   985
}
ds@1952
   986
ds@1952
   987
/*
ds@1952
   988
** Clean up the VM after execution.
ds@1952
   989
**
ds@1952
   990
** This routine will automatically close any cursors, lists, and/or
ds@1952
   991
** sorters that were left open.  It also deletes the values of
ds@1952
   992
** variables in the aVar[] array.
ds@1952
   993
*/
ds@1952
   994
static void Cleanup(Vdbe *p){
ds@1952
   995
  int i;
ds@1952
   996
  if( p->aStack ){
ds@1952
   997
    releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
ds@1952
   998
    p->pTos = &p->aStack[-1];
ds@1952
   999
  }
ds@1952
  1000
  closeAllCursorsExceptActiveVtabs(p);
ds@1952
  1001
  releaseMemArray(p->aMem, p->nMem);
ds@1952
  1002
  sqlite3VdbeFifoClear(&p->sFifo);
ds@1952
  1003
  if( p->contextStack ){
ds@1952
  1004
    for(i=0; i<p->contextStackTop; i++){
ds@1952
  1005
      sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
ds@1952
  1006
    }
ds@1952
  1007
    sqlite3_free(p->contextStack);
ds@1952
  1008
  }
ds@1952
  1009
  p->contextStack = 0;
ds@1952
  1010
  p->contextStackDepth = 0;
ds@1952
  1011
  p->contextStackTop = 0;
ds@1952
  1012
  sqlite3_free(p->zErrMsg);
ds@1952
  1013
  p->zErrMsg = 0;
ds@1952
  1014
  p->resOnStack = 0;
ds@1952
  1015
}
ds@1952
  1016
ds@1952
  1017
/*
ds@1952
  1018
** Set the number of result columns that will be returned by this SQL
ds@1952
  1019
** statement. This is now set at compile time, rather than during
ds@1952
  1020
** execution of the vdbe program so that sqlite3_column_count() can
ds@1952
  1021
** be called on an SQL statement before sqlite3_step().
ds@1952
  1022
*/
ds@1952
  1023
void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
ds@1952
  1024
  Mem *pColName;
ds@1952
  1025
  int n;
ds@1952
  1026
ds@1952
  1027
  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
ds@1952
  1028
  sqlite3_free(p->aColName);
ds@1952
  1029
  n = nResColumn*COLNAME_N;
ds@1952
  1030
  p->nResColumn = nResColumn;
ds@1952
  1031
  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
ds@1952
  1032
  if( p->aColName==0 ) return;
ds@1952
  1033
  while( n-- > 0 ){
ds@1952
  1034
    pColName->flags = MEM_Null;
ds@1952
  1035
    pColName->db = p->db;
ds@1952
  1036
    pColName++;
ds@1952
  1037
  }
ds@1952
  1038
}
ds@1952
  1039
ds@1952
  1040
/*
ds@1952
  1041
** Set the name of the idx'th column to be returned by the SQL statement.
ds@1952
  1042
** zName must be a pointer to a nul terminated string.
ds@1952
  1043
**
ds@1952
  1044
** This call must be made after a call to sqlite3VdbeSetNumCols().
ds@1952
  1045
**
ds@1952
  1046
** If N==P3_STATIC  it means that zName is a pointer to a constant static
ds@1952
  1047
** string and we can just copy the pointer. If it is P3_DYNAMIC, then 
ds@1952
  1048
** the string is freed using sqlite3_free() when the vdbe is finished with
ds@1952
  1049
** it. Otherwise, N bytes of zName are copied.
ds@1952
  1050
*/
ds@1952
  1051
int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
ds@1952
  1052
  int rc;
ds@1952
  1053
  Mem *pColName;
ds@1952
  1054
  assert( idx<p->nResColumn );
ds@1952
  1055
  assert( var<COLNAME_N );
ds@1952
  1056
  if( p->db->mallocFailed ) return SQLITE_NOMEM;
ds@1952
  1057
  assert( p->aColName!=0 );
ds@1952
  1058
  pColName = &(p->aColName[idx+var*p->nResColumn]);
ds@1952
  1059
  if( N==P3_DYNAMIC || N==P3_STATIC ){
ds@1952
  1060
    rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
ds@1952
  1061
  }else{
ds@1952
  1062
    rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
ds@1952
  1063
  }
ds@1952
  1064
  if( rc==SQLITE_OK && N==P3_DYNAMIC ){
ds@1952
  1065
    pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
ds@1952
  1066
    pColName->xDel = 0;
ds@1952
  1067
  }
ds@1952
  1068
  return rc;
ds@1952
  1069
}
ds@1952
  1070
ds@1952
  1071
/*
ds@1952
  1072
** A read or write transaction may or may not be active on database handle
ds@1952
  1073
** db. If a transaction is active, commit it. If there is a
ds@1952
  1074
** write-transaction spanning more than one database file, this routine
ds@1952
  1075
** takes care of the master journal trickery.
ds@1952
  1076
*/
ds@1952
  1077
static int vdbeCommit(sqlite3 *db){
ds@1952
  1078
  int i;
ds@1952
  1079
  int nTrans = 0;  /* Number of databases with an active write-transaction */
ds@1952
  1080
  int rc = SQLITE_OK;
ds@1952
  1081
  int needXcommit = 0;
ds@1952
  1082
ds@1952
  1083
  /* Before doing anything else, call the xSync() callback for any
ds@1952
  1084
  ** virtual module tables written in this transaction. This has to
ds@1952
  1085
  ** be done before determining whether a master journal file is 
ds@1952
  1086
  ** required, as an xSync() callback may add an attached database
ds@1952
  1087
  ** to the transaction.
ds@1952
  1088
  */
ds@1952
  1089
  rc = sqlite3VtabSync(db, rc);
ds@1952
  1090
  if( rc!=SQLITE_OK ){
ds@1952
  1091
    return rc;
ds@1952
  1092
  }
ds@1952
  1093
ds@1952
  1094
  /* This loop determines (a) if the commit hook should be invoked and
ds@1952
  1095
  ** (b) how many database files have open write transactions, not 
ds@1952
  1096
  ** including the temp database. (b) is important because if more than 
ds@1952
  1097
  ** one database file has an open write transaction, a master journal
ds@1952
  1098
  ** file is required for an atomic commit.
ds@1952
  1099
  */ 
ds@1952
  1100
  for(i=0; i<db->nDb; i++){ 
ds@1952
  1101
    Btree *pBt = db->aDb[i].pBt;
ds@1952
  1102
    if( sqlite3BtreeIsInTrans(pBt) ){
ds@1952
  1103
      needXcommit = 1;
ds@1952
  1104
      if( i!=1 ) nTrans++;
ds@1952
  1105
    }
ds@1952
  1106
  }
ds@1952
  1107
ds@1952
  1108
  /* If there are any write-transactions at all, invoke the commit hook */
ds@1952
  1109
  if( needXcommit && db->xCommitCallback ){
ds@1952
  1110
    sqlite3SafetyOff(db);
ds@1952
  1111
    rc = db->xCommitCallback(db->pCommitArg);
ds@1952
  1112
    sqlite3SafetyOn(db);
ds@1952
  1113
    if( rc ){
ds@1952
  1114
      return SQLITE_CONSTRAINT;
ds@1952
  1115
    }
ds@1952
  1116
  }
ds@1952
  1117
ds@1952
  1118
  /* The simple case - no more than one database file (not counting the
ds@1952
  1119
  ** TEMP database) has a transaction active.   There is no need for the
ds@1952
  1120
  ** master-journal.
ds@1952
  1121
  **
ds@1952
  1122
  ** If the return value of sqlite3BtreeGetFilename() is a zero length
ds@1952
  1123
  ** string, it means the main database is :memory:.  In that case we do
ds@1952
  1124
  ** not support atomic multi-file commits, so use the simple case then
ds@1952
  1125
  ** too.
ds@1952
  1126
  */
ds@1952
  1127
  if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
ds@1952
  1128
    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
ds@1952
  1129
      Btree *pBt = db->aDb[i].pBt;
ds@1952
  1130
      if( pBt ){
ds@1952
  1131
        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
ds@1952
  1132
      }
ds@1952
  1133
    }
ds@1952
  1134
ds@1952
  1135
    /* Do the commit only if all databases successfully complete phase 1. 
ds@1952
  1136
    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
ds@1952
  1137
    ** IO error while deleting or truncating a journal file. It is unlikely,
ds@1952
  1138
    ** but could happen. In this case abandon processing and return the error.
ds@1952
  1139
    */
ds@1952
  1140
    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
ds@1952
  1141
      Btree *pBt = db->aDb[i].pBt;
ds@1952
  1142
      if( pBt ){
ds@1952
  1143
        rc = sqlite3BtreeCommitPhaseTwo(pBt);
ds@1952
  1144
      }
ds@1952
  1145
    }
ds@1952
  1146
    if( rc==SQLITE_OK ){
ds@1952
  1147
      sqlite3VtabCommit(db);
ds@1952
  1148
    }
ds@1952
  1149
  }
ds@1952
  1150
ds@1952
  1151
  /* The complex case - There is a multi-file write-transaction active.
ds@1952
  1152
  ** This requires a master journal file to ensure the transaction is
ds@1952
  1153
  ** committed atomicly.
ds@1952
  1154
  */
ds@1952
  1155
#ifndef SQLITE_OMIT_DISKIO
ds@1952
  1156
  else{
ds@1952
  1157
    sqlite3_vfs *pVfs = db->pVfs;
ds@1952
  1158
    int needSync = 0;
ds@1952
  1159
    char *zMaster = 0;   /* File-name for the master journal */
ds@1952
  1160
    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
ds@1952
  1161
    sqlite3_file *pMaster = 0;
ds@1952
  1162
    i64 offset = 0;
ds@1952
  1163
ds@1952
  1164
    /* Select a master journal file name */
ds@1952
  1165
    do {
ds@1952
  1166
      u32 random;
ds@1952
  1167
      sqlite3_free(zMaster);
ds@1952
  1168
      sqlite3Randomness(sizeof(random), &random);
ds@1952
  1169
      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
ds@1952
  1170
      if( !zMaster ){
ds@1952
  1171
        return SQLITE_NOMEM;
ds@1952
  1172
      }
ds@1952
  1173
    }while( sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS) );
ds@1952
  1174
ds@1952
  1175
    /* Open the master journal. */
ds@1952
  1176
    rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
ds@1952
  1177
        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
ds@1952
  1178
        SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
ds@1952
  1179
    );
ds@1952
  1180
    if( rc!=SQLITE_OK ){
ds@1952
  1181
      sqlite3_free(zMaster);
ds@1952
  1182
      return rc;
ds@1952
  1183
    }
ds@1952
  1184
 
ds@1952
  1185
    /* Write the name of each database file in the transaction into the new
ds@1952
  1186
    ** master journal file. If an error occurs at this point close
ds@1952
  1187
    ** and delete the master journal file. All the individual journal files
ds@1952
  1188
    ** still have 'null' as the master journal pointer, so they will roll
ds@1952
  1189
    ** back independently if a failure occurs.
ds@1952
  1190
    */
ds@1952
  1191
    for(i=0; i<db->nDb; i++){
ds@1952
  1192
      Btree *pBt = db->aDb[i].pBt;
ds@1952
  1193
      if( i==1 ) continue;   /* Ignore the TEMP database */
ds@1952
  1194
      if( sqlite3BtreeIsInTrans(pBt) ){
ds@1952
  1195
        char const *zFile = sqlite3BtreeGetJournalname(pBt);
ds@1952
  1196
        if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
ds@1952
  1197
        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
ds@1952
  1198
          needSync = 1;
ds@1952
  1199
        }
ds@1952
  1200
        rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
ds@1952
  1201
        offset += strlen(zFile)+1;
ds@1952
  1202
        if( rc!=SQLITE_OK ){
ds@1952
  1203
          sqlite3OsCloseFree(pMaster);
ds@1952
  1204
          sqlite3OsDelete(pVfs, zMaster, 0);
ds@1952
  1205
          sqlite3_free(zMaster);
ds@1952
  1206
          return rc;
ds@1952
  1207
        }
ds@1952
  1208
      }
ds@1952
  1209
    }
ds@1952
  1210
ds@1952
  1211
    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
ds@1952
  1212
    ** flag is set this is not required.
ds@1952
  1213
    */
ds@1952
  1214
    zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
ds@1952
  1215
    if( (needSync 
ds@1952
  1216
     && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
ds@1952
  1217
     && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
ds@1952
  1218
      sqlite3OsCloseFree(pMaster);
ds@1952
  1219
      sqlite3OsDelete(pVfs, zMaster, 0);
ds@1952
  1220
      sqlite3_free(zMaster);
ds@1952
  1221
      return rc;
ds@1952
  1222
    }
ds@1952
  1223
ds@1952
  1224
    /* Sync all the db files involved in the transaction. The same call
ds@1952
  1225
    ** sets the master journal pointer in each individual journal. If
ds@1952
  1226
    ** an error occurs here, do not delete the master journal file.
ds@1952
  1227
    **
ds@1952
  1228
    ** If the error occurs during the first call to
ds@1952
  1229
    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
ds@1952
  1230
    ** master journal file will be orphaned. But we cannot delete it,
ds@1952
  1231
    ** in case the master journal file name was written into the journal
ds@1952
  1232
    ** file before the failure occured.
ds@1952
  1233
    */
ds@1952
  1234
    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
ds@1952
  1235
      Btree *pBt = db->aDb[i].pBt;
ds@1952
  1236
      if( pBt ){
ds@1952
  1237
        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
ds@1952
  1238
      }
ds@1952
  1239
    }
ds@1952
  1240
    sqlite3OsCloseFree(pMaster);
ds@1952
  1241
    if( rc!=SQLITE_OK ){
ds@1952
  1242
      sqlite3_free(zMaster);
ds@1952
  1243
      return rc;
ds@1952
  1244
    }
ds@1952
  1245
ds@1952
  1246
    /* Delete the master journal file. This commits the transaction. After
ds@1952
  1247
    ** doing this the directory is synced again before any individual
ds@1952
  1248
    ** transaction files are deleted.
ds@1952
  1249
    */
ds@1952
  1250
    rc = sqlite3OsDelete(pVfs, zMaster, 1);
ds@1952
  1251
    sqlite3_free(zMaster);
ds@1952
  1252
    zMaster = 0;
ds@1952
  1253
    if( rc ){
ds@1952
  1254
      return rc;
ds@1952
  1255
    }
ds@1952
  1256
ds@1952
  1257
    /* All files and directories have already been synced, so the following
ds@1952
  1258
    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
ds@1952
  1259
    ** deleting or truncating journals. If something goes wrong while
ds@1952
  1260
    ** this is happening we don't really care. The integrity of the
ds@1952
  1261
    ** transaction is already guaranteed, but some stray 'cold' journals
ds@1952
  1262
    ** may be lying around. Returning an error code won't help matters.
ds@1952
  1263
    */
ds@1952
  1264
    disable_simulated_io_errors();
ds@1952
  1265
    for(i=0; i<db->nDb; i++){ 
ds@1952
  1266
      Btree *pBt = db->aDb[i].pBt;
ds@1952
  1267
      if( pBt ){
ds@1952
  1268
        sqlite3BtreeCommitPhaseTwo(pBt);
ds@1952
  1269
      }
ds@1952
  1270
    }
ds@1952
  1271
    enable_simulated_io_errors();
ds@1952
  1272
ds@1952
  1273
    sqlite3VtabCommit(db);
ds@1952
  1274
  }
ds@1952
  1275
#endif
ds@1952
  1276
ds@1952
  1277
  return rc;
ds@1952
  1278
}
ds@1952
  1279
ds@1952
  1280
/* 
ds@1952
  1281
** This routine checks that the sqlite3.activeVdbeCnt count variable
ds@1952
  1282
** matches the number of vdbe's in the list sqlite3.pVdbe that are
ds@1952
  1283
** currently active. An assertion fails if the two counts do not match.
ds@1952
  1284
** This is an internal self-check only - it is not an essential processing
ds@1952
  1285
** step.
ds@1952
  1286
**
ds@1952
  1287
** This is a no-op if NDEBUG is defined.
ds@1952
  1288
*/
ds@1952
  1289
#ifndef NDEBUG
ds@1952
  1290
static void checkActiveVdbeCnt(sqlite3 *db){
ds@1952
  1291
  Vdbe *p;
ds@1952
  1292
  int cnt = 0;
ds@1952
  1293
  p = db->pVdbe;
ds@1952
  1294
  while( p ){
ds@1952
  1295
    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
ds@1952
  1296
      cnt++;
ds@1952
  1297
    }
ds@1952
  1298
    p = p->pNext;
ds@1952
  1299
  }
ds@1952
  1300
  assert( cnt==db->activeVdbeCnt );
ds@1952
  1301
}
ds@1952
  1302
#else
ds@1952
  1303
#define checkActiveVdbeCnt(x)
ds@1952
  1304
#endif
ds@1952
  1305
ds@1952
  1306
/*
ds@1952
  1307
** For every Btree that in database connection db which 
ds@1952
  1308
** has been modified, "trip" or invalidate each cursor in
ds@1952
  1309
** that Btree might have been modified so that the cursor
ds@1952
  1310
** can never be used again.  This happens when a rollback
ds@1952
  1311
*** occurs.  We have to trip all the other cursors, even
ds@1952
  1312
** cursor from other VMs in different database connections,
ds@1952
  1313
** so that none of them try to use the data at which they
ds@1952
  1314
** were pointing and which now may have been changed due
ds@1952
  1315
** to the rollback.
ds@1952
  1316
**
ds@1952
  1317
** Remember that a rollback can delete tables complete and
ds@1952
  1318
** reorder rootpages.  So it is not sufficient just to save
ds@1952
  1319
** the state of the cursor.  We have to invalidate the cursor
ds@1952
  1320
** so that it is never used again.
ds@1952
  1321
*/
ds@1952
  1322
void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
ds@1952
  1323
  int i;
ds@1952
  1324
  for(i=0; i<db->nDb; i++){
ds@1952
  1325
    Btree *p = db->aDb[i].pBt;
ds@1952
  1326
    if( p && sqlite3BtreeIsInTrans(p) ){
ds@1952
  1327
      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
ds@1952
  1328
    }
ds@1952
  1329
  }
ds@1952
  1330
}
ds@1952
  1331
ds@1952
  1332
/*
ds@1952
  1333
** This routine is called the when a VDBE tries to halt.  If the VDBE
ds@1952
  1334
** has made changes and is in autocommit mode, then commit those
ds@1952
  1335
** changes.  If a rollback is needed, then do the rollback.
ds@1952
  1336
**
ds@1952
  1337
** This routine is the only way to move the state of a VM from
ds@1952
  1338
** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
ds@1952
  1339
** call this on a VM that is in the SQLITE_MAGIC_HALT state.
ds@1952
  1340
**
ds@1952
  1341
** Return an error code.  If the commit could not complete because of
ds@1952
  1342
** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
ds@1952
  1343
** means the close did not happen and needs to be repeated.
ds@1952
  1344
*/
ds@1952
  1345
int sqlite3VdbeHalt(Vdbe *p){
ds@1952
  1346
  sqlite3 *db = p->db;
ds@1952
  1347
  int i;
ds@1952
  1348
  int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
ds@1952
  1349
  int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
ds@1952
  1350
ds@1952
  1351
  /* This function contains the logic that determines if a statement or
ds@1952
  1352
  ** transaction will be committed or rolled back as a result of the
ds@1952
  1353
  ** execution of this virtual machine. 
ds@1952
  1354
  **
ds@1952
  1355
  ** If any of the following errors occur:
ds@1952
  1356
  **
ds@1952
  1357
  **     SQLITE_NOMEM
ds@1952
  1358
  **     SQLITE_IOERR
ds@1952
  1359
  **     SQLITE_FULL
ds@1952
  1360
  **     SQLITE_INTERRUPT
ds@1952
  1361
  **
ds@1952
  1362
  ** Then the internal cache might have been left in an inconsistent
ds@1952
  1363
  ** state.  We need to rollback the statement transaction, if there is
ds@1952
  1364
  ** one, or the complete transaction if there is no statement transaction.
ds@1952
  1365
  */
ds@1952
  1366
ds@1952
  1367
  if( p->db->mallocFailed ){
ds@1952
  1368
    p->rc = SQLITE_NOMEM;
ds@1952
  1369
  }
ds@1952
  1370
  closeAllCursorsExceptActiveVtabs(p);
ds@1952
  1371
  if( p->magic!=VDBE_MAGIC_RUN ){
ds@1952
  1372
    return SQLITE_OK;
ds@1952
  1373
  }
ds@1952
  1374
  checkActiveVdbeCnt(db);
ds@1952
  1375
ds@1952
  1376
  /* No commit or rollback needed if the program never started */
ds@1952
  1377
  if( p->pc>=0 ){
ds@1952
  1378
    int mrc;   /* Primary error code from p->rc */
ds@1952
  1379
ds@1952
  1380
    /* Lock all btrees used by the statement */
ds@1952
  1381
    sqlite3BtreeMutexArrayEnter(&p->aMutex);
ds@1952
  1382
ds@1952
  1383
    /* Check for one of the special errors */
ds@1952
  1384
    mrc = p->rc & 0xff;
ds@1952
  1385
    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
ds@1952
  1386
                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL ;
ds@1952
  1387
    if( isSpecialError ){
ds@1952
  1388
      /* This loop does static analysis of the query to see which of the
ds@1952
  1389
      ** following three categories it falls into:
ds@1952
  1390
      **
ds@1952
  1391
      **     Read-only
ds@1952
  1392
      **     Query with statement journal
ds@1952
  1393
      **     Query without statement journal
ds@1952
  1394
      **
ds@1952
  1395
      ** We could do something more elegant than this static analysis (i.e.
ds@1952
  1396
      ** store the type of query as part of the compliation phase), but 
ds@1952
  1397
      ** handling malloc() or IO failure is a fairly obscure edge case so 
ds@1952
  1398
      ** this is probably easier. Todo: Might be an opportunity to reduce 
ds@1952
  1399
      ** code size a very small amount though...
ds@1952
  1400
      */
ds@1952
  1401
      int notReadOnly = 0;
ds@1952
  1402
      int isStatement = 0;
ds@1952
  1403
      assert(p->aOp || p->nOp==0);
ds@1952
  1404
      for(i=0; i<p->nOp; i++){ 
ds@1952
  1405
        switch( p->aOp[i].opcode ){
ds@1952
  1406
          case OP_Transaction:
ds@1952
  1407
            notReadOnly |= p->aOp[i].p2;
ds@1952
  1408
            break;
ds@1952
  1409
          case OP_Statement:
ds@1952
  1410
            isStatement = 1;
ds@1952
  1411
            break;
ds@1952
  1412
        }
ds@1952
  1413
      }
ds@1952
  1414
ds@1952
  1415
   
ds@1952
  1416
      /* If the query was read-only, we need do no rollback at all. Otherwise,
ds@1952
  1417
      ** proceed with the special handling.
ds@1952
  1418
      */
ds@1952
  1419
      if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
ds@1952
  1420
        if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
ds@1952
  1421
          xFunc = sqlite3BtreeRollbackStmt;
ds@1952
  1422
          p->rc = SQLITE_BUSY;
ds@1952
  1423
        } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
ds@1952
  1424
          xFunc = sqlite3BtreeRollbackStmt;
ds@1952
  1425
        }else{
ds@1952
  1426
          /* We are forced to roll back the active transaction. Before doing
ds@1952
  1427
          ** so, abort any other statements this handle currently has active.
ds@1952
  1428
          */
ds@1952
  1429
          invalidateCursorsOnModifiedBtrees(db);
ds@1952
  1430
          sqlite3RollbackAll(db);
ds@1952
  1431
          db->autoCommit = 1;
ds@1952
  1432
        }
ds@1952
  1433
      }
ds@1952
  1434
    }
ds@1952
  1435
  
ds@1952
  1436
    /* If the auto-commit flag is set and this is the only active vdbe, then
ds@1952
  1437
    ** we do either a commit or rollback of the current transaction. 
ds@1952
  1438
    **
ds@1952
  1439
    ** Note: This block also runs if one of the special errors handled 
ds@1952
  1440
    ** above has occured. 
ds@1952
  1441
    */
ds@1952
  1442
    if( db->autoCommit && db->activeVdbeCnt==1 ){
ds@1952
  1443
      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
ds@1952
  1444
        /* The auto-commit flag is true, and the vdbe program was 
ds@1952
  1445
        ** successful or hit an 'OR FAIL' constraint. This means a commit 
ds@1952
  1446
        ** is required.
ds@1952
  1447
        */
ds@1952
  1448
        int rc = vdbeCommit(db);
ds@1952
  1449
        if( rc==SQLITE_BUSY ){
ds@1952
  1450
          sqlite3BtreeMutexArrayLeave(&p->aMutex);
ds@1952
  1451
          return SQLITE_BUSY;
ds@1952
  1452
        }else if( rc!=SQLITE_OK ){
ds@1952
  1453
          p->rc = rc;
ds@1952
  1454
          sqlite3RollbackAll(db);
ds@1952
  1455
        }else{
ds@1952
  1456
          sqlite3CommitInternalChanges(db);
ds@1952
  1457
        }
ds@1952
  1458
      }else{
ds@1952
  1459
        sqlite3RollbackAll(db);
ds@1952
  1460
      }
ds@1952
  1461
    }else if( !xFunc ){
ds@1952
  1462
      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
ds@1952
  1463
        if( p->openedStatement ){
ds@1952
  1464
          xFunc = sqlite3BtreeCommitStmt;
ds@1952
  1465
        } 
ds@1952
  1466
      }else if( p->errorAction==OE_Abort ){
ds@1952
  1467
        xFunc = sqlite3BtreeRollbackStmt;
ds@1952
  1468
      }else{
ds@1952
  1469
        invalidateCursorsOnModifiedBtrees(db);
ds@1952
  1470
        sqlite3RollbackAll(db);
ds@1952
  1471
        db->autoCommit = 1;
ds@1952
  1472
      }
ds@1952
  1473
    }
ds@1952
  1474
  
ds@1952
  1475
    /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
ds@1952
  1476
    ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
ds@1952
  1477
    ** and the return code is still SQLITE_OK, set the return code to the new
ds@1952
  1478
    ** error value.
ds@1952
  1479
    */
ds@1952
  1480
    assert(!xFunc ||
ds@1952
  1481
      xFunc==sqlite3BtreeCommitStmt ||
ds@1952
  1482
      xFunc==sqlite3BtreeRollbackStmt
ds@1952
  1483
    );
ds@1952
  1484
    for(i=0; xFunc && i<db->nDb; i++){ 
ds@1952
  1485
      int rc;
ds@1952
  1486
      Btree *pBt = db->aDb[i].pBt;
ds@1952
  1487
      if( pBt ){
ds@1952
  1488
        rc = xFunc(pBt);
ds@1952
  1489
        if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
ds@1952
  1490
          p->rc = rc;
ds@1952
  1491
          sqlite3SetString(&p->zErrMsg, 0);
ds@1952
  1492
        }
ds@1952
  1493
      }
ds@1952
  1494
    }
ds@1952
  1495
  
ds@1952
  1496
    /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
ds@1952
  1497
    ** set the change counter. 
ds@1952
  1498
    */
ds@1952
  1499
    if( p->changeCntOn && p->pc>=0 ){
ds@1952
  1500
      if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
ds@1952
  1501
        sqlite3VdbeSetChanges(db, p->nChange);
ds@1952
  1502
      }else{
ds@1952
  1503
        sqlite3VdbeSetChanges(db, 0);
ds@1952
  1504
      }
ds@1952
  1505
      p->nChange = 0;
ds@1952
  1506
    }
ds@1952
  1507
  
ds@1952
  1508
    /* Rollback or commit any schema changes that occurred. */
ds@1952
  1509
    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
ds@1952
  1510
      sqlite3ResetInternalSchema(db, 0);
ds@1952
  1511
      db->flags = (db->flags | SQLITE_InternChanges);
ds@1952
  1512
    }
ds@1952
  1513
ds@1952
  1514
    /* Release the locks */
ds@1952
  1515
    sqlite3BtreeMutexArrayLeave(&p->aMutex);
ds@1952
  1516
  }
ds@1952
  1517
ds@1952
  1518
  /* We have successfully halted and closed the VM.  Record this fact. */
ds@1952
  1519
  if( p->pc>=0 ){
ds@1952
  1520
    db->activeVdbeCnt--;
ds@1952
  1521
  }
ds@1952
  1522
  p->magic = VDBE_MAGIC_HALT;
ds@1952
  1523
  checkActiveVdbeCnt(db);
ds@1952
  1524
  if( p->db->mallocFailed ){
ds@1952
  1525
    p->rc = SQLITE_NOMEM;
ds@1952
  1526
  }
ds@1952
  1527
  checkActiveVdbeCnt(db);
ds@1952
  1528
ds@1952
  1529
  return SQLITE_OK;
ds@1952
  1530
}
ds@1952
  1531
ds@1952
  1532
ds@1952
  1533
/*
ds@1952
  1534
** Each VDBE holds the result of the most recent sqlite3_step() call
ds@1952
  1535
** in p->rc.  This routine sets that result back to SQLITE_OK.
ds@1952
  1536
*/
ds@1952
  1537
void sqlite3VdbeResetStepResult(Vdbe *p){
ds@1952
  1538
  p->rc = SQLITE_OK;
ds@1952
  1539
}
ds@1952
  1540
ds@1952
  1541
/*
ds@1952
  1542
** Clean up a VDBE after execution but do not delete the VDBE just yet.
ds@1952
  1543
** Write any error messages into *pzErrMsg.  Return the result code.
ds@1952
  1544
**
ds@1952
  1545
** After this routine is run, the VDBE should be ready to be executed
ds@1952
  1546
** again.
ds@1952
  1547
**
ds@1952
  1548
** To look at it another way, this routine resets the state of the
ds@1952
  1549
** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
ds@1952
  1550
** VDBE_MAGIC_INIT.
ds@1952
  1551
*/
ds@1952
  1552
int sqlite3VdbeReset(Vdbe *p){
ds@1952
  1553
  sqlite3 *db;
ds@1952
  1554
  db = p->db;
ds@1952
  1555
ds@1952
  1556
  /* If the VM did not run to completion or if it encountered an
ds@1952
  1557
  ** error, then it might not have been halted properly.  So halt
ds@1952
  1558
  ** it now.
ds@1952
  1559
  */
ds@1952
  1560
  sqlite3SafetyOn(db);
ds@1952
  1561
  sqlite3VdbeHalt(p);
ds@1952
  1562
  sqlite3SafetyOff(db);
ds@1952
  1563
ds@1952
  1564
  /* If the VDBE has be run even partially, then transfer the error code
ds@1952
  1565
  ** and error message from the VDBE into the main database structure.  But
ds@1952
  1566
  ** if the VDBE has just been set to run but has not actually executed any
ds@1952
  1567
  ** instructions yet, leave the main database error information unchanged.
ds@1952
  1568
  */
ds@1952
  1569
  if( p->pc>=0 ){
ds@1952
  1570
    if( p->zErrMsg ){
ds@1952
  1571
      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
ds@1952
  1572
      db->errCode = p->rc;
ds@1952
  1573
      p->zErrMsg = 0;
ds@1952
  1574
    }else if( p->rc ){
ds@1952
  1575
      sqlite3Error(db, p->rc, 0);
ds@1952
  1576
    }else{
ds@1952
  1577
      sqlite3Error(db, SQLITE_OK, 0);
ds@1952
  1578
    }
ds@1952
  1579
  }else if( p->rc && p->expired ){
ds@1952
  1580
    /* The expired flag was set on the VDBE before the first call
ds@1952
  1581
    ** to sqlite3_step(). For consistency (since sqlite3_step() was
ds@1952
  1582
    ** called), set the database error in this case as well.
ds@1952
  1583
    */
ds@1952
  1584
    sqlite3Error(db, p->rc, 0);
ds@1952
  1585
  }
ds@1952
  1586
ds@1952
  1587
  /* Reclaim all memory used by the VDBE
ds@1952
  1588
  */
ds@1952
  1589
  Cleanup(p);
ds@1952
  1590
ds@1952
  1591
  /* Save profiling information from this VDBE run.
ds@1952
  1592
  */
ds@1952
  1593
  assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
ds@1952
  1594
#ifdef VDBE_PROFILE
ds@1952
  1595
  {
ds@1952
  1596
    FILE *out = fopen("vdbe_profile.out", "a");
ds@1952
  1597
    if( out ){
ds@1952
  1598
      int i;
ds@1952
  1599
      fprintf(out, "---- ");
ds@1952
  1600
      for(i=0; i<p->nOp; i++){
ds@1952
  1601
        fprintf(out, "%02x", p->aOp[i].opcode);
ds@1952
  1602
      }
ds@1952
  1603
      fprintf(out, "\n");
ds@1952
  1604
      for(i=0; i<p->nOp; i++){
ds@1952
  1605
        fprintf(out, "%6d %10lld %8lld ",
ds@1952
  1606
           p->aOp[i].cnt,
ds@1952
  1607
           p->aOp[i].cycles,
ds@1952
  1608
           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
ds@1952
  1609
        );
ds@1952
  1610
        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
ds@1952
  1611
      }
ds@1952
  1612
      fclose(out);
ds@1952
  1613
    }
ds@1952
  1614
  }
ds@1952
  1615
#endif
ds@1952
  1616
  p->magic = VDBE_MAGIC_INIT;
ds@1952
  1617
  p->aborted = 0;
ds@1952
  1618
  return p->rc & db->errMask;
ds@1952
  1619
}
ds@1952
  1620
 
ds@1952
  1621
/*
ds@1952
  1622
** Clean up and delete a VDBE after execution.  Return an integer which is
ds@1952
  1623
** the result code.  Write any error message text into *pzErrMsg.
ds@1952
  1624
*/
ds@1952
  1625
int sqlite3VdbeFinalize(Vdbe *p){
ds@1952
  1626
  int rc = SQLITE_OK;
ds@1952
  1627
  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
ds@1952
  1628
    rc = sqlite3VdbeReset(p);
ds@1952
  1629
    assert( (rc & p->db->errMask)==rc );
ds@1952
  1630
  }else if( p->magic!=VDBE_MAGIC_INIT ){
ds@1952
  1631
    return SQLITE_MISUSE;
ds@1952
  1632
  }
ds@1952
  1633
  sqlite3VdbeDelete(p);
ds@1952
  1634
  return rc;
ds@1952
  1635
}
ds@1952
  1636
ds@1952
  1637
/*
ds@1952
  1638
** Call the destructor for each auxdata entry in pVdbeFunc for which
ds@1952
  1639
** the corresponding bit in mask is clear.  Auxdata entries beyond 31
ds@1952
  1640
** are always destroyed.  To destroy all auxdata entries, call this
ds@1952
  1641
** routine with mask==0.
ds@1952
  1642
*/
ds@1952
  1643
void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
ds@1952
  1644
  int i;
ds@1952
  1645
  for(i=0; i<pVdbeFunc->nAux; i++){
ds@1952
  1646
    struct AuxData *pAux = &pVdbeFunc->apAux[i];
ds@1952
  1647
    if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
ds@1952
  1648
      if( pAux->xDelete ){
ds@1952
  1649
        pAux->xDelete(pAux->pAux);
ds@1952
  1650
      }
ds@1952
  1651
      pAux->pAux = 0;
ds@1952
  1652
    }
ds@1952
  1653
  }
ds@1952
  1654
}
ds@1952
  1655
ds@1952
  1656
/*
ds@1952
  1657
** Delete an entire VDBE.
ds@1952
  1658
*/
ds@1952
  1659
void sqlite3VdbeDelete(Vdbe *p){
ds@1952
  1660
  int i;
ds@1952
  1661
  if( p==0 ) return;
ds@1952
  1662
  Cleanup(p);
ds@1952
  1663
  if( p->pPrev ){
ds@1952
  1664
    p->pPrev->pNext = p->pNext;
ds@1952
  1665
  }else{
ds@1952
  1666
    assert( p->db->pVdbe==p );
ds@1952
  1667
    p->db->pVdbe = p->pNext;
ds@1952
  1668
  }
ds@1952
  1669
  if( p->pNext ){
ds@1952
  1670
    p->pNext->pPrev = p->pPrev;
ds@1952
  1671
  }
ds@1952
  1672
  if( p->aOp ){
ds@1952
  1673
    for(i=0; i<p->nOp; i++){
ds@1952
  1674
      Op *pOp = &p->aOp[i];
ds@1952
  1675
      freeP3(pOp->p3type, pOp->p3);
ds@1952
  1676
    }
ds@1952
  1677
    sqlite3_free(p->aOp);
ds@1952
  1678
  }
ds@1952
  1679
  releaseMemArray(p->aVar, p->nVar);
ds@1952
  1680
  sqlite3_free(p->aLabel);
ds@1952
  1681
  sqlite3_free(p->aStack);
ds@1952
  1682
  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
ds@1952
  1683
  sqlite3_free(p->aColName);
ds@1952
  1684
  sqlite3_free(p->zSql);
ds@1952
  1685
  p->magic = VDBE_MAGIC_DEAD;
ds@1952
  1686
  sqlite3_free(p);
ds@1952
  1687
}
ds@1952
  1688
ds@1952
  1689
/*
ds@1952
  1690
** If a MoveTo operation is pending on the given cursor, then do that
ds@1952
  1691
** MoveTo now.  Return an error code.  If no MoveTo is pending, this
ds@1952
  1692
** routine does nothing and returns SQLITE_OK.
ds@1952
  1693
*/
ds@1952
  1694
int sqlite3VdbeCursorMoveto(Cursor *p){
ds@1952
  1695
  if( p->deferredMoveto ){
ds@1952
  1696
    int res, rc;
ds@1952
  1697
#ifdef SQLITE_TEST
ds@1952
  1698
    extern int sqlite3_search_count;
ds@1952
  1699
#endif
ds@1952
  1700
    assert( p->isTable );
ds@1952
  1701
    rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
ds@1952
  1702
    if( rc ) return rc;
ds@1952
  1703
    *p->pIncrKey = 0;
ds@1952
  1704
    p->lastRowid = keyToInt(p->movetoTarget);
ds@1952
  1705
    p->rowidIsValid = res==0;
ds@1952
  1706
    if( res<0 ){
ds@1952
  1707
      rc = sqlite3BtreeNext(p->pCursor, &res);
ds@1952
  1708
      if( rc ) return rc;
ds@1952
  1709
    }
ds@1952
  1710
#ifdef SQLITE_TEST
ds@1952
  1711
    sqlite3_search_count++;
ds@1952
  1712
#endif
ds@1952
  1713
    p->deferredMoveto = 0;
ds@1952
  1714
    p->cacheStatus = CACHE_STALE;
ds@1952
  1715
  }
ds@1952
  1716
  return SQLITE_OK;
ds@1952
  1717
}
ds@1952
  1718
ds@1952
  1719
/*
ds@1952
  1720
** The following functions:
ds@1952
  1721
**
ds@1952
  1722
** sqlite3VdbeSerialType()
ds@1952
  1723
** sqlite3VdbeSerialTypeLen()
ds@1952
  1724
** sqlite3VdbeSerialRead()
ds@1952
  1725
** sqlite3VdbeSerialLen()
ds@1952
  1726
** sqlite3VdbeSerialWrite()
ds@1952
  1727
**
ds@1952
  1728
** encapsulate the code that serializes values for storage in SQLite
ds@1952
  1729
** data and index records. Each serialized value consists of a
ds@1952
  1730
** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
ds@1952
  1731
** integer, stored as a varint.
ds@1952
  1732
**
ds@1952
  1733
** In an SQLite index record, the serial type is stored directly before
ds@1952
  1734
** the blob of data that it corresponds to. In a table record, all serial
ds@1952
  1735
** types are stored at the start of the record, and the blobs of data at
ds@1952
  1736
** the end. Hence these functions allow the caller to handle the
ds@1952
  1737
** serial-type and data blob seperately.
ds@1952
  1738
**
ds@1952
  1739
** The following table describes the various storage classes for data:
ds@1952
  1740
**
ds@1952
  1741
**   serial type        bytes of data      type
ds@1952
  1742
**   --------------     ---------------    ---------------
ds@1952
  1743
**      0                     0            NULL
ds@1952
  1744
**      1                     1            signed integer
ds@1952
  1745
**      2                     2            signed integer
ds@1952
  1746
**      3                     3            signed integer
ds@1952
  1747
**      4                     4            signed integer
ds@1952
  1748
**      5                     6            signed integer
ds@1952
  1749
**      6                     8            signed integer
ds@1952
  1750
**      7                     8            IEEE float
ds@1952
  1751
**      8                     0            Integer constant 0
ds@1952
  1752
**      9                     0            Integer constant 1
ds@1952
  1753
**     10,11                               reserved for expansion
ds@1952
  1754
**    N>=12 and even       (N-12)/2        BLOB
ds@1952
  1755
**    N>=13 and odd        (N-13)/2        text
ds@1952
  1756
**
ds@1952
  1757
** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
ds@1952
  1758
** of SQLite will not understand those serial types.
ds@1952
  1759
*/
ds@1952
  1760
ds@1952
  1761
/*
ds@1952
  1762
** Return the serial-type for the value stored in pMem.
ds@1952
  1763
*/
ds@1952
  1764
u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
ds@1952
  1765
  int flags = pMem->flags;
ds@1952
  1766
  int n;
ds@1952
  1767
ds@1952
  1768
  if( flags&MEM_Null ){
ds@1952
  1769
    return 0;
ds@1952
  1770
  }
ds@1952
  1771
  if( flags&MEM_Int ){
ds@1952
  1772
    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
ds@1952
  1773
#   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
ds@1952
  1774
    i64 i = pMem->u.i;
ds@1952
  1775
    u64 u;
ds@1952
  1776
    if( file_format>=4 && (i&1)==i ){
ds@1952
  1777
      return 8+i;
ds@1952
  1778
    }
ds@1952
  1779
    u = i<0 ? -i : i;
ds@1952
  1780
    if( u<=127 ) return 1;
ds@1952
  1781
    if( u<=32767 ) return 2;
ds@1952
  1782
    if( u<=8388607 ) return 3;
ds@1952
  1783
    if( u<=2147483647 ) return 4;
ds@1952
  1784
    if( u<=MAX_6BYTE ) return 5;
ds@1952
  1785
    return 6;
ds@1952
  1786
  }
ds@1952
  1787
  if( flags&MEM_Real ){
ds@1952
  1788
    return 7;
ds@1952
  1789
  }
ds@1952
  1790
  assert( flags&(MEM_Str|MEM_Blob) );
ds@1952
  1791
  n = pMem->n;
ds@1952
  1792
  if( flags & MEM_Zero ){
ds@1952
  1793
    n += pMem->u.i;
ds@1952
  1794
  }
ds@1952
  1795
  assert( n>=0 );
ds@1952
  1796
  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
ds@1952
  1797
}
ds@1952
  1798
ds@1952
  1799
/*
ds@1952
  1800
** Return the length of the data corresponding to the supplied serial-type.
ds@1952
  1801
*/
ds@1952
  1802
int sqlite3VdbeSerialTypeLen(u32 serial_type){
ds@1952
  1803
  if( serial_type>=12 ){
ds@1952
  1804
    return (serial_type-12)/2;
ds@1952
  1805
  }else{
ds@1952
  1806
    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
ds@1952
  1807
    return aSize[serial_type];
ds@1952
  1808
  }
ds@1952
  1809
}
ds@1952
  1810
ds@1952
  1811
/*
ds@1952
  1812
** If we are on an architecture with mixed-endian floating 
ds@1952
  1813
** points (ex: ARM7) then swap the lower 4 bytes with the 
ds@1952
  1814
** upper 4 bytes.  Return the result.
ds@1952
  1815
**
ds@1952
  1816
** For most architectures, this is a no-op.
ds@1952
  1817
**
ds@1952
  1818
** (later):  It is reported to me that the mixed-endian problem
ds@1952
  1819
** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
ds@1952
  1820
** that early versions of GCC stored the two words of a 64-bit
ds@1952
  1821
** float in the wrong order.  And that error has been propagated
ds@1952
  1822
** ever since.  The blame is not necessarily with GCC, though.
ds@1952
  1823
** GCC might have just copying the problem from a prior compiler.
ds@1952
  1824
** I am also told that newer versions of GCC that follow a different
ds@1952
  1825
** ABI get the byte order right.
ds@1952
  1826
**
ds@1952
  1827
** Developers using SQLite on an ARM7 should compile and run their
ds@1952
  1828
** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
ds@1952
  1829
** enabled, some asserts below will ensure that the byte order of
ds@1952
  1830
** floating point values is correct.
ds@1952
  1831
**
ds@1952
  1832
** (2007-08-30)  Frank van Vugt has studied this problem closely
ds@1952
  1833
** and has send his findings to the SQLite developers.  Frank
ds@1952
  1834
** writes that some Linux kernels offer floating point hardware
ds@1952
  1835
** emulation that uses only 32-bit mantissas instead of a full 
ds@1952
  1836
** 48-bits as required by the IEEE standard.  (This is the
ds@1952
  1837
** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
ds@1952
  1838
** byte swapping becomes very complicated.  To avoid problems,
ds@1952
  1839
** the necessary byte swapping is carried out using a 64-bit integer
ds@1952
  1840
** rather than a 64-bit float.  Frank assures us that the code here
ds@1952
  1841
** works for him.  We, the developers, have no way to independently
ds@1952
  1842
** verify this, but Frank seems to know what he is talking about
ds@1952
  1843
** so we trust him.
ds@1952
  1844
*/
ds@1952
  1845
#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
ds@1952
  1846
static u64 floatSwap(u64 in){
ds@1952
  1847
  union {
ds@1952
  1848
    u64 r;
ds@1952
  1849
    u32 i[2];
ds@1952
  1850
  } u;
ds@1952
  1851
  u32 t;
ds@1952
  1852
ds@1952
  1853
  u.r = in;
ds@1952
  1854
  t = u.i[0];
ds@1952
  1855
  u.i[0] = u.i[1];
ds@1952
  1856
  u.i[1] = t;
ds@1952
  1857
  return u.r;
ds@1952
  1858
}
ds@1952
  1859
# define swapMixedEndianFloat(X)  X = floatSwap(X)
ds@1952
  1860
#else
ds@1952
  1861
# define swapMixedEndianFloat(X)
ds@1952
  1862
#endif
ds@1952
  1863
ds@1952
  1864
/*
ds@1952
  1865
** Write the serialized data blob for the value stored in pMem into 
ds@1952
  1866
** buf. It is assumed that the caller has allocated sufficient space.
ds@1952
  1867
** Return the number of bytes written.
ds@1952
  1868
**
ds@1952
  1869
** nBuf is the amount of space left in buf[].  nBuf must always be
ds@1952
  1870
** large enough to hold the entire field.  Except, if the field is
ds@1952
  1871
** a blob with a zero-filled tail, then buf[] might be just the right
ds@1952
  1872
** size to hold everything except for the zero-filled tail.  If buf[]
ds@1952
  1873
** is only big enough to hold the non-zero prefix, then only write that
ds@1952
  1874
** prefix into buf[].  But if buf[] is large enough to hold both the
ds@1952
  1875
** prefix and the tail then write the prefix and set the tail to all
ds@1952
  1876
** zeros.
ds@1952
  1877
**
ds@1952
  1878
** Return the number of bytes actually written into buf[].  The number
ds@1952
  1879
** of bytes in the zero-filled tail is included in the return value only
ds@1952
  1880
** if those bytes were zeroed in buf[].
ds@1952
  1881
*/ 
ds@1952
  1882
int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
ds@1952
  1883
  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
ds@1952
  1884
  int len;
ds@1952
  1885
ds@1952
  1886
  /* Integer and Real */
ds@1952
  1887
  if( serial_type<=7 && serial_type>0 ){
ds@1952
  1888
    u64 v;
ds@1952
  1889
    int i;
ds@1952
  1890
    if( serial_type==7 ){
ds@1952
  1891
      assert( sizeof(v)==sizeof(pMem->r) );
ds@1952
  1892
      memcpy(&v, &pMem->r, sizeof(v));
ds@1952
  1893
      swapMixedEndianFloat(v);
ds@1952
  1894
    }else{
ds@1952
  1895
      v = pMem->u.i;
ds@1952
  1896
    }
ds@1952
  1897
    len = i = sqlite3VdbeSerialTypeLen(serial_type);
ds@1952
  1898
    assert( len<=nBuf );
ds@1952
  1899
    while( i-- ){
ds@1952
  1900
      buf[i] = (v&0xFF);
ds@1952
  1901
      v >>= 8;
ds@1952
  1902
    }
ds@1952
  1903
    return len;
ds@1952
  1904
  }
ds@1952
  1905
ds@1952
  1906
  /* String or blob */
ds@1952
  1907
  if( serial_type>=12 ){
ds@1952
  1908
    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
ds@1952
  1909
             == sqlite3VdbeSerialTypeLen(serial_type) );
ds@1952
  1910
    assert( pMem->n<=nBuf );
ds@1952
  1911
    len = pMem->n;
ds@1952
  1912
    memcpy(buf, pMem->z, len);
ds@1952
  1913
    if( pMem->flags & MEM_Zero ){
ds@1952
  1914
      len += pMem->u.i;
ds@1952
  1915
      if( len>nBuf ){
ds@1952
  1916
        len = nBuf;
ds@1952
  1917
      }
ds@1952
  1918
      memset(&buf[pMem->n], 0, len-pMem->n);
ds@1952
  1919
    }
ds@1952
  1920
    return len;
ds@1952
  1921
  }
ds@1952
  1922
ds@1952
  1923
  /* NULL or constants 0 or 1 */
ds@1952
  1924
  return 0;
ds@1952
  1925
}
ds@1952
  1926
ds@1952
  1927
/*
ds@1952
  1928
** Deserialize the data blob pointed to by buf as serial type serial_type
ds@1952
  1929
** and store the result in pMem.  Return the number of bytes read.
ds@1952
  1930
*/ 
ds@1952
  1931
int sqlite3VdbeSerialGet(
ds@1952
  1932
  const unsigned char *buf,     /* Buffer to deserialize from */
ds@1952
  1933
  u32 serial_type,              /* Serial type to deserialize */
ds@1952
  1934
  Mem *pMem                     /* Memory cell to write value into */
ds@1952
  1935
){
ds@1952
  1936
  switch( serial_type ){
ds@1952
  1937
    case 10:   /* Reserved for future use */
ds@1952
  1938
    case 11:   /* Reserved for future use */
ds@1952
  1939
    case 0: {  /* NULL */
ds@1952
  1940
      pMem->flags = MEM_Null;
ds@1952
  1941
      break;
ds@1952
  1942
    }
ds@1952
  1943
    case 1: { /* 1-byte signed integer */
ds@1952
  1944
      pMem->u.i = (signed char)buf[0];
ds@1952
  1945
      pMem->flags = MEM_Int;
ds@1952
  1946
      return 1;
ds@1952
  1947
    }
ds@1952
  1948
    case 2: { /* 2-byte signed integer */
ds@1952
  1949
      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
ds@1952
  1950
      pMem->flags = MEM_Int;
ds@1952
  1951
      return 2;
ds@1952
  1952
    }
ds@1952
  1953
    case 3: { /* 3-byte signed integer */
ds@1952
  1954
      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
ds@1952
  1955
      pMem->flags = MEM_Int;
ds@1952
  1956
      return 3;
ds@1952
  1957
    }
ds@1952
  1958
    case 4: { /* 4-byte signed integer */
ds@1952
  1959
      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
ds@1952
  1960
      pMem->flags = MEM_Int;
ds@1952
  1961
      return 4;
ds@1952
  1962
    }
ds@1952
  1963
    case 5: { /* 6-byte signed integer */
ds@1952
  1964
      u64 x = (((signed char)buf[0])<<8) | buf[1];
ds@1952
  1965
      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
ds@1952
  1966
      x = (x<<32) | y;
ds@1952
  1967
      pMem->u.i = *(i64*)&x;
ds@1952
  1968
      pMem->flags = MEM_Int;
ds@1952
  1969
      return 6;
ds@1952
  1970
    }
ds@1952
  1971
    case 6:   /* 8-byte signed integer */
ds@1952
  1972
    case 7: { /* IEEE floating point */
ds@1952
  1973
      u64 x;
ds@1952
  1974
      u32 y;
ds@1952
  1975
#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
ds@1952
  1976
      /* Verify that integers and floating point values use the same
ds@1952
  1977
      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
ds@1952
  1978
      ** defined that 64-bit floating point values really are mixed
ds@1952
  1979
      ** endian.
ds@1952
  1980
      */
ds@1952
  1981
      static const u64 t1 = ((u64)0x3ff00000)<<32;
ds@1952
  1982
      static const double r1 = 1.0;
ds@1952
  1983
      u64 t2 = t1;
ds@1952
  1984
      swapMixedEndianFloat(t2);
ds@1952
  1985
      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
ds@1952
  1986
#endif
ds@1952
  1987
ds@1952
  1988
      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
ds@1952
  1989
      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
ds@1952
  1990
      x = (x<<32) | y;
ds@1952
  1991
      if( serial_type==6 ){
ds@1952
  1992
        pMem->u.i = *(i64*)&x;
ds@1952
  1993
        pMem->flags = MEM_Int;
ds@1952
  1994
      }else{
ds@1952
  1995
        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
ds@1952
  1996
        swapMixedEndianFloat(x);
ds@1952
  1997
        memcpy(&pMem->r, &x, sizeof(x));
ds@1952
  1998
        pMem->flags = MEM_Real;
ds@1952
  1999
      }
ds@1952
  2000
      return 8;
ds@1952
  2001
    }
ds@1952
  2002
    case 8:    /* Integer 0 */
ds@1952
  2003
    case 9: {  /* Integer 1 */
ds@1952
  2004
      pMem->u.i = serial_type-8;
ds@1952
  2005
      pMem->flags = MEM_Int;
ds@1952
  2006
      return 0;
ds@1952
  2007
    }
ds@1952
  2008
    default: {
ds@1952
  2009
      int len = (serial_type-12)/2;
ds@1952
  2010
      pMem->z = (char *)buf;
ds@1952
  2011
      pMem->n = len;
ds@1952
  2012
      pMem->xDel = 0;
ds@1952
  2013
      if( serial_type&0x01 ){
ds@1952
  2014
        pMem->flags = MEM_Str | MEM_Ephem;
ds@1952
  2015
      }else{
ds@1952
  2016
        pMem->flags = MEM_Blob | MEM_Ephem;
ds@1952
  2017
      }
ds@1952
  2018
      return len;
ds@1952
  2019
    }
ds@1952
  2020
  }
ds@1952
  2021
  return 0;
ds@1952
  2022
}
ds@1952
  2023
ds@1952
  2024
/*
ds@1952
  2025
** The header of a record consists of a sequence variable-length integers.
ds@1952
  2026
** These integers are almost always small and are encoded as a single byte.
ds@1952
  2027
** The following macro takes advantage this fact to provide a fast decode
ds@1952
  2028
** of the integers in a record header.  It is faster for the common case
ds@1952
  2029
** where the integer is a single byte.  It is a little slower when the
ds@1952
  2030
** integer is two or more bytes.  But overall it is faster.
ds@1952
  2031
**
ds@1952
  2032
** The following expressions are equivalent:
ds@1952
  2033
**
ds@1952
  2034
**     x = sqlite3GetVarint32( A, &B );
ds@1952
  2035
**
ds@1952
  2036
**     x = GetVarint( A, B );
ds@1952
  2037
**
ds@1952
  2038
*/
ds@1952
  2039
#define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
ds@1952
  2040
ds@1952
  2041
/*
ds@1952
  2042
** This function compares the two table rows or index records specified by 
ds@1952
  2043
** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
ds@1952
  2044
** or positive integer if {nKey1, pKey1} is less than, equal to or 
ds@1952
  2045
** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
ds@1952
  2046
** composed by the OP_MakeRecord opcode of the VDBE.
ds@1952
  2047
*/
ds@1952
  2048
int sqlite3VdbeRecordCompare(
ds@1952
  2049
  void *userData,
ds@1952
  2050
  int nKey1, const void *pKey1, 
ds@1952
  2051
  int nKey2, const void *pKey2
ds@1952
  2052
){
ds@1952
  2053
  KeyInfo *pKeyInfo = (KeyInfo*)userData;
ds@1952
  2054
  u32 d1, d2;          /* Offset into aKey[] of next data element */
ds@1952
  2055
  u32 idx1, idx2;      /* Offset into aKey[] of next header element */
ds@1952
  2056
  u32 szHdr1, szHdr2;  /* Number of bytes in header */
ds@1952
  2057
  int i = 0;
ds@1952
  2058
  int nField;
ds@1952
  2059
  int rc = 0;
ds@1952
  2060
  const unsigned char *aKey1 = (const unsigned char *)pKey1;
ds@1952
  2061
  const unsigned char *aKey2 = (const unsigned char *)pKey2;
ds@1952
  2062
ds@1952
  2063
  Mem mem1;
ds@1952
  2064
  Mem mem2;
ds@1952
  2065
  mem1.enc = pKeyInfo->enc;
ds@1952
  2066
  mem1.db = pKeyInfo->db;
ds@1952
  2067
  mem2.enc = pKeyInfo->enc;
ds@1952
  2068
  mem2.db = pKeyInfo->db;
ds@1952
  2069
  
ds@1952
  2070
  idx1 = GetVarint(aKey1, szHdr1);
ds@1952
  2071
  d1 = szHdr1;
ds@1952
  2072
  idx2 = GetVarint(aKey2, szHdr2);
ds@1952
  2073
  d2 = szHdr2;
ds@1952
  2074
  nField = pKeyInfo->nField;
ds@1952
  2075
  while( idx1<szHdr1 && idx2<szHdr2 ){
ds@1952
  2076
    u32 serial_type1;
ds@1952
  2077
    u32 serial_type2;
ds@1952
  2078
ds@1952
  2079
    /* Read the serial types for the next element in each key. */
ds@1952
  2080
    idx1 += GetVarint( aKey1+idx1, serial_type1 );
ds@1952
  2081
    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
ds@1952
  2082
    idx2 += GetVarint( aKey2+idx2, serial_type2 );
ds@1952
  2083
    if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
ds@1952
  2084
ds@1952
  2085
    /* Extract the values to be compared.
ds@1952
  2086
    */
ds@1952
  2087
    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
ds@1952
  2088
    d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
ds@1952
  2089
ds@1952
  2090
    /* Do the comparison
ds@1952
  2091
    */
ds@1952
  2092
    rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
ds@1952
  2093
    if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
ds@1952
  2094
    if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
ds@1952
  2095
    if( rc!=0 ){
ds@1952
  2096
      break;
ds@1952
  2097
    }
ds@1952
  2098
    i++;
ds@1952
  2099
  }
ds@1952
  2100
ds@1952
  2101
  /* One of the keys ran out of fields, but all the fields up to that point
ds@1952
  2102
  ** were equal. If the incrKey flag is true, then the second key is
ds@1952
  2103
  ** treated as larger.
ds@1952
  2104
  */
ds@1952
  2105
  if( rc==0 ){
ds@1952
  2106
    if( pKeyInfo->incrKey ){
ds@1952
  2107
      rc = -1;
ds@1952
  2108
    }else if( d1<nKey1 ){
ds@1952
  2109
      rc = 1;
ds@1952
  2110
    }else if( d2<nKey2 ){
ds@1952
  2111
      rc = -1;
ds@1952
  2112
    }
ds@1952
  2113
  }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
ds@1952
  2114
               && pKeyInfo->aSortOrder[i] ){
ds@1952
  2115
    rc = -rc;
ds@1952
  2116
  }
ds@1952
  2117
ds@1952
  2118
  return rc;
ds@1952
  2119
}
ds@1952
  2120
ds@1952
  2121
/*
ds@1952
  2122
** The argument is an index entry composed using the OP_MakeRecord opcode.
ds@1952
  2123
** The last entry in this record should be an integer (specifically
ds@1952
  2124
** an integer rowid).  This routine returns the number of bytes in
ds@1952
  2125
** that integer.
ds@1952
  2126
*/
ds@1952
  2127
int sqlite3VdbeIdxRowidLen(const u8 *aKey){
ds@1952
  2128
  u32 szHdr;        /* Size of the header */
ds@1952
  2129
  u32 typeRowid;    /* Serial type of the rowid */
ds@1952
  2130
ds@1952
  2131
  sqlite3GetVarint32(aKey, &szHdr);
ds@1952
  2132
  sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
ds@1952
  2133
  return sqlite3VdbeSerialTypeLen(typeRowid);
ds@1952
  2134
}
ds@1952
  2135
  
ds@1952
  2136
ds@1952
  2137
/*
ds@1952
  2138
** pCur points at an index entry created using the OP_MakeRecord opcode.
ds@1952
  2139
** Read the rowid (the last field in the record) and store it in *rowid.
ds@1952
  2140
** Return SQLITE_OK if everything works, or an error code otherwise.
ds@1952
  2141
*/
ds@1952
  2142
int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
ds@1952
  2143
  i64 nCellKey = 0;
ds@1952
  2144
  int rc;
ds@1952
  2145
  u32 szHdr;        /* Size of the header */
ds@1952
  2146
  u32 typeRowid;    /* Serial type of the rowid */
ds@1952
  2147
  u32 lenRowid;     /* Size of the rowid */
ds@1952
  2148
  Mem m, v;
ds@1952
  2149
ds@1952
  2150
  sqlite3BtreeKeySize(pCur, &nCellKey);
ds@1952
  2151
  if( nCellKey<=0 ){
ds@1952
  2152
    return SQLITE_CORRUPT_BKPT;
ds@1952
  2153
  }
ds@1952
  2154
  rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
ds@1952
  2155
  if( rc ){
ds@1952
  2156
    return rc;
ds@1952
  2157
  }
ds@1952
  2158
  sqlite3GetVarint32((u8*)m.z, &szHdr);
ds@1952
  2159
  sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
ds@1952
  2160
  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
ds@1952
  2161
  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
ds@1952
  2162
  *rowid = v.u.i;
ds@1952
  2163
  sqlite3VdbeMemRelease(&m);
ds@1952
  2164
  return SQLITE_OK;
ds@1952
  2165
}
ds@1952
  2166
ds@1952
  2167
/*
ds@1952
  2168
** Compare the key of the index entry that cursor pC is point to against
ds@1952
  2169
** the key string in pKey (of length nKey).  Write into *pRes a number
ds@1952
  2170
** that is negative, zero, or positive if pC is less than, equal to,
ds@1952
  2171
** or greater than pKey.  Return SQLITE_OK on success.
ds@1952
  2172
**
ds@1952
  2173
** pKey is either created without a rowid or is truncated so that it
ds@1952
  2174
** omits the rowid at the end.  The rowid at the end of the index entry
ds@1952
  2175
** is ignored as well.
ds@1952
  2176
*/
ds@1952
  2177
int sqlite3VdbeIdxKeyCompare(
ds@1952
  2178
  Cursor *pC,                 /* The cursor to compare against */
ds@1952
  2179
  int nKey, const u8 *pKey,   /* The key to compare */
ds@1952
  2180
  int *res                    /* Write the comparison result here */
ds@1952
  2181
){
ds@1952
  2182
  i64 nCellKey = 0;
ds@1952
  2183
  int rc;
ds@1952
  2184
  BtCursor *pCur = pC->pCursor;
ds@1952
  2185
  int lenRowid;
ds@1952
  2186
  Mem m;
ds@1952
  2187
ds@1952
  2188
  sqlite3BtreeKeySize(pCur, &nCellKey);
ds@1952
  2189
  if( nCellKey<=0 ){
ds@1952
  2190
    *res = 0;
ds@1952
  2191
    return SQLITE_OK;
ds@1952
  2192
  }
ds@1952
  2193
  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
ds@1952
  2194
  if( rc ){
ds@1952
  2195
    return rc;
ds@1952
  2196
  }
ds@1952
  2197
  lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
ds@1952
  2198
  *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
ds@1952
  2199
  sqlite3VdbeMemRelease(&m);
ds@1952
  2200
  return SQLITE_OK;
ds@1952
  2201
}
ds@1952
  2202
ds@1952
  2203
/*
ds@1952
  2204
** This routine sets the value to be returned by subsequent calls to
ds@1952
  2205
** sqlite3_changes() on the database handle 'db'. 
ds@1952
  2206
*/
ds@1952
  2207
void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
ds@1952
  2208
  assert( sqlite3_mutex_held(db->mutex) );
ds@1952
  2209
  db->nChange = nChange;
ds@1952
  2210
  db->nTotalChange += nChange;
ds@1952
  2211
}
ds@1952
  2212
ds@1952
  2213
/*
ds@1952
  2214
** Set a flag in the vdbe to update the change counter when it is finalised
ds@1952
  2215
** or reset.
ds@1952
  2216
*/
ds@1952
  2217
void sqlite3VdbeCountChanges(Vdbe *v){
ds@1952
  2218
  v->changeCntOn = 1;
ds@1952
  2219
}
ds@1952
  2220
ds@1952
  2221
/*
ds@1952
  2222
** Mark every prepared statement associated with a database connection
ds@1952
  2223
** as expired.
ds@1952
  2224
**
ds@1952
  2225
** An expired statement means that recompilation of the statement is
ds@1952
  2226
** recommend.  Statements expire when things happen that make their
ds@1952
  2227
** programs obsolete.  Removing user-defined functions or collating
ds@1952
  2228
** sequences, or changing an authorization function are the types of
ds@1952
  2229
** things that make prepared statements obsolete.
ds@1952
  2230
*/
ds@1952
  2231
void sqlite3ExpirePreparedStatements(sqlite3 *db){
ds@1952
  2232
  Vdbe *p;
ds@1952
  2233
  for(p = db->pVdbe; p; p=p->pNext){
ds@1952
  2234
    p->expired = 1;
ds@1952
  2235
  }
ds@1952
  2236
}
ds@1952
  2237
ds@1952
  2238
/*
ds@1952
  2239
** Return the database associated with the Vdbe.
ds@1952
  2240
*/
ds@1952
  2241
sqlite3 *sqlite3VdbeDb(Vdbe *v){
ds@1952
  2242
  return v->db;
ds@1952
  2243
}