adjustments for constant time function volatile variables
[sqlcipher.git] / src / vdbe.c
blob2aa4e6df24fcccd5825a2f747536183d4614e9b0
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** The code in this file implements the function that runs the
13 ** bytecode of a prepared statement.
15 ** Various scripts scan this source file in order to generate HTML
16 ** documentation, headers files, or other derived files. The formatting
17 ** of the code in this file is, therefore, important. See other comments
18 ** in this file for details. If in doubt, do not deviate from existing
19 ** commenting and indentation practices when changing or adding code.
21 #include "sqliteInt.h"
22 #include "vdbeInt.h"
25 ** Invoke this macro on memory cells just prior to changing the
26 ** value of the cell. This macro verifies that shallow copies are
27 ** not misused. A shallow copy of a string or blob just copies a
28 ** pointer to the string or blob, not the content. If the original
29 ** is changed while the copy is still in use, the string or blob might
30 ** be changed out from under the copy. This macro verifies that nothing
31 ** like that ever happens.
33 #ifdef SQLITE_DEBUG
34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
35 #else
36 # define memAboutToChange(P,M)
37 #endif
40 ** The following global variable is incremented every time a cursor
41 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
42 ** procedures use this information to make sure that indices are
43 ** working correctly. This variable has no function other than to
44 ** help verify the correct operation of the library.
46 #ifdef SQLITE_TEST
47 int sqlite3_search_count = 0;
48 #endif
51 ** When this global variable is positive, it gets decremented once before
52 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
53 ** field of the sqlite3 structure is set in order to simulate an interrupt.
55 ** This facility is used for testing purposes only. It does not function
56 ** in an ordinary build.
58 #ifdef SQLITE_TEST
59 int sqlite3_interrupt_count = 0;
60 #endif
63 ** The next global variable is incremented each type the OP_Sort opcode
64 ** is executed. The test procedures use this information to make sure that
65 ** sorting is occurring or not occurring at appropriate times. This variable
66 ** has no function other than to help verify the correct operation of the
67 ** library.
69 #ifdef SQLITE_TEST
70 int sqlite3_sort_count = 0;
71 #endif
74 ** The next global variable records the size of the largest MEM_Blob
75 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
76 ** use this information to make sure that the zero-blob functionality
77 ** is working correctly. This variable has no function other than to
78 ** help verify the correct operation of the library.
80 #ifdef SQLITE_TEST
81 int sqlite3_max_blobsize = 0;
82 static void updateMaxBlobsize(Mem *p){
83 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
84 sqlite3_max_blobsize = p->n;
87 #endif
90 ** This macro evaluates to true if either the update hook or the preupdate
91 ** hook are enabled for database connect DB.
93 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
94 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
95 #else
96 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
97 #endif
100 ** The next global variable is incremented each time the OP_Found opcode
101 ** is executed. This is used to test whether or not the foreign key
102 ** operation implemented using OP_FkIsZero is working. This variable
103 ** has no function other than to help verify the correct operation of the
104 ** library.
106 #ifdef SQLITE_TEST
107 int sqlite3_found_count = 0;
108 #endif
111 ** Test a register to see if it exceeds the current maximum blob size.
112 ** If it does, record the new maximum blob size.
114 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
115 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
116 #else
117 # define UPDATE_MAX_BLOBSIZE(P)
118 #endif
120 #ifdef SQLITE_DEBUG
121 /* This routine provides a convenient place to set a breakpoint during
122 ** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after
123 ** each opcode is printed. Variables "pc" (program counter) and pOp are
124 ** available to add conditionals to the breakpoint. GDB example:
126 ** break test_trace_breakpoint if pc=22
128 ** Other useful labels for breakpoints include:
129 ** test_addop_breakpoint(pc,pOp)
130 ** sqlite3CorruptError(lineno)
131 ** sqlite3MisuseError(lineno)
132 ** sqlite3CantopenError(lineno)
134 static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
135 static int n = 0;
136 (void)pc;
137 (void)pOp;
138 (void)v;
139 n++;
141 #endif
144 ** Invoke the VDBE coverage callback, if that callback is defined. This
145 ** feature is used for test suite validation only and does not appear an
146 ** production builds.
148 ** M is the type of branch. I is the direction taken for this instance of
149 ** the branch.
151 ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
152 ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
153 ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
155 ** In other words, if M is 2, then I is either 0 (for fall-through) or
156 ** 1 (for when the branch is taken). If M is 3, the I is 0 for an
157 ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
158 ** if the result of comparison is NULL. For M=3, I=2 the jump may or
159 ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
160 ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
161 ** depending on if the operands are less than, equal, or greater than.
163 ** iSrcLine is the source code line (from the __LINE__ macro) that
164 ** generated the VDBE instruction combined with flag bits. The source
165 ** code line number is in the lower 24 bits of iSrcLine and the upper
166 ** 8 bytes are flags. The lower three bits of the flags indicate
167 ** values for I that should never occur. For example, if the branch is
168 ** always taken, the flags should be 0x05 since the fall-through and
169 ** alternate branch are never taken. If a branch is never taken then
170 ** flags should be 0x06 since only the fall-through approach is allowed.
172 ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
173 ** interested in equal or not-equal. In other words, I==0 and I==2
174 ** should be treated as equivalent
176 ** Since only a line number is retained, not the filename, this macro
177 ** only works for amalgamation builds. But that is ok, since these macros
178 ** should be no-ops except for special builds used to measure test coverage.
180 #if !defined(SQLITE_VDBE_COVERAGE)
181 # define VdbeBranchTaken(I,M)
182 #else
183 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
184 static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
185 u8 mNever;
186 assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
187 assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
188 assert( I<M ); /* I can only be 2 if M is 3 or 4 */
189 /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
190 I = 1<<I;
191 /* The upper 8 bits of iSrcLine are flags. The lower three bits of
192 ** the flags indicate directions that the branch can never go. If
193 ** a branch really does go in one of those directions, assert right
194 ** away. */
195 mNever = iSrcLine >> 24;
196 assert( (I & mNever)==0 );
197 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
198 /* Invoke the branch coverage callback with three arguments:
199 ** iSrcLine - the line number of the VdbeCoverage() macro, with
200 ** flags removed.
201 ** I - Mask of bits 0x07 indicating which cases are are
202 ** fulfilled by this instance of the jump. 0x01 means
203 ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
204 ** impossible cases (ex: if the comparison is never NULL)
205 ** are filled in automatically so that the coverage
206 ** measurement logic does not flag those impossible cases
207 ** as missed coverage.
208 ** M - Type of jump. Same as M argument above
210 I |= mNever;
211 if( M==2 ) I |= 0x04;
212 if( M==4 ){
213 I |= 0x08;
214 if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
216 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
217 iSrcLine&0xffffff, I, M);
219 #endif
222 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
223 ** a pointer to a dynamically allocated string where some other entity
224 ** is responsible for deallocating that string. Because the register
225 ** does not control the string, it might be deleted without the register
226 ** knowing it.
228 ** This routine converts an ephemeral string into a dynamically allocated
229 ** string that the register itself controls. In other words, it
230 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
232 #define Deephemeralize(P) \
233 if( ((P)->flags&MEM_Ephem)!=0 \
234 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
236 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
237 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
240 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
241 ** if we run out of memory.
243 static VdbeCursor *allocateCursor(
244 Vdbe *p, /* The virtual machine */
245 int iCur, /* Index of the new VdbeCursor */
246 int nField, /* Number of fields in the table or index */
247 u8 eCurType /* Type of the new cursor */
249 /* Find the memory cell that will be used to store the blob of memory
250 ** required for this VdbeCursor structure. It is convenient to use a
251 ** vdbe memory cell to manage the memory allocation required for a
252 ** VdbeCursor structure for the following reasons:
254 ** * Sometimes cursor numbers are used for a couple of different
255 ** purposes in a vdbe program. The different uses might require
256 ** different sized allocations. Memory cells provide growable
257 ** allocations.
259 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
260 ** be freed lazily via the sqlite3_release_memory() API. This
261 ** minimizes the number of malloc calls made by the system.
263 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
264 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
265 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
267 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
269 int nByte;
270 VdbeCursor *pCx = 0;
271 nByte =
272 ROUND8P(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
273 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
275 assert( iCur>=0 && iCur<p->nCursor );
276 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
277 sqlite3VdbeFreeCursorNN(p, p->apCsr[iCur]);
278 p->apCsr[iCur] = 0;
281 /* There used to be a call to sqlite3VdbeMemClearAndResize() to make sure
282 ** the pMem used to hold space for the cursor has enough storage available
283 ** in pMem->zMalloc. But for the special case of the aMem[] entries used
284 ** to hold cursors, it is faster to in-line the logic. */
285 assert( pMem->flags==MEM_Undefined );
286 assert( (pMem->flags & MEM_Dyn)==0 );
287 assert( pMem->szMalloc==0 || pMem->z==pMem->zMalloc );
288 if( pMem->szMalloc<nByte ){
289 if( pMem->szMalloc>0 ){
290 sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
292 pMem->z = pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, nByte);
293 if( pMem->zMalloc==0 ){
294 pMem->szMalloc = 0;
295 return 0;
297 pMem->szMalloc = nByte;
300 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc;
301 memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
302 pCx->eCurType = eCurType;
303 pCx->nField = nField;
304 pCx->aOffset = &pCx->aType[nField];
305 if( eCurType==CURTYPE_BTREE ){
306 pCx->uc.pCursor = (BtCursor*)
307 &pMem->z[ROUND8P(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
308 sqlite3BtreeCursorZero(pCx->uc.pCursor);
310 return pCx;
314 ** The string in pRec is known to look like an integer and to have a
315 ** floating point value of rValue. Return true and set *piValue to the
316 ** integer value if the string is in range to be an integer. Otherwise,
317 ** return false.
319 static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){
320 i64 iValue;
321 iValue = sqlite3RealToI64(rValue);
322 if( sqlite3RealSameAsInt(rValue,iValue) ){
323 *piValue = iValue;
324 return 1;
326 return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
330 ** Try to convert a value into a numeric representation if we can
331 ** do so without loss of information. In other words, if the string
332 ** looks like a number, convert it into a number. If it does not
333 ** look like a number, leave it alone.
335 ** If the bTryForInt flag is true, then extra effort is made to give
336 ** an integer representation. Strings that look like floating point
337 ** values but which have no fractional component (example: '48.00')
338 ** will have a MEM_Int representation when bTryForInt is true.
340 ** If bTryForInt is false, then if the input string contains a decimal
341 ** point or exponential notation, the result is only MEM_Real, even
342 ** if there is an exact integer representation of the quantity.
344 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
345 double rValue;
346 u8 enc = pRec->enc;
347 int rc;
348 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
349 rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
350 if( rc<=0 ) return;
351 if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
352 pRec->flags |= MEM_Int;
353 }else{
354 pRec->u.r = rValue;
355 pRec->flags |= MEM_Real;
356 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
358 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
359 ** string representation after computing a numeric equivalent, because the
360 ** string representation might not be the canonical representation for the
361 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
362 pRec->flags &= ~MEM_Str;
366 ** Processing is determine by the affinity parameter:
368 ** SQLITE_AFF_INTEGER:
369 ** SQLITE_AFF_REAL:
370 ** SQLITE_AFF_NUMERIC:
371 ** Try to convert pRec to an integer representation or a
372 ** floating-point representation if an integer representation
373 ** is not possible. Note that the integer representation is
374 ** always preferred, even if the affinity is REAL, because
375 ** an integer representation is more space efficient on disk.
377 ** SQLITE_AFF_FLEXNUM:
378 ** If the value is text, then try to convert it into a number of
379 ** some kind (integer or real) but do not make any other changes.
381 ** SQLITE_AFF_TEXT:
382 ** Convert pRec to a text representation.
384 ** SQLITE_AFF_BLOB:
385 ** SQLITE_AFF_NONE:
386 ** No-op. pRec is unchanged.
388 static void applyAffinity(
389 Mem *pRec, /* The value to apply affinity to */
390 char affinity, /* The affinity to be applied */
391 u8 enc /* Use this text encoding */
393 if( affinity>=SQLITE_AFF_NUMERIC ){
394 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
395 || affinity==SQLITE_AFF_NUMERIC || affinity==SQLITE_AFF_FLEXNUM );
396 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
397 if( (pRec->flags & (MEM_Real|MEM_IntReal))==0 ){
398 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
399 }else if( affinity<=SQLITE_AFF_REAL ){
400 sqlite3VdbeIntegerAffinity(pRec);
403 }else if( affinity==SQLITE_AFF_TEXT ){
404 /* Only attempt the conversion to TEXT if there is an integer or real
405 ** representation (blob and NULL do not get converted) but no string
406 ** representation. It would be harmless to repeat the conversion if
407 ** there is already a string rep, but it is pointless to waste those
408 ** CPU cycles. */
409 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
410 if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
411 testcase( pRec->flags & MEM_Int );
412 testcase( pRec->flags & MEM_Real );
413 testcase( pRec->flags & MEM_IntReal );
414 sqlite3VdbeMemStringify(pRec, enc, 1);
417 pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
422 ** Try to convert the type of a function argument or a result column
423 ** into a numeric representation. Use either INTEGER or REAL whichever
424 ** is appropriate. But only do the conversion if it is possible without
425 ** loss of information and return the revised type of the argument.
427 int sqlite3_value_numeric_type(sqlite3_value *pVal){
428 int eType = sqlite3_value_type(pVal);
429 if( eType==SQLITE_TEXT ){
430 Mem *pMem = (Mem*)pVal;
431 applyNumericAffinity(pMem, 0);
432 eType = sqlite3_value_type(pVal);
434 return eType;
438 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
439 ** not the internal Mem* type.
441 void sqlite3ValueApplyAffinity(
442 sqlite3_value *pVal,
443 u8 affinity,
444 u8 enc
446 applyAffinity((Mem *)pVal, affinity, enc);
450 ** pMem currently only holds a string type (or maybe a BLOB that we can
451 ** interpret as a string if we want to). Compute its corresponding
452 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
453 ** accordingly.
455 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
456 int rc;
457 sqlite3_int64 ix;
458 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
459 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
460 if( ExpandBlob(pMem) ){
461 pMem->u.i = 0;
462 return MEM_Int;
464 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
465 if( rc<=0 ){
466 if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
467 pMem->u.i = ix;
468 return MEM_Int;
469 }else{
470 return MEM_Real;
472 }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
473 pMem->u.i = ix;
474 return MEM_Int;
476 return MEM_Real;
480 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
481 ** none.
483 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
484 ** But it does set pMem->u.r and pMem->u.i appropriately.
486 static u16 numericType(Mem *pMem){
487 assert( (pMem->flags & MEM_Null)==0
488 || pMem->db==0 || pMem->db->mallocFailed );
489 if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null) ){
490 testcase( pMem->flags & MEM_Int );
491 testcase( pMem->flags & MEM_Real );
492 testcase( pMem->flags & MEM_IntReal );
493 return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null);
495 assert( pMem->flags & (MEM_Str|MEM_Blob) );
496 testcase( pMem->flags & MEM_Str );
497 testcase( pMem->flags & MEM_Blob );
498 return computeNumericType(pMem);
499 return 0;
502 #ifdef SQLITE_DEBUG
504 ** Write a nice string representation of the contents of cell pMem
505 ** into buffer zBuf, length nBuf.
507 void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){
508 int f = pMem->flags;
509 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
510 if( f&MEM_Blob ){
511 int i;
512 char c;
513 if( f & MEM_Dyn ){
514 c = 'z';
515 assert( (f & (MEM_Static|MEM_Ephem))==0 );
516 }else if( f & MEM_Static ){
517 c = 't';
518 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
519 }else if( f & MEM_Ephem ){
520 c = 'e';
521 assert( (f & (MEM_Static|MEM_Dyn))==0 );
522 }else{
523 c = 's';
525 sqlite3_str_appendf(pStr, "%cx[", c);
526 for(i=0; i<25 && i<pMem->n; i++){
527 sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
529 sqlite3_str_appendf(pStr, "|");
530 for(i=0; i<25 && i<pMem->n; i++){
531 char z = pMem->z[i];
532 sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);
534 sqlite3_str_appendf(pStr,"]");
535 if( f & MEM_Zero ){
536 sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
538 }else if( f & MEM_Str ){
539 int j;
540 u8 c;
541 if( f & MEM_Dyn ){
542 c = 'z';
543 assert( (f & (MEM_Static|MEM_Ephem))==0 );
544 }else if( f & MEM_Static ){
545 c = 't';
546 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
547 }else if( f & MEM_Ephem ){
548 c = 'e';
549 assert( (f & (MEM_Static|MEM_Dyn))==0 );
550 }else{
551 c = 's';
553 sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
554 for(j=0; j<25 && j<pMem->n; j++){
555 c = pMem->z[j];
556 sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');
558 sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
561 #endif
563 #ifdef SQLITE_DEBUG
565 ** Print the value of a register for tracing purposes:
567 static void memTracePrint(Mem *p){
568 if( p->flags & MEM_Undefined ){
569 printf(" undefined");
570 }else if( p->flags & MEM_Null ){
571 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
572 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
573 printf(" si:%lld", p->u.i);
574 }else if( (p->flags & (MEM_IntReal))!=0 ){
575 printf(" ir:%lld", p->u.i);
576 }else if( p->flags & MEM_Int ){
577 printf(" i:%lld", p->u.i);
578 #ifndef SQLITE_OMIT_FLOATING_POINT
579 }else if( p->flags & MEM_Real ){
580 printf(" r:%.17g", p->u.r);
581 #endif
582 }else if( sqlite3VdbeMemIsRowSet(p) ){
583 printf(" (rowset)");
584 }else{
585 StrAccum acc;
586 char zBuf[1000];
587 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
588 sqlite3VdbeMemPrettyPrint(p, &acc);
589 printf(" %s", sqlite3StrAccumFinish(&acc));
591 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
593 static void registerTrace(int iReg, Mem *p){
594 printf("R[%d] = ", iReg);
595 memTracePrint(p);
596 if( p->pScopyFrom ){
597 printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
599 printf("\n");
600 sqlite3VdbeCheckMemInvariants(p);
602 /**/ void sqlite3PrintMem(Mem *pMem){
603 memTracePrint(pMem);
604 printf("\n");
605 fflush(stdout);
607 #endif
609 #ifdef SQLITE_DEBUG
611 ** Show the values of all registers in the virtual machine. Used for
612 ** interactive debugging.
614 void sqlite3VdbeRegisterDump(Vdbe *v){
615 int i;
616 for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
618 #endif /* SQLITE_DEBUG */
621 #ifdef SQLITE_DEBUG
622 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
623 #else
624 # define REGISTER_TRACE(R,M)
625 #endif
627 #ifndef NDEBUG
629 ** This function is only called from within an assert() expression. It
630 ** checks that the sqlite3.nTransaction variable is correctly set to
631 ** the number of non-transaction savepoints currently in the
632 ** linked list starting at sqlite3.pSavepoint.
634 ** Usage:
636 ** assert( checkSavepointCount(db) );
638 static int checkSavepointCount(sqlite3 *db){
639 int n = 0;
640 Savepoint *p;
641 for(p=db->pSavepoint; p; p=p->pNext) n++;
642 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
643 return 1;
645 #endif
648 ** Return the register of pOp->p2 after first preparing it to be
649 ** overwritten with an integer value.
651 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
652 sqlite3VdbeMemSetNull(pOut);
653 pOut->flags = MEM_Int;
654 return pOut;
656 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
657 Mem *pOut;
658 assert( pOp->p2>0 );
659 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
660 pOut = &p->aMem[pOp->p2];
661 memAboutToChange(p, pOut);
662 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
663 return out2PrereleaseWithClear(pOut);
664 }else{
665 pOut->flags = MEM_Int;
666 return pOut;
671 ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
672 ** with pOp->p3. Return the hash.
674 static u64 filterHash(const Mem *aMem, const Op *pOp){
675 int i, mx;
676 u64 h = 0;
678 assert( pOp->p4type==P4_INT32 );
679 for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
680 const Mem *p = &aMem[i];
681 if( p->flags & (MEM_Int|MEM_IntReal) ){
682 h += p->u.i;
683 }else if( p->flags & MEM_Real ){
684 h += sqlite3VdbeIntValue(p);
685 }else if( p->flags & (MEM_Str|MEM_Blob) ){
686 /* All strings have the same hash and all blobs have the same hash,
687 ** though, at least, those hashes are different from each other and
688 ** from NULL. */
689 h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
692 return h;
696 ** Return the symbolic name for the data type of a pMem
698 static const char *vdbeMemTypeName(Mem *pMem){
699 static const char *azTypes[] = {
700 /* SQLITE_INTEGER */ "INT",
701 /* SQLITE_FLOAT */ "REAL",
702 /* SQLITE_TEXT */ "TEXT",
703 /* SQLITE_BLOB */ "BLOB",
704 /* SQLITE_NULL */ "NULL"
706 return azTypes[sqlite3_value_type(pMem)-1];
710 ** Execute as much of a VDBE program as we can.
711 ** This is the core of sqlite3_step().
713 int sqlite3VdbeExec(
714 Vdbe *p /* The VDBE */
716 Op *aOp = p->aOp; /* Copy of p->aOp */
717 Op *pOp = aOp; /* Current operation */
718 #ifdef SQLITE_DEBUG
719 Op *pOrigOp; /* Value of pOp at the top of the loop */
720 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
721 u8 iCompareIsInit = 0; /* iCompare is initialized */
722 #endif
723 int rc = SQLITE_OK; /* Value to return */
724 sqlite3 *db = p->db; /* The database */
725 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
726 u8 encoding = ENC(db); /* The database encoding */
727 int iCompare = 0; /* Result of last comparison */
728 u64 nVmStep = 0; /* Number of virtual machine steps */
729 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
730 u64 nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
731 #endif
732 Mem *aMem = p->aMem; /* Copy of p->aMem */
733 Mem *pIn1 = 0; /* 1st input operand */
734 Mem *pIn2 = 0; /* 2nd input operand */
735 Mem *pIn3 = 0; /* 3rd input operand */
736 Mem *pOut = 0; /* Output operand */
737 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
738 u64 *pnCycle = 0;
739 int bStmtScanStatus = IS_STMT_SCANSTATUS(db)!=0;
740 #endif
741 /*** INSERT STACK UNION HERE ***/
743 assert( p->eVdbeState==VDBE_RUN_STATE ); /* sqlite3_step() verifies this */
744 if( DbMaskNonZero(p->lockMask) ){
745 sqlite3VdbeEnter(p);
747 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
748 if( db->xProgress ){
749 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
750 assert( 0 < db->nProgressOps );
751 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
752 }else{
753 nProgressLimit = LARGEST_UINT64;
755 #endif
756 if( p->rc==SQLITE_NOMEM ){
757 /* This happens if a malloc() inside a call to sqlite3_column_text() or
758 ** sqlite3_column_text16() failed. */
759 goto no_mem;
761 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
762 testcase( p->rc!=SQLITE_OK );
763 p->rc = SQLITE_OK;
764 assert( p->bIsReader || p->readOnly!=0 );
765 p->iCurrentTime = 0;
766 assert( p->explain==0 );
767 db->busyHandler.nBusy = 0;
768 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
769 sqlite3VdbeIOTraceSql(p);
770 #ifdef SQLITE_DEBUG
771 sqlite3BeginBenignMalloc();
772 if( p->pc==0
773 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
775 int i;
776 int once = 1;
777 sqlite3VdbePrintSql(p);
778 if( p->db->flags & SQLITE_VdbeListing ){
779 printf("VDBE Program Listing:\n");
780 for(i=0; i<p->nOp; i++){
781 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
784 if( p->db->flags & SQLITE_VdbeEQP ){
785 for(i=0; i<p->nOp; i++){
786 if( aOp[i].opcode==OP_Explain ){
787 if( once ) printf("VDBE Query Plan:\n");
788 printf("%s\n", aOp[i].p4.z);
789 once = 0;
793 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
795 sqlite3EndBenignMalloc();
796 #endif
797 for(pOp=&aOp[p->pc]; 1; pOp++){
798 /* Errors are detected by individual opcodes, with an immediate
799 ** jumps to abort_due_to_error. */
800 assert( rc==SQLITE_OK );
802 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
803 nVmStep++;
805 #if defined(VDBE_PROFILE)
806 pOp->nExec++;
807 pnCycle = &pOp->nCycle;
808 if( sqlite3NProfileCnt==0 ) *pnCycle -= sqlite3Hwtime();
809 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
810 if( bStmtScanStatus ){
811 pOp->nExec++;
812 pnCycle = &pOp->nCycle;
813 *pnCycle -= sqlite3Hwtime();
815 #endif
817 /* Only allow tracing if SQLITE_DEBUG is defined.
819 #ifdef SQLITE_DEBUG
820 if( db->flags & SQLITE_VdbeTrace ){
821 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
822 test_trace_breakpoint((int)(pOp - aOp),pOp,p);
824 #endif
827 /* Check to see if we need to simulate an interrupt. This only happens
828 ** if we have a special test build.
830 #ifdef SQLITE_TEST
831 if( sqlite3_interrupt_count>0 ){
832 sqlite3_interrupt_count--;
833 if( sqlite3_interrupt_count==0 ){
834 sqlite3_interrupt(db);
837 #endif
839 /* Sanity checking on other operands */
840 #ifdef SQLITE_DEBUG
842 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
843 if( (opProperty & OPFLG_IN1)!=0 ){
844 assert( pOp->p1>0 );
845 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
846 assert( memIsValid(&aMem[pOp->p1]) );
847 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
848 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
850 if( (opProperty & OPFLG_IN2)!=0 ){
851 assert( pOp->p2>0 );
852 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
853 assert( memIsValid(&aMem[pOp->p2]) );
854 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
855 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
857 if( (opProperty & OPFLG_IN3)!=0 ){
858 assert( pOp->p3>0 );
859 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
860 assert( memIsValid(&aMem[pOp->p3]) );
861 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
862 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
864 if( (opProperty & OPFLG_OUT2)!=0 ){
865 assert( pOp->p2>0 );
866 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
867 memAboutToChange(p, &aMem[pOp->p2]);
869 if( (opProperty & OPFLG_OUT3)!=0 ){
870 assert( pOp->p3>0 );
871 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
872 memAboutToChange(p, &aMem[pOp->p3]);
875 #endif
876 #ifdef SQLITE_DEBUG
877 pOrigOp = pOp;
878 #endif
880 switch( pOp->opcode ){
882 /*****************************************************************************
883 ** What follows is a massive switch statement where each case implements a
884 ** separate instruction in the virtual machine. If we follow the usual
885 ** indentation conventions, each case should be indented by 6 spaces. But
886 ** that is a lot of wasted space on the left margin. So the code within
887 ** the switch statement will break with convention and be flush-left. Another
888 ** big comment (similar to this one) will mark the point in the code where
889 ** we transition back to normal indentation.
891 ** The formatting of each case is important. The makefile for SQLite
892 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
893 ** file looking for lines that begin with "case OP_". The opcodes.h files
894 ** will be filled with #defines that give unique integer values to each
895 ** opcode and the opcodes.c file is filled with an array of strings where
896 ** each string is the symbolic name for the corresponding opcode. If the
897 ** case statement is followed by a comment of the form "/# same as ... #/"
898 ** that comment is used to determine the particular value of the opcode.
900 ** Other keywords in the comment that follows each case are used to
901 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
902 ** Keywords include: in1, in2, in3, out2, out3. See
903 ** the mkopcodeh.awk script for additional information.
905 ** Documentation about VDBE opcodes is generated by scanning this file
906 ** for lines of that contain "Opcode:". That line and all subsequent
907 ** comment lines are used in the generation of the opcode.html documentation
908 ** file.
910 ** SUMMARY:
912 ** Formatting is important to scripts that scan this file.
913 ** Do not deviate from the formatting style currently in use.
915 *****************************************************************************/
917 /* Opcode: Goto * P2 * * *
919 ** An unconditional jump to address P2.
920 ** The next instruction executed will be
921 ** the one at index P2 from the beginning of
922 ** the program.
924 ** The P1 parameter is not actually used by this opcode. However, it
925 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
926 ** that this Goto is the bottom of a loop and that the lines from P2 down
927 ** to the current line should be indented for EXPLAIN output.
929 case OP_Goto: { /* jump */
931 #ifdef SQLITE_DEBUG
932 /* In debuggging mode, when the p5 flags is set on an OP_Goto, that
933 ** means we should really jump back to the preceeding OP_ReleaseReg
934 ** instruction. */
935 if( pOp->p5 ){
936 assert( pOp->p2 < (int)(pOp - aOp) );
937 assert( pOp->p2 > 1 );
938 pOp = &aOp[pOp->p2 - 2];
939 assert( pOp[1].opcode==OP_ReleaseReg );
940 goto check_for_interrupt;
942 #endif
944 jump_to_p2_and_check_for_interrupt:
945 pOp = &aOp[pOp->p2 - 1];
947 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
948 ** OP_VNext, or OP_SorterNext) all jump here upon
949 ** completion. Check to see if sqlite3_interrupt() has been called
950 ** or if the progress callback needs to be invoked.
952 ** This code uses unstructured "goto" statements and does not look clean.
953 ** But that is not due to sloppy coding habits. The code is written this
954 ** way for performance, to avoid having to run the interrupt and progress
955 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
956 ** faster according to "valgrind --tool=cachegrind" */
957 check_for_interrupt:
958 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
959 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
960 /* Call the progress callback if it is configured and the required number
961 ** of VDBE ops have been executed (either since this invocation of
962 ** sqlite3VdbeExec() or since last time the progress callback was called).
963 ** If the progress callback returns non-zero, exit the virtual machine with
964 ** a return code SQLITE_ABORT.
966 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
967 assert( db->nProgressOps!=0 );
968 nProgressLimit += db->nProgressOps;
969 if( db->xProgress(db->pProgressArg) ){
970 nProgressLimit = LARGEST_UINT64;
971 rc = SQLITE_INTERRUPT;
972 goto abort_due_to_error;
975 #endif
977 break;
980 /* Opcode: Gosub P1 P2 * * *
982 ** Write the current address onto register P1
983 ** and then jump to address P2.
985 case OP_Gosub: { /* jump */
986 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
987 pIn1 = &aMem[pOp->p1];
988 assert( VdbeMemDynamic(pIn1)==0 );
989 memAboutToChange(p, pIn1);
990 pIn1->flags = MEM_Int;
991 pIn1->u.i = (int)(pOp-aOp);
992 REGISTER_TRACE(pOp->p1, pIn1);
993 goto jump_to_p2_and_check_for_interrupt;
996 /* Opcode: Return P1 P2 P3 * *
998 ** Jump to the address stored in register P1. If P1 is a return address
999 ** register, then this accomplishes a return from a subroutine.
1001 ** If P3 is 1, then the jump is only taken if register P1 holds an integer
1002 ** values, otherwise execution falls through to the next opcode, and the
1003 ** OP_Return becomes a no-op. If P3 is 0, then register P1 must hold an
1004 ** integer or else an assert() is raised. P3 should be set to 1 when
1005 ** this opcode is used in combination with OP_BeginSubrtn, and set to 0
1006 ** otherwise.
1008 ** The value in register P1 is unchanged by this opcode.
1010 ** P2 is not used by the byte-code engine. However, if P2 is positive
1011 ** and also less than the current address, then the "EXPLAIN" output
1012 ** formatter in the CLI will indent all opcodes from the P2 opcode up
1013 ** to be not including the current Return. P2 should be the first opcode
1014 ** in the subroutine from which this opcode is returning. Thus the P2
1015 ** value is a byte-code indentation hint. See tag-20220407a in
1016 ** wherecode.c and shell.c.
1018 case OP_Return: { /* in1 */
1019 pIn1 = &aMem[pOp->p1];
1020 if( pIn1->flags & MEM_Int ){
1021 if( pOp->p3 ){ VdbeBranchTaken(1, 2); }
1022 pOp = &aOp[pIn1->u.i];
1023 }else if( ALWAYS(pOp->p3) ){
1024 VdbeBranchTaken(0, 2);
1026 break;
1029 /* Opcode: InitCoroutine P1 P2 P3 * *
1031 ** Set up register P1 so that it will Yield to the coroutine
1032 ** located at address P3.
1034 ** If P2!=0 then the coroutine implementation immediately follows
1035 ** this opcode. So jump over the coroutine implementation to
1036 ** address P2.
1038 ** See also: EndCoroutine
1040 case OP_InitCoroutine: { /* jump */
1041 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1042 assert( pOp->p2>=0 && pOp->p2<p->nOp );
1043 assert( pOp->p3>=0 && pOp->p3<p->nOp );
1044 pOut = &aMem[pOp->p1];
1045 assert( !VdbeMemDynamic(pOut) );
1046 pOut->u.i = pOp->p3 - 1;
1047 pOut->flags = MEM_Int;
1048 if( pOp->p2==0 ) break;
1050 /* Most jump operations do a goto to this spot in order to update
1051 ** the pOp pointer. */
1052 jump_to_p2:
1053 assert( pOp->p2>0 ); /* There are never any jumps to instruction 0 */
1054 assert( pOp->p2<p->nOp ); /* Jumps must be in range */
1055 pOp = &aOp[pOp->p2 - 1];
1056 break;
1059 /* Opcode: EndCoroutine P1 * * * *
1061 ** The instruction at the address in register P1 is a Yield.
1062 ** Jump to the P2 parameter of that Yield.
1063 ** After the jump, register P1 becomes undefined.
1065 ** See also: InitCoroutine
1067 case OP_EndCoroutine: { /* in1 */
1068 VdbeOp *pCaller;
1069 pIn1 = &aMem[pOp->p1];
1070 assert( pIn1->flags==MEM_Int );
1071 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
1072 pCaller = &aOp[pIn1->u.i];
1073 assert( pCaller->opcode==OP_Yield );
1074 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
1075 pOp = &aOp[pCaller->p2 - 1];
1076 pIn1->flags = MEM_Undefined;
1077 break;
1080 /* Opcode: Yield P1 P2 * * *
1082 ** Swap the program counter with the value in register P1. This
1083 ** has the effect of yielding to a coroutine.
1085 ** If the coroutine that is launched by this instruction ends with
1086 ** Yield or Return then continue to the next instruction. But if
1087 ** the coroutine launched by this instruction ends with
1088 ** EndCoroutine, then jump to P2 rather than continuing with the
1089 ** next instruction.
1091 ** See also: InitCoroutine
1093 case OP_Yield: { /* in1, jump */
1094 int pcDest;
1095 pIn1 = &aMem[pOp->p1];
1096 assert( VdbeMemDynamic(pIn1)==0 );
1097 pIn1->flags = MEM_Int;
1098 pcDest = (int)pIn1->u.i;
1099 pIn1->u.i = (int)(pOp - aOp);
1100 REGISTER_TRACE(pOp->p1, pIn1);
1101 pOp = &aOp[pcDest];
1102 break;
1105 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
1106 ** Synopsis: if r[P3]=null halt
1108 ** Check the value in register P3. If it is NULL then Halt using
1109 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
1110 ** value in register P3 is not NULL, then this routine is a no-op.
1111 ** The P5 parameter should be 1.
1113 case OP_HaltIfNull: { /* in3 */
1114 pIn3 = &aMem[pOp->p3];
1115 #ifdef SQLITE_DEBUG
1116 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1117 #endif
1118 if( (pIn3->flags & MEM_Null)==0 ) break;
1119 /* Fall through into OP_Halt */
1120 /* no break */ deliberate_fall_through
1123 /* Opcode: Halt P1 P2 * P4 P5
1125 ** Exit immediately. All open cursors, etc are closed
1126 ** automatically.
1128 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
1129 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
1130 ** For errors, it can be some other value. If P1!=0 then P2 will determine
1131 ** whether or not to rollback the current transaction. Do not rollback
1132 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
1133 ** then back out all changes that have occurred during this execution of the
1134 ** VDBE, but do not rollback the transaction.
1136 ** If P4 is not null then it is an error message string.
1138 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
1140 ** 0: (no change)
1141 ** 1: NOT NULL contraint failed: P4
1142 ** 2: UNIQUE constraint failed: P4
1143 ** 3: CHECK constraint failed: P4
1144 ** 4: FOREIGN KEY constraint failed: P4
1146 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
1147 ** omitted.
1149 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
1150 ** every program. So a jump past the last instruction of the program
1151 ** is the same as executing Halt.
1153 case OP_Halt: {
1154 VdbeFrame *pFrame;
1155 int pcx;
1157 #ifdef SQLITE_DEBUG
1158 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1159 #endif
1161 /* A deliberately coded "OP_Halt SQLITE_INTERNAL * * * *" opcode indicates
1162 ** something is wrong with the code generator. Raise an assertion in order
1163 ** to bring this to the attention of fuzzers and other testing tools. */
1164 assert( pOp->p1!=SQLITE_INTERNAL );
1166 if( p->pFrame && pOp->p1==SQLITE_OK ){
1167 /* Halt the sub-program. Return control to the parent frame. */
1168 pFrame = p->pFrame;
1169 p->pFrame = pFrame->pParent;
1170 p->nFrame--;
1171 sqlite3VdbeSetChanges(db, p->nChange);
1172 pcx = sqlite3VdbeFrameRestore(pFrame);
1173 if( pOp->p2==OE_Ignore ){
1174 /* Instruction pcx is the OP_Program that invoked the sub-program
1175 ** currently being halted. If the p2 instruction of this OP_Halt
1176 ** instruction is set to OE_Ignore, then the sub-program is throwing
1177 ** an IGNORE exception. In this case jump to the address specified
1178 ** as the p2 of the calling OP_Program. */
1179 pcx = p->aOp[pcx].p2-1;
1181 aOp = p->aOp;
1182 aMem = p->aMem;
1183 pOp = &aOp[pcx];
1184 break;
1186 p->rc = pOp->p1;
1187 p->errorAction = (u8)pOp->p2;
1188 assert( pOp->p5<=4 );
1189 if( p->rc ){
1190 if( pOp->p5 ){
1191 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
1192 "FOREIGN KEY" };
1193 testcase( pOp->p5==1 );
1194 testcase( pOp->p5==2 );
1195 testcase( pOp->p5==3 );
1196 testcase( pOp->p5==4 );
1197 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
1198 if( pOp->p4.z ){
1199 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
1201 }else{
1202 sqlite3VdbeError(p, "%s", pOp->p4.z);
1204 pcx = (int)(pOp - aOp);
1205 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
1207 rc = sqlite3VdbeHalt(p);
1208 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1209 if( rc==SQLITE_BUSY ){
1210 p->rc = SQLITE_BUSY;
1211 }else{
1212 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1213 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1214 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1216 goto vdbe_return;
1219 /* Opcode: Integer P1 P2 * * *
1220 ** Synopsis: r[P2]=P1
1222 ** The 32-bit integer value P1 is written into register P2.
1224 case OP_Integer: { /* out2 */
1225 pOut = out2Prerelease(p, pOp);
1226 pOut->u.i = pOp->p1;
1227 break;
1230 /* Opcode: Int64 * P2 * P4 *
1231 ** Synopsis: r[P2]=P4
1233 ** P4 is a pointer to a 64-bit integer value.
1234 ** Write that value into register P2.
1236 case OP_Int64: { /* out2 */
1237 pOut = out2Prerelease(p, pOp);
1238 assert( pOp->p4.pI64!=0 );
1239 pOut->u.i = *pOp->p4.pI64;
1240 break;
1243 #ifndef SQLITE_OMIT_FLOATING_POINT
1244 /* Opcode: Real * P2 * P4 *
1245 ** Synopsis: r[P2]=P4
1247 ** P4 is a pointer to a 64-bit floating point value.
1248 ** Write that value into register P2.
1250 case OP_Real: { /* same as TK_FLOAT, out2 */
1251 pOut = out2Prerelease(p, pOp);
1252 pOut->flags = MEM_Real;
1253 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1254 pOut->u.r = *pOp->p4.pReal;
1255 break;
1257 #endif
1259 /* Opcode: String8 * P2 * P4 *
1260 ** Synopsis: r[P2]='P4'
1262 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1263 ** into a String opcode before it is executed for the first time. During
1264 ** this transformation, the length of string P4 is computed and stored
1265 ** as the P1 parameter.
1267 case OP_String8: { /* same as TK_STRING, out2 */
1268 assert( pOp->p4.z!=0 );
1269 pOut = out2Prerelease(p, pOp);
1270 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1272 #ifndef SQLITE_OMIT_UTF16
1273 if( encoding!=SQLITE_UTF8 ){
1274 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1275 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1276 if( rc ) goto too_big;
1277 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1278 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1279 assert( VdbeMemDynamic(pOut)==0 );
1280 pOut->szMalloc = 0;
1281 pOut->flags |= MEM_Static;
1282 if( pOp->p4type==P4_DYNAMIC ){
1283 sqlite3DbFree(db, pOp->p4.z);
1285 pOp->p4type = P4_DYNAMIC;
1286 pOp->p4.z = pOut->z;
1287 pOp->p1 = pOut->n;
1289 #endif
1290 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1291 goto too_big;
1293 pOp->opcode = OP_String;
1294 assert( rc==SQLITE_OK );
1295 /* Fall through to the next case, OP_String */
1296 /* no break */ deliberate_fall_through
1299 /* Opcode: String P1 P2 P3 P4 P5
1300 ** Synopsis: r[P2]='P4' (len=P1)
1302 ** The string value P4 of length P1 (bytes) is stored in register P2.
1304 ** If P3 is not zero and the content of register P3 is equal to P5, then
1305 ** the datatype of the register P2 is converted to BLOB. The content is
1306 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1307 ** of a string, as if it had been CAST. In other words:
1309 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1311 case OP_String: { /* out2 */
1312 assert( pOp->p4.z!=0 );
1313 pOut = out2Prerelease(p, pOp);
1314 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1315 pOut->z = pOp->p4.z;
1316 pOut->n = pOp->p1;
1317 pOut->enc = encoding;
1318 UPDATE_MAX_BLOBSIZE(pOut);
1319 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1320 if( pOp->p3>0 ){
1321 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1322 pIn3 = &aMem[pOp->p3];
1323 assert( pIn3->flags & MEM_Int );
1324 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1326 #endif
1327 break;
1330 /* Opcode: BeginSubrtn * P2 * * *
1331 ** Synopsis: r[P2]=NULL
1333 ** Mark the beginning of a subroutine that can be entered in-line
1334 ** or that can be called using OP_Gosub. The subroutine should
1335 ** be terminated by an OP_Return instruction that has a P1 operand that
1336 ** is the same as the P2 operand to this opcode and that has P3 set to 1.
1337 ** If the subroutine is entered in-line, then the OP_Return will simply
1338 ** fall through. But if the subroutine is entered using OP_Gosub, then
1339 ** the OP_Return will jump back to the first instruction after the OP_Gosub.
1341 ** This routine works by loading a NULL into the P2 register. When the
1342 ** return address register contains a NULL, the OP_Return instruction is
1343 ** a no-op that simply falls through to the next instruction (assuming that
1344 ** the OP_Return opcode has a P3 value of 1). Thus if the subroutine is
1345 ** entered in-line, then the OP_Return will cause in-line execution to
1346 ** continue. But if the subroutine is entered via OP_Gosub, then the
1347 ** OP_Return will cause a return to the address following the OP_Gosub.
1349 ** This opcode is identical to OP_Null. It has a different name
1350 ** only to make the byte code easier to read and verify.
1352 /* Opcode: Null P1 P2 P3 * *
1353 ** Synopsis: r[P2..P3]=NULL
1355 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1356 ** NULL into register P3 and every register in between P2 and P3. If P3
1357 ** is less than P2 (typically P3 is zero) then only register P2 is
1358 ** set to NULL.
1360 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1361 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1362 ** OP_Ne or OP_Eq.
1364 case OP_BeginSubrtn:
1365 case OP_Null: { /* out2 */
1366 int cnt;
1367 u16 nullFlag;
1368 pOut = out2Prerelease(p, pOp);
1369 cnt = pOp->p3-pOp->p2;
1370 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1371 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1372 pOut->n = 0;
1373 #ifdef SQLITE_DEBUG
1374 pOut->uTemp = 0;
1375 #endif
1376 while( cnt>0 ){
1377 pOut++;
1378 memAboutToChange(p, pOut);
1379 sqlite3VdbeMemSetNull(pOut);
1380 pOut->flags = nullFlag;
1381 pOut->n = 0;
1382 cnt--;
1384 break;
1387 /* Opcode: SoftNull P1 * * * *
1388 ** Synopsis: r[P1]=NULL
1390 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1391 ** instruction, but do not free any string or blob memory associated with
1392 ** the register, so that if the value was a string or blob that was
1393 ** previously copied using OP_SCopy, the copies will continue to be valid.
1395 case OP_SoftNull: {
1396 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1397 pOut = &aMem[pOp->p1];
1398 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1399 break;
1402 /* Opcode: Blob P1 P2 * P4 *
1403 ** Synopsis: r[P2]=P4 (len=P1)
1405 ** P4 points to a blob of data P1 bytes long. Store this
1406 ** blob in register P2. If P4 is a NULL pointer, then construct
1407 ** a zero-filled blob that is P1 bytes long in P2.
1409 case OP_Blob: { /* out2 */
1410 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1411 pOut = out2Prerelease(p, pOp);
1412 if( pOp->p4.z==0 ){
1413 sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
1414 if( sqlite3VdbeMemExpandBlob(pOut) ) goto no_mem;
1415 }else{
1416 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1418 pOut->enc = encoding;
1419 UPDATE_MAX_BLOBSIZE(pOut);
1420 break;
1423 /* Opcode: Variable P1 P2 * P4 *
1424 ** Synopsis: r[P2]=parameter(P1,P4)
1426 ** Transfer the values of bound parameter P1 into register P2
1428 ** If the parameter is named, then its name appears in P4.
1429 ** The P4 value is used by sqlite3_bind_parameter_name().
1431 case OP_Variable: { /* out2 */
1432 Mem *pVar; /* Value being transferred */
1434 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1435 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1436 pVar = &p->aVar[pOp->p1 - 1];
1437 if( sqlite3VdbeMemTooBig(pVar) ){
1438 goto too_big;
1440 pOut = &aMem[pOp->p2];
1441 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
1442 memcpy(pOut, pVar, MEMCELLSIZE);
1443 pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
1444 pOut->flags |= MEM_Static|MEM_FromBind;
1445 UPDATE_MAX_BLOBSIZE(pOut);
1446 break;
1449 /* Opcode: Move P1 P2 P3 * *
1450 ** Synopsis: r[P2@P3]=r[P1@P3]
1452 ** Move the P3 values in register P1..P1+P3-1 over into
1453 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1454 ** left holding a NULL. It is an error for register ranges
1455 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1456 ** for P3 to be less than 1.
1458 case OP_Move: {
1459 int n; /* Number of registers left to copy */
1460 int p1; /* Register to copy from */
1461 int p2; /* Register to copy to */
1463 n = pOp->p3;
1464 p1 = pOp->p1;
1465 p2 = pOp->p2;
1466 assert( n>0 && p1>0 && p2>0 );
1467 assert( p1+n<=p2 || p2+n<=p1 );
1469 pIn1 = &aMem[p1];
1470 pOut = &aMem[p2];
1472 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1473 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1474 assert( memIsValid(pIn1) );
1475 memAboutToChange(p, pOut);
1476 sqlite3VdbeMemMove(pOut, pIn1);
1477 #ifdef SQLITE_DEBUG
1478 pIn1->pScopyFrom = 0;
1479 { int i;
1480 for(i=1; i<p->nMem; i++){
1481 if( aMem[i].pScopyFrom==pIn1 ){
1482 aMem[i].pScopyFrom = pOut;
1486 #endif
1487 Deephemeralize(pOut);
1488 REGISTER_TRACE(p2++, pOut);
1489 pIn1++;
1490 pOut++;
1491 }while( --n );
1492 break;
1495 /* Opcode: Copy P1 P2 P3 * P5
1496 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1498 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1500 ** If the 0x0002 bit of P5 is set then also clear the MEM_Subtype flag in the
1501 ** destination. The 0x0001 bit of P5 indicates that this Copy opcode cannot
1502 ** be merged. The 0x0001 bit is used by the query planner and does not
1503 ** come into play during query execution.
1505 ** This instruction makes a deep copy of the value. A duplicate
1506 ** is made of any string or blob constant. See also OP_SCopy.
1508 case OP_Copy: {
1509 int n;
1511 n = pOp->p3;
1512 pIn1 = &aMem[pOp->p1];
1513 pOut = &aMem[pOp->p2];
1514 assert( pOut!=pIn1 );
1515 while( 1 ){
1516 memAboutToChange(p, pOut);
1517 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1518 Deephemeralize(pOut);
1519 if( (pOut->flags & MEM_Subtype)!=0 && (pOp->p5 & 0x0002)!=0 ){
1520 pOut->flags &= ~MEM_Subtype;
1522 #ifdef SQLITE_DEBUG
1523 pOut->pScopyFrom = 0;
1524 #endif
1525 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1526 if( (n--)==0 ) break;
1527 pOut++;
1528 pIn1++;
1530 break;
1533 /* Opcode: SCopy P1 P2 * * *
1534 ** Synopsis: r[P2]=r[P1]
1536 ** Make a shallow copy of register P1 into register P2.
1538 ** This instruction makes a shallow copy of the value. If the value
1539 ** is a string or blob, then the copy is only a pointer to the
1540 ** original and hence if the original changes so will the copy.
1541 ** Worse, if the original is deallocated, the copy becomes invalid.
1542 ** Thus the program must guarantee that the original will not change
1543 ** during the lifetime of the copy. Use OP_Copy to make a complete
1544 ** copy.
1546 case OP_SCopy: { /* out2 */
1547 pIn1 = &aMem[pOp->p1];
1548 pOut = &aMem[pOp->p2];
1549 assert( pOut!=pIn1 );
1550 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1551 #ifdef SQLITE_DEBUG
1552 pOut->pScopyFrom = pIn1;
1553 pOut->mScopyFlags = pIn1->flags;
1554 #endif
1555 break;
1558 /* Opcode: IntCopy P1 P2 * * *
1559 ** Synopsis: r[P2]=r[P1]
1561 ** Transfer the integer value held in register P1 into register P2.
1563 ** This is an optimized version of SCopy that works only for integer
1564 ** values.
1566 case OP_IntCopy: { /* out2 */
1567 pIn1 = &aMem[pOp->p1];
1568 assert( (pIn1->flags & MEM_Int)!=0 );
1569 pOut = &aMem[pOp->p2];
1570 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1571 break;
1574 /* Opcode: FkCheck * * * * *
1576 ** Halt with an SQLITE_CONSTRAINT error if there are any unresolved
1577 ** foreign key constraint violations. If there are no foreign key
1578 ** constraint violations, this is a no-op.
1580 ** FK constraint violations are also checked when the prepared statement
1581 ** exits. This opcode is used to raise foreign key constraint errors prior
1582 ** to returning results such as a row change count or the result of a
1583 ** RETURNING clause.
1585 case OP_FkCheck: {
1586 if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){
1587 goto abort_due_to_error;
1589 break;
1592 /* Opcode: ResultRow P1 P2 * * *
1593 ** Synopsis: output=r[P1@P2]
1595 ** The registers P1 through P1+P2-1 contain a single row of
1596 ** results. This opcode causes the sqlite3_step() call to terminate
1597 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1598 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1599 ** the result row.
1601 case OP_ResultRow: {
1602 assert( p->nResColumn==pOp->p2 );
1603 assert( pOp->p1>0 || CORRUPT_DB );
1604 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1606 p->cacheCtr = (p->cacheCtr + 2)|1;
1607 p->pResultRow = &aMem[pOp->p1];
1608 #ifdef SQLITE_DEBUG
1610 Mem *pMem = p->pResultRow;
1611 int i;
1612 for(i=0; i<pOp->p2; i++){
1613 assert( memIsValid(&pMem[i]) );
1614 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1615 /* The registers in the result will not be used again when the
1616 ** prepared statement restarts. This is because sqlite3_column()
1617 ** APIs might have caused type conversions of made other changes to
1618 ** the register values. Therefore, we can go ahead and break any
1619 ** OP_SCopy dependencies. */
1620 pMem[i].pScopyFrom = 0;
1623 #endif
1624 if( db->mallocFailed ) goto no_mem;
1625 if( db->mTrace & SQLITE_TRACE_ROW ){
1626 db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1628 p->pc = (int)(pOp - aOp) + 1;
1629 rc = SQLITE_ROW;
1630 goto vdbe_return;
1633 /* Opcode: Concat P1 P2 P3 * *
1634 ** Synopsis: r[P3]=r[P2]+r[P1]
1636 ** Add the text in register P1 onto the end of the text in
1637 ** register P2 and store the result in register P3.
1638 ** If either the P1 or P2 text are NULL then store NULL in P3.
1640 ** P3 = P2 || P1
1642 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1643 ** if P3 is the same register as P2, the implementation is able
1644 ** to avoid a memcpy().
1646 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1647 i64 nByte; /* Total size of the output string or blob */
1648 u16 flags1; /* Initial flags for P1 */
1649 u16 flags2; /* Initial flags for P2 */
1651 pIn1 = &aMem[pOp->p1];
1652 pIn2 = &aMem[pOp->p2];
1653 pOut = &aMem[pOp->p3];
1654 testcase( pOut==pIn2 );
1655 assert( pIn1!=pOut );
1656 flags1 = pIn1->flags;
1657 testcase( flags1 & MEM_Null );
1658 testcase( pIn2->flags & MEM_Null );
1659 if( (flags1 | pIn2->flags) & MEM_Null ){
1660 sqlite3VdbeMemSetNull(pOut);
1661 break;
1663 if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
1664 if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
1665 flags1 = pIn1->flags & ~MEM_Str;
1666 }else if( (flags1 & MEM_Zero)!=0 ){
1667 if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
1668 flags1 = pIn1->flags & ~MEM_Str;
1670 flags2 = pIn2->flags;
1671 if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
1672 if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
1673 flags2 = pIn2->flags & ~MEM_Str;
1674 }else if( (flags2 & MEM_Zero)!=0 ){
1675 if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
1676 flags2 = pIn2->flags & ~MEM_Str;
1678 nByte = pIn1->n + pIn2->n;
1679 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1680 goto too_big;
1682 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1683 goto no_mem;
1685 MemSetTypeFlag(pOut, MEM_Str);
1686 if( pOut!=pIn2 ){
1687 memcpy(pOut->z, pIn2->z, pIn2->n);
1688 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
1689 pIn2->flags = flags2;
1691 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1692 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1693 pIn1->flags = flags1;
1694 if( encoding>SQLITE_UTF8 ) nByte &= ~1;
1695 pOut->z[nByte]=0;
1696 pOut->z[nByte+1] = 0;
1697 pOut->flags |= MEM_Term;
1698 pOut->n = (int)nByte;
1699 pOut->enc = encoding;
1700 UPDATE_MAX_BLOBSIZE(pOut);
1701 break;
1704 /* Opcode: Add P1 P2 P3 * *
1705 ** Synopsis: r[P3]=r[P1]+r[P2]
1707 ** Add the value in register P1 to the value in register P2
1708 ** and store the result in register P3.
1709 ** If either input is NULL, the result is NULL.
1711 /* Opcode: Multiply P1 P2 P3 * *
1712 ** Synopsis: r[P3]=r[P1]*r[P2]
1715 ** Multiply the value in register P1 by the value in register P2
1716 ** and store the result in register P3.
1717 ** If either input is NULL, the result is NULL.
1719 /* Opcode: Subtract P1 P2 P3 * *
1720 ** Synopsis: r[P3]=r[P2]-r[P1]
1722 ** Subtract the value in register P1 from the value in register P2
1723 ** and store the result in register P3.
1724 ** If either input is NULL, the result is NULL.
1726 /* Opcode: Divide P1 P2 P3 * *
1727 ** Synopsis: r[P3]=r[P2]/r[P1]
1729 ** Divide the value in register P1 by the value in register P2
1730 ** and store the result in register P3 (P3=P2/P1). If the value in
1731 ** register P1 is zero, then the result is NULL. If either input is
1732 ** NULL, the result is NULL.
1734 /* Opcode: Remainder P1 P2 P3 * *
1735 ** Synopsis: r[P3]=r[P2]%r[P1]
1737 ** Compute the remainder after integer register P2 is divided by
1738 ** register P1 and store the result in register P3.
1739 ** If the value in register P1 is zero the result is NULL.
1740 ** If either operand is NULL, the result is NULL.
1742 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1743 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1744 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1745 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1746 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1747 u16 type1; /* Numeric type of left operand */
1748 u16 type2; /* Numeric type of right operand */
1749 i64 iA; /* Integer value of left operand */
1750 i64 iB; /* Integer value of right operand */
1751 double rA; /* Real value of left operand */
1752 double rB; /* Real value of right operand */
1754 pIn1 = &aMem[pOp->p1];
1755 type1 = pIn1->flags;
1756 pIn2 = &aMem[pOp->p2];
1757 type2 = pIn2->flags;
1758 pOut = &aMem[pOp->p3];
1759 if( (type1 & type2 & MEM_Int)!=0 ){
1760 int_math:
1761 iA = pIn1->u.i;
1762 iB = pIn2->u.i;
1763 switch( pOp->opcode ){
1764 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1765 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1766 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1767 case OP_Divide: {
1768 if( iA==0 ) goto arithmetic_result_is_null;
1769 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1770 iB /= iA;
1771 break;
1773 default: {
1774 if( iA==0 ) goto arithmetic_result_is_null;
1775 if( iA==-1 ) iA = 1;
1776 iB %= iA;
1777 break;
1780 pOut->u.i = iB;
1781 MemSetTypeFlag(pOut, MEM_Int);
1782 }else if( ((type1 | type2) & MEM_Null)!=0 ){
1783 goto arithmetic_result_is_null;
1784 }else{
1785 type1 = numericType(pIn1);
1786 type2 = numericType(pIn2);
1787 if( (type1 & type2 & MEM_Int)!=0 ) goto int_math;
1788 fp_math:
1789 rA = sqlite3VdbeRealValue(pIn1);
1790 rB = sqlite3VdbeRealValue(pIn2);
1791 switch( pOp->opcode ){
1792 case OP_Add: rB += rA; break;
1793 case OP_Subtract: rB -= rA; break;
1794 case OP_Multiply: rB *= rA; break;
1795 case OP_Divide: {
1796 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1797 if( rA==(double)0 ) goto arithmetic_result_is_null;
1798 rB /= rA;
1799 break;
1801 default: {
1802 iA = sqlite3VdbeIntValue(pIn1);
1803 iB = sqlite3VdbeIntValue(pIn2);
1804 if( iA==0 ) goto arithmetic_result_is_null;
1805 if( iA==-1 ) iA = 1;
1806 rB = (double)(iB % iA);
1807 break;
1810 #ifdef SQLITE_OMIT_FLOATING_POINT
1811 pOut->u.i = rB;
1812 MemSetTypeFlag(pOut, MEM_Int);
1813 #else
1814 if( sqlite3IsNaN(rB) ){
1815 goto arithmetic_result_is_null;
1817 pOut->u.r = rB;
1818 MemSetTypeFlag(pOut, MEM_Real);
1819 #endif
1821 break;
1823 arithmetic_result_is_null:
1824 sqlite3VdbeMemSetNull(pOut);
1825 break;
1828 /* Opcode: CollSeq P1 * * P4
1830 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1831 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1832 ** be returned. This is used by the built-in min(), max() and nullif()
1833 ** functions.
1835 ** If P1 is not zero, then it is a register that a subsequent min() or
1836 ** max() aggregate will set to 1 if the current row is not the minimum or
1837 ** maximum. The P1 register is initialized to 0 by this instruction.
1839 ** The interface used by the implementation of the aforementioned functions
1840 ** to retrieve the collation sequence set by this opcode is not available
1841 ** publicly. Only built-in functions have access to this feature.
1843 case OP_CollSeq: {
1844 assert( pOp->p4type==P4_COLLSEQ );
1845 if( pOp->p1 ){
1846 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1848 break;
1851 /* Opcode: BitAnd P1 P2 P3 * *
1852 ** Synopsis: r[P3]=r[P1]&r[P2]
1854 ** Take the bit-wise AND of the values in register P1 and P2 and
1855 ** store the result in register P3.
1856 ** If either input is NULL, the result is NULL.
1858 /* Opcode: BitOr P1 P2 P3 * *
1859 ** Synopsis: r[P3]=r[P1]|r[P2]
1861 ** Take the bit-wise OR of the values in register P1 and P2 and
1862 ** store the result in register P3.
1863 ** If either input is NULL, the result is NULL.
1865 /* Opcode: ShiftLeft P1 P2 P3 * *
1866 ** Synopsis: r[P3]=r[P2]<<r[P1]
1868 ** Shift the integer value in register P2 to the left by the
1869 ** number of bits specified by the integer in register P1.
1870 ** Store the result in register P3.
1871 ** If either input is NULL, the result is NULL.
1873 /* Opcode: ShiftRight P1 P2 P3 * *
1874 ** Synopsis: r[P3]=r[P2]>>r[P1]
1876 ** Shift the integer value in register P2 to the right by the
1877 ** number of bits specified by the integer in register P1.
1878 ** Store the result in register P3.
1879 ** If either input is NULL, the result is NULL.
1881 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1882 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1883 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1884 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1885 i64 iA;
1886 u64 uA;
1887 i64 iB;
1888 u8 op;
1890 pIn1 = &aMem[pOp->p1];
1891 pIn2 = &aMem[pOp->p2];
1892 pOut = &aMem[pOp->p3];
1893 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1894 sqlite3VdbeMemSetNull(pOut);
1895 break;
1897 iA = sqlite3VdbeIntValue(pIn2);
1898 iB = sqlite3VdbeIntValue(pIn1);
1899 op = pOp->opcode;
1900 if( op==OP_BitAnd ){
1901 iA &= iB;
1902 }else if( op==OP_BitOr ){
1903 iA |= iB;
1904 }else if( iB!=0 ){
1905 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1907 /* If shifting by a negative amount, shift in the other direction */
1908 if( iB<0 ){
1909 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1910 op = 2*OP_ShiftLeft + 1 - op;
1911 iB = iB>(-64) ? -iB : 64;
1914 if( iB>=64 ){
1915 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1916 }else{
1917 memcpy(&uA, &iA, sizeof(uA));
1918 if( op==OP_ShiftLeft ){
1919 uA <<= iB;
1920 }else{
1921 uA >>= iB;
1922 /* Sign-extend on a right shift of a negative number */
1923 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1925 memcpy(&iA, &uA, sizeof(iA));
1928 pOut->u.i = iA;
1929 MemSetTypeFlag(pOut, MEM_Int);
1930 break;
1933 /* Opcode: AddImm P1 P2 * * *
1934 ** Synopsis: r[P1]=r[P1]+P2
1936 ** Add the constant P2 to the value in register P1.
1937 ** The result is always an integer.
1939 ** To force any register to be an integer, just add 0.
1941 case OP_AddImm: { /* in1 */
1942 pIn1 = &aMem[pOp->p1];
1943 memAboutToChange(p, pIn1);
1944 sqlite3VdbeMemIntegerify(pIn1);
1945 pIn1->u.i += pOp->p2;
1946 break;
1949 /* Opcode: MustBeInt P1 P2 * * *
1951 ** Force the value in register P1 to be an integer. If the value
1952 ** in P1 is not an integer and cannot be converted into an integer
1953 ** without data loss, then jump immediately to P2, or if P2==0
1954 ** raise an SQLITE_MISMATCH exception.
1956 case OP_MustBeInt: { /* jump, in1 */
1957 pIn1 = &aMem[pOp->p1];
1958 if( (pIn1->flags & MEM_Int)==0 ){
1959 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1960 if( (pIn1->flags & MEM_Int)==0 ){
1961 VdbeBranchTaken(1, 2);
1962 if( pOp->p2==0 ){
1963 rc = SQLITE_MISMATCH;
1964 goto abort_due_to_error;
1965 }else{
1966 goto jump_to_p2;
1970 VdbeBranchTaken(0, 2);
1971 MemSetTypeFlag(pIn1, MEM_Int);
1972 break;
1975 #ifndef SQLITE_OMIT_FLOATING_POINT
1976 /* Opcode: RealAffinity P1 * * * *
1978 ** If register P1 holds an integer convert it to a real value.
1980 ** This opcode is used when extracting information from a column that
1981 ** has REAL affinity. Such column values may still be stored as
1982 ** integers, for space efficiency, but after extraction we want them
1983 ** to have only a real value.
1985 case OP_RealAffinity: { /* in1 */
1986 pIn1 = &aMem[pOp->p1];
1987 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
1988 testcase( pIn1->flags & MEM_Int );
1989 testcase( pIn1->flags & MEM_IntReal );
1990 sqlite3VdbeMemRealify(pIn1);
1991 REGISTER_TRACE(pOp->p1, pIn1);
1993 break;
1995 #endif
1997 #ifndef SQLITE_OMIT_CAST
1998 /* Opcode: Cast P1 P2 * * *
1999 ** Synopsis: affinity(r[P1])
2001 ** Force the value in register P1 to be the type defined by P2.
2003 ** <ul>
2004 ** <li> P2=='A' &rarr; BLOB
2005 ** <li> P2=='B' &rarr; TEXT
2006 ** <li> P2=='C' &rarr; NUMERIC
2007 ** <li> P2=='D' &rarr; INTEGER
2008 ** <li> P2=='E' &rarr; REAL
2009 ** </ul>
2011 ** A NULL value is not changed by this routine. It remains NULL.
2013 case OP_Cast: { /* in1 */
2014 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
2015 testcase( pOp->p2==SQLITE_AFF_TEXT );
2016 testcase( pOp->p2==SQLITE_AFF_BLOB );
2017 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
2018 testcase( pOp->p2==SQLITE_AFF_INTEGER );
2019 testcase( pOp->p2==SQLITE_AFF_REAL );
2020 pIn1 = &aMem[pOp->p1];
2021 memAboutToChange(p, pIn1);
2022 rc = ExpandBlob(pIn1);
2023 if( rc ) goto abort_due_to_error;
2024 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
2025 if( rc ) goto abort_due_to_error;
2026 UPDATE_MAX_BLOBSIZE(pIn1);
2027 REGISTER_TRACE(pOp->p1, pIn1);
2028 break;
2030 #endif /* SQLITE_OMIT_CAST */
2032 /* Opcode: Eq P1 P2 P3 P4 P5
2033 ** Synopsis: IF r[P3]==r[P1]
2035 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
2036 ** jump to address P2.
2038 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2039 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2040 ** to coerce both inputs according to this affinity before the
2041 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2042 ** affinity is used. Note that the affinity conversions are stored
2043 ** back into the input registers P1 and P3. So this opcode can cause
2044 ** persistent changes to registers P1 and P3.
2046 ** Once any conversions have taken place, and neither value is NULL,
2047 ** the values are compared. If both values are blobs then memcmp() is
2048 ** used to determine the results of the comparison. If both values
2049 ** are text, then the appropriate collating function specified in
2050 ** P4 is used to do the comparison. If P4 is not specified then
2051 ** memcmp() is used to compare text string. If both values are
2052 ** numeric, then a numeric comparison is used. If the two values
2053 ** are of different types, then numbers are considered less than
2054 ** strings and strings are considered less than blobs.
2056 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
2057 ** true or false and is never NULL. If both operands are NULL then the result
2058 ** of comparison is true. If either operand is NULL then the result is false.
2059 ** If neither operand is NULL the result is the same as it would be if
2060 ** the SQLITE_NULLEQ flag were omitted from P5.
2062 ** This opcode saves the result of comparison for use by the new
2063 ** OP_Jump opcode.
2065 /* Opcode: Ne P1 P2 P3 P4 P5
2066 ** Synopsis: IF r[P3]!=r[P1]
2068 ** This works just like the Eq opcode except that the jump is taken if
2069 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
2070 ** additional information.
2072 /* Opcode: Lt P1 P2 P3 P4 P5
2073 ** Synopsis: IF r[P3]<r[P1]
2075 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
2076 ** jump to address P2.
2078 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
2079 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
2080 ** bit is clear then fall through if either operand is NULL.
2082 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2083 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2084 ** to coerce both inputs according to this affinity before the
2085 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2086 ** affinity is used. Note that the affinity conversions are stored
2087 ** back into the input registers P1 and P3. So this opcode can cause
2088 ** persistent changes to registers P1 and P3.
2090 ** Once any conversions have taken place, and neither value is NULL,
2091 ** the values are compared. If both values are blobs then memcmp() is
2092 ** used to determine the results of the comparison. If both values
2093 ** are text, then the appropriate collating function specified in
2094 ** P4 is used to do the comparison. If P4 is not specified then
2095 ** memcmp() is used to compare text string. If both values are
2096 ** numeric, then a numeric comparison is used. If the two values
2097 ** are of different types, then numbers are considered less than
2098 ** strings and strings are considered less than blobs.
2100 ** This opcode saves the result of comparison for use by the new
2101 ** OP_Jump opcode.
2103 /* Opcode: Le P1 P2 P3 P4 P5
2104 ** Synopsis: IF r[P3]<=r[P1]
2106 ** This works just like the Lt opcode except that the jump is taken if
2107 ** the content of register P3 is less than or equal to the content of
2108 ** register P1. See the Lt opcode for additional information.
2110 /* Opcode: Gt P1 P2 P3 P4 P5
2111 ** Synopsis: IF r[P3]>r[P1]
2113 ** This works just like the Lt opcode except that the jump is taken if
2114 ** the content of register P3 is greater than the content of
2115 ** register P1. See the Lt opcode for additional information.
2117 /* Opcode: Ge P1 P2 P3 P4 P5
2118 ** Synopsis: IF r[P3]>=r[P1]
2120 ** This works just like the Lt opcode except that the jump is taken if
2121 ** the content of register P3 is greater than or equal to the content of
2122 ** register P1. See the Lt opcode for additional information.
2124 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
2125 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
2126 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
2127 case OP_Le: /* same as TK_LE, jump, in1, in3 */
2128 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
2129 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
2130 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
2131 char affinity; /* Affinity to use for comparison */
2132 u16 flags1; /* Copy of initial value of pIn1->flags */
2133 u16 flags3; /* Copy of initial value of pIn3->flags */
2135 pIn1 = &aMem[pOp->p1];
2136 pIn3 = &aMem[pOp->p3];
2137 flags1 = pIn1->flags;
2138 flags3 = pIn3->flags;
2139 if( (flags1 & flags3 & MEM_Int)!=0 ){
2140 /* Common case of comparison of two integers */
2141 if( pIn3->u.i > pIn1->u.i ){
2142 if( sqlite3aGTb[pOp->opcode] ){
2143 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2144 goto jump_to_p2;
2146 iCompare = +1;
2147 VVA_ONLY( iCompareIsInit = 1; )
2148 }else if( pIn3->u.i < pIn1->u.i ){
2149 if( sqlite3aLTb[pOp->opcode] ){
2150 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2151 goto jump_to_p2;
2153 iCompare = -1;
2154 VVA_ONLY( iCompareIsInit = 1; )
2155 }else{
2156 if( sqlite3aEQb[pOp->opcode] ){
2157 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2158 goto jump_to_p2;
2160 iCompare = 0;
2161 VVA_ONLY( iCompareIsInit = 1; )
2163 VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2164 break;
2166 if( (flags1 | flags3)&MEM_Null ){
2167 /* One or both operands are NULL */
2168 if( pOp->p5 & SQLITE_NULLEQ ){
2169 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
2170 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
2171 ** or not both operands are null.
2173 assert( (flags1 & MEM_Cleared)==0 );
2174 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
2175 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
2176 if( (flags1&flags3&MEM_Null)!=0
2177 && (flags3&MEM_Cleared)==0
2179 res = 0; /* Operands are equal */
2180 }else{
2181 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
2183 }else{
2184 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
2185 ** then the result is always NULL.
2186 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
2188 VdbeBranchTaken(2,3);
2189 if( pOp->p5 & SQLITE_JUMPIFNULL ){
2190 goto jump_to_p2;
2192 iCompare = 1; /* Operands are not equal */
2193 VVA_ONLY( iCompareIsInit = 1; )
2194 break;
2196 }else{
2197 /* Neither operand is NULL and we couldn't do the special high-speed
2198 ** integer comparison case. So do a general-case comparison. */
2199 affinity = pOp->p5 & SQLITE_AFF_MASK;
2200 if( affinity>=SQLITE_AFF_NUMERIC ){
2201 if( (flags1 | flags3)&MEM_Str ){
2202 if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2203 applyNumericAffinity(pIn1,0);
2204 assert( flags3==pIn3->flags || CORRUPT_DB );
2205 flags3 = pIn3->flags;
2207 if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2208 applyNumericAffinity(pIn3,0);
2211 }else if( affinity==SQLITE_AFF_TEXT && ((flags1 | flags3) & MEM_Str)!=0 ){
2212 if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2213 testcase( pIn1->flags & MEM_Int );
2214 testcase( pIn1->flags & MEM_Real );
2215 testcase( pIn1->flags & MEM_IntReal );
2216 sqlite3VdbeMemStringify(pIn1, encoding, 1);
2217 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
2218 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
2219 if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
2221 if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2222 testcase( pIn3->flags & MEM_Int );
2223 testcase( pIn3->flags & MEM_Real );
2224 testcase( pIn3->flags & MEM_IntReal );
2225 sqlite3VdbeMemStringify(pIn3, encoding, 1);
2226 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
2227 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
2230 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
2231 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
2234 /* At this point, res is negative, zero, or positive if reg[P1] is
2235 ** less than, equal to, or greater than reg[P3], respectively. Compute
2236 ** the answer to this operator in res2, depending on what the comparison
2237 ** operator actually is. The next block of code depends on the fact
2238 ** that the 6 comparison operators are consecutive integers in this
2239 ** order: NE, EQ, GT, LE, LT, GE */
2240 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
2241 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
2242 if( res<0 ){
2243 res2 = sqlite3aLTb[pOp->opcode];
2244 }else if( res==0 ){
2245 res2 = sqlite3aEQb[pOp->opcode];
2246 }else{
2247 res2 = sqlite3aGTb[pOp->opcode];
2249 iCompare = res;
2250 VVA_ONLY( iCompareIsInit = 1; )
2252 /* Undo any changes made by applyAffinity() to the input registers. */
2253 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
2254 pIn3->flags = flags3;
2255 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
2256 pIn1->flags = flags1;
2258 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2259 if( res2 ){
2260 goto jump_to_p2;
2262 break;
2265 /* Opcode: ElseEq * P2 * * *
2267 ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
2268 ** can be zero or more OP_ReleaseReg opcodes intervening, but no other
2269 ** opcodes are allowed to occur between this instruction and the previous
2270 ** OP_Lt or OP_Gt.
2272 ** If result of an OP_Eq comparison on the same two operands as the
2273 ** prior OP_Lt or OP_Gt would have been true, then jump to P2.
2274 ** If the result of an OP_Eq comparison on the two previous
2275 ** operands would have been false or NULL, then fall through.
2277 case OP_ElseEq: { /* same as TK_ESCAPE, jump */
2279 #ifdef SQLITE_DEBUG
2280 /* Verify the preconditions of this opcode - that it follows an OP_Lt or
2281 ** OP_Gt with zero or more intervening OP_ReleaseReg opcodes */
2282 int iAddr;
2283 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
2284 if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
2285 assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
2286 break;
2288 #endif /* SQLITE_DEBUG */
2289 assert( iCompareIsInit );
2290 VdbeBranchTaken(iCompare==0, 2);
2291 if( iCompare==0 ) goto jump_to_p2;
2292 break;
2296 /* Opcode: Permutation * * * P4 *
2298 ** Set the permutation used by the OP_Compare operator in the next
2299 ** instruction. The permutation is stored in the P4 operand.
2301 ** The permutation is only valid for the next opcode which must be
2302 ** an OP_Compare that has the OPFLAG_PERMUTE bit set in P5.
2304 ** The first integer in the P4 integer array is the length of the array
2305 ** and does not become part of the permutation.
2307 case OP_Permutation: {
2308 assert( pOp->p4type==P4_INTARRAY );
2309 assert( pOp->p4.ai );
2310 assert( pOp[1].opcode==OP_Compare );
2311 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2312 break;
2315 /* Opcode: Compare P1 P2 P3 P4 P5
2316 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2318 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2319 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2320 ** the comparison for use by the next OP_Jump instruct.
2322 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2323 ** determined by the most recent OP_Permutation operator. If the
2324 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2325 ** order.
2327 ** P4 is a KeyInfo structure that defines collating sequences and sort
2328 ** orders for the comparison. The permutation applies to registers
2329 ** only. The KeyInfo elements are used sequentially.
2331 ** The comparison is a sort comparison, so NULLs compare equal,
2332 ** NULLs are less than numbers, numbers are less than strings,
2333 ** and strings are less than blobs.
2335 ** This opcode must be immediately followed by an OP_Jump opcode.
2337 case OP_Compare: {
2338 int n;
2339 int i;
2340 int p1;
2341 int p2;
2342 const KeyInfo *pKeyInfo;
2343 u32 idx;
2344 CollSeq *pColl; /* Collating sequence to use on this term */
2345 int bRev; /* True for DESCENDING sort order */
2346 u32 *aPermute; /* The permutation */
2348 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2349 aPermute = 0;
2350 }else{
2351 assert( pOp>aOp );
2352 assert( pOp[-1].opcode==OP_Permutation );
2353 assert( pOp[-1].p4type==P4_INTARRAY );
2354 aPermute = pOp[-1].p4.ai + 1;
2355 assert( aPermute!=0 );
2357 n = pOp->p3;
2358 pKeyInfo = pOp->p4.pKeyInfo;
2359 assert( n>0 );
2360 assert( pKeyInfo!=0 );
2361 p1 = pOp->p1;
2362 p2 = pOp->p2;
2363 #ifdef SQLITE_DEBUG
2364 if( aPermute ){
2365 int k, mx = 0;
2366 for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
2367 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2368 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2369 }else{
2370 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2371 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2373 #endif /* SQLITE_DEBUG */
2374 for(i=0; i<n; i++){
2375 idx = aPermute ? aPermute[i] : (u32)i;
2376 assert( memIsValid(&aMem[p1+idx]) );
2377 assert( memIsValid(&aMem[p2+idx]) );
2378 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2379 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2380 assert( i<pKeyInfo->nKeyField );
2381 pColl = pKeyInfo->aColl[i];
2382 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
2383 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2384 VVA_ONLY( iCompareIsInit = 1; )
2385 if( iCompare ){
2386 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
2387 && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
2389 iCompare = -iCompare;
2391 if( bRev ) iCompare = -iCompare;
2392 break;
2395 assert( pOp[1].opcode==OP_Jump );
2396 break;
2399 /* Opcode: Jump P1 P2 P3 * *
2401 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2402 ** in the most recent OP_Compare instruction the P1 vector was less than,
2403 ** equal to, or greater than the P2 vector, respectively.
2405 ** This opcode must immediately follow an OP_Compare opcode.
2407 case OP_Jump: { /* jump */
2408 assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
2409 assert( iCompareIsInit );
2410 if( iCompare<0 ){
2411 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
2412 }else if( iCompare==0 ){
2413 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
2414 }else{
2415 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
2417 break;
2420 /* Opcode: And P1 P2 P3 * *
2421 ** Synopsis: r[P3]=(r[P1] && r[P2])
2423 ** Take the logical AND of the values in registers P1 and P2 and
2424 ** write the result into register P3.
2426 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2427 ** the other input is NULL. A NULL and true or two NULLs give
2428 ** a NULL output.
2430 /* Opcode: Or P1 P2 P3 * *
2431 ** Synopsis: r[P3]=(r[P1] || r[P2])
2433 ** Take the logical OR of the values in register P1 and P2 and
2434 ** store the answer in register P3.
2436 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2437 ** even if the other input is NULL. A NULL and false or two NULLs
2438 ** give a NULL output.
2440 case OP_And: /* same as TK_AND, in1, in2, out3 */
2441 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2442 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2443 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2445 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2446 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2447 if( pOp->opcode==OP_And ){
2448 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2449 v1 = and_logic[v1*3+v2];
2450 }else{
2451 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2452 v1 = or_logic[v1*3+v2];
2454 pOut = &aMem[pOp->p3];
2455 if( v1==2 ){
2456 MemSetTypeFlag(pOut, MEM_Null);
2457 }else{
2458 pOut->u.i = v1;
2459 MemSetTypeFlag(pOut, MEM_Int);
2461 break;
2464 /* Opcode: IsTrue P1 P2 P3 P4 *
2465 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2467 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2468 ** IS NOT FALSE operators.
2470 ** Interpret the value in register P1 as a boolean value. Store that
2471 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2472 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2473 ** is 1.
2475 ** The logic is summarized like this:
2477 ** <ul>
2478 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2479 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2480 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2481 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2482 ** </ul>
2484 case OP_IsTrue: { /* in1, out2 */
2485 assert( pOp->p4type==P4_INT32 );
2486 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2487 assert( pOp->p3==0 || pOp->p3==1 );
2488 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2489 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2490 break;
2493 /* Opcode: Not P1 P2 * * *
2494 ** Synopsis: r[P2]= !r[P1]
2496 ** Interpret the value in register P1 as a boolean value. Store the
2497 ** boolean complement in register P2. If the value in register P1 is
2498 ** NULL, then a NULL is stored in P2.
2500 case OP_Not: { /* same as TK_NOT, in1, out2 */
2501 pIn1 = &aMem[pOp->p1];
2502 pOut = &aMem[pOp->p2];
2503 if( (pIn1->flags & MEM_Null)==0 ){
2504 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2505 }else{
2506 sqlite3VdbeMemSetNull(pOut);
2508 break;
2511 /* Opcode: BitNot P1 P2 * * *
2512 ** Synopsis: r[P2]= ~r[P1]
2514 ** Interpret the content of register P1 as an integer. Store the
2515 ** ones-complement of the P1 value into register P2. If P1 holds
2516 ** a NULL then store a NULL in P2.
2518 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2519 pIn1 = &aMem[pOp->p1];
2520 pOut = &aMem[pOp->p2];
2521 sqlite3VdbeMemSetNull(pOut);
2522 if( (pIn1->flags & MEM_Null)==0 ){
2523 pOut->flags = MEM_Int;
2524 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2526 break;
2529 /* Opcode: Once P1 P2 * * *
2531 ** Fall through to the next instruction the first time this opcode is
2532 ** encountered on each invocation of the byte-code program. Jump to P2
2533 ** on the second and all subsequent encounters during the same invocation.
2535 ** Top-level programs determine first invocation by comparing the P1
2536 ** operand against the P1 operand on the OP_Init opcode at the beginning
2537 ** of the program. If the P1 values differ, then fall through and make
2538 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2539 ** the same then take the jump.
2541 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2542 ** whether or not the jump should be taken. The bitmask is necessary
2543 ** because the self-altering code trick does not work for recursive
2544 ** triggers.
2546 case OP_Once: { /* jump */
2547 u32 iAddr; /* Address of this instruction */
2548 assert( p->aOp[0].opcode==OP_Init );
2549 if( p->pFrame ){
2550 iAddr = (int)(pOp - p->aOp);
2551 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2552 VdbeBranchTaken(1, 2);
2553 goto jump_to_p2;
2555 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2556 }else{
2557 if( p->aOp[0].p1==pOp->p1 ){
2558 VdbeBranchTaken(1, 2);
2559 goto jump_to_p2;
2562 VdbeBranchTaken(0, 2);
2563 pOp->p1 = p->aOp[0].p1;
2564 break;
2567 /* Opcode: If P1 P2 P3 * *
2569 ** Jump to P2 if the value in register P1 is true. The value
2570 ** is considered true if it is numeric and non-zero. If the value
2571 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2573 case OP_If: { /* jump, in1 */
2574 int c;
2575 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2576 VdbeBranchTaken(c!=0, 2);
2577 if( c ) goto jump_to_p2;
2578 break;
2581 /* Opcode: IfNot P1 P2 P3 * *
2583 ** Jump to P2 if the value in register P1 is False. The value
2584 ** is considered false if it has a numeric value of zero. If the value
2585 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2587 case OP_IfNot: { /* jump, in1 */
2588 int c;
2589 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2590 VdbeBranchTaken(c!=0, 2);
2591 if( c ) goto jump_to_p2;
2592 break;
2595 /* Opcode: IsNull P1 P2 * * *
2596 ** Synopsis: if r[P1]==NULL goto P2
2598 ** Jump to P2 if the value in register P1 is NULL.
2600 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2601 pIn1 = &aMem[pOp->p1];
2602 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2603 if( (pIn1->flags & MEM_Null)!=0 ){
2604 goto jump_to_p2;
2606 break;
2609 /* Opcode: IsType P1 P2 P3 P4 P5
2610 ** Synopsis: if typeof(P1.P3) in P5 goto P2
2612 ** Jump to P2 if the type of a column in a btree is one of the types specified
2613 ** by the P5 bitmask.
2615 ** P1 is normally a cursor on a btree for which the row decode cache is
2616 ** valid through at least column P3. In other words, there should have been
2617 ** a prior OP_Column for column P3 or greater. If the cursor is not valid,
2618 ** then this opcode might give spurious results.
2619 ** The the btree row has fewer than P3 columns, then use P4 as the
2620 ** datatype.
2622 ** If P1 is -1, then P3 is a register number and the datatype is taken
2623 ** from the value in that register.
2625 ** P5 is a bitmask of data types. SQLITE_INTEGER is the least significant
2626 ** (0x01) bit. SQLITE_FLOAT is the 0x02 bit. SQLITE_TEXT is 0x04.
2627 ** SQLITE_BLOB is 0x08. SQLITE_NULL is 0x10.
2629 ** WARNING: This opcode does not reliably distinguish between NULL and REAL
2630 ** when P1>=0. If the database contains a NaN value, this opcode will think
2631 ** that the datatype is REAL when it should be NULL. When P1<0 and the value
2632 ** is already stored in register P3, then this opcode does reliably
2633 ** distinguish between NULL and REAL. The problem only arises then P1>=0.
2635 ** Take the jump to address P2 if and only if the datatype of the
2636 ** value determined by P1 and P3 corresponds to one of the bits in the
2637 ** P5 bitmask.
2640 case OP_IsType: { /* jump */
2641 VdbeCursor *pC;
2642 u16 typeMask;
2643 u32 serialType;
2645 assert( pOp->p1>=(-1) && pOp->p1<p->nCursor );
2646 assert( pOp->p1>=0 || (pOp->p3>=0 && pOp->p3<=(p->nMem+1 - p->nCursor)) );
2647 if( pOp->p1>=0 ){
2648 pC = p->apCsr[pOp->p1];
2649 assert( pC!=0 );
2650 assert( pOp->p3>=0 );
2651 if( pOp->p3<pC->nHdrParsed ){
2652 serialType = pC->aType[pOp->p3];
2653 if( serialType>=12 ){
2654 if( serialType&1 ){
2655 typeMask = 0x04; /* SQLITE_TEXT */
2656 }else{
2657 typeMask = 0x08; /* SQLITE_BLOB */
2659 }else{
2660 static const unsigned char aMask[] = {
2661 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2,
2662 0x01, 0x01, 0x10, 0x10
2664 testcase( serialType==0 );
2665 testcase( serialType==1 );
2666 testcase( serialType==2 );
2667 testcase( serialType==3 );
2668 testcase( serialType==4 );
2669 testcase( serialType==5 );
2670 testcase( serialType==6 );
2671 testcase( serialType==7 );
2672 testcase( serialType==8 );
2673 testcase( serialType==9 );
2674 testcase( serialType==10 );
2675 testcase( serialType==11 );
2676 typeMask = aMask[serialType];
2678 }else{
2679 typeMask = 1 << (pOp->p4.i - 1);
2680 testcase( typeMask==0x01 );
2681 testcase( typeMask==0x02 );
2682 testcase( typeMask==0x04 );
2683 testcase( typeMask==0x08 );
2684 testcase( typeMask==0x10 );
2686 }else{
2687 assert( memIsValid(&aMem[pOp->p3]) );
2688 typeMask = 1 << (sqlite3_value_type((sqlite3_value*)&aMem[pOp->p3])-1);
2689 testcase( typeMask==0x01 );
2690 testcase( typeMask==0x02 );
2691 testcase( typeMask==0x04 );
2692 testcase( typeMask==0x08 );
2693 testcase( typeMask==0x10 );
2695 VdbeBranchTaken( (typeMask & pOp->p5)!=0, 2);
2696 if( typeMask & pOp->p5 ){
2697 goto jump_to_p2;
2699 break;
2702 /* Opcode: ZeroOrNull P1 P2 P3 * *
2703 ** Synopsis: r[P2] = 0 OR NULL
2705 ** If all both registers P1 and P3 are NOT NULL, then store a zero in
2706 ** register P2. If either registers P1 or P3 are NULL then put
2707 ** a NULL in register P2.
2709 case OP_ZeroOrNull: { /* in1, in2, out2, in3 */
2710 if( (aMem[pOp->p1].flags & MEM_Null)!=0
2711 || (aMem[pOp->p3].flags & MEM_Null)!=0
2713 sqlite3VdbeMemSetNull(aMem + pOp->p2);
2714 }else{
2715 sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
2717 break;
2720 /* Opcode: NotNull P1 P2 * * *
2721 ** Synopsis: if r[P1]!=NULL goto P2
2723 ** Jump to P2 if the value in register P1 is not NULL.
2725 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2726 pIn1 = &aMem[pOp->p1];
2727 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2728 if( (pIn1->flags & MEM_Null)==0 ){
2729 goto jump_to_p2;
2731 break;
2734 /* Opcode: IfNullRow P1 P2 P3 * *
2735 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2737 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2738 ** If it is, then set register P3 to NULL and jump immediately to P2.
2739 ** If P1 is not on a NULL row, then fall through without making any
2740 ** changes.
2742 ** If P1 is not an open cursor, then this opcode is a no-op.
2744 case OP_IfNullRow: { /* jump */
2745 VdbeCursor *pC;
2746 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2747 pC = p->apCsr[pOp->p1];
2748 if( pC && pC->nullRow ){
2749 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2750 goto jump_to_p2;
2752 break;
2755 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2756 /* Opcode: Offset P1 P2 P3 * *
2757 ** Synopsis: r[P3] = sqlite_offset(P1)
2759 ** Store in register r[P3] the byte offset into the database file that is the
2760 ** start of the payload for the record at which that cursor P1 is currently
2761 ** pointing.
2763 ** P2 is the column number for the argument to the sqlite_offset() function.
2764 ** This opcode does not use P2 itself, but the P2 value is used by the
2765 ** code generator. The P1, P2, and P3 operands to this opcode are the
2766 ** same as for OP_Column.
2768 ** This opcode is only available if SQLite is compiled with the
2769 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2771 case OP_Offset: { /* out3 */
2772 VdbeCursor *pC; /* The VDBE cursor */
2773 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2774 pC = p->apCsr[pOp->p1];
2775 pOut = &p->aMem[pOp->p3];
2776 if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
2777 sqlite3VdbeMemSetNull(pOut);
2778 }else{
2779 if( pC->deferredMoveto ){
2780 rc = sqlite3VdbeFinishMoveto(pC);
2781 if( rc ) goto abort_due_to_error;
2783 if( sqlite3BtreeEof(pC->uc.pCursor) ){
2784 sqlite3VdbeMemSetNull(pOut);
2785 }else{
2786 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2789 break;
2791 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2793 /* Opcode: Column P1 P2 P3 P4 P5
2794 ** Synopsis: r[P3]=PX cursor P1 column P2
2796 ** Interpret the data that cursor P1 points to as a structure built using
2797 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2798 ** information about the format of the data.) Extract the P2-th column
2799 ** from this record. If there are less than (P2+1)
2800 ** values in the record, extract a NULL.
2802 ** The value extracted is stored in register P3.
2804 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2805 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2806 ** the result.
2808 ** If the OPFLAG_LENGTHARG bit is set in P5 then the result is guaranteed
2809 ** to only be used by the length() function or the equivalent. The content
2810 ** of large blobs is not loaded, thus saving CPU cycles. If the
2811 ** OPFLAG_TYPEOFARG bit is set then the result will only be used by the
2812 ** typeof() function or the IS NULL or IS NOT NULL operators or the
2813 ** equivalent. In this case, all content loading can be omitted.
2815 case OP_Column: { /* ncycle */
2816 u32 p2; /* column number to retrieve */
2817 VdbeCursor *pC; /* The VDBE cursor */
2818 BtCursor *pCrsr; /* The B-Tree cursor corresponding to pC */
2819 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2820 int len; /* The length of the serialized data for the column */
2821 int i; /* Loop counter */
2822 Mem *pDest; /* Where to write the extracted value */
2823 Mem sMem; /* For storing the record being decoded */
2824 const u8 *zData; /* Part of the record being decoded */
2825 const u8 *zHdr; /* Next unparsed byte of the header */
2826 const u8 *zEndHdr; /* Pointer to first byte after the header */
2827 u64 offset64; /* 64-bit offset */
2828 u32 t; /* A type code from the record header */
2829 Mem *pReg; /* PseudoTable input register */
2831 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2832 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2833 pC = p->apCsr[pOp->p1];
2834 p2 = (u32)pOp->p2;
2836 op_column_restart:
2837 assert( pC!=0 );
2838 assert( p2<(u32)pC->nField
2839 || (pC->eCurType==CURTYPE_PSEUDO && pC->seekResult==0) );
2840 aOffset = pC->aOffset;
2841 assert( aOffset==pC->aType+pC->nField );
2842 assert( pC->eCurType!=CURTYPE_VTAB );
2843 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2844 assert( pC->eCurType!=CURTYPE_SORTER );
2846 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2847 if( pC->nullRow ){
2848 if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
2849 /* For the special case of as pseudo-cursor, the seekResult field
2850 ** identifies the register that holds the record */
2851 pReg = &aMem[pC->seekResult];
2852 assert( pReg->flags & MEM_Blob );
2853 assert( memIsValid(pReg) );
2854 pC->payloadSize = pC->szRow = pReg->n;
2855 pC->aRow = (u8*)pReg->z;
2856 }else{
2857 pDest = &aMem[pOp->p3];
2858 memAboutToChange(p, pDest);
2859 sqlite3VdbeMemSetNull(pDest);
2860 goto op_column_out;
2862 }else{
2863 pCrsr = pC->uc.pCursor;
2864 if( pC->deferredMoveto ){
2865 u32 iMap;
2866 assert( !pC->isEphemeral );
2867 if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0 ){
2868 pC = pC->pAltCursor;
2869 p2 = iMap - 1;
2870 goto op_column_restart;
2872 rc = sqlite3VdbeFinishMoveto(pC);
2873 if( rc ) goto abort_due_to_error;
2874 }else if( sqlite3BtreeCursorHasMoved(pCrsr) ){
2875 rc = sqlite3VdbeHandleMovedCursor(pC);
2876 if( rc ) goto abort_due_to_error;
2877 goto op_column_restart;
2879 assert( pC->eCurType==CURTYPE_BTREE );
2880 assert( pCrsr );
2881 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2882 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2883 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2884 assert( pC->szRow<=pC->payloadSize );
2885 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2887 pC->cacheStatus = p->cacheCtr;
2888 if( (aOffset[0] = pC->aRow[0])<0x80 ){
2889 pC->iHdrOffset = 1;
2890 }else{
2891 pC->iHdrOffset = sqlite3GetVarint32(pC->aRow, aOffset);
2893 pC->nHdrParsed = 0;
2895 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2896 /* pC->aRow does not have to hold the entire row, but it does at least
2897 ** need to cover the header of the record. If pC->aRow does not contain
2898 ** the complete header, then set it to zero, forcing the header to be
2899 ** dynamically allocated. */
2900 pC->aRow = 0;
2901 pC->szRow = 0;
2903 /* Make sure a corrupt database has not given us an oversize header.
2904 ** Do this now to avoid an oversize memory allocation.
2906 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2907 ** types use so much data space that there can only be 4096 and 32 of
2908 ** them, respectively. So the maximum header length results from a
2909 ** 3-byte type for each of the maximum of 32768 columns plus three
2910 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2912 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2913 goto op_column_corrupt;
2915 }else{
2916 /* This is an optimization. By skipping over the first few tests
2917 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2918 ** measurable performance gain.
2920 ** This branch is taken even if aOffset[0]==0. Such a record is never
2921 ** generated by SQLite, and could be considered corruption, but we
2922 ** accept it for historical reasons. When aOffset[0]==0, the code this
2923 ** branch jumps to reads past the end of the record, but never more
2924 ** than a few bytes. Even if the record occurs at the end of the page
2925 ** content area, the "page header" comes after the page content and so
2926 ** this overread is harmless. Similar overreads can occur for a corrupt
2927 ** database file.
2929 zData = pC->aRow;
2930 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2931 testcase( aOffset[0]==0 );
2932 goto op_column_read_header;
2934 }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
2935 rc = sqlite3VdbeHandleMovedCursor(pC);
2936 if( rc ) goto abort_due_to_error;
2937 goto op_column_restart;
2940 /* Make sure at least the first p2+1 entries of the header have been
2941 ** parsed and valid information is in aOffset[] and pC->aType[].
2943 if( pC->nHdrParsed<=p2 ){
2944 /* If there is more header available for parsing in the record, try
2945 ** to extract additional fields up through the p2+1-th field
2947 if( pC->iHdrOffset<aOffset[0] ){
2948 /* Make sure zData points to enough of the record to cover the header. */
2949 if( pC->aRow==0 ){
2950 memset(&sMem, 0, sizeof(sMem));
2951 rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
2952 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2953 zData = (u8*)sMem.z;
2954 }else{
2955 zData = pC->aRow;
2958 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2959 op_column_read_header:
2960 i = pC->nHdrParsed;
2961 offset64 = aOffset[i];
2962 zHdr = zData + pC->iHdrOffset;
2963 zEndHdr = zData + aOffset[0];
2964 testcase( zHdr>=zEndHdr );
2966 if( (pC->aType[i] = t = zHdr[0])<0x80 ){
2967 zHdr++;
2968 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2969 }else{
2970 zHdr += sqlite3GetVarint32(zHdr, &t);
2971 pC->aType[i] = t;
2972 offset64 += sqlite3VdbeSerialTypeLen(t);
2974 aOffset[++i] = (u32)(offset64 & 0xffffffff);
2975 }while( (u32)i<=p2 && zHdr<zEndHdr );
2977 /* The record is corrupt if any of the following are true:
2978 ** (1) the bytes of the header extend past the declared header size
2979 ** (2) the entire header was used but not all data was used
2980 ** (3) the end of the data extends beyond the end of the record.
2982 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2983 || (offset64 > pC->payloadSize)
2985 if( aOffset[0]==0 ){
2986 i = 0;
2987 zHdr = zEndHdr;
2988 }else{
2989 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2990 goto op_column_corrupt;
2994 pC->nHdrParsed = i;
2995 pC->iHdrOffset = (u32)(zHdr - zData);
2996 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2997 }else{
2998 t = 0;
3001 /* If after trying to extract new entries from the header, nHdrParsed is
3002 ** still not up to p2, that means that the record has fewer than p2
3003 ** columns. So the result will be either the default value or a NULL.
3005 if( pC->nHdrParsed<=p2 ){
3006 pDest = &aMem[pOp->p3];
3007 memAboutToChange(p, pDest);
3008 if( pOp->p4type==P4_MEM ){
3009 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
3010 }else{
3011 sqlite3VdbeMemSetNull(pDest);
3013 goto op_column_out;
3015 }else{
3016 t = pC->aType[p2];
3019 /* Extract the content for the p2+1-th column. Control can only
3020 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
3021 ** all valid.
3023 assert( p2<pC->nHdrParsed );
3024 assert( rc==SQLITE_OK );
3025 pDest = &aMem[pOp->p3];
3026 memAboutToChange(p, pDest);
3027 assert( sqlite3VdbeCheckMemInvariants(pDest) );
3028 if( VdbeMemDynamic(pDest) ){
3029 sqlite3VdbeMemSetNull(pDest);
3031 assert( t==pC->aType[p2] );
3032 if( pC->szRow>=aOffset[p2+1] ){
3033 /* This is the common case where the desired content fits on the original
3034 ** page - where the content is not on an overflow page */
3035 zData = pC->aRow + aOffset[p2];
3036 if( t<12 ){
3037 sqlite3VdbeSerialGet(zData, t, pDest);
3038 }else{
3039 /* If the column value is a string, we need a persistent value, not
3040 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
3041 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
3043 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
3044 pDest->n = len = (t-12)/2;
3045 pDest->enc = encoding;
3046 if( pDest->szMalloc < len+2 ){
3047 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
3048 pDest->flags = MEM_Null;
3049 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
3050 }else{
3051 pDest->z = pDest->zMalloc;
3053 memcpy(pDest->z, zData, len);
3054 pDest->z[len] = 0;
3055 pDest->z[len+1] = 0;
3056 pDest->flags = aFlag[t&1];
3058 }else{
3059 pDest->enc = encoding;
3060 /* This branch happens only when content is on overflow pages */
3061 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
3062 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
3063 || (len = sqlite3VdbeSerialTypeLen(t))==0
3065 /* Content is irrelevant for
3066 ** 1. the typeof() function,
3067 ** 2. the length(X) function if X is a blob, and
3068 ** 3. if the content length is zero.
3069 ** So we might as well use bogus content rather than reading
3070 ** content from disk.
3072 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
3073 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
3074 ** read more. Use the global constant sqlite3CtypeMap[] as the array,
3075 ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
3076 ** and it begins with a bunch of zeros.
3078 sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
3079 }else{
3080 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
3081 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
3082 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3083 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
3084 pDest->flags &= ~MEM_Ephem;
3088 op_column_out:
3089 UPDATE_MAX_BLOBSIZE(pDest);
3090 REGISTER_TRACE(pOp->p3, pDest);
3091 break;
3093 op_column_corrupt:
3094 if( aOp[0].p3>0 ){
3095 pOp = &aOp[aOp[0].p3-1];
3096 break;
3097 }else{
3098 rc = SQLITE_CORRUPT_BKPT;
3099 goto abort_due_to_error;
3103 /* Opcode: TypeCheck P1 P2 P3 P4 *
3104 ** Synopsis: typecheck(r[P1@P2])
3106 ** Apply affinities to the range of P2 registers beginning with P1.
3107 ** Take the affinities from the Table object in P4. If any value
3108 ** cannot be coerced into the correct type, then raise an error.
3110 ** This opcode is similar to OP_Affinity except that this opcode
3111 ** forces the register type to the Table column type. This is used
3112 ** to implement "strict affinity".
3114 ** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
3115 ** is zero. When P3 is non-zero, no type checking occurs for
3116 ** static generated columns. Virtual columns are computed at query time
3117 ** and so they are never checked.
3119 ** Preconditions:
3121 ** <ul>
3122 ** <li> P2 should be the number of non-virtual columns in the
3123 ** table of P4.
3124 ** <li> Table P4 should be a STRICT table.
3125 ** </ul>
3127 ** If any precondition is false, an assertion fault occurs.
3129 case OP_TypeCheck: {
3130 Table *pTab;
3131 Column *aCol;
3132 int i;
3134 assert( pOp->p4type==P4_TABLE );
3135 pTab = pOp->p4.pTab;
3136 assert( pTab->tabFlags & TF_Strict );
3137 assert( pTab->nNVCol==pOp->p2 );
3138 aCol = pTab->aCol;
3139 pIn1 = &aMem[pOp->p1];
3140 for(i=0; i<pTab->nCol; i++){
3141 if( aCol[i].colFlags & COLFLAG_GENERATED ){
3142 if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
3143 if( pOp->p3 ){ pIn1++; continue; }
3145 assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
3146 applyAffinity(pIn1, aCol[i].affinity, encoding);
3147 if( (pIn1->flags & MEM_Null)==0 ){
3148 switch( aCol[i].eCType ){
3149 case COLTYPE_BLOB: {
3150 if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
3151 break;
3153 case COLTYPE_INTEGER:
3154 case COLTYPE_INT: {
3155 if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
3156 break;
3158 case COLTYPE_TEXT: {
3159 if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
3160 break;
3162 case COLTYPE_REAL: {
3163 testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
3164 assert( (pIn1->flags & MEM_IntReal)==0 );
3165 if( pIn1->flags & MEM_Int ){
3166 /* When applying REAL affinity, if the result is still an MEM_Int
3167 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3168 ** so that we keep the high-resolution integer value but know that
3169 ** the type really wants to be REAL. */
3170 testcase( pIn1->u.i==140737488355328LL );
3171 testcase( pIn1->u.i==140737488355327LL );
3172 testcase( pIn1->u.i==-140737488355328LL );
3173 testcase( pIn1->u.i==-140737488355329LL );
3174 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
3175 pIn1->flags |= MEM_IntReal;
3176 pIn1->flags &= ~MEM_Int;
3177 }else{
3178 pIn1->u.r = (double)pIn1->u.i;
3179 pIn1->flags |= MEM_Real;
3180 pIn1->flags &= ~MEM_Int;
3182 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
3183 goto vdbe_type_error;
3185 break;
3187 default: {
3188 /* COLTYPE_ANY. Accept anything. */
3189 break;
3193 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3194 pIn1++;
3196 assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
3197 break;
3199 vdbe_type_error:
3200 sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
3201 vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
3202 pTab->zName, aCol[i].zCnName);
3203 rc = SQLITE_CONSTRAINT_DATATYPE;
3204 goto abort_due_to_error;
3207 /* Opcode: Affinity P1 P2 * P4 *
3208 ** Synopsis: affinity(r[P1@P2])
3210 ** Apply affinities to a range of P2 registers starting with P1.
3212 ** P4 is a string that is P2 characters long. The N-th character of the
3213 ** string indicates the column affinity that should be used for the N-th
3214 ** memory cell in the range.
3216 case OP_Affinity: {
3217 const char *zAffinity; /* The affinity to be applied */
3219 zAffinity = pOp->p4.z;
3220 assert( zAffinity!=0 );
3221 assert( pOp->p2>0 );
3222 assert( zAffinity[pOp->p2]==0 );
3223 pIn1 = &aMem[pOp->p1];
3224 while( 1 /*exit-by-break*/ ){
3225 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
3226 assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
3227 applyAffinity(pIn1, zAffinity[0], encoding);
3228 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
3229 /* When applying REAL affinity, if the result is still an MEM_Int
3230 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3231 ** so that we keep the high-resolution integer value but know that
3232 ** the type really wants to be REAL. */
3233 testcase( pIn1->u.i==140737488355328LL );
3234 testcase( pIn1->u.i==140737488355327LL );
3235 testcase( pIn1->u.i==-140737488355328LL );
3236 testcase( pIn1->u.i==-140737488355329LL );
3237 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
3238 pIn1->flags |= MEM_IntReal;
3239 pIn1->flags &= ~MEM_Int;
3240 }else{
3241 pIn1->u.r = (double)pIn1->u.i;
3242 pIn1->flags |= MEM_Real;
3243 pIn1->flags &= ~(MEM_Int|MEM_Str);
3246 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3247 zAffinity++;
3248 if( zAffinity[0]==0 ) break;
3249 pIn1++;
3251 break;
3254 /* Opcode: MakeRecord P1 P2 P3 P4 *
3255 ** Synopsis: r[P3]=mkrec(r[P1@P2])
3257 ** Convert P2 registers beginning with P1 into the [record format]
3258 ** use as a data record in a database table or as a key
3259 ** in an index. The OP_Column opcode can decode the record later.
3261 ** P4 may be a string that is P2 characters long. The N-th character of the
3262 ** string indicates the column affinity that should be used for the N-th
3263 ** field of the index key.
3265 ** The mapping from character to affinity is given by the SQLITE_AFF_
3266 ** macros defined in sqliteInt.h.
3268 ** If P4 is NULL then all index fields have the affinity BLOB.
3270 ** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
3271 ** compile-time option is enabled:
3273 ** * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
3274 ** of the right-most table that can be null-trimmed.
3276 ** * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
3277 ** OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
3278 ** accept no-change records with serial_type 10. This value is
3279 ** only used inside an assert() and does not affect the end result.
3281 case OP_MakeRecord: {
3282 Mem *pRec; /* The new record */
3283 u64 nData; /* Number of bytes of data space */
3284 int nHdr; /* Number of bytes of header space */
3285 i64 nByte; /* Data space required for this record */
3286 i64 nZero; /* Number of zero bytes at the end of the record */
3287 int nVarint; /* Number of bytes in a varint */
3288 u32 serial_type; /* Type field */
3289 Mem *pData0; /* First field to be combined into the record */
3290 Mem *pLast; /* Last field of the record */
3291 int nField; /* Number of fields in the record */
3292 char *zAffinity; /* The affinity string for the record */
3293 u32 len; /* Length of a field */
3294 u8 *zHdr; /* Where to write next byte of the header */
3295 u8 *zPayload; /* Where to write next byte of the payload */
3297 /* Assuming the record contains N fields, the record format looks
3298 ** like this:
3300 ** ------------------------------------------------------------------------
3301 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
3302 ** ------------------------------------------------------------------------
3304 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
3305 ** and so forth.
3307 ** Each type field is a varint representing the serial type of the
3308 ** corresponding data element (see sqlite3VdbeSerialType()). The
3309 ** hdr-size field is also a varint which is the offset from the beginning
3310 ** of the record to data0.
3312 nData = 0; /* Number of bytes of data space */
3313 nHdr = 0; /* Number of bytes of header space */
3314 nZero = 0; /* Number of zero bytes at the end of the record */
3315 nField = pOp->p1;
3316 zAffinity = pOp->p4.z;
3317 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
3318 pData0 = &aMem[nField];
3319 nField = pOp->p2;
3320 pLast = &pData0[nField-1];
3322 /* Identify the output register */
3323 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
3324 pOut = &aMem[pOp->p3];
3325 memAboutToChange(p, pOut);
3327 /* Apply the requested affinity to all inputs
3329 assert( pData0<=pLast );
3330 if( zAffinity ){
3331 pRec = pData0;
3333 applyAffinity(pRec, zAffinity[0], encoding);
3334 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
3335 pRec->flags |= MEM_IntReal;
3336 pRec->flags &= ~(MEM_Int);
3338 REGISTER_TRACE((int)(pRec-aMem), pRec);
3339 zAffinity++;
3340 pRec++;
3341 assert( zAffinity[0]==0 || pRec<=pLast );
3342 }while( zAffinity[0] );
3345 #ifdef SQLITE_ENABLE_NULL_TRIM
3346 /* NULLs can be safely trimmed from the end of the record, as long as
3347 ** as the schema format is 2 or more and none of the omitted columns
3348 ** have a non-NULL default value. Also, the record must be left with
3349 ** at least one field. If P5>0 then it will be one more than the
3350 ** index of the right-most column with a non-NULL default value */
3351 if( pOp->p5 ){
3352 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
3353 pLast--;
3354 nField--;
3357 #endif
3359 /* Loop through the elements that will make up the record to figure
3360 ** out how much space is required for the new record. After this loop,
3361 ** the Mem.uTemp field of each term should hold the serial-type that will
3362 ** be used for that term in the generated record:
3364 ** Mem.uTemp value type
3365 ** --------------- ---------------
3366 ** 0 NULL
3367 ** 1 1-byte signed integer
3368 ** 2 2-byte signed integer
3369 ** 3 3-byte signed integer
3370 ** 4 4-byte signed integer
3371 ** 5 6-byte signed integer
3372 ** 6 8-byte signed integer
3373 ** 7 IEEE float
3374 ** 8 Integer constant 0
3375 ** 9 Integer constant 1
3376 ** 10,11 reserved for expansion
3377 ** N>=12 and even BLOB
3378 ** N>=13 and odd text
3380 ** The following additional values are computed:
3381 ** nHdr Number of bytes needed for the record header
3382 ** nData Number of bytes of data space needed for the record
3383 ** nZero Zero bytes at the end of the record
3385 pRec = pLast;
3387 assert( memIsValid(pRec) );
3388 if( pRec->flags & MEM_Null ){
3389 if( pRec->flags & MEM_Zero ){
3390 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
3391 ** table methods that never invoke sqlite3_result_xxxxx() while
3392 ** computing an unchanging column value in an UPDATE statement.
3393 ** Give such values a special internal-use-only serial-type of 10
3394 ** so that they can be passed through to xUpdate and have
3395 ** a true sqlite3_value_nochange(). */
3396 #ifndef SQLITE_ENABLE_NULL_TRIM
3397 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
3398 #endif
3399 pRec->uTemp = 10;
3400 }else{
3401 pRec->uTemp = 0;
3403 nHdr++;
3404 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
3405 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3406 i64 i = pRec->u.i;
3407 u64 uu;
3408 testcase( pRec->flags & MEM_Int );
3409 testcase( pRec->flags & MEM_IntReal );
3410 if( i<0 ){
3411 uu = ~i;
3412 }else{
3413 uu = i;
3415 nHdr++;
3416 testcase( uu==127 ); testcase( uu==128 );
3417 testcase( uu==32767 ); testcase( uu==32768 );
3418 testcase( uu==8388607 ); testcase( uu==8388608 );
3419 testcase( uu==2147483647 ); testcase( uu==2147483648LL );
3420 testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
3421 if( uu<=127 ){
3422 if( (i&1)==i && p->minWriteFileFormat>=4 ){
3423 pRec->uTemp = 8+(u32)uu;
3424 }else{
3425 nData++;
3426 pRec->uTemp = 1;
3428 }else if( uu<=32767 ){
3429 nData += 2;
3430 pRec->uTemp = 2;
3431 }else if( uu<=8388607 ){
3432 nData += 3;
3433 pRec->uTemp = 3;
3434 }else if( uu<=2147483647 ){
3435 nData += 4;
3436 pRec->uTemp = 4;
3437 }else if( uu<=140737488355327LL ){
3438 nData += 6;
3439 pRec->uTemp = 5;
3440 }else{
3441 nData += 8;
3442 if( pRec->flags & MEM_IntReal ){
3443 /* If the value is IntReal and is going to take up 8 bytes to store
3444 ** as an integer, then we might as well make it an 8-byte floating
3445 ** point value */
3446 pRec->u.r = (double)pRec->u.i;
3447 pRec->flags &= ~MEM_IntReal;
3448 pRec->flags |= MEM_Real;
3449 pRec->uTemp = 7;
3450 }else{
3451 pRec->uTemp = 6;
3454 }else if( pRec->flags & MEM_Real ){
3455 nHdr++;
3456 nData += 8;
3457 pRec->uTemp = 7;
3458 }else{
3459 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
3460 assert( pRec->n>=0 );
3461 len = (u32)pRec->n;
3462 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
3463 if( pRec->flags & MEM_Zero ){
3464 serial_type += pRec->u.nZero*2;
3465 if( nData ){
3466 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
3467 len += pRec->u.nZero;
3468 }else{
3469 nZero += pRec->u.nZero;
3472 nData += len;
3473 nHdr += sqlite3VarintLen(serial_type);
3474 pRec->uTemp = serial_type;
3476 if( pRec==pData0 ) break;
3477 pRec--;
3478 }while(1);
3480 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
3481 ** which determines the total number of bytes in the header. The varint
3482 ** value is the size of the header in bytes including the size varint
3483 ** itself. */
3484 testcase( nHdr==126 );
3485 testcase( nHdr==127 );
3486 if( nHdr<=126 ){
3487 /* The common case */
3488 nHdr += 1;
3489 }else{
3490 /* Rare case of a really large header */
3491 nVarint = sqlite3VarintLen(nHdr);
3492 nHdr += nVarint;
3493 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
3495 nByte = nHdr+nData;
3497 /* Make sure the output register has a buffer large enough to store
3498 ** the new record. The output register (pOp->p3) is not allowed to
3499 ** be one of the input registers (because the following call to
3500 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
3502 if( nByte+nZero<=pOut->szMalloc ){
3503 /* The output register is already large enough to hold the record.
3504 ** No error checks or buffer enlargement is required */
3505 pOut->z = pOut->zMalloc;
3506 }else{
3507 /* Need to make sure that the output is not too big and then enlarge
3508 ** the output register to hold the full result */
3509 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3510 goto too_big;
3512 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
3513 goto no_mem;
3516 pOut->n = (int)nByte;
3517 pOut->flags = MEM_Blob;
3518 if( nZero ){
3519 pOut->u.nZero = nZero;
3520 pOut->flags |= MEM_Zero;
3522 UPDATE_MAX_BLOBSIZE(pOut);
3523 zHdr = (u8 *)pOut->z;
3524 zPayload = zHdr + nHdr;
3526 /* Write the record */
3527 if( nHdr<0x80 ){
3528 *(zHdr++) = nHdr;
3529 }else{
3530 zHdr += sqlite3PutVarint(zHdr,nHdr);
3532 assert( pData0<=pLast );
3533 pRec = pData0;
3534 while( 1 /*exit-by-break*/ ){
3535 serial_type = pRec->uTemp;
3536 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
3537 ** additional varints, one per column.
3538 ** EVIDENCE-OF: R-64536-51728 The values for each column in the record
3539 ** immediately follow the header. */
3540 if( serial_type<=7 ){
3541 *(zHdr++) = serial_type;
3542 if( serial_type==0 ){
3543 /* NULL value. No change in zPayload */
3544 }else{
3545 u64 v;
3546 u32 i;
3547 if( serial_type==7 ){
3548 assert( sizeof(v)==sizeof(pRec->u.r) );
3549 memcpy(&v, &pRec->u.r, sizeof(v));
3550 swapMixedEndianFloat(v);
3551 }else{
3552 v = pRec->u.i;
3554 len = i = sqlite3SmallTypeSizes[serial_type];
3555 assert( i>0 );
3556 while( 1 /*exit-by-break*/ ){
3557 zPayload[--i] = (u8)(v&0xFF);
3558 if( i==0 ) break;
3559 v >>= 8;
3561 zPayload += len;
3563 }else if( serial_type<0x80 ){
3564 *(zHdr++) = serial_type;
3565 if( serial_type>=14 && pRec->n>0 ){
3566 assert( pRec->z!=0 );
3567 memcpy(zPayload, pRec->z, pRec->n);
3568 zPayload += pRec->n;
3570 }else{
3571 zHdr += sqlite3PutVarint(zHdr, serial_type);
3572 if( pRec->n ){
3573 assert( pRec->z!=0 );
3574 memcpy(zPayload, pRec->z, pRec->n);
3575 zPayload += pRec->n;
3578 if( pRec==pLast ) break;
3579 pRec++;
3581 assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
3582 assert( nByte==(int)(zPayload - (u8*)pOut->z) );
3584 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
3585 REGISTER_TRACE(pOp->p3, pOut);
3586 break;
3589 /* Opcode: Count P1 P2 P3 * *
3590 ** Synopsis: r[P2]=count()
3592 ** Store the number of entries (an integer value) in the table or index
3593 ** opened by cursor P1 in register P2.
3595 ** If P3==0, then an exact count is obtained, which involves visiting
3596 ** every btree page of the table. But if P3 is non-zero, an estimate
3597 ** is returned based on the current cursor position.
3599 case OP_Count: { /* out2 */
3600 i64 nEntry;
3601 BtCursor *pCrsr;
3603 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
3604 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
3605 assert( pCrsr );
3606 if( pOp->p3 ){
3607 nEntry = sqlite3BtreeRowCountEst(pCrsr);
3608 }else{
3609 nEntry = 0; /* Not needed. Only used to silence a warning. */
3610 rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
3611 if( rc ) goto abort_due_to_error;
3613 pOut = out2Prerelease(p, pOp);
3614 pOut->u.i = nEntry;
3615 goto check_for_interrupt;
3618 /* Opcode: Savepoint P1 * * P4 *
3620 ** Open, release or rollback the savepoint named by parameter P4, depending
3621 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
3622 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
3623 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
3625 case OP_Savepoint: {
3626 int p1; /* Value of P1 operand */
3627 char *zName; /* Name of savepoint */
3628 int nName;
3629 Savepoint *pNew;
3630 Savepoint *pSavepoint;
3631 Savepoint *pTmp;
3632 int iSavepoint;
3633 int ii;
3635 p1 = pOp->p1;
3636 zName = pOp->p4.z;
3638 /* Assert that the p1 parameter is valid. Also that if there is no open
3639 ** transaction, then there cannot be any savepoints.
3641 assert( db->pSavepoint==0 || db->autoCommit==0 );
3642 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
3643 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
3644 assert( checkSavepointCount(db) );
3645 assert( p->bIsReader );
3647 if( p1==SAVEPOINT_BEGIN ){
3648 if( db->nVdbeWrite>0 ){
3649 /* A new savepoint cannot be created if there are active write
3650 ** statements (i.e. open read/write incremental blob handles).
3652 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
3653 rc = SQLITE_BUSY;
3654 }else{
3655 nName = sqlite3Strlen30(zName);
3657 #ifndef SQLITE_OMIT_VIRTUALTABLE
3658 /* This call is Ok even if this savepoint is actually a transaction
3659 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3660 ** If this is a transaction savepoint being opened, it is guaranteed
3661 ** that the db->aVTrans[] array is empty. */
3662 assert( db->autoCommit==0 || db->nVTrans==0 );
3663 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
3664 db->nStatement+db->nSavepoint);
3665 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3666 #endif
3668 /* Create a new savepoint structure. */
3669 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
3670 if( pNew ){
3671 pNew->zName = (char *)&pNew[1];
3672 memcpy(pNew->zName, zName, nName+1);
3674 /* If there is no open transaction, then mark this as a special
3675 ** "transaction savepoint". */
3676 if( db->autoCommit ){
3677 db->autoCommit = 0;
3678 db->isTransactionSavepoint = 1;
3679 }else{
3680 db->nSavepoint++;
3683 /* Link the new savepoint into the database handle's list. */
3684 pNew->pNext = db->pSavepoint;
3685 db->pSavepoint = pNew;
3686 pNew->nDeferredCons = db->nDeferredCons;
3687 pNew->nDeferredImmCons = db->nDeferredImmCons;
3690 }else{
3691 assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
3692 iSavepoint = 0;
3694 /* Find the named savepoint. If there is no such savepoint, then an
3695 ** an error is returned to the user. */
3696 for(
3697 pSavepoint = db->pSavepoint;
3698 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3699 pSavepoint = pSavepoint->pNext
3701 iSavepoint++;
3703 if( !pSavepoint ){
3704 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3705 rc = SQLITE_ERROR;
3706 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3707 /* It is not possible to release (commit) a savepoint if there are
3708 ** active write statements.
3710 sqlite3VdbeError(p, "cannot release savepoint - "
3711 "SQL statements in progress");
3712 rc = SQLITE_BUSY;
3713 }else{
3715 /* Determine whether or not this is a transaction savepoint. If so,
3716 ** and this is a RELEASE command, then the current transaction
3717 ** is committed.
3719 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3720 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3721 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3722 goto vdbe_return;
3724 db->autoCommit = 1;
3725 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3726 p->pc = (int)(pOp - aOp);
3727 db->autoCommit = 0;
3728 p->rc = rc = SQLITE_BUSY;
3729 goto vdbe_return;
3731 rc = p->rc;
3732 if( rc ){
3733 db->autoCommit = 0;
3734 }else{
3735 db->isTransactionSavepoint = 0;
3737 }else{
3738 int isSchemaChange;
3739 iSavepoint = db->nSavepoint - iSavepoint - 1;
3740 if( p1==SAVEPOINT_ROLLBACK ){
3741 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3742 for(ii=0; ii<db->nDb; ii++){
3743 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3744 SQLITE_ABORT_ROLLBACK,
3745 isSchemaChange==0);
3746 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3748 }else{
3749 assert( p1==SAVEPOINT_RELEASE );
3750 isSchemaChange = 0;
3752 for(ii=0; ii<db->nDb; ii++){
3753 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3754 if( rc!=SQLITE_OK ){
3755 goto abort_due_to_error;
3758 if( isSchemaChange ){
3759 sqlite3ExpirePreparedStatements(db, 0);
3760 sqlite3ResetAllSchemasOfConnection(db);
3761 db->mDbFlags |= DBFLAG_SchemaChange;
3764 if( rc ) goto abort_due_to_error;
3766 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3767 ** savepoints nested inside of the savepoint being operated on. */
3768 while( db->pSavepoint!=pSavepoint ){
3769 pTmp = db->pSavepoint;
3770 db->pSavepoint = pTmp->pNext;
3771 sqlite3DbFree(db, pTmp);
3772 db->nSavepoint--;
3775 /* If it is a RELEASE, then destroy the savepoint being operated on
3776 ** too. If it is a ROLLBACK TO, then set the number of deferred
3777 ** constraint violations present in the database to the value stored
3778 ** when the savepoint was created. */
3779 if( p1==SAVEPOINT_RELEASE ){
3780 assert( pSavepoint==db->pSavepoint );
3781 db->pSavepoint = pSavepoint->pNext;
3782 sqlite3DbFree(db, pSavepoint);
3783 if( !isTransaction ){
3784 db->nSavepoint--;
3786 }else{
3787 assert( p1==SAVEPOINT_ROLLBACK );
3788 db->nDeferredCons = pSavepoint->nDeferredCons;
3789 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3792 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3793 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3794 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3798 if( rc ) goto abort_due_to_error;
3799 if( p->eVdbeState==VDBE_HALT_STATE ){
3800 rc = SQLITE_DONE;
3801 goto vdbe_return;
3803 break;
3806 /* Opcode: AutoCommit P1 P2 * * *
3808 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3809 ** back any currently active btree transactions. If there are any active
3810 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3811 ** there are active writing VMs or active VMs that use shared cache.
3813 ** This instruction causes the VM to halt.
3815 case OP_AutoCommit: {
3816 int desiredAutoCommit;
3817 int iRollback;
3819 desiredAutoCommit = pOp->p1;
3820 iRollback = pOp->p2;
3821 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3822 assert( desiredAutoCommit==1 || iRollback==0 );
3823 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3824 assert( p->bIsReader );
3826 if( desiredAutoCommit!=db->autoCommit ){
3827 if( iRollback ){
3828 assert( desiredAutoCommit==1 );
3829 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3830 db->autoCommit = 1;
3831 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3832 /* If this instruction implements a COMMIT and other VMs are writing
3833 ** return an error indicating that the other VMs must complete first.
3835 sqlite3VdbeError(p, "cannot commit transaction - "
3836 "SQL statements in progress");
3837 rc = SQLITE_BUSY;
3838 goto abort_due_to_error;
3839 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3840 goto vdbe_return;
3841 }else{
3842 db->autoCommit = (u8)desiredAutoCommit;
3844 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3845 p->pc = (int)(pOp - aOp);
3846 db->autoCommit = (u8)(1-desiredAutoCommit);
3847 p->rc = rc = SQLITE_BUSY;
3848 goto vdbe_return;
3850 sqlite3CloseSavepoints(db);
3851 if( p->rc==SQLITE_OK ){
3852 rc = SQLITE_DONE;
3853 }else{
3854 rc = SQLITE_ERROR;
3856 goto vdbe_return;
3857 }else{
3858 sqlite3VdbeError(p,
3859 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3860 (iRollback)?"cannot rollback - no transaction is active":
3861 "cannot commit - no transaction is active"));
3863 rc = SQLITE_ERROR;
3864 goto abort_due_to_error;
3866 /*NOTREACHED*/ assert(0);
3869 /* Opcode: Transaction P1 P2 P3 P4 P5
3871 ** Begin a transaction on database P1 if a transaction is not already
3872 ** active.
3873 ** If P2 is non-zero, then a write-transaction is started, or if a
3874 ** read-transaction is already active, it is upgraded to a write-transaction.
3875 ** If P2 is zero, then a read-transaction is started. If P2 is 2 or more
3876 ** then an exclusive transaction is started.
3878 ** P1 is the index of the database file on which the transaction is
3879 ** started. Index 0 is the main database file and index 1 is the
3880 ** file used for temporary tables. Indices of 2 or more are used for
3881 ** attached databases.
3883 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3884 ** true (this flag is set if the Vdbe may modify more than one row and may
3885 ** throw an ABORT exception), a statement transaction may also be opened.
3886 ** More specifically, a statement transaction is opened iff the database
3887 ** connection is currently not in autocommit mode, or if there are other
3888 ** active statements. A statement transaction allows the changes made by this
3889 ** VDBE to be rolled back after an error without having to roll back the
3890 ** entire transaction. If no error is encountered, the statement transaction
3891 ** will automatically commit when the VDBE halts.
3893 ** If P5!=0 then this opcode also checks the schema cookie against P3
3894 ** and the schema generation counter against P4.
3895 ** The cookie changes its value whenever the database schema changes.
3896 ** This operation is used to detect when that the cookie has changed
3897 ** and that the current process needs to reread the schema. If the schema
3898 ** cookie in P3 differs from the schema cookie in the database header or
3899 ** if the schema generation counter in P4 differs from the current
3900 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3901 ** halts. The sqlite3_step() wrapper function might then reprepare the
3902 ** statement and rerun it from the beginning.
3904 case OP_Transaction: {
3905 Btree *pBt;
3906 Db *pDb;
3907 int iMeta = 0;
3909 assert( p->bIsReader );
3910 assert( p->readOnly==0 || pOp->p2==0 );
3911 assert( pOp->p2>=0 && pOp->p2<=2 );
3912 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3913 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3914 assert( rc==SQLITE_OK );
3915 if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
3916 if( db->flags & SQLITE_QueryOnly ){
3917 /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
3918 rc = SQLITE_READONLY;
3919 }else{
3920 /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
3921 ** transaction */
3922 rc = SQLITE_CORRUPT;
3924 goto abort_due_to_error;
3926 pDb = &db->aDb[pOp->p1];
3927 pBt = pDb->pBt;
3929 if( pBt ){
3930 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
3931 testcase( rc==SQLITE_BUSY_SNAPSHOT );
3932 testcase( rc==SQLITE_BUSY_RECOVERY );
3933 if( rc!=SQLITE_OK ){
3934 if( (rc&0xff)==SQLITE_BUSY ){
3935 p->pc = (int)(pOp - aOp);
3936 p->rc = rc;
3937 goto vdbe_return;
3939 goto abort_due_to_error;
3942 if( p->usesStmtJournal
3943 && pOp->p2
3944 && (db->autoCommit==0 || db->nVdbeRead>1)
3946 assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
3947 if( p->iStatement==0 ){
3948 assert( db->nStatement>=0 && db->nSavepoint>=0 );
3949 db->nStatement++;
3950 p->iStatement = db->nSavepoint + db->nStatement;
3953 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3954 if( rc==SQLITE_OK ){
3955 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3958 /* Store the current value of the database handles deferred constraint
3959 ** counter. If the statement transaction needs to be rolled back,
3960 ** the value of this counter needs to be restored too. */
3961 p->nStmtDefCons = db->nDeferredCons;
3962 p->nStmtDefImmCons = db->nDeferredImmCons;
3965 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3966 if( rc==SQLITE_OK
3967 && pOp->p5
3968 && (iMeta!=pOp->p3 || pDb->pSchema->iGeneration!=pOp->p4.i)
3971 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3972 ** version is checked to ensure that the schema has not changed since the
3973 ** SQL statement was prepared.
3975 sqlite3DbFree(db, p->zErrMsg);
3976 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3977 /* If the schema-cookie from the database file matches the cookie
3978 ** stored with the in-memory representation of the schema, do
3979 ** not reload the schema from the database file.
3981 ** If virtual-tables are in use, this is not just an optimization.
3982 ** Often, v-tables store their data in other SQLite tables, which
3983 ** are queried from within xNext() and other v-table methods using
3984 ** prepared queries. If such a query is out-of-date, we do not want to
3985 ** discard the database schema, as the user code implementing the
3986 ** v-table would have to be ready for the sqlite3_vtab structure itself
3987 ** to be invalidated whenever sqlite3_step() is called from within
3988 ** a v-table method.
3990 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3991 sqlite3ResetOneSchema(db, pOp->p1);
3993 p->expired = 1;
3994 rc = SQLITE_SCHEMA;
3996 /* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
3997 ** from being modified in sqlite3VdbeHalt(). If this statement is
3998 ** reprepared, changeCntOn will be set again. */
3999 p->changeCntOn = 0;
4001 if( rc ) goto abort_due_to_error;
4002 break;
4005 /* Opcode: ReadCookie P1 P2 P3 * *
4007 ** Read cookie number P3 from database P1 and write it into register P2.
4008 ** P3==1 is the schema version. P3==2 is the database format.
4009 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
4010 ** the main database file and P1==1 is the database file used to store
4011 ** temporary tables.
4013 ** There must be a read-lock on the database (either a transaction
4014 ** must be started or there must be an open cursor) before
4015 ** executing this instruction.
4017 case OP_ReadCookie: { /* out2 */
4018 int iMeta;
4019 int iDb;
4020 int iCookie;
4022 assert( p->bIsReader );
4023 iDb = pOp->p1;
4024 iCookie = pOp->p3;
4025 assert( pOp->p3<SQLITE_N_BTREE_META );
4026 assert( iDb>=0 && iDb<db->nDb );
4027 assert( db->aDb[iDb].pBt!=0 );
4028 assert( DbMaskTest(p->btreeMask, iDb) );
4030 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
4031 pOut = out2Prerelease(p, pOp);
4032 pOut->u.i = iMeta;
4033 break;
4036 /* Opcode: SetCookie P1 P2 P3 * P5
4038 ** Write the integer value P3 into cookie number P2 of database P1.
4039 ** P2==1 is the schema version. P2==2 is the database format.
4040 ** P2==3 is the recommended pager cache
4041 ** size, and so forth. P1==0 is the main database file and P1==1 is the
4042 ** database file used to store temporary tables.
4044 ** A transaction must be started before executing this opcode.
4046 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
4047 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
4048 ** has P5 set to 1, so that the internal schema version will be different
4049 ** from the database schema version, resulting in a schema reset.
4051 case OP_SetCookie: {
4052 Db *pDb;
4054 sqlite3VdbeIncrWriteCounter(p, 0);
4055 assert( pOp->p2<SQLITE_N_BTREE_META );
4056 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4057 assert( DbMaskTest(p->btreeMask, pOp->p1) );
4058 assert( p->readOnly==0 );
4059 pDb = &db->aDb[pOp->p1];
4060 assert( pDb->pBt!=0 );
4061 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
4062 /* See note about index shifting on OP_ReadCookie */
4063 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
4064 if( pOp->p2==BTREE_SCHEMA_VERSION ){
4065 /* When the schema cookie changes, record the new cookie internally */
4066 *(u32*)&pDb->pSchema->schema_cookie = *(u32*)&pOp->p3 - pOp->p5;
4067 db->mDbFlags |= DBFLAG_SchemaChange;
4068 sqlite3FkClearTriggerCache(db, pOp->p1);
4069 }else if( pOp->p2==BTREE_FILE_FORMAT ){
4070 /* Record changes in the file format */
4071 pDb->pSchema->file_format = pOp->p3;
4073 if( pOp->p1==1 ){
4074 /* Invalidate all prepared statements whenever the TEMP database
4075 ** schema is changed. Ticket #1644 */
4076 sqlite3ExpirePreparedStatements(db, 0);
4077 p->expired = 0;
4079 if( rc ) goto abort_due_to_error;
4080 break;
4083 /* Opcode: OpenRead P1 P2 P3 P4 P5
4084 ** Synopsis: root=P2 iDb=P3
4086 ** Open a read-only cursor for the database table whose root page is
4087 ** P2 in a database file. The database file is determined by P3.
4088 ** P3==0 means the main database, P3==1 means the database used for
4089 ** temporary tables, and P3>1 means used the corresponding attached
4090 ** database. Give the new cursor an identifier of P1. The P1
4091 ** values need not be contiguous but all P1 values should be small integers.
4092 ** It is an error for P1 to be negative.
4094 ** Allowed P5 bits:
4095 ** <ul>
4096 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4097 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4098 ** of OP_SeekLE/OP_IdxLT)
4099 ** </ul>
4101 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4102 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4103 ** object, then table being opened must be an [index b-tree] where the
4104 ** KeyInfo object defines the content and collating
4105 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4106 ** value, then the table being opened must be a [table b-tree] with a
4107 ** number of columns no less than the value of P4.
4109 ** See also: OpenWrite, ReopenIdx
4111 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
4112 ** Synopsis: root=P2 iDb=P3
4114 ** The ReopenIdx opcode works like OP_OpenRead except that it first
4115 ** checks to see if the cursor on P1 is already open on the same
4116 ** b-tree and if it is this opcode becomes a no-op. In other words,
4117 ** if the cursor is already open, do not reopen it.
4119 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
4120 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
4121 ** be the same as every other ReopenIdx or OpenRead for the same cursor
4122 ** number.
4124 ** Allowed P5 bits:
4125 ** <ul>
4126 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4127 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4128 ** of OP_SeekLE/OP_IdxLT)
4129 ** </ul>
4131 ** See also: OP_OpenRead, OP_OpenWrite
4133 /* Opcode: OpenWrite P1 P2 P3 P4 P5
4134 ** Synopsis: root=P2 iDb=P3
4136 ** Open a read/write cursor named P1 on the table or index whose root
4137 ** page is P2 (or whose root page is held in register P2 if the
4138 ** OPFLAG_P2ISREG bit is set in P5 - see below).
4140 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4141 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4142 ** object, then table being opened must be an [index b-tree] where the
4143 ** KeyInfo object defines the content and collating
4144 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4145 ** value, then the table being opened must be a [table b-tree] with a
4146 ** number of columns no less than the value of P4.
4148 ** Allowed P5 bits:
4149 ** <ul>
4150 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4151 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4152 ** of OP_SeekLE/OP_IdxLT)
4153 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
4154 ** and subsequently delete entries in an index btree. This is a
4155 ** hint to the storage engine that the storage engine is allowed to
4156 ** ignore. The hint is not used by the official SQLite b*tree storage
4157 ** engine, but is used by COMDB2.
4158 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
4159 ** as the root page, not the value of P2 itself.
4160 ** </ul>
4162 ** This instruction works like OpenRead except that it opens the cursor
4163 ** in read/write mode.
4165 ** See also: OP_OpenRead, OP_ReopenIdx
4167 case OP_ReopenIdx: { /* ncycle */
4168 int nField;
4169 KeyInfo *pKeyInfo;
4170 u32 p2;
4171 int iDb;
4172 int wrFlag;
4173 Btree *pX;
4174 VdbeCursor *pCur;
4175 Db *pDb;
4177 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4178 assert( pOp->p4type==P4_KEYINFO );
4179 pCur = p->apCsr[pOp->p1];
4180 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
4181 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
4182 assert( pCur->eCurType==CURTYPE_BTREE );
4183 sqlite3BtreeClearCursor(pCur->uc.pCursor);
4184 goto open_cursor_set_hints;
4186 /* If the cursor is not currently open or is open on a different
4187 ** index, then fall through into OP_OpenRead to force a reopen */
4188 case OP_OpenRead: /* ncycle */
4189 case OP_OpenWrite:
4191 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4192 assert( p->bIsReader );
4193 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
4194 || p->readOnly==0 );
4196 if( p->expired==1 ){
4197 rc = SQLITE_ABORT_ROLLBACK;
4198 goto abort_due_to_error;
4201 nField = 0;
4202 pKeyInfo = 0;
4203 p2 = (u32)pOp->p2;
4204 iDb = pOp->p3;
4205 assert( iDb>=0 && iDb<db->nDb );
4206 assert( DbMaskTest(p->btreeMask, iDb) );
4207 pDb = &db->aDb[iDb];
4208 pX = pDb->pBt;
4209 assert( pX!=0 );
4210 if( pOp->opcode==OP_OpenWrite ){
4211 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
4212 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
4213 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4214 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
4215 p->minWriteFileFormat = pDb->pSchema->file_format;
4217 }else{
4218 wrFlag = 0;
4220 if( pOp->p5 & OPFLAG_P2ISREG ){
4221 assert( p2>0 );
4222 assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
4223 assert( pOp->opcode==OP_OpenWrite );
4224 pIn2 = &aMem[p2];
4225 assert( memIsValid(pIn2) );
4226 assert( (pIn2->flags & MEM_Int)!=0 );
4227 sqlite3VdbeMemIntegerify(pIn2);
4228 p2 = (int)pIn2->u.i;
4229 /* The p2 value always comes from a prior OP_CreateBtree opcode and
4230 ** that opcode will always set the p2 value to 2 or more or else fail.
4231 ** If there were a failure, the prepared statement would have halted
4232 ** before reaching this instruction. */
4233 assert( p2>=2 );
4235 if( pOp->p4type==P4_KEYINFO ){
4236 pKeyInfo = pOp->p4.pKeyInfo;
4237 assert( pKeyInfo->enc==ENC(db) );
4238 assert( pKeyInfo->db==db );
4239 nField = pKeyInfo->nAllField;
4240 }else if( pOp->p4type==P4_INT32 ){
4241 nField = pOp->p4.i;
4243 assert( pOp->p1>=0 );
4244 assert( nField>=0 );
4245 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
4246 pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
4247 if( pCur==0 ) goto no_mem;
4248 pCur->iDb = iDb;
4249 pCur->nullRow = 1;
4250 pCur->isOrdered = 1;
4251 pCur->pgnoRoot = p2;
4252 #ifdef SQLITE_DEBUG
4253 pCur->wrFlag = wrFlag;
4254 #endif
4255 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
4256 pCur->pKeyInfo = pKeyInfo;
4257 /* Set the VdbeCursor.isTable variable. Previous versions of
4258 ** SQLite used to check if the root-page flags were sane at this point
4259 ** and report database corruption if they were not, but this check has
4260 ** since moved into the btree layer. */
4261 pCur->isTable = pOp->p4type!=P4_KEYINFO;
4263 open_cursor_set_hints:
4264 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
4265 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
4266 testcase( pOp->p5 & OPFLAG_BULKCSR );
4267 testcase( pOp->p2 & OPFLAG_SEEKEQ );
4268 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
4269 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
4270 if( rc ) goto abort_due_to_error;
4271 break;
4274 /* Opcode: OpenDup P1 P2 * * *
4276 ** Open a new cursor P1 that points to the same ephemeral table as
4277 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
4278 ** opcode. Only ephemeral cursors may be duplicated.
4280 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
4282 case OP_OpenDup: { /* ncycle */
4283 VdbeCursor *pOrig; /* The original cursor to be duplicated */
4284 VdbeCursor *pCx; /* The new cursor */
4286 pOrig = p->apCsr[pOp->p2];
4287 assert( pOrig );
4288 assert( pOrig->isEphemeral ); /* Only ephemeral cursors can be duplicated */
4290 pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
4291 if( pCx==0 ) goto no_mem;
4292 pCx->nullRow = 1;
4293 pCx->isEphemeral = 1;
4294 pCx->pKeyInfo = pOrig->pKeyInfo;
4295 pCx->isTable = pOrig->isTable;
4296 pCx->pgnoRoot = pOrig->pgnoRoot;
4297 pCx->isOrdered = pOrig->isOrdered;
4298 pCx->ub.pBtx = pOrig->ub.pBtx;
4299 pCx->noReuse = 1;
4300 pOrig->noReuse = 1;
4301 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4302 pCx->pKeyInfo, pCx->uc.pCursor);
4303 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
4304 ** opened for a database. Since there is already an open cursor when this
4305 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
4306 assert( rc==SQLITE_OK );
4307 break;
4311 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5
4312 ** Synopsis: nColumn=P2
4314 ** Open a new cursor P1 to a transient table.
4315 ** The cursor is always opened read/write even if
4316 ** the main database is read-only. The ephemeral
4317 ** table is deleted automatically when the cursor is closed.
4319 ** If the cursor P1 is already opened on an ephemeral table, the table
4320 ** is cleared (all content is erased).
4322 ** P2 is the number of columns in the ephemeral table.
4323 ** The cursor points to a BTree table if P4==0 and to a BTree index
4324 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
4325 ** that defines the format of keys in the index.
4327 ** The P5 parameter can be a mask of the BTREE_* flags defined
4328 ** in btree.h. These flags control aspects of the operation of
4329 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
4330 ** added automatically.
4332 ** If P3 is positive, then reg[P3] is modified slightly so that it
4333 ** can be used as zero-length data for OP_Insert. This is an optimization
4334 ** that avoids an extra OP_Blob opcode to initialize that register.
4336 /* Opcode: OpenAutoindex P1 P2 * P4 *
4337 ** Synopsis: nColumn=P2
4339 ** This opcode works the same as OP_OpenEphemeral. It has a
4340 ** different name to distinguish its use. Tables created using
4341 ** by this opcode will be used for automatically created transient
4342 ** indices in joins.
4344 case OP_OpenAutoindex: /* ncycle */
4345 case OP_OpenEphemeral: { /* ncycle */
4346 VdbeCursor *pCx;
4347 KeyInfo *pKeyInfo;
4349 static const int vfsFlags =
4350 SQLITE_OPEN_READWRITE |
4351 SQLITE_OPEN_CREATE |
4352 SQLITE_OPEN_EXCLUSIVE |
4353 SQLITE_OPEN_DELETEONCLOSE |
4354 SQLITE_OPEN_TRANSIENT_DB;
4355 assert( pOp->p1>=0 );
4356 assert( pOp->p2>=0 );
4357 if( pOp->p3>0 ){
4358 /* Make register reg[P3] into a value that can be used as the data
4359 ** form sqlite3BtreeInsert() where the length of the data is zero. */
4360 assert( pOp->p2==0 ); /* Only used when number of columns is zero */
4361 assert( pOp->opcode==OP_OpenEphemeral );
4362 assert( aMem[pOp->p3].flags & MEM_Null );
4363 aMem[pOp->p3].n = 0;
4364 aMem[pOp->p3].z = "";
4366 pCx = p->apCsr[pOp->p1];
4367 if( pCx && !pCx->noReuse && ALWAYS(pOp->p2<=pCx->nField) ){
4368 /* If the ephermeral table is already open and has no duplicates from
4369 ** OP_OpenDup, then erase all existing content so that the table is
4370 ** empty again, rather than creating a new table. */
4371 assert( pCx->isEphemeral );
4372 pCx->seqCount = 0;
4373 pCx->cacheStatus = CACHE_STALE;
4374 rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
4375 }else{
4376 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
4377 if( pCx==0 ) goto no_mem;
4378 pCx->isEphemeral = 1;
4379 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
4380 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
4381 vfsFlags);
4382 if( rc==SQLITE_OK ){
4383 rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
4384 if( rc==SQLITE_OK ){
4385 /* If a transient index is required, create it by calling
4386 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
4387 ** opening it. If a transient table is required, just use the
4388 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
4390 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
4391 assert( pOp->p4type==P4_KEYINFO );
4392 rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
4393 BTREE_BLOBKEY | pOp->p5);
4394 if( rc==SQLITE_OK ){
4395 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
4396 assert( pKeyInfo->db==db );
4397 assert( pKeyInfo->enc==ENC(db) );
4398 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4399 pKeyInfo, pCx->uc.pCursor);
4401 pCx->isTable = 0;
4402 }else{
4403 pCx->pgnoRoot = SCHEMA_ROOT;
4404 rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
4405 0, pCx->uc.pCursor);
4406 pCx->isTable = 1;
4409 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
4410 if( rc ){
4411 sqlite3BtreeClose(pCx->ub.pBtx);
4415 if( rc ) goto abort_due_to_error;
4416 pCx->nullRow = 1;
4417 break;
4420 /* Opcode: SorterOpen P1 P2 P3 P4 *
4422 ** This opcode works like OP_OpenEphemeral except that it opens
4423 ** a transient index that is specifically designed to sort large
4424 ** tables using an external merge-sort algorithm.
4426 ** If argument P3 is non-zero, then it indicates that the sorter may
4427 ** assume that a stable sort considering the first P3 fields of each
4428 ** key is sufficient to produce the required results.
4430 case OP_SorterOpen: {
4431 VdbeCursor *pCx;
4433 assert( pOp->p1>=0 );
4434 assert( pOp->p2>=0 );
4435 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
4436 if( pCx==0 ) goto no_mem;
4437 pCx->pKeyInfo = pOp->p4.pKeyInfo;
4438 assert( pCx->pKeyInfo->db==db );
4439 assert( pCx->pKeyInfo->enc==ENC(db) );
4440 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4441 if( rc ) goto abort_due_to_error;
4442 break;
4445 /* Opcode: SequenceTest P1 P2 * * *
4446 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4448 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4449 ** to P2. Regardless of whether or not the jump is taken, increment the
4450 ** the sequence value.
4452 case OP_SequenceTest: {
4453 VdbeCursor *pC;
4454 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4455 pC = p->apCsr[pOp->p1];
4456 assert( isSorter(pC) );
4457 if( (pC->seqCount++)==0 ){
4458 goto jump_to_p2;
4460 break;
4463 /* Opcode: OpenPseudo P1 P2 P3 * *
4464 ** Synopsis: P3 columns in r[P2]
4466 ** Open a new cursor that points to a fake table that contains a single
4467 ** row of data. The content of that one row is the content of memory
4468 ** register P2. In other words, cursor P1 becomes an alias for the
4469 ** MEM_Blob content contained in register P2.
4471 ** A pseudo-table created by this opcode is used to hold a single
4472 ** row output from the sorter so that the row can be decomposed into
4473 ** individual columns using the OP_Column opcode. The OP_Column opcode
4474 ** is the only cursor opcode that works with a pseudo-table.
4476 ** P3 is the number of fields in the records that will be stored by
4477 ** the pseudo-table.
4479 case OP_OpenPseudo: {
4480 VdbeCursor *pCx;
4482 assert( pOp->p1>=0 );
4483 assert( pOp->p3>=0 );
4484 pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
4485 if( pCx==0 ) goto no_mem;
4486 pCx->nullRow = 1;
4487 pCx->seekResult = pOp->p2;
4488 pCx->isTable = 1;
4489 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4490 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
4491 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4492 ** which is a performance optimization */
4493 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4494 assert( pOp->p5==0 );
4495 break;
4498 /* Opcode: Close P1 * * * *
4500 ** Close a cursor previously opened as P1. If P1 is not
4501 ** currently open, this instruction is a no-op.
4503 case OP_Close: { /* ncycle */
4504 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4505 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4506 p->apCsr[pOp->p1] = 0;
4507 break;
4510 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4511 /* Opcode: ColumnsUsed P1 * * P4 *
4513 ** This opcode (which only exists if SQLite was compiled with
4514 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4515 ** table or index for cursor P1 are used. P4 is a 64-bit integer
4516 ** (P4_INT64) in which the first 63 bits are one for each of the
4517 ** first 63 columns of the table or index that are actually used
4518 ** by the cursor. The high-order bit is set if any column after
4519 ** the 64th is used.
4521 case OP_ColumnsUsed: {
4522 VdbeCursor *pC;
4523 pC = p->apCsr[pOp->p1];
4524 assert( pC->eCurType==CURTYPE_BTREE );
4525 pC->maskUsed = *(u64*)pOp->p4.pI64;
4526 break;
4528 #endif
4530 /* Opcode: SeekGE P1 P2 P3 P4 *
4531 ** Synopsis: key=r[P3@P4]
4533 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4534 ** use the value in register P3 as the key. If cursor P1 refers
4535 ** to an SQL index, then P3 is the first in an array of P4 registers
4536 ** that are used as an unpacked index key.
4538 ** Reposition cursor P1 so that it points to the smallest entry that
4539 ** is greater than or equal to the key value. If there are no records
4540 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4542 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4543 ** opcode will either land on a record that exactly matches the key, or
4544 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4545 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4546 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4547 ** IdxGT opcode will be used on subsequent loop iterations. The
4548 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4549 ** is an equality search.
4551 ** This opcode leaves the cursor configured to move in forward order,
4552 ** from the beginning toward the end. In other words, the cursor is
4553 ** configured to use Next, not Prev.
4555 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4557 /* Opcode: SeekGT P1 P2 P3 P4 *
4558 ** Synopsis: key=r[P3@P4]
4560 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4561 ** use the value in register P3 as a key. If cursor P1 refers
4562 ** to an SQL index, then P3 is the first in an array of P4 registers
4563 ** that are used as an unpacked index key.
4565 ** Reposition cursor P1 so that it points to the smallest entry that
4566 ** is greater than the key value. If there are no records greater than
4567 ** the key and P2 is not zero, then jump to P2.
4569 ** This opcode leaves the cursor configured to move in forward order,
4570 ** from the beginning toward the end. In other words, the cursor is
4571 ** configured to use Next, not Prev.
4573 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4575 /* Opcode: SeekLT P1 P2 P3 P4 *
4576 ** Synopsis: key=r[P3@P4]
4578 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4579 ** use the value in register P3 as a key. If cursor P1 refers
4580 ** to an SQL index, then P3 is the first in an array of P4 registers
4581 ** that are used as an unpacked index key.
4583 ** Reposition cursor P1 so that it points to the largest entry that
4584 ** is less than the key value. If there are no records less than
4585 ** the key and P2 is not zero, then jump to P2.
4587 ** This opcode leaves the cursor configured to move in reverse order,
4588 ** from the end toward the beginning. In other words, the cursor is
4589 ** configured to use Prev, not Next.
4591 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4593 /* Opcode: SeekLE P1 P2 P3 P4 *
4594 ** Synopsis: key=r[P3@P4]
4596 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4597 ** use the value in register P3 as a key. If cursor P1 refers
4598 ** to an SQL index, then P3 is the first in an array of P4 registers
4599 ** that are used as an unpacked index key.
4601 ** Reposition cursor P1 so that it points to the largest entry that
4602 ** is less than or equal to the key value. If there are no records
4603 ** less than or equal to the key and P2 is not zero, then jump to P2.
4605 ** This opcode leaves the cursor configured to move in reverse order,
4606 ** from the end toward the beginning. In other words, the cursor is
4607 ** configured to use Prev, not Next.
4609 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4610 ** opcode will either land on a record that exactly matches the key, or
4611 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4612 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4613 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4614 ** IdxGE opcode will be used on subsequent loop iterations. The
4615 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4616 ** is an equality search.
4618 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4620 case OP_SeekLT: /* jump, in3, group, ncycle */
4621 case OP_SeekLE: /* jump, in3, group, ncycle */
4622 case OP_SeekGE: /* jump, in3, group, ncycle */
4623 case OP_SeekGT: { /* jump, in3, group, ncycle */
4624 int res; /* Comparison result */
4625 int oc; /* Opcode */
4626 VdbeCursor *pC; /* The cursor to seek */
4627 UnpackedRecord r; /* The key to seek for */
4628 int nField; /* Number of columns or fields in the key */
4629 i64 iKey; /* The rowid we are to seek to */
4630 int eqOnly; /* Only interested in == results */
4632 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4633 assert( pOp->p2!=0 );
4634 pC = p->apCsr[pOp->p1];
4635 assert( pC!=0 );
4636 assert( pC->eCurType==CURTYPE_BTREE );
4637 assert( OP_SeekLE == OP_SeekLT+1 );
4638 assert( OP_SeekGE == OP_SeekLT+2 );
4639 assert( OP_SeekGT == OP_SeekLT+3 );
4640 assert( pC->isOrdered );
4641 assert( pC->uc.pCursor!=0 );
4642 oc = pOp->opcode;
4643 eqOnly = 0;
4644 pC->nullRow = 0;
4645 #ifdef SQLITE_DEBUG
4646 pC->seekOp = pOp->opcode;
4647 #endif
4649 pC->deferredMoveto = 0;
4650 pC->cacheStatus = CACHE_STALE;
4651 if( pC->isTable ){
4652 u16 flags3, newType;
4653 /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4654 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4655 || CORRUPT_DB );
4657 /* The input value in P3 might be of any type: integer, real, string,
4658 ** blob, or NULL. But it needs to be an integer before we can do
4659 ** the seek, so convert it. */
4660 pIn3 = &aMem[pOp->p3];
4661 flags3 = pIn3->flags;
4662 if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4663 applyNumericAffinity(pIn3, 0);
4665 iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4666 newType = pIn3->flags; /* Record the type after applying numeric affinity */
4667 pIn3->flags = flags3; /* But convert the type back to its original */
4669 /* If the P3 value could not be converted into an integer without
4670 ** loss of information, then special processing is required... */
4671 if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4672 int c;
4673 if( (newType & MEM_Real)==0 ){
4674 if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4675 VdbeBranchTaken(1,2);
4676 goto jump_to_p2;
4677 }else{
4678 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4679 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4680 goto seek_not_found;
4683 c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
4685 /* If the approximation iKey is larger than the actual real search
4686 ** term, substitute >= for > and < for <=. e.g. if the search term
4687 ** is 4.9 and the integer approximation 5:
4689 ** (x > 4.9) -> (x >= 5)
4690 ** (x <= 4.9) -> (x < 5)
4692 if( c>0 ){
4693 assert( OP_SeekGE==(OP_SeekGT-1) );
4694 assert( OP_SeekLT==(OP_SeekLE-1) );
4695 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4696 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4699 /* If the approximation iKey is smaller than the actual real search
4700 ** term, substitute <= for < and > for >=. */
4701 else if( c<0 ){
4702 assert( OP_SeekLE==(OP_SeekLT+1) );
4703 assert( OP_SeekGT==(OP_SeekGE+1) );
4704 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4705 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4708 rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
4709 pC->movetoTarget = iKey; /* Used by OP_Delete */
4710 if( rc!=SQLITE_OK ){
4711 goto abort_due_to_error;
4713 }else{
4714 /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4715 ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4716 ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4717 ** with the same key.
4719 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4720 eqOnly = 1;
4721 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4722 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4723 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4724 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4725 assert( pOp[1].p1==pOp[0].p1 );
4726 assert( pOp[1].p2==pOp[0].p2 );
4727 assert( pOp[1].p3==pOp[0].p3 );
4728 assert( pOp[1].p4.i==pOp[0].p4.i );
4731 nField = pOp->p4.i;
4732 assert( pOp->p4type==P4_INT32 );
4733 assert( nField>0 );
4734 r.pKeyInfo = pC->pKeyInfo;
4735 r.nField = (u16)nField;
4737 /* The next line of code computes as follows, only faster:
4738 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
4739 ** r.default_rc = -1;
4740 ** }else{
4741 ** r.default_rc = +1;
4742 ** }
4744 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4745 assert( oc!=OP_SeekGT || r.default_rc==-1 );
4746 assert( oc!=OP_SeekLE || r.default_rc==-1 );
4747 assert( oc!=OP_SeekGE || r.default_rc==+1 );
4748 assert( oc!=OP_SeekLT || r.default_rc==+1 );
4750 r.aMem = &aMem[pOp->p3];
4751 #ifdef SQLITE_DEBUG
4753 int i;
4754 for(i=0; i<r.nField; i++){
4755 assert( memIsValid(&r.aMem[i]) );
4756 if( i>0 ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
4759 #endif
4760 r.eqSeen = 0;
4761 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
4762 if( rc!=SQLITE_OK ){
4763 goto abort_due_to_error;
4765 if( eqOnly && r.eqSeen==0 ){
4766 assert( res!=0 );
4767 goto seek_not_found;
4770 #ifdef SQLITE_TEST
4771 sqlite3_search_count++;
4772 #endif
4773 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
4774 if( res<0 || (res==0 && oc==OP_SeekGT) ){
4775 res = 0;
4776 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4777 if( rc!=SQLITE_OK ){
4778 if( rc==SQLITE_DONE ){
4779 rc = SQLITE_OK;
4780 res = 1;
4781 }else{
4782 goto abort_due_to_error;
4785 }else{
4786 res = 0;
4788 }else{
4789 assert( oc==OP_SeekLT || oc==OP_SeekLE );
4790 if( res>0 || (res==0 && oc==OP_SeekLT) ){
4791 res = 0;
4792 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4793 if( rc!=SQLITE_OK ){
4794 if( rc==SQLITE_DONE ){
4795 rc = SQLITE_OK;
4796 res = 1;
4797 }else{
4798 goto abort_due_to_error;
4801 }else{
4802 /* res might be negative because the table is empty. Check to
4803 ** see if this is the case.
4805 res = sqlite3BtreeEof(pC->uc.pCursor);
4808 seek_not_found:
4809 assert( pOp->p2>0 );
4810 VdbeBranchTaken(res!=0,2);
4811 if( res ){
4812 goto jump_to_p2;
4813 }else if( eqOnly ){
4814 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4815 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4817 break;
4821 /* Opcode: SeekScan P1 P2 * * P5
4822 ** Synopsis: Scan-ahead up to P1 rows
4824 ** This opcode is a prefix opcode to OP_SeekGE. In other words, this
4825 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4826 ** checked by assert() statements.
4828 ** This opcode uses the P1 through P4 operands of the subsequent
4829 ** OP_SeekGE. In the text that follows, the operands of the subsequent
4830 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4. Only
4831 ** the P1, P2 and P5 operands of this opcode are also used, and are called
4832 ** This.P1, This.P2 and This.P5.
4834 ** This opcode helps to optimize IN operators on a multi-column index
4835 ** where the IN operator is on the later terms of the index by avoiding
4836 ** unnecessary seeks on the btree, substituting steps to the next row
4837 ** of the b-tree instead. A correct answer is obtained if this opcode
4838 ** is omitted or is a no-op.
4840 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4841 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4842 ** to. Call this SeekGE.P3/P4 row the "target".
4844 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4845 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4847 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4848 ** might be the target row, or it might be near and slightly before the
4849 ** target row, or it might be after the target row. If the cursor is
4850 ** currently before the target row, then this opcode attempts to position
4851 ** the cursor on or after the target row by invoking sqlite3BtreeStep()
4852 ** on the cursor between 1 and This.P1 times.
4854 ** The This.P5 parameter is a flag that indicates what to do if the
4855 ** cursor ends up pointing at a valid row that is past the target
4856 ** row. If This.P5 is false (0) then a jump is made to SeekGE.P2. If
4857 ** This.P5 is true (non-zero) then a jump is made to This.P2. The P5==0
4858 ** case occurs when there are no inequality constraints to the right of
4859 ** the IN constraing. The jump to SeekGE.P2 ends the loop. The P5!=0 case
4860 ** occurs when there are inequality constraints to the right of the IN
4861 ** operator. In that case, the This.P2 will point either directly to or
4862 ** to setup code prior to the OP_IdxGT or OP_IdxGE opcode that checks for
4863 ** loop terminate.
4865 ** Possible outcomes from this opcode:<ol>
4867 ** <li> If the cursor is initally not pointed to any valid row, then
4868 ** fall through into the subsequent OP_SeekGE opcode.
4870 ** <li> If the cursor is left pointing to a row that is before the target
4871 ** row, even after making as many as This.P1 calls to
4872 ** sqlite3BtreeNext(), then also fall through into OP_SeekGE.
4874 ** <li> If the cursor is left pointing at the target row, either because it
4875 ** was at the target row to begin with or because one or more
4876 ** sqlite3BtreeNext() calls moved the cursor to the target row,
4877 ** then jump to This.P2..,
4879 ** <li> If the cursor started out before the target row and a call to
4880 ** to sqlite3BtreeNext() moved the cursor off the end of the index
4881 ** (indicating that the target row definitely does not exist in the
4882 ** btree) then jump to SeekGE.P2, ending the loop.
4884 ** <li> If the cursor ends up on a valid row that is past the target row
4885 ** (indicating that the target row does not exist in the btree) then
4886 ** jump to SeekOP.P2 if This.P5==0 or to This.P2 if This.P5>0.
4887 ** </ol>
4889 case OP_SeekScan: { /* ncycle */
4890 VdbeCursor *pC;
4891 int res;
4892 int nStep;
4893 UnpackedRecord r;
4895 assert( pOp[1].opcode==OP_SeekGE );
4897 /* If pOp->p5 is clear, then pOp->p2 points to the first instruction past the
4898 ** OP_IdxGT that follows the OP_SeekGE. Otherwise, it points to the first
4899 ** opcode past the OP_SeekGE itself. */
4900 assert( pOp->p2>=(int)(pOp-aOp)+2 );
4901 #ifdef SQLITE_DEBUG
4902 if( pOp->p5==0 ){
4903 /* There are no inequality constraints following the IN constraint. */
4904 assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
4905 assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
4906 assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
4907 assert( aOp[pOp->p2-1].opcode==OP_IdxGT
4908 || aOp[pOp->p2-1].opcode==OP_IdxGE );
4909 testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
4910 }else{
4911 /* There are inequality constraints. */
4912 assert( pOp->p2==(int)(pOp-aOp)+2 );
4913 assert( aOp[pOp->p2-1].opcode==OP_SeekGE );
4915 #endif
4917 assert( pOp->p1>0 );
4918 pC = p->apCsr[pOp[1].p1];
4919 assert( pC!=0 );
4920 assert( pC->eCurType==CURTYPE_BTREE );
4921 assert( !pC->isTable );
4922 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
4923 #ifdef SQLITE_DEBUG
4924 if( db->flags&SQLITE_VdbeTrace ){
4925 printf("... cursor not valid - fall through\n");
4927 #endif
4928 break;
4930 nStep = pOp->p1;
4931 assert( nStep>=1 );
4932 r.pKeyInfo = pC->pKeyInfo;
4933 r.nField = (u16)pOp[1].p4.i;
4934 r.default_rc = 0;
4935 r.aMem = &aMem[pOp[1].p3];
4936 #ifdef SQLITE_DEBUG
4938 int i;
4939 for(i=0; i<r.nField; i++){
4940 assert( memIsValid(&r.aMem[i]) );
4941 REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
4944 #endif
4945 res = 0; /* Not needed. Only used to silence a warning. */
4946 while(1){
4947 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
4948 if( rc ) goto abort_due_to_error;
4949 if( res>0 && pOp->p5==0 ){
4950 seekscan_search_fail:
4951 /* Jump to SeekGE.P2, ending the loop */
4952 #ifdef SQLITE_DEBUG
4953 if( db->flags&SQLITE_VdbeTrace ){
4954 printf("... %d steps and then skip\n", pOp->p1 - nStep);
4956 #endif
4957 VdbeBranchTaken(1,3);
4958 pOp++;
4959 goto jump_to_p2;
4961 if( res>=0 ){
4962 /* Jump to This.P2, bypassing the OP_SeekGE opcode */
4963 #ifdef SQLITE_DEBUG
4964 if( db->flags&SQLITE_VdbeTrace ){
4965 printf("... %d steps and then success\n", pOp->p1 - nStep);
4967 #endif
4968 VdbeBranchTaken(2,3);
4969 goto jump_to_p2;
4970 break;
4972 if( nStep<=0 ){
4973 #ifdef SQLITE_DEBUG
4974 if( db->flags&SQLITE_VdbeTrace ){
4975 printf("... fall through after %d steps\n", pOp->p1);
4977 #endif
4978 VdbeBranchTaken(0,3);
4979 break;
4981 nStep--;
4982 pC->cacheStatus = CACHE_STALE;
4983 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4984 if( rc ){
4985 if( rc==SQLITE_DONE ){
4986 rc = SQLITE_OK;
4987 goto seekscan_search_fail;
4988 }else{
4989 goto abort_due_to_error;
4994 break;
4998 /* Opcode: SeekHit P1 P2 P3 * *
4999 ** Synopsis: set P2<=seekHit<=P3
5001 ** Increase or decrease the seekHit value for cursor P1, if necessary,
5002 ** so that it is no less than P2 and no greater than P3.
5004 ** The seekHit integer represents the maximum of terms in an index for which
5005 ** there is known to be at least one match. If the seekHit value is smaller
5006 ** than the total number of equality terms in an index lookup, then the
5007 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
5008 ** early, thus saving work. This is part of the IN-early-out optimization.
5010 ** P1 must be a valid b-tree cursor.
5012 case OP_SeekHit: { /* ncycle */
5013 VdbeCursor *pC;
5014 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5015 pC = p->apCsr[pOp->p1];
5016 assert( pC!=0 );
5017 assert( pOp->p3>=pOp->p2 );
5018 if( pC->seekHit<pOp->p2 ){
5019 #ifdef SQLITE_DEBUG
5020 if( db->flags&SQLITE_VdbeTrace ){
5021 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
5023 #endif
5024 pC->seekHit = pOp->p2;
5025 }else if( pC->seekHit>pOp->p3 ){
5026 #ifdef SQLITE_DEBUG
5027 if( db->flags&SQLITE_VdbeTrace ){
5028 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
5030 #endif
5031 pC->seekHit = pOp->p3;
5033 break;
5036 /* Opcode: IfNotOpen P1 P2 * * *
5037 ** Synopsis: if( !csr[P1] ) goto P2
5039 ** If cursor P1 is not open or if P1 is set to a NULL row using the
5040 ** OP_NullRow opcode, then jump to instruction P2. Otherwise, fall through.
5042 case OP_IfNotOpen: { /* jump */
5043 VdbeCursor *pCur;
5045 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5046 pCur = p->apCsr[pOp->p1];
5047 VdbeBranchTaken(pCur==0 || pCur->nullRow, 2);
5048 if( pCur==0 || pCur->nullRow ){
5049 goto jump_to_p2_and_check_for_interrupt;
5051 break;
5054 /* Opcode: Found P1 P2 P3 P4 *
5055 ** Synopsis: key=r[P3@P4]
5057 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5058 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5059 ** record.
5061 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5062 ** is a prefix of any entry in P1 then a jump is made to P2 and
5063 ** P1 is left pointing at the matching entry.
5065 ** This operation leaves the cursor in a state where it can be
5066 ** advanced in the forward direction. The Next instruction will work,
5067 ** but not the Prev instruction.
5069 ** See also: NotFound, NoConflict, NotExists. SeekGe
5071 /* Opcode: NotFound P1 P2 P3 P4 *
5072 ** Synopsis: key=r[P3@P4]
5074 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5075 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5076 ** record.
5078 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5079 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
5080 ** does contain an entry whose prefix matches the P3/P4 record then control
5081 ** falls through to the next instruction and P1 is left pointing at the
5082 ** matching entry.
5084 ** This operation leaves the cursor in a state where it cannot be
5085 ** advanced in either direction. In other words, the Next and Prev
5086 ** opcodes do not work after this operation.
5088 ** See also: Found, NotExists, NoConflict, IfNoHope
5090 /* Opcode: IfNoHope P1 P2 P3 P4 *
5091 ** Synopsis: key=r[P3@P4]
5093 ** Register P3 is the first of P4 registers that form an unpacked
5094 ** record. Cursor P1 is an index btree. P2 is a jump destination.
5095 ** In other words, the operands to this opcode are the same as the
5096 ** operands to OP_NotFound and OP_IdxGT.
5098 ** This opcode is an optimization attempt only. If this opcode always
5099 ** falls through, the correct answer is still obtained, but extra works
5100 ** is performed.
5102 ** A value of N in the seekHit flag of cursor P1 means that there exists
5103 ** a key P3:N that will match some record in the index. We want to know
5104 ** if it is possible for a record P3:P4 to match some record in the
5105 ** index. If it is not possible, we can skips some work. So if seekHit
5106 ** is less than P4, attempt to find out if a match is possible by running
5107 ** OP_NotFound.
5109 ** This opcode is used in IN clause processing for a multi-column key.
5110 ** If an IN clause is attached to an element of the key other than the
5111 ** left-most element, and if there are no matches on the most recent
5112 ** seek over the whole key, then it might be that one of the key element
5113 ** to the left is prohibiting a match, and hence there is "no hope" of
5114 ** any match regardless of how many IN clause elements are checked.
5115 ** In such a case, we abandon the IN clause search early, using this
5116 ** opcode. The opcode name comes from the fact that the
5117 ** jump is taken if there is "no hope" of achieving a match.
5119 ** See also: NotFound, SeekHit
5121 /* Opcode: NoConflict P1 P2 P3 P4 *
5122 ** Synopsis: key=r[P3@P4]
5124 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5125 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5126 ** record.
5128 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5129 ** contains any NULL value, jump immediately to P2. If all terms of the
5130 ** record are not-NULL then a check is done to determine if any row in the
5131 ** P1 index btree has a matching key prefix. If there are no matches, jump
5132 ** immediately to P2. If there is a match, fall through and leave the P1
5133 ** cursor pointing to the matching row.
5135 ** This opcode is similar to OP_NotFound with the exceptions that the
5136 ** branch is always taken if any part of the search key input is NULL.
5138 ** This operation leaves the cursor in a state where it cannot be
5139 ** advanced in either direction. In other words, the Next and Prev
5140 ** opcodes do not work after this operation.
5142 ** See also: NotFound, Found, NotExists
5144 case OP_IfNoHope: { /* jump, in3, ncycle */
5145 VdbeCursor *pC;
5146 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5147 pC = p->apCsr[pOp->p1];
5148 assert( pC!=0 );
5149 #ifdef SQLITE_DEBUG
5150 if( db->flags&SQLITE_VdbeTrace ){
5151 printf("seekHit is %d\n", pC->seekHit);
5153 #endif
5154 if( pC->seekHit>=pOp->p4.i ) break;
5155 /* Fall through into OP_NotFound */
5156 /* no break */ deliberate_fall_through
5158 case OP_NoConflict: /* jump, in3, ncycle */
5159 case OP_NotFound: /* jump, in3, ncycle */
5160 case OP_Found: { /* jump, in3, ncycle */
5161 int alreadyExists;
5162 int ii;
5163 VdbeCursor *pC;
5164 UnpackedRecord *pIdxKey;
5165 UnpackedRecord r;
5167 #ifdef SQLITE_TEST
5168 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
5169 #endif
5171 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5172 assert( pOp->p4type==P4_INT32 );
5173 pC = p->apCsr[pOp->p1];
5174 assert( pC!=0 );
5175 #ifdef SQLITE_DEBUG
5176 pC->seekOp = pOp->opcode;
5177 #endif
5178 r.aMem = &aMem[pOp->p3];
5179 assert( pC->eCurType==CURTYPE_BTREE );
5180 assert( pC->uc.pCursor!=0 );
5181 assert( pC->isTable==0 );
5182 r.nField = (u16)pOp->p4.i;
5183 if( r.nField>0 ){
5184 /* Key values in an array of registers */
5185 r.pKeyInfo = pC->pKeyInfo;
5186 r.default_rc = 0;
5187 #ifdef SQLITE_DEBUG
5188 for(ii=0; ii<r.nField; ii++){
5189 assert( memIsValid(&r.aMem[ii]) );
5190 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
5191 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
5193 #endif
5194 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &pC->seekResult);
5195 }else{
5196 /* Composite key generated by OP_MakeRecord */
5197 assert( r.aMem->flags & MEM_Blob );
5198 assert( pOp->opcode!=OP_NoConflict );
5199 rc = ExpandBlob(r.aMem);
5200 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
5201 if( rc ) goto no_mem;
5202 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
5203 if( pIdxKey==0 ) goto no_mem;
5204 sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);
5205 pIdxKey->default_rc = 0;
5206 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);
5207 sqlite3DbFreeNN(db, pIdxKey);
5209 if( rc!=SQLITE_OK ){
5210 goto abort_due_to_error;
5212 alreadyExists = (pC->seekResult==0);
5213 pC->nullRow = 1-alreadyExists;
5214 pC->deferredMoveto = 0;
5215 pC->cacheStatus = CACHE_STALE;
5216 if( pOp->opcode==OP_Found ){
5217 VdbeBranchTaken(alreadyExists!=0,2);
5218 if( alreadyExists ) goto jump_to_p2;
5219 }else{
5220 if( !alreadyExists ){
5221 VdbeBranchTaken(1,2);
5222 goto jump_to_p2;
5224 if( pOp->opcode==OP_NoConflict ){
5225 /* For the OP_NoConflict opcode, take the jump if any of the
5226 ** input fields are NULL, since any key with a NULL will not
5227 ** conflict */
5228 for(ii=0; ii<r.nField; ii++){
5229 if( r.aMem[ii].flags & MEM_Null ){
5230 VdbeBranchTaken(1,2);
5231 goto jump_to_p2;
5235 VdbeBranchTaken(0,2);
5236 if( pOp->opcode==OP_IfNoHope ){
5237 pC->seekHit = pOp->p4.i;
5240 break;
5243 /* Opcode: SeekRowid P1 P2 P3 * *
5244 ** Synopsis: intkey=r[P3]
5246 ** P1 is the index of a cursor open on an SQL table btree (with integer
5247 ** keys). If register P3 does not contain an integer or if P1 does not
5248 ** contain a record with rowid P3 then jump immediately to P2.
5249 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
5250 ** a record with rowid P3 then
5251 ** leave the cursor pointing at that record and fall through to the next
5252 ** instruction.
5254 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
5255 ** the P3 register must be guaranteed to contain an integer value. With this
5256 ** opcode, register P3 might not contain an integer.
5258 ** The OP_NotFound opcode performs the same operation on index btrees
5259 ** (with arbitrary multi-value keys).
5261 ** This opcode leaves the cursor in a state where it cannot be advanced
5262 ** in either direction. In other words, the Next and Prev opcodes will
5263 ** not work following this opcode.
5265 ** See also: Found, NotFound, NoConflict, SeekRowid
5267 /* Opcode: NotExists P1 P2 P3 * *
5268 ** Synopsis: intkey=r[P3]
5270 ** P1 is the index of a cursor open on an SQL table btree (with integer
5271 ** keys). P3 is an integer rowid. If P1 does not contain a record with
5272 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
5273 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
5274 ** leave the cursor pointing at that record and fall through to the next
5275 ** instruction.
5277 ** The OP_SeekRowid opcode performs the same operation but also allows the
5278 ** P3 register to contain a non-integer value, in which case the jump is
5279 ** always taken. This opcode requires that P3 always contain an integer.
5281 ** The OP_NotFound opcode performs the same operation on index btrees
5282 ** (with arbitrary multi-value keys).
5284 ** This opcode leaves the cursor in a state where it cannot be advanced
5285 ** in either direction. In other words, the Next and Prev opcodes will
5286 ** not work following this opcode.
5288 ** See also: Found, NotFound, NoConflict, SeekRowid
5290 case OP_SeekRowid: { /* jump, in3, ncycle */
5291 VdbeCursor *pC;
5292 BtCursor *pCrsr;
5293 int res;
5294 u64 iKey;
5296 pIn3 = &aMem[pOp->p3];
5297 testcase( pIn3->flags & MEM_Int );
5298 testcase( pIn3->flags & MEM_IntReal );
5299 testcase( pIn3->flags & MEM_Real );
5300 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
5301 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
5302 /* If pIn3->u.i does not contain an integer, compute iKey as the
5303 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
5304 ** into an integer without loss of information. Take care to avoid
5305 ** changing the datatype of pIn3, however, as it is used by other
5306 ** parts of the prepared statement. */
5307 Mem x = pIn3[0];
5308 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
5309 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
5310 iKey = x.u.i;
5311 goto notExistsWithKey;
5313 /* Fall through into OP_NotExists */
5314 /* no break */ deliberate_fall_through
5315 case OP_NotExists: /* jump, in3, ncycle */
5316 pIn3 = &aMem[pOp->p3];
5317 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
5318 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5319 iKey = pIn3->u.i;
5320 notExistsWithKey:
5321 pC = p->apCsr[pOp->p1];
5322 assert( pC!=0 );
5323 #ifdef SQLITE_DEBUG
5324 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
5325 #endif
5326 assert( pC->isTable );
5327 assert( pC->eCurType==CURTYPE_BTREE );
5328 pCrsr = pC->uc.pCursor;
5329 assert( pCrsr!=0 );
5330 res = 0;
5331 rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
5332 assert( rc==SQLITE_OK || res==0 );
5333 pC->movetoTarget = iKey; /* Used by OP_Delete */
5334 pC->nullRow = 0;
5335 pC->cacheStatus = CACHE_STALE;
5336 pC->deferredMoveto = 0;
5337 VdbeBranchTaken(res!=0,2);
5338 pC->seekResult = res;
5339 if( res!=0 ){
5340 assert( rc==SQLITE_OK );
5341 if( pOp->p2==0 ){
5342 rc = SQLITE_CORRUPT_BKPT;
5343 }else{
5344 goto jump_to_p2;
5347 if( rc ) goto abort_due_to_error;
5348 break;
5351 /* Opcode: Sequence P1 P2 * * *
5352 ** Synopsis: r[P2]=cursor[P1].ctr++
5354 ** Find the next available sequence number for cursor P1.
5355 ** Write the sequence number into register P2.
5356 ** The sequence number on the cursor is incremented after this
5357 ** instruction.
5359 case OP_Sequence: { /* out2 */
5360 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5361 assert( p->apCsr[pOp->p1]!=0 );
5362 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
5363 pOut = out2Prerelease(p, pOp);
5364 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
5365 break;
5369 /* Opcode: NewRowid P1 P2 P3 * *
5370 ** Synopsis: r[P2]=rowid
5372 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
5373 ** The record number is not previously used as a key in the database
5374 ** table that cursor P1 points to. The new record number is written
5375 ** written to register P2.
5377 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
5378 ** the largest previously generated record number. No new record numbers are
5379 ** allowed to be less than this value. When this value reaches its maximum,
5380 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
5381 ** generated record number. This P3 mechanism is used to help implement the
5382 ** AUTOINCREMENT feature.
5384 case OP_NewRowid: { /* out2 */
5385 i64 v; /* The new rowid */
5386 VdbeCursor *pC; /* Cursor of table to get the new rowid */
5387 int res; /* Result of an sqlite3BtreeLast() */
5388 int cnt; /* Counter to limit the number of searches */
5389 #ifndef SQLITE_OMIT_AUTOINCREMENT
5390 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
5391 VdbeFrame *pFrame; /* Root frame of VDBE */
5392 #endif
5394 v = 0;
5395 res = 0;
5396 pOut = out2Prerelease(p, pOp);
5397 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5398 pC = p->apCsr[pOp->p1];
5399 assert( pC!=0 );
5400 assert( pC->isTable );
5401 assert( pC->eCurType==CURTYPE_BTREE );
5402 assert( pC->uc.pCursor!=0 );
5404 /* The next rowid or record number (different terms for the same
5405 ** thing) is obtained in a two-step algorithm.
5407 ** First we attempt to find the largest existing rowid and add one
5408 ** to that. But if the largest existing rowid is already the maximum
5409 ** positive integer, we have to fall through to the second
5410 ** probabilistic algorithm
5412 ** The second algorithm is to select a rowid at random and see if
5413 ** it already exists in the table. If it does not exist, we have
5414 ** succeeded. If the random rowid does exist, we select a new one
5415 ** and try again, up to 100 times.
5417 assert( pC->isTable );
5419 #ifdef SQLITE_32BIT_ROWID
5420 # define MAX_ROWID 0x7fffffff
5421 #else
5422 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
5423 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
5424 ** to provide the constant while making all compilers happy.
5426 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
5427 #endif
5429 if( !pC->useRandomRowid ){
5430 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
5431 if( rc!=SQLITE_OK ){
5432 goto abort_due_to_error;
5434 if( res ){
5435 v = 1; /* IMP: R-61914-48074 */
5436 }else{
5437 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
5438 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5439 if( v>=MAX_ROWID ){
5440 pC->useRandomRowid = 1;
5441 }else{
5442 v++; /* IMP: R-29538-34987 */
5447 #ifndef SQLITE_OMIT_AUTOINCREMENT
5448 if( pOp->p3 ){
5449 /* Assert that P3 is a valid memory cell. */
5450 assert( pOp->p3>0 );
5451 if( p->pFrame ){
5452 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5453 /* Assert that P3 is a valid memory cell. */
5454 assert( pOp->p3<=pFrame->nMem );
5455 pMem = &pFrame->aMem[pOp->p3];
5456 }else{
5457 /* Assert that P3 is a valid memory cell. */
5458 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
5459 pMem = &aMem[pOp->p3];
5460 memAboutToChange(p, pMem);
5462 assert( memIsValid(pMem) );
5464 REGISTER_TRACE(pOp->p3, pMem);
5465 sqlite3VdbeMemIntegerify(pMem);
5466 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
5467 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
5468 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
5469 goto abort_due_to_error;
5471 if( v<pMem->u.i+1 ){
5472 v = pMem->u.i + 1;
5474 pMem->u.i = v;
5476 #endif
5477 if( pC->useRandomRowid ){
5478 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
5479 ** largest possible integer (9223372036854775807) then the database
5480 ** engine starts picking positive candidate ROWIDs at random until
5481 ** it finds one that is not previously used. */
5482 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
5483 ** an AUTOINCREMENT table. */
5484 cnt = 0;
5486 sqlite3_randomness(sizeof(v), &v);
5487 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
5488 }while( ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
5489 0, &res))==SQLITE_OK)
5490 && (res==0)
5491 && (++cnt<100));
5492 if( rc ) goto abort_due_to_error;
5493 if( res==0 ){
5494 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
5495 goto abort_due_to_error;
5497 assert( v>0 ); /* EV: R-40812-03570 */
5499 pC->deferredMoveto = 0;
5500 pC->cacheStatus = CACHE_STALE;
5502 pOut->u.i = v;
5503 break;
5506 /* Opcode: Insert P1 P2 P3 P4 P5
5507 ** Synopsis: intkey=r[P3] data=r[P2]
5509 ** Write an entry into the table of cursor P1. A new entry is
5510 ** created if it doesn't already exist or the data for an existing
5511 ** entry is overwritten. The data is the value MEM_Blob stored in register
5512 ** number P2. The key is stored in register P3. The key must
5513 ** be a MEM_Int.
5515 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5516 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
5517 ** then rowid is stored for subsequent return by the
5518 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5520 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5521 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5522 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5523 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5525 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5526 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
5527 ** is part of an INSERT operation. The difference is only important to
5528 ** the update hook.
5530 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5531 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5532 ** following a successful insert.
5534 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5535 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5536 ** and register P2 becomes ephemeral. If the cursor is changed, the
5537 ** value of register P2 will then change. Make sure this does not
5538 ** cause any problems.)
5540 ** This instruction only works on tables. The equivalent instruction
5541 ** for indices is OP_IdxInsert.
5543 case OP_Insert: {
5544 Mem *pData; /* MEM cell holding data for the record to be inserted */
5545 Mem *pKey; /* MEM cell holding key for the record */
5546 VdbeCursor *pC; /* Cursor to table into which insert is written */
5547 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
5548 const char *zDb; /* database name - used by the update hook */
5549 Table *pTab; /* Table structure - used by update and pre-update hooks */
5550 BtreePayload x; /* Payload to be inserted */
5552 pData = &aMem[pOp->p2];
5553 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5554 assert( memIsValid(pData) );
5555 pC = p->apCsr[pOp->p1];
5556 assert( pC!=0 );
5557 assert( pC->eCurType==CURTYPE_BTREE );
5558 assert( pC->deferredMoveto==0 );
5559 assert( pC->uc.pCursor!=0 );
5560 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5561 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5562 REGISTER_TRACE(pOp->p2, pData);
5563 sqlite3VdbeIncrWriteCounter(p, pC);
5565 pKey = &aMem[pOp->p3];
5566 assert( pKey->flags & MEM_Int );
5567 assert( memIsValid(pKey) );
5568 REGISTER_TRACE(pOp->p3, pKey);
5569 x.nKey = pKey->u.i;
5571 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5572 assert( pC->iDb>=0 );
5573 zDb = db->aDb[pC->iDb].zDbSName;
5574 pTab = pOp->p4.pTab;
5575 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5576 }else{
5577 pTab = 0;
5578 zDb = 0;
5581 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5582 /* Invoke the pre-update hook, if any */
5583 if( pTab ){
5584 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5585 sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
5587 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5588 /* Prevent post-update hook from running in cases when it should not */
5589 pTab = 0;
5592 if( pOp->p5 & OPFLAG_ISNOOP ) break;
5593 #endif
5595 assert( (pOp->p5 & OPFLAG_LASTROWID)==0 || (pOp->p5 & OPFLAG_NCHANGE)!=0 );
5596 if( pOp->p5 & OPFLAG_NCHANGE ){
5597 p->nChange++;
5598 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5600 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5601 x.pData = pData->z;
5602 x.nData = pData->n;
5603 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5604 if( pData->flags & MEM_Zero ){
5605 x.nZero = pData->u.nZero;
5606 }else{
5607 x.nZero = 0;
5609 x.pKey = 0;
5610 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
5611 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5612 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5613 seekResult
5615 pC->deferredMoveto = 0;
5616 pC->cacheStatus = CACHE_STALE;
5618 /* Invoke the update-hook if required. */
5619 if( rc ) goto abort_due_to_error;
5620 if( pTab ){
5621 assert( db->xUpdateCallback!=0 );
5622 assert( pTab->aCol!=0 );
5623 db->xUpdateCallback(db->pUpdateArg,
5624 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5625 zDb, pTab->zName, x.nKey);
5627 break;
5630 /* Opcode: RowCell P1 P2 P3 * *
5632 ** P1 and P2 are both open cursors. Both must be opened on the same type
5633 ** of table - intkey or index. This opcode is used as part of copying
5634 ** the current row from P2 into P1. If the cursors are opened on intkey
5635 ** tables, register P3 contains the rowid to use with the new record in
5636 ** P1. If they are opened on index tables, P3 is not used.
5638 ** This opcode must be followed by either an Insert or InsertIdx opcode
5639 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
5641 case OP_RowCell: {
5642 VdbeCursor *pDest; /* Cursor to write to */
5643 VdbeCursor *pSrc; /* Cursor to read from */
5644 i64 iKey; /* Rowid value to insert with */
5645 assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
5646 assert( pOp[1].opcode==OP_Insert || pOp->p3==0 );
5647 assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
5648 assert( pOp[1].p5 & OPFLAG_PREFORMAT );
5649 pDest = p->apCsr[pOp->p1];
5650 pSrc = p->apCsr[pOp->p2];
5651 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
5652 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
5653 if( rc!=SQLITE_OK ) goto abort_due_to_error;
5654 break;
5657 /* Opcode: Delete P1 P2 P3 P4 P5
5659 ** Delete the record at which the P1 cursor is currently pointing.
5661 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5662 ** the cursor will be left pointing at either the next or the previous
5663 ** record in the table. If it is left pointing at the next record, then
5664 ** the next Next instruction will be a no-op. As a result, in this case
5665 ** it is ok to delete a record from within a Next loop. If
5666 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5667 ** left in an undefined state.
5669 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5670 ** delete one of several associated with deleting a table row and all its
5671 ** associated index entries. Exactly one of those deletes is the "primary"
5672 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
5673 ** marked with the AUXDELETE flag.
5675 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
5676 ** change count is incremented (otherwise not).
5678 ** P1 must not be pseudo-table. It has to be a real table with
5679 ** multiple rows.
5681 ** If P4 is not NULL then it points to a Table object. In this case either
5682 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5683 ** have been positioned using OP_NotFound prior to invoking this opcode in
5684 ** this case. Specifically, if one is configured, the pre-update hook is
5685 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5686 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5688 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5689 ** of the memory cell that contains the value that the rowid of the row will
5690 ** be set to by the update.
5692 case OP_Delete: {
5693 VdbeCursor *pC;
5694 const char *zDb;
5695 Table *pTab;
5696 int opflags;
5698 opflags = pOp->p2;
5699 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5700 pC = p->apCsr[pOp->p1];
5701 assert( pC!=0 );
5702 assert( pC->eCurType==CURTYPE_BTREE );
5703 assert( pC->uc.pCursor!=0 );
5704 assert( pC->deferredMoveto==0 );
5705 sqlite3VdbeIncrWriteCounter(p, pC);
5707 #ifdef SQLITE_DEBUG
5708 if( pOp->p4type==P4_TABLE
5709 && HasRowid(pOp->p4.pTab)
5710 && pOp->p5==0
5711 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5713 /* If p5 is zero, the seek operation that positioned the cursor prior to
5714 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5715 ** the row that is being deleted */
5716 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5717 assert( CORRUPT_DB || pC->movetoTarget==iKey );
5719 #endif
5721 /* If the update-hook or pre-update-hook will be invoked, set zDb to
5722 ** the name of the db to pass as to it. Also set local pTab to a copy
5723 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5724 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5725 ** VdbeCursor.movetoTarget to the current rowid. */
5726 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5727 assert( pC->iDb>=0 );
5728 assert( pOp->p4.pTab!=0 );
5729 zDb = db->aDb[pC->iDb].zDbSName;
5730 pTab = pOp->p4.pTab;
5731 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5732 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5734 }else{
5735 zDb = 0;
5736 pTab = 0;
5739 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5740 /* Invoke the pre-update-hook if required. */
5741 assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
5742 if( db->xPreUpdateCallback && pTab ){
5743 assert( !(opflags & OPFLAG_ISUPDATE)
5744 || HasRowid(pTab)==0
5745 || (aMem[pOp->p3].flags & MEM_Int)
5747 sqlite3VdbePreUpdateHook(p, pC,
5748 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5749 zDb, pTab, pC->movetoTarget,
5750 pOp->p3, -1
5753 if( opflags & OPFLAG_ISNOOP ) break;
5754 #endif
5756 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5757 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5758 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5759 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5761 #ifdef SQLITE_DEBUG
5762 if( p->pFrame==0 ){
5763 if( pC->isEphemeral==0
5764 && (pOp->p5 & OPFLAG_AUXDELETE)==0
5765 && (pC->wrFlag & OPFLAG_FORDELETE)==0
5767 nExtraDelete++;
5769 if( pOp->p2 & OPFLAG_NCHANGE ){
5770 nExtraDelete--;
5773 #endif
5775 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5776 pC->cacheStatus = CACHE_STALE;
5777 pC->seekResult = 0;
5778 if( rc ) goto abort_due_to_error;
5780 /* Invoke the update-hook if required. */
5781 if( opflags & OPFLAG_NCHANGE ){
5782 p->nChange++;
5783 if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
5784 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5785 pC->movetoTarget);
5786 assert( pC->iDb>=0 );
5790 break;
5792 /* Opcode: ResetCount * * * * *
5794 ** The value of the change counter is copied to the database handle
5795 ** change counter (returned by subsequent calls to sqlite3_changes()).
5796 ** Then the VMs internal change counter resets to 0.
5797 ** This is used by trigger programs.
5799 case OP_ResetCount: {
5800 sqlite3VdbeSetChanges(db, p->nChange);
5801 p->nChange = 0;
5802 break;
5805 /* Opcode: SorterCompare P1 P2 P3 P4
5806 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5808 ** P1 is a sorter cursor. This instruction compares a prefix of the
5809 ** record blob in register P3 against a prefix of the entry that
5810 ** the sorter cursor currently points to. Only the first P4 fields
5811 ** of r[P3] and the sorter record are compared.
5813 ** If either P3 or the sorter contains a NULL in one of their significant
5814 ** fields (not counting the P4 fields at the end which are ignored) then
5815 ** the comparison is assumed to be equal.
5817 ** Fall through to next instruction if the two records compare equal to
5818 ** each other. Jump to P2 if they are different.
5820 case OP_SorterCompare: {
5821 VdbeCursor *pC;
5822 int res;
5823 int nKeyCol;
5825 pC = p->apCsr[pOp->p1];
5826 assert( isSorter(pC) );
5827 assert( pOp->p4type==P4_INT32 );
5828 pIn3 = &aMem[pOp->p3];
5829 nKeyCol = pOp->p4.i;
5830 res = 0;
5831 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5832 VdbeBranchTaken(res!=0,2);
5833 if( rc ) goto abort_due_to_error;
5834 if( res ) goto jump_to_p2;
5835 break;
5838 /* Opcode: SorterData P1 P2 P3 * *
5839 ** Synopsis: r[P2]=data
5841 ** Write into register P2 the current sorter data for sorter cursor P1.
5842 ** Then clear the column header cache on cursor P3.
5844 ** This opcode is normally use to move a record out of the sorter and into
5845 ** a register that is the source for a pseudo-table cursor created using
5846 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
5847 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
5848 ** us from having to issue a separate NullRow instruction to clear that cache.
5850 case OP_SorterData: {
5851 VdbeCursor *pC;
5853 pOut = &aMem[pOp->p2];
5854 pC = p->apCsr[pOp->p1];
5855 assert( isSorter(pC) );
5856 rc = sqlite3VdbeSorterRowkey(pC, pOut);
5857 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5858 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5859 if( rc ) goto abort_due_to_error;
5860 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5861 break;
5864 /* Opcode: RowData P1 P2 P3 * *
5865 ** Synopsis: r[P2]=data
5867 ** Write into register P2 the complete row content for the row at
5868 ** which cursor P1 is currently pointing.
5869 ** There is no interpretation of the data.
5870 ** It is just copied onto the P2 register exactly as
5871 ** it is found in the database file.
5873 ** If cursor P1 is an index, then the content is the key of the row.
5874 ** If cursor P2 is a table, then the content extracted is the data.
5876 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5877 ** of a real table, not a pseudo-table.
5879 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5880 ** into the database page. That means that the content of the output
5881 ** register will be invalidated as soon as the cursor moves - including
5882 ** moves caused by other cursors that "save" the current cursors
5883 ** position in order that they can write to the same table. If P3==0
5884 ** then a copy of the data is made into memory. P3!=0 is faster, but
5885 ** P3==0 is safer.
5887 ** If P3!=0 then the content of the P2 register is unsuitable for use
5888 ** in OP_Result and any OP_Result will invalidate the P2 register content.
5889 ** The P2 register content is invalidated by opcodes like OP_Function or
5890 ** by any use of another cursor pointing to the same table.
5892 case OP_RowData: {
5893 VdbeCursor *pC;
5894 BtCursor *pCrsr;
5895 u32 n;
5897 pOut = out2Prerelease(p, pOp);
5899 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5900 pC = p->apCsr[pOp->p1];
5901 assert( pC!=0 );
5902 assert( pC->eCurType==CURTYPE_BTREE );
5903 assert( isSorter(pC)==0 );
5904 assert( pC->nullRow==0 );
5905 assert( pC->uc.pCursor!=0 );
5906 pCrsr = pC->uc.pCursor;
5908 /* The OP_RowData opcodes always follow OP_NotExists or
5909 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
5910 ** that might invalidate the cursor.
5911 ** If this where not the case, on of the following assert()s
5912 ** would fail. Should this ever change (because of changes in the code
5913 ** generator) then the fix would be to insert a call to
5914 ** sqlite3VdbeCursorMoveto().
5916 assert( pC->deferredMoveto==0 );
5917 assert( sqlite3BtreeCursorIsValid(pCrsr) );
5919 n = sqlite3BtreePayloadSize(pCrsr);
5920 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
5921 goto too_big;
5923 testcase( n==0 );
5924 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
5925 if( rc ) goto abort_due_to_error;
5926 if( !pOp->p3 ) Deephemeralize(pOut);
5927 UPDATE_MAX_BLOBSIZE(pOut);
5928 REGISTER_TRACE(pOp->p2, pOut);
5929 break;
5932 /* Opcode: Rowid P1 P2 * * *
5933 ** Synopsis: r[P2]=PX rowid of P1
5935 ** Store in register P2 an integer which is the key of the table entry that
5936 ** P1 is currently point to.
5938 ** P1 can be either an ordinary table or a virtual table. There used to
5939 ** be a separate OP_VRowid opcode for use with virtual tables, but this
5940 ** one opcode now works for both table types.
5942 case OP_Rowid: { /* out2, ncycle */
5943 VdbeCursor *pC;
5944 i64 v;
5945 sqlite3_vtab *pVtab;
5946 const sqlite3_module *pModule;
5948 pOut = out2Prerelease(p, pOp);
5949 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5950 pC = p->apCsr[pOp->p1];
5951 assert( pC!=0 );
5952 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
5953 if( pC->nullRow ){
5954 pOut->flags = MEM_Null;
5955 break;
5956 }else if( pC->deferredMoveto ){
5957 v = pC->movetoTarget;
5958 #ifndef SQLITE_OMIT_VIRTUALTABLE
5959 }else if( pC->eCurType==CURTYPE_VTAB ){
5960 assert( pC->uc.pVCur!=0 );
5961 pVtab = pC->uc.pVCur->pVtab;
5962 pModule = pVtab->pModule;
5963 assert( pModule->xRowid );
5964 rc = pModule->xRowid(pC->uc.pVCur, &v);
5965 sqlite3VtabImportErrmsg(p, pVtab);
5966 if( rc ) goto abort_due_to_error;
5967 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5968 }else{
5969 assert( pC->eCurType==CURTYPE_BTREE );
5970 assert( pC->uc.pCursor!=0 );
5971 rc = sqlite3VdbeCursorRestore(pC);
5972 if( rc ) goto abort_due_to_error;
5973 if( pC->nullRow ){
5974 pOut->flags = MEM_Null;
5975 break;
5977 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5979 pOut->u.i = v;
5980 break;
5983 /* Opcode: NullRow P1 * * * *
5985 ** Move the cursor P1 to a null row. Any OP_Column operations
5986 ** that occur while the cursor is on the null row will always
5987 ** write a NULL.
5989 ** If cursor P1 is not previously opened, open it now to a special
5990 ** pseudo-cursor that always returns NULL for every column.
5992 case OP_NullRow: {
5993 VdbeCursor *pC;
5995 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5996 pC = p->apCsr[pOp->p1];
5997 if( pC==0 ){
5998 /* If the cursor is not already open, create a special kind of
5999 ** pseudo-cursor that always gives null rows. */
6000 pC = allocateCursor(p, pOp->p1, 1, CURTYPE_PSEUDO);
6001 if( pC==0 ) goto no_mem;
6002 pC->seekResult = 0;
6003 pC->isTable = 1;
6004 pC->noReuse = 1;
6005 pC->uc.pCursor = sqlite3BtreeFakeValidCursor();
6007 pC->nullRow = 1;
6008 pC->cacheStatus = CACHE_STALE;
6009 if( pC->eCurType==CURTYPE_BTREE ){
6010 assert( pC->uc.pCursor!=0 );
6011 sqlite3BtreeClearCursor(pC->uc.pCursor);
6013 #ifdef SQLITE_DEBUG
6014 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
6015 #endif
6016 break;
6019 /* Opcode: SeekEnd P1 * * * *
6021 ** Position cursor P1 at the end of the btree for the purpose of
6022 ** appending a new entry onto the btree.
6024 ** It is assumed that the cursor is used only for appending and so
6025 ** if the cursor is valid, then the cursor must already be pointing
6026 ** at the end of the btree and so no changes are made to
6027 ** the cursor.
6029 /* Opcode: Last P1 P2 * * *
6031 ** The next use of the Rowid or Column or Prev instruction for P1
6032 ** will refer to the last entry in the database table or index.
6033 ** If the table or index is empty and P2>0, then jump immediately to P2.
6034 ** If P2 is 0 or if the table or index is not empty, fall through
6035 ** to the following instruction.
6037 ** This opcode leaves the cursor configured to move in reverse order,
6038 ** from the end toward the beginning. In other words, the cursor is
6039 ** configured to use Prev, not Next.
6041 case OP_SeekEnd: /* ncycle */
6042 case OP_Last: { /* jump, ncycle */
6043 VdbeCursor *pC;
6044 BtCursor *pCrsr;
6045 int res;
6047 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6048 pC = p->apCsr[pOp->p1];
6049 assert( pC!=0 );
6050 assert( pC->eCurType==CURTYPE_BTREE );
6051 pCrsr = pC->uc.pCursor;
6052 res = 0;
6053 assert( pCrsr!=0 );
6054 #ifdef SQLITE_DEBUG
6055 pC->seekOp = pOp->opcode;
6056 #endif
6057 if( pOp->opcode==OP_SeekEnd ){
6058 assert( pOp->p2==0 );
6059 pC->seekResult = -1;
6060 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
6061 break;
6064 rc = sqlite3BtreeLast(pCrsr, &res);
6065 pC->nullRow = (u8)res;
6066 pC->deferredMoveto = 0;
6067 pC->cacheStatus = CACHE_STALE;
6068 if( rc ) goto abort_due_to_error;
6069 if( pOp->p2>0 ){
6070 VdbeBranchTaken(res!=0,2);
6071 if( res ) goto jump_to_p2;
6073 break;
6076 /* Opcode: IfSmaller P1 P2 P3 * *
6078 ** Estimate the number of rows in the table P1. Jump to P2 if that
6079 ** estimate is less than approximately 2**(0.1*P3).
6081 case OP_IfSmaller: { /* jump */
6082 VdbeCursor *pC;
6083 BtCursor *pCrsr;
6084 int res;
6085 i64 sz;
6087 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6088 pC = p->apCsr[pOp->p1];
6089 assert( pC!=0 );
6090 pCrsr = pC->uc.pCursor;
6091 assert( pCrsr );
6092 rc = sqlite3BtreeFirst(pCrsr, &res);
6093 if( rc ) goto abort_due_to_error;
6094 if( res==0 ){
6095 sz = sqlite3BtreeRowCountEst(pCrsr);
6096 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
6098 VdbeBranchTaken(res!=0,2);
6099 if( res ) goto jump_to_p2;
6100 break;
6104 /* Opcode: SorterSort P1 P2 * * *
6106 ** After all records have been inserted into the Sorter object
6107 ** identified by P1, invoke this opcode to actually do the sorting.
6108 ** Jump to P2 if there are no records to be sorted.
6110 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
6111 ** for Sorter objects.
6113 /* Opcode: Sort P1 P2 * * *
6115 ** This opcode does exactly the same thing as OP_Rewind except that
6116 ** it increments an undocumented global variable used for testing.
6118 ** Sorting is accomplished by writing records into a sorting index,
6119 ** then rewinding that index and playing it back from beginning to
6120 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
6121 ** rewinding so that the global variable will be incremented and
6122 ** regression tests can determine whether or not the optimizer is
6123 ** correctly optimizing out sorts.
6125 case OP_SorterSort: /* jump */
6126 case OP_Sort: { /* jump */
6127 #ifdef SQLITE_TEST
6128 sqlite3_sort_count++;
6129 sqlite3_search_count--;
6130 #endif
6131 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
6132 /* Fall through into OP_Rewind */
6133 /* no break */ deliberate_fall_through
6135 /* Opcode: Rewind P1 P2 * * *
6137 ** The next use of the Rowid or Column or Next instruction for P1
6138 ** will refer to the first entry in the database table or index.
6139 ** If the table or index is empty, jump immediately to P2.
6140 ** If the table or index is not empty, fall through to the following
6141 ** instruction.
6143 ** If P2 is zero, that is an assertion that the P1 table is never
6144 ** empty and hence the jump will never be taken.
6146 ** This opcode leaves the cursor configured to move in forward order,
6147 ** from the beginning toward the end. In other words, the cursor is
6148 ** configured to use Next, not Prev.
6150 case OP_Rewind: { /* jump, ncycle */
6151 VdbeCursor *pC;
6152 BtCursor *pCrsr;
6153 int res;
6155 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6156 assert( pOp->p5==0 );
6157 assert( pOp->p2>=0 && pOp->p2<p->nOp );
6159 pC = p->apCsr[pOp->p1];
6160 assert( pC!=0 );
6161 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
6162 res = 1;
6163 #ifdef SQLITE_DEBUG
6164 pC->seekOp = OP_Rewind;
6165 #endif
6166 if( isSorter(pC) ){
6167 rc = sqlite3VdbeSorterRewind(pC, &res);
6168 }else{
6169 assert( pC->eCurType==CURTYPE_BTREE );
6170 pCrsr = pC->uc.pCursor;
6171 assert( pCrsr );
6172 rc = sqlite3BtreeFirst(pCrsr, &res);
6173 pC->deferredMoveto = 0;
6174 pC->cacheStatus = CACHE_STALE;
6176 if( rc ) goto abort_due_to_error;
6177 pC->nullRow = (u8)res;
6178 if( pOp->p2>0 ){
6179 VdbeBranchTaken(res!=0,2);
6180 if( res ) goto jump_to_p2;
6182 break;
6185 /* Opcode: Next P1 P2 P3 * P5
6187 ** Advance cursor P1 so that it points to the next key/data pair in its
6188 ** table or index. If there are no more key/value pairs then fall through
6189 ** to the following instruction. But if the cursor advance was successful,
6190 ** jump immediately to P2.
6192 ** The Next opcode is only valid following an SeekGT, SeekGE, or
6193 ** OP_Rewind opcode used to position the cursor. Next is not allowed
6194 ** to follow SeekLT, SeekLE, or OP_Last.
6196 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
6197 ** been opened prior to this opcode or the program will segfault.
6199 ** The P3 value is a hint to the btree implementation. If P3==1, that
6200 ** means P1 is an SQL index and that this instruction could have been
6201 ** omitted if that index had been unique. P3 is usually 0. P3 is
6202 ** always either 0 or 1.
6204 ** If P5 is positive and the jump is taken, then event counter
6205 ** number P5-1 in the prepared statement is incremented.
6207 ** See also: Prev
6209 /* Opcode: Prev P1 P2 P3 * P5
6211 ** Back up cursor P1 so that it points to the previous key/data pair in its
6212 ** table or index. If there is no previous key/value pairs then fall through
6213 ** to the following instruction. But if the cursor backup was successful,
6214 ** jump immediately to P2.
6217 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
6218 ** OP_Last opcode used to position the cursor. Prev is not allowed
6219 ** to follow SeekGT, SeekGE, or OP_Rewind.
6221 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
6222 ** not open then the behavior is undefined.
6224 ** The P3 value is a hint to the btree implementation. If P3==1, that
6225 ** means P1 is an SQL index and that this instruction could have been
6226 ** omitted if that index had been unique. P3 is usually 0. P3 is
6227 ** always either 0 or 1.
6229 ** If P5 is positive and the jump is taken, then event counter
6230 ** number P5-1 in the prepared statement is incremented.
6232 /* Opcode: SorterNext P1 P2 * * P5
6234 ** This opcode works just like OP_Next except that P1 must be a
6235 ** sorter object for which the OP_SorterSort opcode has been
6236 ** invoked. This opcode advances the cursor to the next sorted
6237 ** record, or jumps to P2 if there are no more sorted records.
6239 case OP_SorterNext: { /* jump */
6240 VdbeCursor *pC;
6242 pC = p->apCsr[pOp->p1];
6243 assert( isSorter(pC) );
6244 rc = sqlite3VdbeSorterNext(db, pC);
6245 goto next_tail;
6247 case OP_Prev: /* jump, ncycle */
6248 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6249 assert( pOp->p5==0
6250 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6251 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6252 pC = p->apCsr[pOp->p1];
6253 assert( pC!=0 );
6254 assert( pC->deferredMoveto==0 );
6255 assert( pC->eCurType==CURTYPE_BTREE );
6256 assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
6257 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
6258 || pC->seekOp==OP_NullRow);
6259 rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
6260 goto next_tail;
6262 case OP_Next: /* jump, ncycle */
6263 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6264 assert( pOp->p5==0
6265 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6266 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6267 pC = p->apCsr[pOp->p1];
6268 assert( pC!=0 );
6269 assert( pC->deferredMoveto==0 );
6270 assert( pC->eCurType==CURTYPE_BTREE );
6271 assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
6272 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
6273 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
6274 || pC->seekOp==OP_IfNoHope);
6275 rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
6277 next_tail:
6278 pC->cacheStatus = CACHE_STALE;
6279 VdbeBranchTaken(rc==SQLITE_OK,2);
6280 if( rc==SQLITE_OK ){
6281 pC->nullRow = 0;
6282 p->aCounter[pOp->p5]++;
6283 #ifdef SQLITE_TEST
6284 sqlite3_search_count++;
6285 #endif
6286 goto jump_to_p2_and_check_for_interrupt;
6288 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6289 rc = SQLITE_OK;
6290 pC->nullRow = 1;
6291 goto check_for_interrupt;
6294 /* Opcode: IdxInsert P1 P2 P3 P4 P5
6295 ** Synopsis: key=r[P2]
6297 ** Register P2 holds an SQL index key made using the
6298 ** MakeRecord instructions. This opcode writes that key
6299 ** into the index P1. Data for the entry is nil.
6301 ** If P4 is not zero, then it is the number of values in the unpacked
6302 ** key of reg(P2). In that case, P3 is the index of the first register
6303 ** for the unpacked key. The availability of the unpacked key can sometimes
6304 ** be an optimization.
6306 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
6307 ** that this insert is likely to be an append.
6309 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
6310 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
6311 ** then the change counter is unchanged.
6313 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
6314 ** run faster by avoiding an unnecessary seek on cursor P1. However,
6315 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
6316 ** seeks on the cursor or if the most recent seek used a key equivalent
6317 ** to P2.
6319 ** This instruction only works for indices. The equivalent instruction
6320 ** for tables is OP_Insert.
6322 case OP_IdxInsert: { /* in2 */
6323 VdbeCursor *pC;
6324 BtreePayload x;
6326 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6327 pC = p->apCsr[pOp->p1];
6328 sqlite3VdbeIncrWriteCounter(p, pC);
6329 assert( pC!=0 );
6330 assert( !isSorter(pC) );
6331 pIn2 = &aMem[pOp->p2];
6332 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
6333 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
6334 assert( pC->eCurType==CURTYPE_BTREE );
6335 assert( pC->isTable==0 );
6336 rc = ExpandBlob(pIn2);
6337 if( rc ) goto abort_due_to_error;
6338 x.nKey = pIn2->n;
6339 x.pKey = pIn2->z;
6340 x.aMem = aMem + pOp->p3;
6341 x.nMem = (u16)pOp->p4.i;
6342 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
6343 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
6344 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
6346 assert( pC->deferredMoveto==0 );
6347 pC->cacheStatus = CACHE_STALE;
6348 if( rc) goto abort_due_to_error;
6349 break;
6352 /* Opcode: SorterInsert P1 P2 * * *
6353 ** Synopsis: key=r[P2]
6355 ** Register P2 holds an SQL index key made using the
6356 ** MakeRecord instructions. This opcode writes that key
6357 ** into the sorter P1. Data for the entry is nil.
6359 case OP_SorterInsert: { /* in2 */
6360 VdbeCursor *pC;
6362 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6363 pC = p->apCsr[pOp->p1];
6364 sqlite3VdbeIncrWriteCounter(p, pC);
6365 assert( pC!=0 );
6366 assert( isSorter(pC) );
6367 pIn2 = &aMem[pOp->p2];
6368 assert( pIn2->flags & MEM_Blob );
6369 assert( pC->isTable==0 );
6370 rc = ExpandBlob(pIn2);
6371 if( rc ) goto abort_due_to_error;
6372 rc = sqlite3VdbeSorterWrite(pC, pIn2);
6373 if( rc) goto abort_due_to_error;
6374 break;
6377 /* Opcode: IdxDelete P1 P2 P3 * P5
6378 ** Synopsis: key=r[P2@P3]
6380 ** The content of P3 registers starting at register P2 form
6381 ** an unpacked index key. This opcode removes that entry from the
6382 ** index opened by cursor P1.
6384 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
6385 ** if no matching index entry is found. This happens when running
6386 ** an UPDATE or DELETE statement and the index entry to be updated
6387 ** or deleted is not found. For some uses of IdxDelete
6388 ** (example: the EXCEPT operator) it does not matter that no matching
6389 ** entry is found. For those cases, P5 is zero. Also, do not raise
6390 ** this (self-correcting and non-critical) error if in writable_schema mode.
6392 case OP_IdxDelete: {
6393 VdbeCursor *pC;
6394 BtCursor *pCrsr;
6395 int res;
6396 UnpackedRecord r;
6398 assert( pOp->p3>0 );
6399 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
6400 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6401 pC = p->apCsr[pOp->p1];
6402 assert( pC!=0 );
6403 assert( pC->eCurType==CURTYPE_BTREE );
6404 sqlite3VdbeIncrWriteCounter(p, pC);
6405 pCrsr = pC->uc.pCursor;
6406 assert( pCrsr!=0 );
6407 r.pKeyInfo = pC->pKeyInfo;
6408 r.nField = (u16)pOp->p3;
6409 r.default_rc = 0;
6410 r.aMem = &aMem[pOp->p2];
6411 rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
6412 if( rc ) goto abort_due_to_error;
6413 if( res==0 ){
6414 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
6415 if( rc ) goto abort_due_to_error;
6416 }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
6417 rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
6418 goto abort_due_to_error;
6420 assert( pC->deferredMoveto==0 );
6421 pC->cacheStatus = CACHE_STALE;
6422 pC->seekResult = 0;
6423 break;
6426 /* Opcode: DeferredSeek P1 * P3 P4 *
6427 ** Synopsis: Move P3 to P1.rowid if needed
6429 ** P1 is an open index cursor and P3 is a cursor on the corresponding
6430 ** table. This opcode does a deferred seek of the P3 table cursor
6431 ** to the row that corresponds to the current row of P1.
6433 ** This is a deferred seek. Nothing actually happens until
6434 ** the cursor is used to read a record. That way, if no reads
6435 ** occur, no unnecessary I/O happens.
6437 ** P4 may be an array of integers (type P4_INTARRAY) containing
6438 ** one entry for each column in the P3 table. If array entry a(i)
6439 ** is non-zero, then reading column a(i)-1 from cursor P3 is
6440 ** equivalent to performing the deferred seek and then reading column i
6441 ** from P1. This information is stored in P3 and used to redirect
6442 ** reads against P3 over to P1, thus possibly avoiding the need to
6443 ** seek and read cursor P3.
6445 /* Opcode: IdxRowid P1 P2 * * *
6446 ** Synopsis: r[P2]=rowid
6448 ** Write into register P2 an integer which is the last entry in the record at
6449 ** the end of the index key pointed to by cursor P1. This integer should be
6450 ** the rowid of the table entry to which this index entry points.
6452 ** See also: Rowid, MakeRecord.
6454 case OP_DeferredSeek: /* ncycle */
6455 case OP_IdxRowid: { /* out2, ncycle */
6456 VdbeCursor *pC; /* The P1 index cursor */
6457 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
6458 i64 rowid; /* Rowid that P1 current points to */
6460 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6461 pC = p->apCsr[pOp->p1];
6462 assert( pC!=0 );
6463 assert( pC->eCurType==CURTYPE_BTREE || IsNullCursor(pC) );
6464 assert( pC->uc.pCursor!=0 );
6465 assert( pC->isTable==0 || IsNullCursor(pC) );
6466 assert( pC->deferredMoveto==0 );
6467 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
6469 /* The IdxRowid and Seek opcodes are combined because of the commonality
6470 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
6471 rc = sqlite3VdbeCursorRestore(pC);
6473 /* sqlite3VdbeCursorRestore() may fail if the cursor has been disturbed
6474 ** since it was last positioned and an error (e.g. OOM or an IO error)
6475 ** occurs while trying to reposition it. */
6476 if( rc!=SQLITE_OK ) goto abort_due_to_error;
6478 if( !pC->nullRow ){
6479 rowid = 0; /* Not needed. Only used to silence a warning. */
6480 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
6481 if( rc!=SQLITE_OK ){
6482 goto abort_due_to_error;
6484 if( pOp->opcode==OP_DeferredSeek ){
6485 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
6486 pTabCur = p->apCsr[pOp->p3];
6487 assert( pTabCur!=0 );
6488 assert( pTabCur->eCurType==CURTYPE_BTREE );
6489 assert( pTabCur->uc.pCursor!=0 );
6490 assert( pTabCur->isTable );
6491 pTabCur->nullRow = 0;
6492 pTabCur->movetoTarget = rowid;
6493 pTabCur->deferredMoveto = 1;
6494 pTabCur->cacheStatus = CACHE_STALE;
6495 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
6496 assert( !pTabCur->isEphemeral );
6497 pTabCur->ub.aAltMap = pOp->p4.ai;
6498 assert( !pC->isEphemeral );
6499 pTabCur->pAltCursor = pC;
6500 }else{
6501 pOut = out2Prerelease(p, pOp);
6502 pOut->u.i = rowid;
6504 }else{
6505 assert( pOp->opcode==OP_IdxRowid );
6506 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
6508 break;
6511 /* Opcode: FinishSeek P1 * * * *
6513 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
6514 ** seek operation now, without further delay. If the cursor seek has
6515 ** already occurred, this instruction is a no-op.
6517 case OP_FinishSeek: { /* ncycle */
6518 VdbeCursor *pC; /* The P1 index cursor */
6520 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6521 pC = p->apCsr[pOp->p1];
6522 if( pC->deferredMoveto ){
6523 rc = sqlite3VdbeFinishMoveto(pC);
6524 if( rc ) goto abort_due_to_error;
6526 break;
6529 /* Opcode: IdxGE P1 P2 P3 P4 *
6530 ** Synopsis: key=r[P3@P4]
6532 ** The P4 register values beginning with P3 form an unpacked index
6533 ** key that omits the PRIMARY KEY. Compare this key value against the index
6534 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6535 ** fields at the end.
6537 ** If the P1 index entry is greater than or equal to the key value
6538 ** then jump to P2. Otherwise fall through to the next instruction.
6540 /* Opcode: IdxGT P1 P2 P3 P4 *
6541 ** Synopsis: key=r[P3@P4]
6543 ** The P4 register values beginning with P3 form an unpacked index
6544 ** key that omits the PRIMARY KEY. Compare this key value against the index
6545 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6546 ** fields at the end.
6548 ** If the P1 index entry is greater than the key value
6549 ** then jump to P2. Otherwise fall through to the next instruction.
6551 /* Opcode: IdxLT P1 P2 P3 P4 *
6552 ** Synopsis: key=r[P3@P4]
6554 ** The P4 register values beginning with P3 form an unpacked index
6555 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6556 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6557 ** ROWID on the P1 index.
6559 ** If the P1 index entry is less than the key value then jump to P2.
6560 ** Otherwise fall through to the next instruction.
6562 /* Opcode: IdxLE P1 P2 P3 P4 *
6563 ** Synopsis: key=r[P3@P4]
6565 ** The P4 register values beginning with P3 form an unpacked index
6566 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6567 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6568 ** ROWID on the P1 index.
6570 ** If the P1 index entry is less than or equal to the key value then jump
6571 ** to P2. Otherwise fall through to the next instruction.
6573 case OP_IdxLE: /* jump, ncycle */
6574 case OP_IdxGT: /* jump, ncycle */
6575 case OP_IdxLT: /* jump, ncycle */
6576 case OP_IdxGE: { /* jump, ncycle */
6577 VdbeCursor *pC;
6578 int res;
6579 UnpackedRecord r;
6581 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6582 pC = p->apCsr[pOp->p1];
6583 assert( pC!=0 );
6584 assert( pC->isOrdered );
6585 assert( pC->eCurType==CURTYPE_BTREE );
6586 assert( pC->uc.pCursor!=0);
6587 assert( pC->deferredMoveto==0 );
6588 assert( pOp->p4type==P4_INT32 );
6589 r.pKeyInfo = pC->pKeyInfo;
6590 r.nField = (u16)pOp->p4.i;
6591 if( pOp->opcode<OP_IdxLT ){
6592 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6593 r.default_rc = -1;
6594 }else{
6595 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6596 r.default_rc = 0;
6598 r.aMem = &aMem[pOp->p3];
6599 #ifdef SQLITE_DEBUG
6601 int i;
6602 for(i=0; i<r.nField; i++){
6603 assert( memIsValid(&r.aMem[i]) );
6604 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6607 #endif
6609 /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6611 i64 nCellKey = 0;
6612 BtCursor *pCur;
6613 Mem m;
6615 assert( pC->eCurType==CURTYPE_BTREE );
6616 pCur = pC->uc.pCursor;
6617 assert( sqlite3BtreeCursorIsValid(pCur) );
6618 nCellKey = sqlite3BtreePayloadSize(pCur);
6619 /* nCellKey will always be between 0 and 0xffffffff because of the way
6620 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6621 if( nCellKey<=0 || nCellKey>0x7fffffff ){
6622 rc = SQLITE_CORRUPT_BKPT;
6623 goto abort_due_to_error;
6625 sqlite3VdbeMemInit(&m, db, 0);
6626 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6627 if( rc ) goto abort_due_to_error;
6628 res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6629 sqlite3VdbeMemReleaseMalloc(&m);
6631 /* End of inlined sqlite3VdbeIdxKeyCompare() */
6633 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6634 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6635 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6636 res = -res;
6637 }else{
6638 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6639 res++;
6641 VdbeBranchTaken(res>0,2);
6642 assert( rc==SQLITE_OK );
6643 if( res>0 ) goto jump_to_p2;
6644 break;
6647 /* Opcode: Destroy P1 P2 P3 * *
6649 ** Delete an entire database table or index whose root page in the database
6650 ** file is given by P1.
6652 ** The table being destroyed is in the main database file if P3==0. If
6653 ** P3==1 then the table to be clear is in the auxiliary database file
6654 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6656 ** If AUTOVACUUM is enabled then it is possible that another root page
6657 ** might be moved into the newly deleted root page in order to keep all
6658 ** root pages contiguous at the beginning of the database. The former
6659 ** value of the root page that moved - its value before the move occurred -
6660 ** is stored in register P2. If no page movement was required (because the
6661 ** table being dropped was already the last one in the database) then a
6662 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
6663 ** is stored in register P2.
6665 ** This opcode throws an error if there are any active reader VMs when
6666 ** it is invoked. This is done to avoid the difficulty associated with
6667 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6668 ** database. This error is thrown even if the database is not an AUTOVACUUM
6669 ** db in order to avoid introducing an incompatibility between autovacuum
6670 ** and non-autovacuum modes.
6672 ** See also: Clear
6674 case OP_Destroy: { /* out2 */
6675 int iMoved;
6676 int iDb;
6678 sqlite3VdbeIncrWriteCounter(p, 0);
6679 assert( p->readOnly==0 );
6680 assert( pOp->p1>1 );
6681 pOut = out2Prerelease(p, pOp);
6682 pOut->flags = MEM_Null;
6683 if( db->nVdbeRead > db->nVDestroy+1 ){
6684 rc = SQLITE_LOCKED;
6685 p->errorAction = OE_Abort;
6686 goto abort_due_to_error;
6687 }else{
6688 iDb = pOp->p3;
6689 assert( DbMaskTest(p->btreeMask, iDb) );
6690 iMoved = 0; /* Not needed. Only to silence a warning. */
6691 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6692 pOut->flags = MEM_Int;
6693 pOut->u.i = iMoved;
6694 if( rc ) goto abort_due_to_error;
6695 #ifndef SQLITE_OMIT_AUTOVACUUM
6696 if( iMoved!=0 ){
6697 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6698 /* All OP_Destroy operations occur on the same btree */
6699 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6700 resetSchemaOnFault = iDb+1;
6702 #endif
6704 break;
6707 /* Opcode: Clear P1 P2 P3
6709 ** Delete all contents of the database table or index whose root page
6710 ** in the database file is given by P1. But, unlike Destroy, do not
6711 ** remove the table or index from the database file.
6713 ** The table being clear is in the main database file if P2==0. If
6714 ** P2==1 then the table to be clear is in the auxiliary database file
6715 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6717 ** If the P3 value is non-zero, then the row change count is incremented
6718 ** by the number of rows in the table being cleared. If P3 is greater
6719 ** than zero, then the value stored in register P3 is also incremented
6720 ** by the number of rows in the table being cleared.
6722 ** See also: Destroy
6724 case OP_Clear: {
6725 i64 nChange;
6727 sqlite3VdbeIncrWriteCounter(p, 0);
6728 nChange = 0;
6729 assert( p->readOnly==0 );
6730 assert( DbMaskTest(p->btreeMask, pOp->p2) );
6731 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
6732 if( pOp->p3 ){
6733 p->nChange += nChange;
6734 if( pOp->p3>0 ){
6735 assert( memIsValid(&aMem[pOp->p3]) );
6736 memAboutToChange(p, &aMem[pOp->p3]);
6737 aMem[pOp->p3].u.i += nChange;
6740 if( rc ) goto abort_due_to_error;
6741 break;
6744 /* Opcode: ResetSorter P1 * * * *
6746 ** Delete all contents from the ephemeral table or sorter
6747 ** that is open on cursor P1.
6749 ** This opcode only works for cursors used for sorting and
6750 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6752 case OP_ResetSorter: {
6753 VdbeCursor *pC;
6755 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6756 pC = p->apCsr[pOp->p1];
6757 assert( pC!=0 );
6758 if( isSorter(pC) ){
6759 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6760 }else{
6761 assert( pC->eCurType==CURTYPE_BTREE );
6762 assert( pC->isEphemeral );
6763 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6764 if( rc ) goto abort_due_to_error;
6766 break;
6769 /* Opcode: CreateBtree P1 P2 P3 * *
6770 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6772 ** Allocate a new b-tree in the main database file if P1==0 or in the
6773 ** TEMP database file if P1==1 or in an attached database if
6774 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6775 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6776 ** The root page number of the new b-tree is stored in register P2.
6778 case OP_CreateBtree: { /* out2 */
6779 Pgno pgno;
6780 Db *pDb;
6782 sqlite3VdbeIncrWriteCounter(p, 0);
6783 pOut = out2Prerelease(p, pOp);
6784 pgno = 0;
6785 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6786 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6787 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6788 assert( p->readOnly==0 );
6789 pDb = &db->aDb[pOp->p1];
6790 assert( pDb->pBt!=0 );
6791 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6792 if( rc ) goto abort_due_to_error;
6793 pOut->u.i = pgno;
6794 break;
6797 /* Opcode: SqlExec * * * P4 *
6799 ** Run the SQL statement or statements specified in the P4 string.
6801 case OP_SqlExec: {
6802 sqlite3VdbeIncrWriteCounter(p, 0);
6803 db->nSqlExec++;
6804 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
6805 db->nSqlExec--;
6806 if( rc ) goto abort_due_to_error;
6807 break;
6810 /* Opcode: ParseSchema P1 * * P4 *
6812 ** Read and parse all entries from the schema table of database P1
6813 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
6814 ** entire schema for P1 is reparsed.
6816 ** This opcode invokes the parser to create a new virtual machine,
6817 ** then runs the new virtual machine. It is thus a re-entrant opcode.
6819 case OP_ParseSchema: {
6820 int iDb;
6821 const char *zSchema;
6822 char *zSql;
6823 InitData initData;
6825 /* Any prepared statement that invokes this opcode will hold mutexes
6826 ** on every btree. This is a prerequisite for invoking
6827 ** sqlite3InitCallback().
6829 #ifdef SQLITE_DEBUG
6830 for(iDb=0; iDb<db->nDb; iDb++){
6831 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
6833 #endif
6835 iDb = pOp->p1;
6836 assert( iDb>=0 && iDb<db->nDb );
6837 assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
6838 || db->mallocFailed
6839 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
6841 #ifndef SQLITE_OMIT_ALTERTABLE
6842 if( pOp->p4.z==0 ){
6843 sqlite3SchemaClear(db->aDb[iDb].pSchema);
6844 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
6845 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
6846 db->mDbFlags |= DBFLAG_SchemaChange;
6847 p->expired = 0;
6848 }else
6849 #endif
6851 zSchema = LEGACY_SCHEMA_TABLE;
6852 initData.db = db;
6853 initData.iDb = iDb;
6854 initData.pzErrMsg = &p->zErrMsg;
6855 initData.mInitFlags = 0;
6856 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
6857 zSql = sqlite3MPrintf(db,
6858 "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
6859 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
6860 if( zSql==0 ){
6861 rc = SQLITE_NOMEM_BKPT;
6862 }else{
6863 assert( db->init.busy==0 );
6864 db->init.busy = 1;
6865 initData.rc = SQLITE_OK;
6866 initData.nInitRow = 0;
6867 assert( !db->mallocFailed );
6868 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
6869 if( rc==SQLITE_OK ) rc = initData.rc;
6870 if( rc==SQLITE_OK && initData.nInitRow==0 ){
6871 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
6872 ** at least one SQL statement. Any less than that indicates that
6873 ** the sqlite_schema table is corrupt. */
6874 rc = SQLITE_CORRUPT_BKPT;
6876 sqlite3DbFreeNN(db, zSql);
6877 db->init.busy = 0;
6880 if( rc ){
6881 sqlite3ResetAllSchemasOfConnection(db);
6882 if( rc==SQLITE_NOMEM ){
6883 goto no_mem;
6885 goto abort_due_to_error;
6887 break;
6890 #if !defined(SQLITE_OMIT_ANALYZE)
6891 /* Opcode: LoadAnalysis P1 * * * *
6893 ** Read the sqlite_stat1 table for database P1 and load the content
6894 ** of that table into the internal index hash table. This will cause
6895 ** the analysis to be used when preparing all subsequent queries.
6897 case OP_LoadAnalysis: {
6898 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6899 rc = sqlite3AnalysisLoad(db, pOp->p1);
6900 if( rc ) goto abort_due_to_error;
6901 break;
6903 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
6905 /* Opcode: DropTable P1 * * P4 *
6907 ** Remove the internal (in-memory) data structures that describe
6908 ** the table named P4 in database P1. This is called after a table
6909 ** is dropped from disk (using the Destroy opcode) in order to keep
6910 ** the internal representation of the
6911 ** schema consistent with what is on disk.
6913 case OP_DropTable: {
6914 sqlite3VdbeIncrWriteCounter(p, 0);
6915 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
6916 break;
6919 /* Opcode: DropIndex P1 * * P4 *
6921 ** Remove the internal (in-memory) data structures that describe
6922 ** the index named P4 in database P1. This is called after an index
6923 ** is dropped from disk (using the Destroy opcode)
6924 ** in order to keep the internal representation of the
6925 ** schema consistent with what is on disk.
6927 case OP_DropIndex: {
6928 sqlite3VdbeIncrWriteCounter(p, 0);
6929 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
6930 break;
6933 /* Opcode: DropTrigger P1 * * P4 *
6935 ** Remove the internal (in-memory) data structures that describe
6936 ** the trigger named P4 in database P1. This is called after a trigger
6937 ** is dropped from disk (using the Destroy opcode) in order to keep
6938 ** the internal representation of the
6939 ** schema consistent with what is on disk.
6941 case OP_DropTrigger: {
6942 sqlite3VdbeIncrWriteCounter(p, 0);
6943 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
6944 break;
6948 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
6949 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
6951 ** Do an analysis of the currently open database. Store in
6952 ** register P1 the text of an error message describing any problems.
6953 ** If no problems are found, store a NULL in register P1.
6955 ** The register P3 contains one less than the maximum number of allowed errors.
6956 ** At most reg(P3) errors will be reported.
6957 ** In other words, the analysis stops as soon as reg(P1) errors are
6958 ** seen. Reg(P1) is updated with the number of errors remaining.
6960 ** The root page numbers of all tables in the database are integers
6961 ** stored in P4_INTARRAY argument.
6963 ** If P5 is not zero, the check is done on the auxiliary database
6964 ** file, not the main database file.
6966 ** This opcode is used to implement the integrity_check pragma.
6968 case OP_IntegrityCk: {
6969 int nRoot; /* Number of tables to check. (Number of root pages.) */
6970 Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */
6971 int nErr; /* Number of errors reported */
6972 char *z; /* Text of the error report */
6973 Mem *pnErr; /* Register keeping track of errors remaining */
6975 assert( p->bIsReader );
6976 nRoot = pOp->p2;
6977 aRoot = pOp->p4.ai;
6978 assert( nRoot>0 );
6979 assert( aRoot[0]==(Pgno)nRoot );
6980 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6981 pnErr = &aMem[pOp->p3];
6982 assert( (pnErr->flags & MEM_Int)!=0 );
6983 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
6984 pIn1 = &aMem[pOp->p1];
6985 assert( pOp->p5<db->nDb );
6986 assert( DbMaskTest(p->btreeMask, pOp->p5) );
6987 rc = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
6988 (int)pnErr->u.i+1, &nErr, &z);
6989 sqlite3VdbeMemSetNull(pIn1);
6990 if( nErr==0 ){
6991 assert( z==0 );
6992 }else if( rc ){
6993 sqlite3_free(z);
6994 goto abort_due_to_error;
6995 }else{
6996 pnErr->u.i -= nErr-1;
6997 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
6999 UPDATE_MAX_BLOBSIZE(pIn1);
7000 sqlite3VdbeChangeEncoding(pIn1, encoding);
7001 goto check_for_interrupt;
7003 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
7005 /* Opcode: RowSetAdd P1 P2 * * *
7006 ** Synopsis: rowset(P1)=r[P2]
7008 ** Insert the integer value held by register P2 into a RowSet object
7009 ** held in register P1.
7011 ** An assertion fails if P2 is not an integer.
7013 case OP_RowSetAdd: { /* in1, in2 */
7014 pIn1 = &aMem[pOp->p1];
7015 pIn2 = &aMem[pOp->p2];
7016 assert( (pIn2->flags & MEM_Int)!=0 );
7017 if( (pIn1->flags & MEM_Blob)==0 ){
7018 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7020 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7021 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
7022 break;
7025 /* Opcode: RowSetRead P1 P2 P3 * *
7026 ** Synopsis: r[P3]=rowset(P1)
7028 ** Extract the smallest value from the RowSet object in P1
7029 ** and put that value into register P3.
7030 ** Or, if RowSet object P1 is initially empty, leave P3
7031 ** unchanged and jump to instruction P2.
7033 case OP_RowSetRead: { /* jump, in1, out3 */
7034 i64 val;
7036 pIn1 = &aMem[pOp->p1];
7037 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
7038 if( (pIn1->flags & MEM_Blob)==0
7039 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
7041 /* The boolean index is empty */
7042 sqlite3VdbeMemSetNull(pIn1);
7043 VdbeBranchTaken(1,2);
7044 goto jump_to_p2_and_check_for_interrupt;
7045 }else{
7046 /* A value was pulled from the index */
7047 VdbeBranchTaken(0,2);
7048 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
7050 goto check_for_interrupt;
7053 /* Opcode: RowSetTest P1 P2 P3 P4
7054 ** Synopsis: if r[P3] in rowset(P1) goto P2
7056 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
7057 ** contains a RowSet object and that RowSet object contains
7058 ** the value held in P3, jump to register P2. Otherwise, insert the
7059 ** integer in P3 into the RowSet and continue on to the
7060 ** next opcode.
7062 ** The RowSet object is optimized for the case where sets of integers
7063 ** are inserted in distinct phases, which each set contains no duplicates.
7064 ** Each set is identified by a unique P4 value. The first set
7065 ** must have P4==0, the final set must have P4==-1, and for all other sets
7066 ** must have P4>0.
7068 ** This allows optimizations: (a) when P4==0 there is no need to test
7069 ** the RowSet object for P3, as it is guaranteed not to contain it,
7070 ** (b) when P4==-1 there is no need to insert the value, as it will
7071 ** never be tested for, and (c) when a value that is part of set X is
7072 ** inserted, there is no need to search to see if the same value was
7073 ** previously inserted as part of set X (only if it was previously
7074 ** inserted as part of some other set).
7076 case OP_RowSetTest: { /* jump, in1, in3 */
7077 int iSet;
7078 int exists;
7080 pIn1 = &aMem[pOp->p1];
7081 pIn3 = &aMem[pOp->p3];
7082 iSet = pOp->p4.i;
7083 assert( pIn3->flags&MEM_Int );
7085 /* If there is anything other than a rowset object in memory cell P1,
7086 ** delete it now and initialize P1 with an empty rowset
7088 if( (pIn1->flags & MEM_Blob)==0 ){
7089 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7091 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7092 assert( pOp->p4type==P4_INT32 );
7093 assert( iSet==-1 || iSet>=0 );
7094 if( iSet ){
7095 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
7096 VdbeBranchTaken(exists!=0,2);
7097 if( exists ) goto jump_to_p2;
7099 if( iSet>=0 ){
7100 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
7102 break;
7106 #ifndef SQLITE_OMIT_TRIGGER
7108 /* Opcode: Program P1 P2 P3 P4 P5
7110 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
7112 ** P1 contains the address of the memory cell that contains the first memory
7113 ** cell in an array of values used as arguments to the sub-program. P2
7114 ** contains the address to jump to if the sub-program throws an IGNORE
7115 ** exception using the RAISE() function. Register P3 contains the address
7116 ** of a memory cell in this (the parent) VM that is used to allocate the
7117 ** memory required by the sub-vdbe at runtime.
7119 ** P4 is a pointer to the VM containing the trigger program.
7121 ** If P5 is non-zero, then recursive program invocation is enabled.
7123 case OP_Program: { /* jump */
7124 int nMem; /* Number of memory registers for sub-program */
7125 int nByte; /* Bytes of runtime space required for sub-program */
7126 Mem *pRt; /* Register to allocate runtime space */
7127 Mem *pMem; /* Used to iterate through memory cells */
7128 Mem *pEnd; /* Last memory cell in new array */
7129 VdbeFrame *pFrame; /* New vdbe frame to execute in */
7130 SubProgram *pProgram; /* Sub-program to execute */
7131 void *t; /* Token identifying trigger */
7133 pProgram = pOp->p4.pProgram;
7134 pRt = &aMem[pOp->p3];
7135 assert( pProgram->nOp>0 );
7137 /* If the p5 flag is clear, then recursive invocation of triggers is
7138 ** disabled for backwards compatibility (p5 is set if this sub-program
7139 ** is really a trigger, not a foreign key action, and the flag set
7140 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
7142 ** It is recursive invocation of triggers, at the SQL level, that is
7143 ** disabled. In some cases a single trigger may generate more than one
7144 ** SubProgram (if the trigger may be executed with more than one different
7145 ** ON CONFLICT algorithm). SubProgram structures associated with a
7146 ** single trigger all have the same value for the SubProgram.token
7147 ** variable. */
7148 if( pOp->p5 ){
7149 t = pProgram->token;
7150 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
7151 if( pFrame ) break;
7154 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
7155 rc = SQLITE_ERROR;
7156 sqlite3VdbeError(p, "too many levels of trigger recursion");
7157 goto abort_due_to_error;
7160 /* Register pRt is used to store the memory required to save the state
7161 ** of the current program, and the memory required at runtime to execute
7162 ** the trigger program. If this trigger has been fired before, then pRt
7163 ** is already allocated. Otherwise, it must be initialized. */
7164 if( (pRt->flags&MEM_Blob)==0 ){
7165 /* SubProgram.nMem is set to the number of memory cells used by the
7166 ** program stored in SubProgram.aOp. As well as these, one memory
7167 ** cell is required for each cursor used by the program. Set local
7168 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
7170 nMem = pProgram->nMem + pProgram->nCsr;
7171 assert( nMem>0 );
7172 if( pProgram->nCsr==0 ) nMem++;
7173 nByte = ROUND8(sizeof(VdbeFrame))
7174 + nMem * sizeof(Mem)
7175 + pProgram->nCsr * sizeof(VdbeCursor*)
7176 + (pProgram->nOp + 7)/8;
7177 pFrame = sqlite3DbMallocZero(db, nByte);
7178 if( !pFrame ){
7179 goto no_mem;
7181 sqlite3VdbeMemRelease(pRt);
7182 pRt->flags = MEM_Blob|MEM_Dyn;
7183 pRt->z = (char*)pFrame;
7184 pRt->n = nByte;
7185 pRt->xDel = sqlite3VdbeFrameMemDel;
7187 pFrame->v = p;
7188 pFrame->nChildMem = nMem;
7189 pFrame->nChildCsr = pProgram->nCsr;
7190 pFrame->pc = (int)(pOp - aOp);
7191 pFrame->aMem = p->aMem;
7192 pFrame->nMem = p->nMem;
7193 pFrame->apCsr = p->apCsr;
7194 pFrame->nCursor = p->nCursor;
7195 pFrame->aOp = p->aOp;
7196 pFrame->nOp = p->nOp;
7197 pFrame->token = pProgram->token;
7198 #ifdef SQLITE_DEBUG
7199 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
7200 #endif
7202 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
7203 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
7204 pMem->flags = MEM_Undefined;
7205 pMem->db = db;
7207 }else{
7208 pFrame = (VdbeFrame*)pRt->z;
7209 assert( pRt->xDel==sqlite3VdbeFrameMemDel );
7210 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
7211 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
7212 assert( pProgram->nCsr==pFrame->nChildCsr );
7213 assert( (int)(pOp - aOp)==pFrame->pc );
7216 p->nFrame++;
7217 pFrame->pParent = p->pFrame;
7218 pFrame->lastRowid = db->lastRowid;
7219 pFrame->nChange = p->nChange;
7220 pFrame->nDbChange = p->db->nChange;
7221 assert( pFrame->pAuxData==0 );
7222 pFrame->pAuxData = p->pAuxData;
7223 p->pAuxData = 0;
7224 p->nChange = 0;
7225 p->pFrame = pFrame;
7226 p->aMem = aMem = VdbeFrameMem(pFrame);
7227 p->nMem = pFrame->nChildMem;
7228 p->nCursor = (u16)pFrame->nChildCsr;
7229 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
7230 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
7231 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
7232 p->aOp = aOp = pProgram->aOp;
7233 p->nOp = pProgram->nOp;
7234 #ifdef SQLITE_DEBUG
7235 /* Verify that second and subsequent executions of the same trigger do not
7236 ** try to reuse register values from the first use. */
7238 int i;
7239 for(i=0; i<p->nMem; i++){
7240 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
7241 MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
7244 #endif
7245 pOp = &aOp[-1];
7246 goto check_for_interrupt;
7249 /* Opcode: Param P1 P2 * * *
7251 ** This opcode is only ever present in sub-programs called via the
7252 ** OP_Program instruction. Copy a value currently stored in a memory
7253 ** cell of the calling (parent) frame to cell P2 in the current frames
7254 ** address space. This is used by trigger programs to access the new.*
7255 ** and old.* values.
7257 ** The address of the cell in the parent frame is determined by adding
7258 ** the value of the P1 argument to the value of the P1 argument to the
7259 ** calling OP_Program instruction.
7261 case OP_Param: { /* out2 */
7262 VdbeFrame *pFrame;
7263 Mem *pIn;
7264 pOut = out2Prerelease(p, pOp);
7265 pFrame = p->pFrame;
7266 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
7267 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
7268 break;
7271 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
7273 #ifndef SQLITE_OMIT_FOREIGN_KEY
7274 /* Opcode: FkCounter P1 P2 * * *
7275 ** Synopsis: fkctr[P1]+=P2
7277 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
7278 ** If P1 is non-zero, the database constraint counter is incremented
7279 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
7280 ** statement counter is incremented (immediate foreign key constraints).
7282 case OP_FkCounter: {
7283 if( db->flags & SQLITE_DeferFKs ){
7284 db->nDeferredImmCons += pOp->p2;
7285 }else if( pOp->p1 ){
7286 db->nDeferredCons += pOp->p2;
7287 }else{
7288 p->nFkConstraint += pOp->p2;
7290 break;
7293 /* Opcode: FkIfZero P1 P2 * * *
7294 ** Synopsis: if fkctr[P1]==0 goto P2
7296 ** This opcode tests if a foreign key constraint-counter is currently zero.
7297 ** If so, jump to instruction P2. Otherwise, fall through to the next
7298 ** instruction.
7300 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
7301 ** is zero (the one that counts deferred constraint violations). If P1 is
7302 ** zero, the jump is taken if the statement constraint-counter is zero
7303 ** (immediate foreign key constraint violations).
7305 case OP_FkIfZero: { /* jump */
7306 if( pOp->p1 ){
7307 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
7308 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7309 }else{
7310 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
7311 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7313 break;
7315 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
7317 #ifndef SQLITE_OMIT_AUTOINCREMENT
7318 /* Opcode: MemMax P1 P2 * * *
7319 ** Synopsis: r[P1]=max(r[P1],r[P2])
7321 ** P1 is a register in the root frame of this VM (the root frame is
7322 ** different from the current frame if this instruction is being executed
7323 ** within a sub-program). Set the value of register P1 to the maximum of
7324 ** its current value and the value in register P2.
7326 ** This instruction throws an error if the memory cell is not initially
7327 ** an integer.
7329 case OP_MemMax: { /* in2 */
7330 VdbeFrame *pFrame;
7331 if( p->pFrame ){
7332 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
7333 pIn1 = &pFrame->aMem[pOp->p1];
7334 }else{
7335 pIn1 = &aMem[pOp->p1];
7337 assert( memIsValid(pIn1) );
7338 sqlite3VdbeMemIntegerify(pIn1);
7339 pIn2 = &aMem[pOp->p2];
7340 sqlite3VdbeMemIntegerify(pIn2);
7341 if( pIn1->u.i<pIn2->u.i){
7342 pIn1->u.i = pIn2->u.i;
7344 break;
7346 #endif /* SQLITE_OMIT_AUTOINCREMENT */
7348 /* Opcode: IfPos P1 P2 P3 * *
7349 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
7351 ** Register P1 must contain an integer.
7352 ** If the value of register P1 is 1 or greater, subtract P3 from the
7353 ** value in P1 and jump to P2.
7355 ** If the initial value of register P1 is less than 1, then the
7356 ** value is unchanged and control passes through to the next instruction.
7358 case OP_IfPos: { /* jump, in1 */
7359 pIn1 = &aMem[pOp->p1];
7360 assert( pIn1->flags&MEM_Int );
7361 VdbeBranchTaken( pIn1->u.i>0, 2);
7362 if( pIn1->u.i>0 ){
7363 pIn1->u.i -= pOp->p3;
7364 goto jump_to_p2;
7366 break;
7369 /* Opcode: OffsetLimit P1 P2 P3 * *
7370 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
7372 ** This opcode performs a commonly used computation associated with
7373 ** LIMIT and OFFSET processing. r[P1] holds the limit counter. r[P3]
7374 ** holds the offset counter. The opcode computes the combined value
7375 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
7376 ** value computed is the total number of rows that will need to be
7377 ** visited in order to complete the query.
7379 ** If r[P3] is zero or negative, that means there is no OFFSET
7380 ** and r[P2] is set to be the value of the LIMIT, r[P1].
7382 ** if r[P1] is zero or negative, that means there is no LIMIT
7383 ** and r[P2] is set to -1.
7385 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
7387 case OP_OffsetLimit: { /* in1, out2, in3 */
7388 i64 x;
7389 pIn1 = &aMem[pOp->p1];
7390 pIn3 = &aMem[pOp->p3];
7391 pOut = out2Prerelease(p, pOp);
7392 assert( pIn1->flags & MEM_Int );
7393 assert( pIn3->flags & MEM_Int );
7394 x = pIn1->u.i;
7395 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
7396 /* If the LIMIT is less than or equal to zero, loop forever. This
7397 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
7398 ** also loop forever. This is undocumented. In fact, one could argue
7399 ** that the loop should terminate. But assuming 1 billion iterations
7400 ** per second (far exceeding the capabilities of any current hardware)
7401 ** it would take nearly 300 years to actually reach the limit. So
7402 ** looping forever is a reasonable approximation. */
7403 pOut->u.i = -1;
7404 }else{
7405 pOut->u.i = x;
7407 break;
7410 /* Opcode: IfNotZero P1 P2 * * *
7411 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
7413 ** Register P1 must contain an integer. If the content of register P1 is
7414 ** initially greater than zero, then decrement the value in register P1.
7415 ** If it is non-zero (negative or positive) and then also jump to P2.
7416 ** If register P1 is initially zero, leave it unchanged and fall through.
7418 case OP_IfNotZero: { /* jump, in1 */
7419 pIn1 = &aMem[pOp->p1];
7420 assert( pIn1->flags&MEM_Int );
7421 VdbeBranchTaken(pIn1->u.i<0, 2);
7422 if( pIn1->u.i ){
7423 if( pIn1->u.i>0 ) pIn1->u.i--;
7424 goto jump_to_p2;
7426 break;
7429 /* Opcode: DecrJumpZero P1 P2 * * *
7430 ** Synopsis: if (--r[P1])==0 goto P2
7432 ** Register P1 must hold an integer. Decrement the value in P1
7433 ** and jump to P2 if the new value is exactly zero.
7435 case OP_DecrJumpZero: { /* jump, in1 */
7436 pIn1 = &aMem[pOp->p1];
7437 assert( pIn1->flags&MEM_Int );
7438 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
7439 VdbeBranchTaken(pIn1->u.i==0, 2);
7440 if( pIn1->u.i==0 ) goto jump_to_p2;
7441 break;
7445 /* Opcode: AggStep * P2 P3 P4 P5
7446 ** Synopsis: accum=r[P3] step(r[P2@P5])
7448 ** Execute the xStep function for an aggregate.
7449 ** The function has P5 arguments. P4 is a pointer to the
7450 ** FuncDef structure that specifies the function. Register P3 is the
7451 ** accumulator.
7453 ** The P5 arguments are taken from register P2 and its
7454 ** successors.
7456 /* Opcode: AggInverse * P2 P3 P4 P5
7457 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
7459 ** Execute the xInverse function for an aggregate.
7460 ** The function has P5 arguments. P4 is a pointer to the
7461 ** FuncDef structure that specifies the function. Register P3 is the
7462 ** accumulator.
7464 ** The P5 arguments are taken from register P2 and its
7465 ** successors.
7467 /* Opcode: AggStep1 P1 P2 P3 P4 P5
7468 ** Synopsis: accum=r[P3] step(r[P2@P5])
7470 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
7471 ** aggregate. The function has P5 arguments. P4 is a pointer to the
7472 ** FuncDef structure that specifies the function. Register P3 is the
7473 ** accumulator.
7475 ** The P5 arguments are taken from register P2 and its
7476 ** successors.
7478 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
7479 ** the FuncDef stored in P4 is converted into an sqlite3_context and
7480 ** the opcode is changed. In this way, the initialization of the
7481 ** sqlite3_context only happens once, instead of on each call to the
7482 ** step function.
7484 case OP_AggInverse:
7485 case OP_AggStep: {
7486 int n;
7487 sqlite3_context *pCtx;
7489 assert( pOp->p4type==P4_FUNCDEF );
7490 n = pOp->p5;
7491 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7492 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7493 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7494 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
7495 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
7496 if( pCtx==0 ) goto no_mem;
7497 pCtx->pMem = 0;
7498 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
7499 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
7500 pCtx->pFunc = pOp->p4.pFunc;
7501 pCtx->iOp = (int)(pOp - aOp);
7502 pCtx->pVdbe = p;
7503 pCtx->skipFlag = 0;
7504 pCtx->isError = 0;
7505 pCtx->enc = encoding;
7506 pCtx->argc = n;
7507 pOp->p4type = P4_FUNCCTX;
7508 pOp->p4.pCtx = pCtx;
7510 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
7511 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
7513 pOp->opcode = OP_AggStep1;
7514 /* Fall through into OP_AggStep */
7515 /* no break */ deliberate_fall_through
7517 case OP_AggStep1: {
7518 int i;
7519 sqlite3_context *pCtx;
7520 Mem *pMem;
7522 assert( pOp->p4type==P4_FUNCCTX );
7523 pCtx = pOp->p4.pCtx;
7524 pMem = &aMem[pOp->p3];
7526 #ifdef SQLITE_DEBUG
7527 if( pOp->p1 ){
7528 /* This is an OP_AggInverse call. Verify that xStep has always
7529 ** been called at least once prior to any xInverse call. */
7530 assert( pMem->uTemp==0x1122e0e3 );
7531 }else{
7532 /* This is an OP_AggStep call. Mark it as such. */
7533 pMem->uTemp = 0x1122e0e3;
7535 #endif
7537 /* If this function is inside of a trigger, the register array in aMem[]
7538 ** might change from one evaluation to the next. The next block of code
7539 ** checks to see if the register array has changed, and if so it
7540 ** reinitializes the relavant parts of the sqlite3_context object */
7541 if( pCtx->pMem != pMem ){
7542 pCtx->pMem = pMem;
7543 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7546 #ifdef SQLITE_DEBUG
7547 for(i=0; i<pCtx->argc; i++){
7548 assert( memIsValid(pCtx->argv[i]) );
7549 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7551 #endif
7553 pMem->n++;
7554 assert( pCtx->pOut->flags==MEM_Null );
7555 assert( pCtx->isError==0 );
7556 assert( pCtx->skipFlag==0 );
7557 #ifndef SQLITE_OMIT_WINDOWFUNC
7558 if( pOp->p1 ){
7559 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7560 }else
7561 #endif
7562 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7564 if( pCtx->isError ){
7565 if( pCtx->isError>0 ){
7566 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7567 rc = pCtx->isError;
7569 if( pCtx->skipFlag ){
7570 assert( pOp[-1].opcode==OP_CollSeq );
7571 i = pOp[-1].p1;
7572 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7573 pCtx->skipFlag = 0;
7575 sqlite3VdbeMemRelease(pCtx->pOut);
7576 pCtx->pOut->flags = MEM_Null;
7577 pCtx->isError = 0;
7578 if( rc ) goto abort_due_to_error;
7580 assert( pCtx->pOut->flags==MEM_Null );
7581 assert( pCtx->skipFlag==0 );
7582 break;
7585 /* Opcode: AggFinal P1 P2 * P4 *
7586 ** Synopsis: accum=r[P1] N=P2
7588 ** P1 is the memory location that is the accumulator for an aggregate
7589 ** or window function. Execute the finalizer function
7590 ** for an aggregate and store the result in P1.
7592 ** P2 is the number of arguments that the step function takes and
7593 ** P4 is a pointer to the FuncDef for this function. The P2
7594 ** argument is not used by this opcode. It is only there to disambiguate
7595 ** functions that can take varying numbers of arguments. The
7596 ** P4 argument is only needed for the case where
7597 ** the step function was not previously called.
7599 /* Opcode: AggValue * P2 P3 P4 *
7600 ** Synopsis: r[P3]=value N=P2
7602 ** Invoke the xValue() function and store the result in register P3.
7604 ** P2 is the number of arguments that the step function takes and
7605 ** P4 is a pointer to the FuncDef for this function. The P2
7606 ** argument is not used by this opcode. It is only there to disambiguate
7607 ** functions that can take varying numbers of arguments. The
7608 ** P4 argument is only needed for the case where
7609 ** the step function was not previously called.
7611 case OP_AggValue:
7612 case OP_AggFinal: {
7613 Mem *pMem;
7614 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7615 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7616 pMem = &aMem[pOp->p1];
7617 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7618 #ifndef SQLITE_OMIT_WINDOWFUNC
7619 if( pOp->p3 ){
7620 memAboutToChange(p, &aMem[pOp->p3]);
7621 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7622 pMem = &aMem[pOp->p3];
7623 }else
7624 #endif
7626 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7629 if( rc ){
7630 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7631 goto abort_due_to_error;
7633 sqlite3VdbeChangeEncoding(pMem, encoding);
7634 UPDATE_MAX_BLOBSIZE(pMem);
7635 REGISTER_TRACE((int)(pMem-aMem), pMem);
7636 break;
7639 #ifndef SQLITE_OMIT_WAL
7640 /* Opcode: Checkpoint P1 P2 P3 * *
7642 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7643 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7644 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
7645 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
7646 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7647 ** in the WAL that have been checkpointed after the checkpoint
7648 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
7649 ** mem[P3+2] are initialized to -1.
7651 case OP_Checkpoint: {
7652 int i; /* Loop counter */
7653 int aRes[3]; /* Results */
7654 Mem *pMem; /* Write results here */
7656 assert( p->readOnly==0 );
7657 aRes[0] = 0;
7658 aRes[1] = aRes[2] = -1;
7659 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7660 || pOp->p2==SQLITE_CHECKPOINT_FULL
7661 || pOp->p2==SQLITE_CHECKPOINT_RESTART
7662 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7664 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7665 if( rc ){
7666 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7667 rc = SQLITE_OK;
7668 aRes[0] = 1;
7670 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7671 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7673 break;
7675 #endif
7677 #ifndef SQLITE_OMIT_PRAGMA
7678 /* Opcode: JournalMode P1 P2 P3 * *
7680 ** Change the journal mode of database P1 to P3. P3 must be one of the
7681 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7682 ** modes (delete, truncate, persist, off and memory), this is a simple
7683 ** operation. No IO is required.
7685 ** If changing into or out of WAL mode the procedure is more complicated.
7687 ** Write a string containing the final journal-mode to register P2.
7689 case OP_JournalMode: { /* out2 */
7690 Btree *pBt; /* Btree to change journal mode of */
7691 Pager *pPager; /* Pager associated with pBt */
7692 int eNew; /* New journal mode */
7693 int eOld; /* The old journal mode */
7694 #ifndef SQLITE_OMIT_WAL
7695 const char *zFilename; /* Name of database file for pPager */
7696 #endif
7698 pOut = out2Prerelease(p, pOp);
7699 eNew = pOp->p3;
7700 assert( eNew==PAGER_JOURNALMODE_DELETE
7701 || eNew==PAGER_JOURNALMODE_TRUNCATE
7702 || eNew==PAGER_JOURNALMODE_PERSIST
7703 || eNew==PAGER_JOURNALMODE_OFF
7704 || eNew==PAGER_JOURNALMODE_MEMORY
7705 || eNew==PAGER_JOURNALMODE_WAL
7706 || eNew==PAGER_JOURNALMODE_QUERY
7708 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7709 assert( p->readOnly==0 );
7711 pBt = db->aDb[pOp->p1].pBt;
7712 pPager = sqlite3BtreePager(pBt);
7713 eOld = sqlite3PagerGetJournalMode(pPager);
7714 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7715 assert( sqlite3BtreeHoldsMutex(pBt) );
7716 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7718 #ifndef SQLITE_OMIT_WAL
7719 zFilename = sqlite3PagerFilename(pPager, 1);
7721 /* Do not allow a transition to journal_mode=WAL for a database
7722 ** in temporary storage or if the VFS does not support shared memory
7724 if( eNew==PAGER_JOURNALMODE_WAL
7725 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
7726 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
7728 eNew = eOld;
7731 if( (eNew!=eOld)
7732 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7734 if( !db->autoCommit || db->nVdbeRead>1 ){
7735 rc = SQLITE_ERROR;
7736 sqlite3VdbeError(p,
7737 "cannot change %s wal mode from within a transaction",
7738 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7740 goto abort_due_to_error;
7741 }else{
7743 if( eOld==PAGER_JOURNALMODE_WAL ){
7744 /* If leaving WAL mode, close the log file. If successful, the call
7745 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7746 ** file. An EXCLUSIVE lock may still be held on the database file
7747 ** after a successful return.
7749 rc = sqlite3PagerCloseWal(pPager, db);
7750 if( rc==SQLITE_OK ){
7751 sqlite3PagerSetJournalMode(pPager, eNew);
7753 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7754 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
7755 ** as an intermediate */
7756 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7759 /* Open a transaction on the database file. Regardless of the journal
7760 ** mode, this transaction always uses a rollback journal.
7762 assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7763 if( rc==SQLITE_OK ){
7764 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7768 #endif /* ifndef SQLITE_OMIT_WAL */
7770 if( rc ) eNew = eOld;
7771 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7773 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7774 pOut->z = (char *)sqlite3JournalModename(eNew);
7775 pOut->n = sqlite3Strlen30(pOut->z);
7776 pOut->enc = SQLITE_UTF8;
7777 sqlite3VdbeChangeEncoding(pOut, encoding);
7778 if( rc ) goto abort_due_to_error;
7779 break;
7781 #endif /* SQLITE_OMIT_PRAGMA */
7783 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7784 /* Opcode: Vacuum P1 P2 * * *
7786 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
7787 ** for an attached database. The "temp" database may not be vacuumed.
7789 ** If P2 is not zero, then it is a register holding a string which is
7790 ** the file into which the result of vacuum should be written. When
7791 ** P2 is zero, the vacuum overwrites the original database.
7793 case OP_Vacuum: {
7794 assert( p->readOnly==0 );
7795 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7796 pOp->p2 ? &aMem[pOp->p2] : 0);
7797 if( rc ) goto abort_due_to_error;
7798 break;
7800 #endif
7802 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7803 /* Opcode: IncrVacuum P1 P2 * * *
7805 ** Perform a single step of the incremental vacuum procedure on
7806 ** the P1 database. If the vacuum has finished, jump to instruction
7807 ** P2. Otherwise, fall through to the next instruction.
7809 case OP_IncrVacuum: { /* jump */
7810 Btree *pBt;
7812 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7813 assert( DbMaskTest(p->btreeMask, pOp->p1) );
7814 assert( p->readOnly==0 );
7815 pBt = db->aDb[pOp->p1].pBt;
7816 rc = sqlite3BtreeIncrVacuum(pBt);
7817 VdbeBranchTaken(rc==SQLITE_DONE,2);
7818 if( rc ){
7819 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7820 rc = SQLITE_OK;
7821 goto jump_to_p2;
7823 break;
7825 #endif
7827 /* Opcode: Expire P1 P2 * * *
7829 ** Cause precompiled statements to expire. When an expired statement
7830 ** is executed using sqlite3_step() it will either automatically
7831 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
7832 ** or it will fail with SQLITE_SCHEMA.
7834 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
7835 ** then only the currently executing statement is expired.
7837 ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
7838 ** then running SQL statements are allowed to continue to run to completion.
7839 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
7840 ** that might help the statement run faster but which does not affect the
7841 ** correctness of operation.
7843 case OP_Expire: {
7844 assert( pOp->p2==0 || pOp->p2==1 );
7845 if( !pOp->p1 ){
7846 sqlite3ExpirePreparedStatements(db, pOp->p2);
7847 }else{
7848 p->expired = pOp->p2+1;
7850 break;
7853 /* Opcode: CursorLock P1 * * * *
7855 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
7856 ** written by an other cursor.
7858 case OP_CursorLock: {
7859 VdbeCursor *pC;
7860 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7861 pC = p->apCsr[pOp->p1];
7862 assert( pC!=0 );
7863 assert( pC->eCurType==CURTYPE_BTREE );
7864 sqlite3BtreeCursorPin(pC->uc.pCursor);
7865 break;
7868 /* Opcode: CursorUnlock P1 * * * *
7870 ** Unlock the btree to which cursor P1 is pointing so that it can be
7871 ** written by other cursors.
7873 case OP_CursorUnlock: {
7874 VdbeCursor *pC;
7875 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7876 pC = p->apCsr[pOp->p1];
7877 assert( pC!=0 );
7878 assert( pC->eCurType==CURTYPE_BTREE );
7879 sqlite3BtreeCursorUnpin(pC->uc.pCursor);
7880 break;
7883 #ifndef SQLITE_OMIT_SHARED_CACHE
7884 /* Opcode: TableLock P1 P2 P3 P4 *
7885 ** Synopsis: iDb=P1 root=P2 write=P3
7887 ** Obtain a lock on a particular table. This instruction is only used when
7888 ** the shared-cache feature is enabled.
7890 ** P1 is the index of the database in sqlite3.aDb[] of the database
7891 ** on which the lock is acquired. A readlock is obtained if P3==0 or
7892 ** a write lock if P3==1.
7894 ** P2 contains the root-page of the table to lock.
7896 ** P4 contains a pointer to the name of the table being locked. This is only
7897 ** used to generate an error message if the lock cannot be obtained.
7899 case OP_TableLock: {
7900 u8 isWriteLock = (u8)pOp->p3;
7901 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
7902 int p1 = pOp->p1;
7903 assert( p1>=0 && p1<db->nDb );
7904 assert( DbMaskTest(p->btreeMask, p1) );
7905 assert( isWriteLock==0 || isWriteLock==1 );
7906 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
7907 if( rc ){
7908 if( (rc&0xFF)==SQLITE_LOCKED ){
7909 const char *z = pOp->p4.z;
7910 sqlite3VdbeError(p, "database table is locked: %s", z);
7912 goto abort_due_to_error;
7915 break;
7917 #endif /* SQLITE_OMIT_SHARED_CACHE */
7919 #ifndef SQLITE_OMIT_VIRTUALTABLE
7920 /* Opcode: VBegin * * * P4 *
7922 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
7923 ** xBegin method for that table.
7925 ** Also, whether or not P4 is set, check that this is not being called from
7926 ** within a callback to a virtual table xSync() method. If it is, the error
7927 ** code will be set to SQLITE_LOCKED.
7929 case OP_VBegin: {
7930 VTable *pVTab;
7931 pVTab = pOp->p4.pVtab;
7932 rc = sqlite3VtabBegin(db, pVTab);
7933 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
7934 if( rc ) goto abort_due_to_error;
7935 break;
7937 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7939 #ifndef SQLITE_OMIT_VIRTUALTABLE
7940 /* Opcode: VCreate P1 P2 * * *
7942 ** P2 is a register that holds the name of a virtual table in database
7943 ** P1. Call the xCreate method for that table.
7945 case OP_VCreate: {
7946 Mem sMem; /* For storing the record being decoded */
7947 const char *zTab; /* Name of the virtual table */
7949 memset(&sMem, 0, sizeof(sMem));
7950 sMem.db = db;
7951 /* Because P2 is always a static string, it is impossible for the
7952 ** sqlite3VdbeMemCopy() to fail */
7953 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
7954 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
7955 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
7956 assert( rc==SQLITE_OK );
7957 zTab = (const char*)sqlite3_value_text(&sMem);
7958 assert( zTab || db->mallocFailed );
7959 if( zTab ){
7960 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
7962 sqlite3VdbeMemRelease(&sMem);
7963 if( rc ) goto abort_due_to_error;
7964 break;
7966 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7968 #ifndef SQLITE_OMIT_VIRTUALTABLE
7969 /* Opcode: VDestroy P1 * * P4 *
7971 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
7972 ** of that table.
7974 case OP_VDestroy: {
7975 db->nVDestroy++;
7976 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
7977 db->nVDestroy--;
7978 assert( p->errorAction==OE_Abort && p->usesStmtJournal );
7979 if( rc ) goto abort_due_to_error;
7980 break;
7982 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7984 #ifndef SQLITE_OMIT_VIRTUALTABLE
7985 /* Opcode: VOpen P1 * * P4 *
7987 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7988 ** P1 is a cursor number. This opcode opens a cursor to the virtual
7989 ** table and stores that cursor in P1.
7991 case OP_VOpen: { /* ncycle */
7992 VdbeCursor *pCur;
7993 sqlite3_vtab_cursor *pVCur;
7994 sqlite3_vtab *pVtab;
7995 const sqlite3_module *pModule;
7997 assert( p->bIsReader );
7998 pCur = 0;
7999 pVCur = 0;
8000 pVtab = pOp->p4.pVtab->pVtab;
8001 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8002 rc = SQLITE_LOCKED;
8003 goto abort_due_to_error;
8005 pModule = pVtab->pModule;
8006 rc = pModule->xOpen(pVtab, &pVCur);
8007 sqlite3VtabImportErrmsg(p, pVtab);
8008 if( rc ) goto abort_due_to_error;
8010 /* Initialize sqlite3_vtab_cursor base class */
8011 pVCur->pVtab = pVtab;
8013 /* Initialize vdbe cursor object */
8014 pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
8015 if( pCur ){
8016 pCur->uc.pVCur = pVCur;
8017 pVtab->nRef++;
8018 }else{
8019 assert( db->mallocFailed );
8020 pModule->xClose(pVCur);
8021 goto no_mem;
8023 break;
8025 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8027 #ifndef SQLITE_OMIT_VIRTUALTABLE
8028 /* Opcode: VInitIn P1 P2 P3 * *
8029 ** Synopsis: r[P2]=ValueList(P1,P3)
8031 ** Set register P2 to be a pointer to a ValueList object for cursor P1
8032 ** with cache register P3 and output register P3+1. This ValueList object
8033 ** can be used as the first argument to sqlite3_vtab_in_first() and
8034 ** sqlite3_vtab_in_next() to extract all of the values stored in the P1
8035 ** cursor. Register P3 is used to hold the values returned by
8036 ** sqlite3_vtab_in_first() and sqlite3_vtab_in_next().
8038 case OP_VInitIn: { /* out2, ncycle */
8039 VdbeCursor *pC; /* The cursor containing the RHS values */
8040 ValueList *pRhs; /* New ValueList object to put in reg[P2] */
8042 pC = p->apCsr[pOp->p1];
8043 pRhs = sqlite3_malloc64( sizeof(*pRhs) );
8044 if( pRhs==0 ) goto no_mem;
8045 pRhs->pCsr = pC->uc.pCursor;
8046 pRhs->pOut = &aMem[pOp->p3];
8047 pOut = out2Prerelease(p, pOp);
8048 pOut->flags = MEM_Null;
8049 sqlite3VdbeMemSetPointer(pOut, pRhs, "ValueList", sqlite3VdbeValueListFree);
8050 break;
8052 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8055 #ifndef SQLITE_OMIT_VIRTUALTABLE
8056 /* Opcode: VFilter P1 P2 P3 P4 *
8057 ** Synopsis: iplan=r[P3] zplan='P4'
8059 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
8060 ** the filtered result set is empty.
8062 ** P4 is either NULL or a string that was generated by the xBestIndex
8063 ** method of the module. The interpretation of the P4 string is left
8064 ** to the module implementation.
8066 ** This opcode invokes the xFilter method on the virtual table specified
8067 ** by P1. The integer query plan parameter to xFilter is stored in register
8068 ** P3. Register P3+1 stores the argc parameter to be passed to the
8069 ** xFilter method. Registers P3+2..P3+1+argc are the argc
8070 ** additional parameters which are passed to
8071 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
8073 ** A jump is made to P2 if the result set after filtering would be empty.
8075 case OP_VFilter: { /* jump, ncycle */
8076 int nArg;
8077 int iQuery;
8078 const sqlite3_module *pModule;
8079 Mem *pQuery;
8080 Mem *pArgc;
8081 sqlite3_vtab_cursor *pVCur;
8082 sqlite3_vtab *pVtab;
8083 VdbeCursor *pCur;
8084 int res;
8085 int i;
8086 Mem **apArg;
8088 pQuery = &aMem[pOp->p3];
8089 pArgc = &pQuery[1];
8090 pCur = p->apCsr[pOp->p1];
8091 assert( memIsValid(pQuery) );
8092 REGISTER_TRACE(pOp->p3, pQuery);
8093 assert( pCur!=0 );
8094 assert( pCur->eCurType==CURTYPE_VTAB );
8095 pVCur = pCur->uc.pVCur;
8096 pVtab = pVCur->pVtab;
8097 pModule = pVtab->pModule;
8099 /* Grab the index number and argc parameters */
8100 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
8101 nArg = (int)pArgc->u.i;
8102 iQuery = (int)pQuery->u.i;
8104 /* Invoke the xFilter method */
8105 apArg = p->apArg;
8106 for(i = 0; i<nArg; i++){
8107 apArg[i] = &pArgc[i+1];
8109 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
8110 sqlite3VtabImportErrmsg(p, pVtab);
8111 if( rc ) goto abort_due_to_error;
8112 res = pModule->xEof(pVCur);
8113 pCur->nullRow = 0;
8114 VdbeBranchTaken(res!=0,2);
8115 if( res ) goto jump_to_p2;
8116 break;
8118 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8120 #ifndef SQLITE_OMIT_VIRTUALTABLE
8121 /* Opcode: VColumn P1 P2 P3 * P5
8122 ** Synopsis: r[P3]=vcolumn(P2)
8124 ** Store in register P3 the value of the P2-th column of
8125 ** the current row of the virtual-table of cursor P1.
8127 ** If the VColumn opcode is being used to fetch the value of
8128 ** an unchanging column during an UPDATE operation, then the P5
8129 ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
8130 ** function to return true inside the xColumn method of the virtual
8131 ** table implementation. The P5 column might also contain other
8132 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
8133 ** unused by OP_VColumn.
8135 case OP_VColumn: { /* ncycle */
8136 sqlite3_vtab *pVtab;
8137 const sqlite3_module *pModule;
8138 Mem *pDest;
8139 sqlite3_context sContext;
8141 VdbeCursor *pCur = p->apCsr[pOp->p1];
8142 assert( pCur!=0 );
8143 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
8144 pDest = &aMem[pOp->p3];
8145 memAboutToChange(p, pDest);
8146 if( pCur->nullRow ){
8147 sqlite3VdbeMemSetNull(pDest);
8148 break;
8150 assert( pCur->eCurType==CURTYPE_VTAB );
8151 pVtab = pCur->uc.pVCur->pVtab;
8152 pModule = pVtab->pModule;
8153 assert( pModule->xColumn );
8154 memset(&sContext, 0, sizeof(sContext));
8155 sContext.pOut = pDest;
8156 sContext.enc = encoding;
8157 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
8158 if( pOp->p5 & OPFLAG_NOCHNG ){
8159 sqlite3VdbeMemSetNull(pDest);
8160 pDest->flags = MEM_Null|MEM_Zero;
8161 pDest->u.nZero = 0;
8162 }else{
8163 MemSetTypeFlag(pDest, MEM_Null);
8165 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
8166 sqlite3VtabImportErrmsg(p, pVtab);
8167 if( sContext.isError>0 ){
8168 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
8169 rc = sContext.isError;
8171 sqlite3VdbeChangeEncoding(pDest, encoding);
8172 REGISTER_TRACE(pOp->p3, pDest);
8173 UPDATE_MAX_BLOBSIZE(pDest);
8175 if( rc ) goto abort_due_to_error;
8176 break;
8178 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8180 #ifndef SQLITE_OMIT_VIRTUALTABLE
8181 /* Opcode: VNext P1 P2 * * *
8183 ** Advance virtual table P1 to the next row in its result set and
8184 ** jump to instruction P2. Or, if the virtual table has reached
8185 ** the end of its result set, then fall through to the next instruction.
8187 case OP_VNext: { /* jump, ncycle */
8188 sqlite3_vtab *pVtab;
8189 const sqlite3_module *pModule;
8190 int res;
8191 VdbeCursor *pCur;
8193 pCur = p->apCsr[pOp->p1];
8194 assert( pCur!=0 );
8195 assert( pCur->eCurType==CURTYPE_VTAB );
8196 if( pCur->nullRow ){
8197 break;
8199 pVtab = pCur->uc.pVCur->pVtab;
8200 pModule = pVtab->pModule;
8201 assert( pModule->xNext );
8203 /* Invoke the xNext() method of the module. There is no way for the
8204 ** underlying implementation to return an error if one occurs during
8205 ** xNext(). Instead, if an error occurs, true is returned (indicating that
8206 ** data is available) and the error code returned when xColumn or
8207 ** some other method is next invoked on the save virtual table cursor.
8209 rc = pModule->xNext(pCur->uc.pVCur);
8210 sqlite3VtabImportErrmsg(p, pVtab);
8211 if( rc ) goto abort_due_to_error;
8212 res = pModule->xEof(pCur->uc.pVCur);
8213 VdbeBranchTaken(!res,2);
8214 if( !res ){
8215 /* If there is data, jump to P2 */
8216 goto jump_to_p2_and_check_for_interrupt;
8218 goto check_for_interrupt;
8220 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8222 #ifndef SQLITE_OMIT_VIRTUALTABLE
8223 /* Opcode: VRename P1 * * P4 *
8225 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8226 ** This opcode invokes the corresponding xRename method. The value
8227 ** in register P1 is passed as the zName argument to the xRename method.
8229 case OP_VRename: {
8230 sqlite3_vtab *pVtab;
8231 Mem *pName;
8232 int isLegacy;
8234 isLegacy = (db->flags & SQLITE_LegacyAlter);
8235 db->flags |= SQLITE_LegacyAlter;
8236 pVtab = pOp->p4.pVtab->pVtab;
8237 pName = &aMem[pOp->p1];
8238 assert( pVtab->pModule->xRename );
8239 assert( memIsValid(pName) );
8240 assert( p->readOnly==0 );
8241 REGISTER_TRACE(pOp->p1, pName);
8242 assert( pName->flags & MEM_Str );
8243 testcase( pName->enc==SQLITE_UTF8 );
8244 testcase( pName->enc==SQLITE_UTF16BE );
8245 testcase( pName->enc==SQLITE_UTF16LE );
8246 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
8247 if( rc ) goto abort_due_to_error;
8248 rc = pVtab->pModule->xRename(pVtab, pName->z);
8249 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
8250 sqlite3VtabImportErrmsg(p, pVtab);
8251 p->expired = 0;
8252 if( rc ) goto abort_due_to_error;
8253 break;
8255 #endif
8257 #ifndef SQLITE_OMIT_VIRTUALTABLE
8258 /* Opcode: VUpdate P1 P2 P3 P4 P5
8259 ** Synopsis: data=r[P3@P2]
8261 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8262 ** This opcode invokes the corresponding xUpdate method. P2 values
8263 ** are contiguous memory cells starting at P3 to pass to the xUpdate
8264 ** invocation. The value in register (P3+P2-1) corresponds to the
8265 ** p2th element of the argv array passed to xUpdate.
8267 ** The xUpdate method will do a DELETE or an INSERT or both.
8268 ** The argv[0] element (which corresponds to memory cell P3)
8269 ** is the rowid of a row to delete. If argv[0] is NULL then no
8270 ** deletion occurs. The argv[1] element is the rowid of the new
8271 ** row. This can be NULL to have the virtual table select the new
8272 ** rowid for itself. The subsequent elements in the array are
8273 ** the values of columns in the new row.
8275 ** If P2==1 then no insert is performed. argv[0] is the rowid of
8276 ** a row to delete.
8278 ** P1 is a boolean flag. If it is set to true and the xUpdate call
8279 ** is successful, then the value returned by sqlite3_last_insert_rowid()
8280 ** is set to the value of the rowid for the row just inserted.
8282 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
8283 ** apply in the case of a constraint failure on an insert or update.
8285 case OP_VUpdate: {
8286 sqlite3_vtab *pVtab;
8287 const sqlite3_module *pModule;
8288 int nArg;
8289 int i;
8290 sqlite_int64 rowid = 0;
8291 Mem **apArg;
8292 Mem *pX;
8294 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
8295 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
8297 assert( p->readOnly==0 );
8298 if( db->mallocFailed ) goto no_mem;
8299 sqlite3VdbeIncrWriteCounter(p, 0);
8300 pVtab = pOp->p4.pVtab->pVtab;
8301 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8302 rc = SQLITE_LOCKED;
8303 goto abort_due_to_error;
8305 pModule = pVtab->pModule;
8306 nArg = pOp->p2;
8307 assert( pOp->p4type==P4_VTAB );
8308 if( ALWAYS(pModule->xUpdate) ){
8309 u8 vtabOnConflict = db->vtabOnConflict;
8310 apArg = p->apArg;
8311 pX = &aMem[pOp->p3];
8312 for(i=0; i<nArg; i++){
8313 assert( memIsValid(pX) );
8314 memAboutToChange(p, pX);
8315 apArg[i] = pX;
8316 pX++;
8318 db->vtabOnConflict = pOp->p5;
8319 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
8320 db->vtabOnConflict = vtabOnConflict;
8321 sqlite3VtabImportErrmsg(p, pVtab);
8322 if( rc==SQLITE_OK && pOp->p1 ){
8323 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
8324 db->lastRowid = rowid;
8326 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
8327 if( pOp->p5==OE_Ignore ){
8328 rc = SQLITE_OK;
8329 }else{
8330 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
8332 }else{
8333 p->nChange++;
8335 if( rc ) goto abort_due_to_error;
8337 break;
8339 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8341 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8342 /* Opcode: Pagecount P1 P2 * * *
8344 ** Write the current number of pages in database P1 to memory cell P2.
8346 case OP_Pagecount: { /* out2 */
8347 pOut = out2Prerelease(p, pOp);
8348 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
8349 break;
8351 #endif
8354 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8355 /* Opcode: MaxPgcnt P1 P2 P3 * *
8357 ** Try to set the maximum page count for database P1 to the value in P3.
8358 ** Do not let the maximum page count fall below the current page count and
8359 ** do not change the maximum page count value if P3==0.
8361 ** Store the maximum page count after the change in register P2.
8363 case OP_MaxPgcnt: { /* out2 */
8364 unsigned int newMax;
8365 Btree *pBt;
8367 pOut = out2Prerelease(p, pOp);
8368 pBt = db->aDb[pOp->p1].pBt;
8369 newMax = 0;
8370 if( pOp->p3 ){
8371 newMax = sqlite3BtreeLastPage(pBt);
8372 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
8374 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
8375 break;
8377 #endif
8379 /* Opcode: Function P1 P2 P3 P4 *
8380 ** Synopsis: r[P3]=func(r[P2@NP])
8382 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8383 ** contains a pointer to the function to be run) with arguments taken
8384 ** from register P2 and successors. The number of arguments is in
8385 ** the sqlite3_context object that P4 points to.
8386 ** The result of the function is stored
8387 ** in register P3. Register P3 must not be one of the function inputs.
8389 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8390 ** function was determined to be constant at compile time. If the first
8391 ** argument was constant then bit 0 of P1 is set. This is used to determine
8392 ** whether meta data associated with a user function argument using the
8393 ** sqlite3_set_auxdata() API may be safely retained until the next
8394 ** invocation of this opcode.
8396 ** See also: AggStep, AggFinal, PureFunc
8398 /* Opcode: PureFunc P1 P2 P3 P4 *
8399 ** Synopsis: r[P3]=func(r[P2@NP])
8401 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8402 ** contains a pointer to the function to be run) with arguments taken
8403 ** from register P2 and successors. The number of arguments is in
8404 ** the sqlite3_context object that P4 points to.
8405 ** The result of the function is stored
8406 ** in register P3. Register P3 must not be one of the function inputs.
8408 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8409 ** function was determined to be constant at compile time. If the first
8410 ** argument was constant then bit 0 of P1 is set. This is used to determine
8411 ** whether meta data associated with a user function argument using the
8412 ** sqlite3_set_auxdata() API may be safely retained until the next
8413 ** invocation of this opcode.
8415 ** This opcode works exactly like OP_Function. The only difference is in
8416 ** its name. This opcode is used in places where the function must be
8417 ** purely non-deterministic. Some built-in date/time functions can be
8418 ** either determinitic of non-deterministic, depending on their arguments.
8419 ** When those function are used in a non-deterministic way, they will check
8420 ** to see if they were called using OP_PureFunc instead of OP_Function, and
8421 ** if they were, they throw an error.
8423 ** See also: AggStep, AggFinal, Function
8425 case OP_PureFunc: /* group */
8426 case OP_Function: { /* group */
8427 int i;
8428 sqlite3_context *pCtx;
8430 assert( pOp->p4type==P4_FUNCCTX );
8431 pCtx = pOp->p4.pCtx;
8433 /* If this function is inside of a trigger, the register array in aMem[]
8434 ** might change from one evaluation to the next. The next block of code
8435 ** checks to see if the register array has changed, and if so it
8436 ** reinitializes the relavant parts of the sqlite3_context object */
8437 pOut = &aMem[pOp->p3];
8438 if( pCtx->pOut != pOut ){
8439 pCtx->pVdbe = p;
8440 pCtx->pOut = pOut;
8441 pCtx->enc = encoding;
8442 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
8444 assert( pCtx->pVdbe==p );
8446 memAboutToChange(p, pOut);
8447 #ifdef SQLITE_DEBUG
8448 for(i=0; i<pCtx->argc; i++){
8449 assert( memIsValid(pCtx->argv[i]) );
8450 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
8452 #endif
8453 MemSetTypeFlag(pOut, MEM_Null);
8454 assert( pCtx->isError==0 );
8455 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
8457 /* If the function returned an error, throw an exception */
8458 if( pCtx->isError ){
8459 if( pCtx->isError>0 ){
8460 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
8461 rc = pCtx->isError;
8463 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
8464 pCtx->isError = 0;
8465 if( rc ) goto abort_due_to_error;
8468 assert( (pOut->flags&MEM_Str)==0
8469 || pOut->enc==encoding
8470 || db->mallocFailed );
8471 assert( !sqlite3VdbeMemTooBig(pOut) );
8473 REGISTER_TRACE(pOp->p3, pOut);
8474 UPDATE_MAX_BLOBSIZE(pOut);
8475 break;
8478 /* Opcode: ClrSubtype P1 * * * *
8479 ** Synopsis: r[P1].subtype = 0
8481 ** Clear the subtype from register P1.
8483 case OP_ClrSubtype: { /* in1 */
8484 pIn1 = &aMem[pOp->p1];
8485 pIn1->flags &= ~MEM_Subtype;
8486 break;
8489 /* Opcode: FilterAdd P1 * P3 P4 *
8490 ** Synopsis: filter(P1) += key(P3@P4)
8492 ** Compute a hash on the P4 registers starting with r[P3] and
8493 ** add that hash to the bloom filter contained in r[P1].
8495 case OP_FilterAdd: {
8496 u64 h;
8498 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8499 pIn1 = &aMem[pOp->p1];
8500 assert( pIn1->flags & MEM_Blob );
8501 assert( pIn1->n>0 );
8502 h = filterHash(aMem, pOp);
8503 #ifdef SQLITE_DEBUG
8504 if( db->flags&SQLITE_VdbeTrace ){
8505 int ii;
8506 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8507 registerTrace(ii, &aMem[ii]);
8509 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8511 #endif
8512 h %= pIn1->n;
8513 pIn1->z[h/8] |= 1<<(h&7);
8514 break;
8517 /* Opcode: Filter P1 P2 P3 P4 *
8518 ** Synopsis: if key(P3@P4) not in filter(P1) goto P2
8520 ** Compute a hash on the key contained in the P4 registers starting
8521 ** with r[P3]. Check to see if that hash is found in the
8522 ** bloom filter hosted by register P1. If it is not present then
8523 ** maybe jump to P2. Otherwise fall through.
8525 ** False negatives are harmless. It is always safe to fall through,
8526 ** even if the value is in the bloom filter. A false negative causes
8527 ** more CPU cycles to be used, but it should still yield the correct
8528 ** answer. However, an incorrect answer may well arise from a
8529 ** false positive - if the jump is taken when it should fall through.
8531 case OP_Filter: { /* jump */
8532 u64 h;
8534 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8535 pIn1 = &aMem[pOp->p1];
8536 assert( (pIn1->flags & MEM_Blob)!=0 );
8537 assert( pIn1->n >= 1 );
8538 h = filterHash(aMem, pOp);
8539 #ifdef SQLITE_DEBUG
8540 if( db->flags&SQLITE_VdbeTrace ){
8541 int ii;
8542 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8543 registerTrace(ii, &aMem[ii]);
8545 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8547 #endif
8548 h %= pIn1->n;
8549 if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
8550 VdbeBranchTaken(1, 2);
8551 p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
8552 goto jump_to_p2;
8553 }else{
8554 p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
8555 VdbeBranchTaken(0, 2);
8557 break;
8560 /* Opcode: Trace P1 P2 * P4 *
8562 ** Write P4 on the statement trace output if statement tracing is
8563 ** enabled.
8565 ** Operand P1 must be 0x7fffffff and P2 must positive.
8567 /* Opcode: Init P1 P2 P3 P4 *
8568 ** Synopsis: Start at P2
8570 ** Programs contain a single instance of this opcode as the very first
8571 ** opcode.
8573 ** If tracing is enabled (by the sqlite3_trace()) interface, then
8574 ** the UTF-8 string contained in P4 is emitted on the trace callback.
8575 ** Or if P4 is blank, use the string returned by sqlite3_sql().
8577 ** If P2 is not zero, jump to instruction P2.
8579 ** Increment the value of P1 so that OP_Once opcodes will jump the
8580 ** first time they are evaluated for this run.
8582 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
8583 ** error is encountered.
8585 case OP_Trace:
8586 case OP_Init: { /* jump */
8587 int i;
8588 #ifndef SQLITE_OMIT_TRACE
8589 char *zTrace;
8590 #endif
8592 /* If the P4 argument is not NULL, then it must be an SQL comment string.
8593 ** The "--" string is broken up to prevent false-positives with srcck1.c.
8595 ** This assert() provides evidence for:
8596 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
8597 ** would have been returned by the legacy sqlite3_trace() interface by
8598 ** using the X argument when X begins with "--" and invoking
8599 ** sqlite3_expanded_sql(P) otherwise.
8601 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
8603 /* OP_Init is always instruction 0 */
8604 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
8606 #ifndef SQLITE_OMIT_TRACE
8607 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
8608 && p->minWriteFileFormat!=254 /* tag-20220401a */
8609 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8611 #ifndef SQLITE_OMIT_DEPRECATED
8612 if( db->mTrace & SQLITE_TRACE_LEGACY ){
8613 char *z = sqlite3VdbeExpandSql(p, zTrace);
8614 db->trace.xLegacy(db->pTraceArg, z);
8615 sqlite3_free(z);
8616 }else
8617 #endif
8618 if( db->nVdbeExec>1 ){
8619 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
8620 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
8621 sqlite3DbFree(db, z);
8622 }else{
8623 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
8626 #ifdef SQLITE_USE_FCNTL_TRACE
8627 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
8628 if( zTrace ){
8629 int j;
8630 for(j=0; j<db->nDb; j++){
8631 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
8632 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
8635 #endif /* SQLITE_USE_FCNTL_TRACE */
8636 #ifdef SQLITE_DEBUG
8637 if( (db->flags & SQLITE_SqlTrace)!=0
8638 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8640 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8642 #endif /* SQLITE_DEBUG */
8643 #endif /* SQLITE_OMIT_TRACE */
8644 assert( pOp->p2>0 );
8645 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8646 if( pOp->opcode==OP_Trace ) break;
8647 for(i=1; i<p->nOp; i++){
8648 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8650 pOp->p1 = 0;
8652 pOp->p1++;
8653 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8654 goto jump_to_p2;
8657 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8658 /* Opcode: CursorHint P1 * * P4 *
8660 ** Provide a hint to cursor P1 that it only needs to return rows that
8661 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
8662 ** to values currently held in registers. TK_COLUMN terms in the P4
8663 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8665 case OP_CursorHint: {
8666 VdbeCursor *pC;
8668 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8669 assert( pOp->p4type==P4_EXPR );
8670 pC = p->apCsr[pOp->p1];
8671 if( pC ){
8672 assert( pC->eCurType==CURTYPE_BTREE );
8673 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8674 pOp->p4.pExpr, aMem);
8676 break;
8678 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8680 #ifdef SQLITE_DEBUG
8681 /* Opcode: Abortable * * * * *
8683 ** Verify that an Abort can happen. Assert if an Abort at this point
8684 ** might cause database corruption. This opcode only appears in debugging
8685 ** builds.
8687 ** An Abort is safe if either there have been no writes, or if there is
8688 ** an active statement journal.
8690 case OP_Abortable: {
8691 sqlite3VdbeAssertAbortable(p);
8692 break;
8694 #endif
8696 #ifdef SQLITE_DEBUG
8697 /* Opcode: ReleaseReg P1 P2 P3 * P5
8698 ** Synopsis: release r[P1@P2] mask P3
8700 ** Release registers from service. Any content that was in the
8701 ** the registers is unreliable after this opcode completes.
8703 ** The registers released will be the P2 registers starting at P1,
8704 ** except if bit ii of P3 set, then do not release register P1+ii.
8705 ** In other words, P3 is a mask of registers to preserve.
8707 ** Releasing a register clears the Mem.pScopyFrom pointer. That means
8708 ** that if the content of the released register was set using OP_SCopy,
8709 ** a change to the value of the source register for the OP_SCopy will no longer
8710 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8712 ** If P5 is set, then all released registers have their type set
8713 ** to MEM_Undefined so that any subsequent attempt to read the released
8714 ** register (before it is reinitialized) will generate an assertion fault.
8716 ** P5 ought to be set on every call to this opcode.
8717 ** However, there are places in the code generator will release registers
8718 ** before their are used, under the (valid) assumption that the registers
8719 ** will not be reallocated for some other purpose before they are used and
8720 ** hence are safe to release.
8722 ** This opcode is only available in testing and debugging builds. It is
8723 ** not generated for release builds. The purpose of this opcode is to help
8724 ** validate the generated bytecode. This opcode does not actually contribute
8725 ** to computing an answer.
8727 case OP_ReleaseReg: {
8728 Mem *pMem;
8729 int i;
8730 u32 constMask;
8731 assert( pOp->p1>0 );
8732 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8733 pMem = &aMem[pOp->p1];
8734 constMask = pOp->p3;
8735 for(i=0; i<pOp->p2; i++, pMem++){
8736 if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8737 pMem->pScopyFrom = 0;
8738 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
8741 break;
8743 #endif
8745 /* Opcode: Noop * * * * *
8747 ** Do nothing. This instruction is often useful as a jump
8748 ** destination.
8751 ** The magic Explain opcode are only inserted when explain==2 (which
8752 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
8753 ** This opcode records information from the optimizer. It is the
8754 ** the same as a no-op. This opcodesnever appears in a real VM program.
8756 default: { /* This is really OP_Noop, OP_Explain */
8757 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
8759 break;
8762 /*****************************************************************************
8763 ** The cases of the switch statement above this line should all be indented
8764 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
8765 ** readability. From this point on down, the normal indentation rules are
8766 ** restored.
8767 *****************************************************************************/
8770 #if defined(VDBE_PROFILE)
8771 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
8772 pnCycle = 0;
8773 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
8774 if( pnCycle ){
8775 *pnCycle += sqlite3Hwtime();
8776 pnCycle = 0;
8778 #endif
8780 /* The following code adds nothing to the actual functionality
8781 ** of the program. It is only here for testing and debugging.
8782 ** On the other hand, it does burn CPU cycles every time through
8783 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
8785 #ifndef NDEBUG
8786 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
8788 #ifdef SQLITE_DEBUG
8789 if( db->flags & SQLITE_VdbeTrace ){
8790 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
8791 if( rc!=0 ) printf("rc=%d\n",rc);
8792 if( opProperty & (OPFLG_OUT2) ){
8793 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
8795 if( opProperty & OPFLG_OUT3 ){
8796 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
8798 if( opProperty==0xff ){
8799 /* Never happens. This code exists to avoid a harmless linkage
8800 ** warning aboud sqlite3VdbeRegisterDump() being defined but not
8801 ** used. */
8802 sqlite3VdbeRegisterDump(p);
8805 #endif /* SQLITE_DEBUG */
8806 #endif /* NDEBUG */
8807 } /* The end of the for(;;) loop the loops through opcodes */
8809 /* If we reach this point, it means that execution is finished with
8810 ** an error of some kind.
8812 abort_due_to_error:
8813 if( db->mallocFailed ){
8814 rc = SQLITE_NOMEM_BKPT;
8815 }else if( rc==SQLITE_IOERR_CORRUPTFS ){
8816 rc = SQLITE_CORRUPT_BKPT;
8818 assert( rc );
8819 #ifdef SQLITE_DEBUG
8820 if( db->flags & SQLITE_VdbeTrace ){
8821 const char *zTrace = p->zSql;
8822 if( zTrace==0 ){
8823 if( aOp[0].opcode==OP_Trace ){
8824 zTrace = aOp[0].p4.z;
8826 if( zTrace==0 ) zTrace = "???";
8828 printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
8830 #endif
8831 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
8832 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
8834 p->rc = rc;
8835 sqlite3SystemError(db, rc);
8836 testcase( sqlite3GlobalConfig.xLog!=0 );
8837 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
8838 (int)(pOp - aOp), p->zSql, p->zErrMsg);
8839 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
8840 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
8841 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
8842 db->flags |= SQLITE_CorruptRdOnly;
8844 rc = SQLITE_ERROR;
8845 if( resetSchemaOnFault>0 ){
8846 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
8849 /* This is the only way out of this procedure. We have to
8850 ** release the mutexes on btrees that were acquired at the
8851 ** top. */
8852 vdbe_return:
8853 #if defined(VDBE_PROFILE)
8854 if( pnCycle ){
8855 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
8856 pnCycle = 0;
8858 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
8859 if( pnCycle ){
8860 *pnCycle += sqlite3Hwtime();
8861 pnCycle = 0;
8863 #endif
8865 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8866 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
8867 nProgressLimit += db->nProgressOps;
8868 if( db->xProgress(db->pProgressArg) ){
8869 nProgressLimit = LARGEST_UINT64;
8870 rc = SQLITE_INTERRUPT;
8871 goto abort_due_to_error;
8874 #endif
8875 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
8876 if( DbMaskNonZero(p->lockMask) ){
8877 sqlite3VdbeLeave(p);
8879 assert( rc!=SQLITE_OK || nExtraDelete==0
8880 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
8882 return rc;
8884 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
8885 ** is encountered.
8887 too_big:
8888 sqlite3VdbeError(p, "string or blob too big");
8889 rc = SQLITE_TOOBIG;
8890 goto abort_due_to_error;
8892 /* Jump to here if a malloc() fails.
8894 no_mem:
8895 sqlite3OomFault(db);
8896 sqlite3VdbeError(p, "out of memory");
8897 rc = SQLITE_NOMEM_BKPT;
8898 goto abort_due_to_error;
8900 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
8901 ** flag.
8903 abort_due_to_interrupt:
8904 assert( AtomicLoad(&db->u1.isInterrupted) );
8905 rc = SQLITE_INTERRUPT;
8906 goto abort_due_to_error;