Merge trunk into jni-post-3.44 branch.
[sqlite.git] / src / vdbe.c
blob221e8847dbbb02b8795489f3d4d73c8f5380fc80
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]);
559 if( f & MEM_Term ){
560 sqlite3_str_appendf(pStr, "(0-term)");
564 #endif
566 #ifdef SQLITE_DEBUG
568 ** Print the value of a register for tracing purposes:
570 static void memTracePrint(Mem *p){
571 if( p->flags & MEM_Undefined ){
572 printf(" undefined");
573 }else if( p->flags & MEM_Null ){
574 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
575 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
576 printf(" si:%lld", p->u.i);
577 }else if( (p->flags & (MEM_IntReal))!=0 ){
578 printf(" ir:%lld", p->u.i);
579 }else if( p->flags & MEM_Int ){
580 printf(" i:%lld", p->u.i);
581 #ifndef SQLITE_OMIT_FLOATING_POINT
582 }else if( p->flags & MEM_Real ){
583 printf(" r:%.17g", p->u.r);
584 #endif
585 }else if( sqlite3VdbeMemIsRowSet(p) ){
586 printf(" (rowset)");
587 }else{
588 StrAccum acc;
589 char zBuf[1000];
590 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
591 sqlite3VdbeMemPrettyPrint(p, &acc);
592 printf(" %s", sqlite3StrAccumFinish(&acc));
594 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
596 static void registerTrace(int iReg, Mem *p){
597 printf("R[%d] = ", iReg);
598 memTracePrint(p);
599 if( p->pScopyFrom ){
600 printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
602 printf("\n");
603 sqlite3VdbeCheckMemInvariants(p);
605 /**/ void sqlite3PrintMem(Mem *pMem){
606 memTracePrint(pMem);
607 printf("\n");
608 fflush(stdout);
610 #endif
612 #ifdef SQLITE_DEBUG
614 ** Show the values of all registers in the virtual machine. Used for
615 ** interactive debugging.
617 void sqlite3VdbeRegisterDump(Vdbe *v){
618 int i;
619 for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
621 #endif /* SQLITE_DEBUG */
624 #ifdef SQLITE_DEBUG
625 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
626 #else
627 # define REGISTER_TRACE(R,M)
628 #endif
630 #ifndef NDEBUG
632 ** This function is only called from within an assert() expression. It
633 ** checks that the sqlite3.nTransaction variable is correctly set to
634 ** the number of non-transaction savepoints currently in the
635 ** linked list starting at sqlite3.pSavepoint.
637 ** Usage:
639 ** assert( checkSavepointCount(db) );
641 static int checkSavepointCount(sqlite3 *db){
642 int n = 0;
643 Savepoint *p;
644 for(p=db->pSavepoint; p; p=p->pNext) n++;
645 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
646 return 1;
648 #endif
651 ** Return the register of pOp->p2 after first preparing it to be
652 ** overwritten with an integer value.
654 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
655 sqlite3VdbeMemSetNull(pOut);
656 pOut->flags = MEM_Int;
657 return pOut;
659 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
660 Mem *pOut;
661 assert( pOp->p2>0 );
662 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
663 pOut = &p->aMem[pOp->p2];
664 memAboutToChange(p, pOut);
665 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
666 return out2PrereleaseWithClear(pOut);
667 }else{
668 pOut->flags = MEM_Int;
669 return pOut;
674 ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
675 ** with pOp->p3. Return the hash.
677 static u64 filterHash(const Mem *aMem, const Op *pOp){
678 int i, mx;
679 u64 h = 0;
681 assert( pOp->p4type==P4_INT32 );
682 for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
683 const Mem *p = &aMem[i];
684 if( p->flags & (MEM_Int|MEM_IntReal) ){
685 h += p->u.i;
686 }else if( p->flags & MEM_Real ){
687 h += sqlite3VdbeIntValue(p);
688 }else if( p->flags & (MEM_Str|MEM_Blob) ){
689 /* All strings have the same hash and all blobs have the same hash,
690 ** though, at least, those hashes are different from each other and
691 ** from NULL. */
692 h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
695 return h;
700 ** For OP_Column, factor out the case where content is loaded from
701 ** overflow pages, so that the code to implement this case is separate
702 ** the common case where all content fits on the page. Factoring out
703 ** the code reduces register pressure and helps the common case
704 ** to run faster.
706 static SQLITE_NOINLINE int vdbeColumnFromOverflow(
707 VdbeCursor *pC, /* The BTree cursor from which we are reading */
708 int iCol, /* The column to read */
709 int t, /* The serial-type code for the column value */
710 i64 iOffset, /* Offset to the start of the content value */
711 u32 cacheStatus, /* Current Vdbe.cacheCtr value */
712 u32 colCacheCtr, /* Current value of the column cache counter */
713 Mem *pDest /* Store the value into this register. */
715 int rc;
716 sqlite3 *db = pDest->db;
717 int encoding = pDest->enc;
718 int len = sqlite3VdbeSerialTypeLen(t);
719 assert( pC->eCurType==CURTYPE_BTREE );
720 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) return SQLITE_TOOBIG;
721 if( len > 4000 && pC->pKeyInfo==0 ){
722 /* Cache large column values that are on overflow pages using
723 ** an RCStr (reference counted string) so that if they are reloaded,
724 ** that do not have to be copied a second time. The overhead of
725 ** creating and managing the cache is such that this is only
726 ** profitable for larger TEXT and BLOB values.
728 ** Only do this on table-btrees so that writes to index-btrees do not
729 ** need to clear the cache. This buys performance in the common case
730 ** in exchange for generality.
732 VdbeTxtBlbCache *pCache;
733 char *pBuf;
734 if( pC->colCache==0 ){
735 pC->pCache = sqlite3DbMallocZero(db, sizeof(VdbeTxtBlbCache) );
736 if( pC->pCache==0 ) return SQLITE_NOMEM;
737 pC->colCache = 1;
739 pCache = pC->pCache;
740 if( pCache->pCValue==0
741 || pCache->iCol!=iCol
742 || pCache->cacheStatus!=cacheStatus
743 || pCache->colCacheCtr!=colCacheCtr
744 || pCache->iOffset!=sqlite3BtreeOffset(pC->uc.pCursor)
746 if( pCache->pCValue ) sqlite3RCStrUnref(pCache->pCValue);
747 pBuf = pCache->pCValue = sqlite3RCStrNew( len+3 );
748 if( pBuf==0 ) return SQLITE_NOMEM;
749 rc = sqlite3BtreePayload(pC->uc.pCursor, iOffset, len, pBuf);
750 if( rc ) return rc;
751 pBuf[len] = 0;
752 pBuf[len+1] = 0;
753 pBuf[len+2] = 0;
754 pCache->iCol = iCol;
755 pCache->cacheStatus = cacheStatus;
756 pCache->colCacheCtr = colCacheCtr;
757 pCache->iOffset = sqlite3BtreeOffset(pC->uc.pCursor);
758 }else{
759 pBuf = pCache->pCValue;
761 assert( t>=12 );
762 sqlite3RCStrRef(pBuf);
763 if( t&1 ){
764 rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, encoding,
765 sqlite3RCStrUnref);
766 pDest->flags |= MEM_Term;
767 }else{
768 rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, 0,
769 sqlite3RCStrUnref);
771 }else{
772 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, iOffset, len, pDest);
773 if( rc ) return rc;
774 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
775 if( (t&1)!=0 && encoding==SQLITE_UTF8 ){
776 pDest->z[len] = 0;
777 pDest->flags |= MEM_Term;
780 pDest->flags &= ~MEM_Ephem;
781 return rc;
786 ** Return the symbolic name for the data type of a pMem
788 static const char *vdbeMemTypeName(Mem *pMem){
789 static const char *azTypes[] = {
790 /* SQLITE_INTEGER */ "INT",
791 /* SQLITE_FLOAT */ "REAL",
792 /* SQLITE_TEXT */ "TEXT",
793 /* SQLITE_BLOB */ "BLOB",
794 /* SQLITE_NULL */ "NULL"
796 return azTypes[sqlite3_value_type(pMem)-1];
800 ** Execute as much of a VDBE program as we can.
801 ** This is the core of sqlite3_step().
803 int sqlite3VdbeExec(
804 Vdbe *p /* The VDBE */
806 Op *aOp = p->aOp; /* Copy of p->aOp */
807 Op *pOp = aOp; /* Current operation */
808 #ifdef SQLITE_DEBUG
809 Op *pOrigOp; /* Value of pOp at the top of the loop */
810 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
811 u8 iCompareIsInit = 0; /* iCompare is initialized */
812 #endif
813 int rc = SQLITE_OK; /* Value to return */
814 sqlite3 *db = p->db; /* The database */
815 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
816 u8 encoding = ENC(db); /* The database encoding */
817 int iCompare = 0; /* Result of last comparison */
818 u64 nVmStep = 0; /* Number of virtual machine steps */
819 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
820 u64 nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
821 #endif
822 Mem *aMem = p->aMem; /* Copy of p->aMem */
823 Mem *pIn1 = 0; /* 1st input operand */
824 Mem *pIn2 = 0; /* 2nd input operand */
825 Mem *pIn3 = 0; /* 3rd input operand */
826 Mem *pOut = 0; /* Output operand */
827 u32 colCacheCtr = 0; /* Column cache counter */
828 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
829 u64 *pnCycle = 0;
830 int bStmtScanStatus = IS_STMT_SCANSTATUS(db)!=0;
831 #endif
832 /*** INSERT STACK UNION HERE ***/
834 assert( p->eVdbeState==VDBE_RUN_STATE ); /* sqlite3_step() verifies this */
835 if( DbMaskNonZero(p->lockMask) ){
836 sqlite3VdbeEnter(p);
838 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
839 if( db->xProgress ){
840 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
841 assert( 0 < db->nProgressOps );
842 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
843 }else{
844 nProgressLimit = LARGEST_UINT64;
846 #endif
847 if( p->rc==SQLITE_NOMEM ){
848 /* This happens if a malloc() inside a call to sqlite3_column_text() or
849 ** sqlite3_column_text16() failed. */
850 goto no_mem;
852 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
853 testcase( p->rc!=SQLITE_OK );
854 p->rc = SQLITE_OK;
855 assert( p->bIsReader || p->readOnly!=0 );
856 p->iCurrentTime = 0;
857 assert( p->explain==0 );
858 db->busyHandler.nBusy = 0;
859 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
860 sqlite3VdbeIOTraceSql(p);
861 #ifdef SQLITE_DEBUG
862 sqlite3BeginBenignMalloc();
863 if( p->pc==0
864 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
866 int i;
867 int once = 1;
868 sqlite3VdbePrintSql(p);
869 if( p->db->flags & SQLITE_VdbeListing ){
870 printf("VDBE Program Listing:\n");
871 for(i=0; i<p->nOp; i++){
872 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
875 if( p->db->flags & SQLITE_VdbeEQP ){
876 for(i=0; i<p->nOp; i++){
877 if( aOp[i].opcode==OP_Explain ){
878 if( once ) printf("VDBE Query Plan:\n");
879 printf("%s\n", aOp[i].p4.z);
880 once = 0;
884 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
886 sqlite3EndBenignMalloc();
887 #endif
888 for(pOp=&aOp[p->pc]; 1; pOp++){
889 /* Errors are detected by individual opcodes, with an immediate
890 ** jumps to abort_due_to_error. */
891 assert( rc==SQLITE_OK );
893 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
894 nVmStep++;
896 #if defined(VDBE_PROFILE)
897 pOp->nExec++;
898 pnCycle = &pOp->nCycle;
899 if( sqlite3NProfileCnt==0 ) *pnCycle -= sqlite3Hwtime();
900 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
901 if( bStmtScanStatus ){
902 pOp->nExec++;
903 pnCycle = &pOp->nCycle;
904 *pnCycle -= sqlite3Hwtime();
906 #endif
908 /* Only allow tracing if SQLITE_DEBUG is defined.
910 #ifdef SQLITE_DEBUG
911 if( db->flags & SQLITE_VdbeTrace ){
912 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
913 test_trace_breakpoint((int)(pOp - aOp),pOp,p);
915 #endif
918 /* Check to see if we need to simulate an interrupt. This only happens
919 ** if we have a special test build.
921 #ifdef SQLITE_TEST
922 if( sqlite3_interrupt_count>0 ){
923 sqlite3_interrupt_count--;
924 if( sqlite3_interrupt_count==0 ){
925 sqlite3_interrupt(db);
928 #endif
930 /* Sanity checking on other operands */
931 #ifdef SQLITE_DEBUG
933 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
934 if( (opProperty & OPFLG_IN1)!=0 ){
935 assert( pOp->p1>0 );
936 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
937 assert( memIsValid(&aMem[pOp->p1]) );
938 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
939 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
941 if( (opProperty & OPFLG_IN2)!=0 ){
942 assert( pOp->p2>0 );
943 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
944 assert( memIsValid(&aMem[pOp->p2]) );
945 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
946 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
948 if( (opProperty & OPFLG_IN3)!=0 ){
949 assert( pOp->p3>0 );
950 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
951 assert( memIsValid(&aMem[pOp->p3]) );
952 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
953 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
955 if( (opProperty & OPFLG_OUT2)!=0 ){
956 assert( pOp->p2>0 );
957 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
958 memAboutToChange(p, &aMem[pOp->p2]);
960 if( (opProperty & OPFLG_OUT3)!=0 ){
961 assert( pOp->p3>0 );
962 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
963 memAboutToChange(p, &aMem[pOp->p3]);
966 #endif
967 #ifdef SQLITE_DEBUG
968 pOrigOp = pOp;
969 #endif
971 switch( pOp->opcode ){
973 /*****************************************************************************
974 ** What follows is a massive switch statement where each case implements a
975 ** separate instruction in the virtual machine. If we follow the usual
976 ** indentation conventions, each case should be indented by 6 spaces. But
977 ** that is a lot of wasted space on the left margin. So the code within
978 ** the switch statement will break with convention and be flush-left. Another
979 ** big comment (similar to this one) will mark the point in the code where
980 ** we transition back to normal indentation.
982 ** The formatting of each case is important. The makefile for SQLite
983 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
984 ** file looking for lines that begin with "case OP_". The opcodes.h files
985 ** will be filled with #defines that give unique integer values to each
986 ** opcode and the opcodes.c file is filled with an array of strings where
987 ** each string is the symbolic name for the corresponding opcode. If the
988 ** case statement is followed by a comment of the form "/# same as ... #/"
989 ** that comment is used to determine the particular value of the opcode.
991 ** Other keywords in the comment that follows each case are used to
992 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
993 ** Keywords include: in1, in2, in3, out2, out3. See
994 ** the mkopcodeh.awk script for additional information.
996 ** Documentation about VDBE opcodes is generated by scanning this file
997 ** for lines of that contain "Opcode:". That line and all subsequent
998 ** comment lines are used in the generation of the opcode.html documentation
999 ** file.
1001 ** SUMMARY:
1003 ** Formatting is important to scripts that scan this file.
1004 ** Do not deviate from the formatting style currently in use.
1006 *****************************************************************************/
1008 /* Opcode: Goto * P2 * * *
1010 ** An unconditional jump to address P2.
1011 ** The next instruction executed will be
1012 ** the one at index P2 from the beginning of
1013 ** the program.
1015 ** The P1 parameter is not actually used by this opcode. However, it
1016 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
1017 ** that this Goto is the bottom of a loop and that the lines from P2 down
1018 ** to the current line should be indented for EXPLAIN output.
1020 case OP_Goto: { /* jump */
1022 #ifdef SQLITE_DEBUG
1023 /* In debugging mode, when the p5 flags is set on an OP_Goto, that
1024 ** means we should really jump back to the preceding OP_ReleaseReg
1025 ** instruction. */
1026 if( pOp->p5 ){
1027 assert( pOp->p2 < (int)(pOp - aOp) );
1028 assert( pOp->p2 > 1 );
1029 pOp = &aOp[pOp->p2 - 2];
1030 assert( pOp[1].opcode==OP_ReleaseReg );
1031 goto check_for_interrupt;
1033 #endif
1035 jump_to_p2_and_check_for_interrupt:
1036 pOp = &aOp[pOp->p2 - 1];
1038 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
1039 ** OP_VNext, or OP_SorterNext) all jump here upon
1040 ** completion. Check to see if sqlite3_interrupt() has been called
1041 ** or if the progress callback needs to be invoked.
1043 ** This code uses unstructured "goto" statements and does not look clean.
1044 ** But that is not due to sloppy coding habits. The code is written this
1045 ** way for performance, to avoid having to run the interrupt and progress
1046 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
1047 ** faster according to "valgrind --tool=cachegrind" */
1048 check_for_interrupt:
1049 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
1050 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1051 /* Call the progress callback if it is configured and the required number
1052 ** of VDBE ops have been executed (either since this invocation of
1053 ** sqlite3VdbeExec() or since last time the progress callback was called).
1054 ** If the progress callback returns non-zero, exit the virtual machine with
1055 ** a return code SQLITE_ABORT.
1057 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
1058 assert( db->nProgressOps!=0 );
1059 nProgressLimit += db->nProgressOps;
1060 if( db->xProgress(db->pProgressArg) ){
1061 nProgressLimit = LARGEST_UINT64;
1062 rc = SQLITE_INTERRUPT;
1063 goto abort_due_to_error;
1066 #endif
1068 break;
1071 /* Opcode: Gosub P1 P2 * * *
1073 ** Write the current address onto register P1
1074 ** and then jump to address P2.
1076 case OP_Gosub: { /* jump */
1077 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1078 pIn1 = &aMem[pOp->p1];
1079 assert( VdbeMemDynamic(pIn1)==0 );
1080 memAboutToChange(p, pIn1);
1081 pIn1->flags = MEM_Int;
1082 pIn1->u.i = (int)(pOp-aOp);
1083 REGISTER_TRACE(pOp->p1, pIn1);
1084 goto jump_to_p2_and_check_for_interrupt;
1087 /* Opcode: Return P1 P2 P3 * *
1089 ** Jump to the address stored in register P1. If P1 is a return address
1090 ** register, then this accomplishes a return from a subroutine.
1092 ** If P3 is 1, then the jump is only taken if register P1 holds an integer
1093 ** values, otherwise execution falls through to the next opcode, and the
1094 ** OP_Return becomes a no-op. If P3 is 0, then register P1 must hold an
1095 ** integer or else an assert() is raised. P3 should be set to 1 when
1096 ** this opcode is used in combination with OP_BeginSubrtn, and set to 0
1097 ** otherwise.
1099 ** The value in register P1 is unchanged by this opcode.
1101 ** P2 is not used by the byte-code engine. However, if P2 is positive
1102 ** and also less than the current address, then the "EXPLAIN" output
1103 ** formatter in the CLI will indent all opcodes from the P2 opcode up
1104 ** to be not including the current Return. P2 should be the first opcode
1105 ** in the subroutine from which this opcode is returning. Thus the P2
1106 ** value is a byte-code indentation hint. See tag-20220407a in
1107 ** wherecode.c and shell.c.
1109 case OP_Return: { /* in1 */
1110 pIn1 = &aMem[pOp->p1];
1111 if( pIn1->flags & MEM_Int ){
1112 if( pOp->p3 ){ VdbeBranchTaken(1, 2); }
1113 pOp = &aOp[pIn1->u.i];
1114 }else if( ALWAYS(pOp->p3) ){
1115 VdbeBranchTaken(0, 2);
1117 break;
1120 /* Opcode: InitCoroutine P1 P2 P3 * *
1122 ** Set up register P1 so that it will Yield to the coroutine
1123 ** located at address P3.
1125 ** If P2!=0 then the coroutine implementation immediately follows
1126 ** this opcode. So jump over the coroutine implementation to
1127 ** address P2.
1129 ** See also: EndCoroutine
1131 case OP_InitCoroutine: { /* jump */
1132 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1133 assert( pOp->p2>=0 && pOp->p2<p->nOp );
1134 assert( pOp->p3>=0 && pOp->p3<p->nOp );
1135 pOut = &aMem[pOp->p1];
1136 assert( !VdbeMemDynamic(pOut) );
1137 pOut->u.i = pOp->p3 - 1;
1138 pOut->flags = MEM_Int;
1139 if( pOp->p2==0 ) break;
1141 /* Most jump operations do a goto to this spot in order to update
1142 ** the pOp pointer. */
1143 jump_to_p2:
1144 assert( pOp->p2>0 ); /* There are never any jumps to instruction 0 */
1145 assert( pOp->p2<p->nOp ); /* Jumps must be in range */
1146 pOp = &aOp[pOp->p2 - 1];
1147 break;
1150 /* Opcode: EndCoroutine P1 * * * *
1152 ** The instruction at the address in register P1 is a Yield.
1153 ** Jump to the P2 parameter of that Yield.
1154 ** After the jump, register P1 becomes undefined.
1156 ** See also: InitCoroutine
1158 case OP_EndCoroutine: { /* in1 */
1159 VdbeOp *pCaller;
1160 pIn1 = &aMem[pOp->p1];
1161 assert( pIn1->flags==MEM_Int );
1162 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
1163 pCaller = &aOp[pIn1->u.i];
1164 assert( pCaller->opcode==OP_Yield );
1165 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
1166 pOp = &aOp[pCaller->p2 - 1];
1167 pIn1->flags = MEM_Undefined;
1168 break;
1171 /* Opcode: Yield P1 P2 * * *
1173 ** Swap the program counter with the value in register P1. This
1174 ** has the effect of yielding to a coroutine.
1176 ** If the coroutine that is launched by this instruction ends with
1177 ** Yield or Return then continue to the next instruction. But if
1178 ** the coroutine launched by this instruction ends with
1179 ** EndCoroutine, then jump to P2 rather than continuing with the
1180 ** next instruction.
1182 ** See also: InitCoroutine
1184 case OP_Yield: { /* in1, jump */
1185 int pcDest;
1186 pIn1 = &aMem[pOp->p1];
1187 assert( VdbeMemDynamic(pIn1)==0 );
1188 pIn1->flags = MEM_Int;
1189 pcDest = (int)pIn1->u.i;
1190 pIn1->u.i = (int)(pOp - aOp);
1191 REGISTER_TRACE(pOp->p1, pIn1);
1192 pOp = &aOp[pcDest];
1193 break;
1196 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
1197 ** Synopsis: if r[P3]=null halt
1199 ** Check the value in register P3. If it is NULL then Halt using
1200 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
1201 ** value in register P3 is not NULL, then this routine is a no-op.
1202 ** The P5 parameter should be 1.
1204 case OP_HaltIfNull: { /* in3 */
1205 pIn3 = &aMem[pOp->p3];
1206 #ifdef SQLITE_DEBUG
1207 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1208 #endif
1209 if( (pIn3->flags & MEM_Null)==0 ) break;
1210 /* Fall through into OP_Halt */
1211 /* no break */ deliberate_fall_through
1214 /* Opcode: Halt P1 P2 * P4 P5
1216 ** Exit immediately. All open cursors, etc are closed
1217 ** automatically.
1219 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
1220 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
1221 ** For errors, it can be some other value. If P1!=0 then P2 will determine
1222 ** whether or not to rollback the current transaction. Do not rollback
1223 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
1224 ** then back out all changes that have occurred during this execution of the
1225 ** VDBE, but do not rollback the transaction.
1227 ** If P4 is not null then it is an error message string.
1229 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
1231 ** 0: (no change)
1232 ** 1: NOT NULL constraint failed: P4
1233 ** 2: UNIQUE constraint failed: P4
1234 ** 3: CHECK constraint failed: P4
1235 ** 4: FOREIGN KEY constraint failed: P4
1237 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
1238 ** omitted.
1240 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
1241 ** every program. So a jump past the last instruction of the program
1242 ** is the same as executing Halt.
1244 case OP_Halt: {
1245 VdbeFrame *pFrame;
1246 int pcx;
1248 #ifdef SQLITE_DEBUG
1249 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1250 #endif
1252 /* A deliberately coded "OP_Halt SQLITE_INTERNAL * * * *" opcode indicates
1253 ** something is wrong with the code generator. Raise an assertion in order
1254 ** to bring this to the attention of fuzzers and other testing tools. */
1255 assert( pOp->p1!=SQLITE_INTERNAL );
1257 if( p->pFrame && pOp->p1==SQLITE_OK ){
1258 /* Halt the sub-program. Return control to the parent frame. */
1259 pFrame = p->pFrame;
1260 p->pFrame = pFrame->pParent;
1261 p->nFrame--;
1262 sqlite3VdbeSetChanges(db, p->nChange);
1263 pcx = sqlite3VdbeFrameRestore(pFrame);
1264 if( pOp->p2==OE_Ignore ){
1265 /* Instruction pcx is the OP_Program that invoked the sub-program
1266 ** currently being halted. If the p2 instruction of this OP_Halt
1267 ** instruction is set to OE_Ignore, then the sub-program is throwing
1268 ** an IGNORE exception. In this case jump to the address specified
1269 ** as the p2 of the calling OP_Program. */
1270 pcx = p->aOp[pcx].p2-1;
1272 aOp = p->aOp;
1273 aMem = p->aMem;
1274 pOp = &aOp[pcx];
1275 break;
1277 p->rc = pOp->p1;
1278 p->errorAction = (u8)pOp->p2;
1279 assert( pOp->p5<=4 );
1280 if( p->rc ){
1281 if( pOp->p5 ){
1282 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
1283 "FOREIGN KEY" };
1284 testcase( pOp->p5==1 );
1285 testcase( pOp->p5==2 );
1286 testcase( pOp->p5==3 );
1287 testcase( pOp->p5==4 );
1288 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
1289 if( pOp->p4.z ){
1290 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
1292 }else{
1293 sqlite3VdbeError(p, "%s", pOp->p4.z);
1295 pcx = (int)(pOp - aOp);
1296 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
1298 rc = sqlite3VdbeHalt(p);
1299 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1300 if( rc==SQLITE_BUSY ){
1301 p->rc = SQLITE_BUSY;
1302 }else{
1303 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1304 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1305 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1307 goto vdbe_return;
1310 /* Opcode: Integer P1 P2 * * *
1311 ** Synopsis: r[P2]=P1
1313 ** The 32-bit integer value P1 is written into register P2.
1315 case OP_Integer: { /* out2 */
1316 pOut = out2Prerelease(p, pOp);
1317 pOut->u.i = pOp->p1;
1318 break;
1321 /* Opcode: Int64 * P2 * P4 *
1322 ** Synopsis: r[P2]=P4
1324 ** P4 is a pointer to a 64-bit integer value.
1325 ** Write that value into register P2.
1327 case OP_Int64: { /* out2 */
1328 pOut = out2Prerelease(p, pOp);
1329 assert( pOp->p4.pI64!=0 );
1330 pOut->u.i = *pOp->p4.pI64;
1331 break;
1334 #ifndef SQLITE_OMIT_FLOATING_POINT
1335 /* Opcode: Real * P2 * P4 *
1336 ** Synopsis: r[P2]=P4
1338 ** P4 is a pointer to a 64-bit floating point value.
1339 ** Write that value into register P2.
1341 case OP_Real: { /* same as TK_FLOAT, out2 */
1342 pOut = out2Prerelease(p, pOp);
1343 pOut->flags = MEM_Real;
1344 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1345 pOut->u.r = *pOp->p4.pReal;
1346 break;
1348 #endif
1350 /* Opcode: String8 * P2 * P4 *
1351 ** Synopsis: r[P2]='P4'
1353 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1354 ** into a String opcode before it is executed for the first time. During
1355 ** this transformation, the length of string P4 is computed and stored
1356 ** as the P1 parameter.
1358 case OP_String8: { /* same as TK_STRING, out2 */
1359 assert( pOp->p4.z!=0 );
1360 pOut = out2Prerelease(p, pOp);
1361 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1363 #ifndef SQLITE_OMIT_UTF16
1364 if( encoding!=SQLITE_UTF8 ){
1365 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1366 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1367 if( rc ) goto too_big;
1368 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1369 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1370 assert( VdbeMemDynamic(pOut)==0 );
1371 pOut->szMalloc = 0;
1372 pOut->flags |= MEM_Static;
1373 if( pOp->p4type==P4_DYNAMIC ){
1374 sqlite3DbFree(db, pOp->p4.z);
1376 pOp->p4type = P4_DYNAMIC;
1377 pOp->p4.z = pOut->z;
1378 pOp->p1 = pOut->n;
1380 #endif
1381 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1382 goto too_big;
1384 pOp->opcode = OP_String;
1385 assert( rc==SQLITE_OK );
1386 /* Fall through to the next case, OP_String */
1387 /* no break */ deliberate_fall_through
1390 /* Opcode: String P1 P2 P3 P4 P5
1391 ** Synopsis: r[P2]='P4' (len=P1)
1393 ** The string value P4 of length P1 (bytes) is stored in register P2.
1395 ** If P3 is not zero and the content of register P3 is equal to P5, then
1396 ** the datatype of the register P2 is converted to BLOB. The content is
1397 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1398 ** of a string, as if it had been CAST. In other words:
1400 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1402 case OP_String: { /* out2 */
1403 assert( pOp->p4.z!=0 );
1404 pOut = out2Prerelease(p, pOp);
1405 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1406 pOut->z = pOp->p4.z;
1407 pOut->n = pOp->p1;
1408 pOut->enc = encoding;
1409 UPDATE_MAX_BLOBSIZE(pOut);
1410 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1411 if( pOp->p3>0 ){
1412 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1413 pIn3 = &aMem[pOp->p3];
1414 assert( pIn3->flags & MEM_Int );
1415 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1417 #endif
1418 break;
1421 /* Opcode: BeginSubrtn * P2 * * *
1422 ** Synopsis: r[P2]=NULL
1424 ** Mark the beginning of a subroutine that can be entered in-line
1425 ** or that can be called using OP_Gosub. The subroutine should
1426 ** be terminated by an OP_Return instruction that has a P1 operand that
1427 ** is the same as the P2 operand to this opcode and that has P3 set to 1.
1428 ** If the subroutine is entered in-line, then the OP_Return will simply
1429 ** fall through. But if the subroutine is entered using OP_Gosub, then
1430 ** the OP_Return will jump back to the first instruction after the OP_Gosub.
1432 ** This routine works by loading a NULL into the P2 register. When the
1433 ** return address register contains a NULL, the OP_Return instruction is
1434 ** a no-op that simply falls through to the next instruction (assuming that
1435 ** the OP_Return opcode has a P3 value of 1). Thus if the subroutine is
1436 ** entered in-line, then the OP_Return will cause in-line execution to
1437 ** continue. But if the subroutine is entered via OP_Gosub, then the
1438 ** OP_Return will cause a return to the address following the OP_Gosub.
1440 ** This opcode is identical to OP_Null. It has a different name
1441 ** only to make the byte code easier to read and verify.
1443 /* Opcode: Null P1 P2 P3 * *
1444 ** Synopsis: r[P2..P3]=NULL
1446 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1447 ** NULL into register P3 and every register in between P2 and P3. If P3
1448 ** is less than P2 (typically P3 is zero) then only register P2 is
1449 ** set to NULL.
1451 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1452 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1453 ** OP_Ne or OP_Eq.
1455 case OP_BeginSubrtn:
1456 case OP_Null: { /* out2 */
1457 int cnt;
1458 u16 nullFlag;
1459 pOut = out2Prerelease(p, pOp);
1460 cnt = pOp->p3-pOp->p2;
1461 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1462 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1463 pOut->n = 0;
1464 #ifdef SQLITE_DEBUG
1465 pOut->uTemp = 0;
1466 #endif
1467 while( cnt>0 ){
1468 pOut++;
1469 memAboutToChange(p, pOut);
1470 sqlite3VdbeMemSetNull(pOut);
1471 pOut->flags = nullFlag;
1472 pOut->n = 0;
1473 cnt--;
1475 break;
1478 /* Opcode: SoftNull P1 * * * *
1479 ** Synopsis: r[P1]=NULL
1481 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1482 ** instruction, but do not free any string or blob memory associated with
1483 ** the register, so that if the value was a string or blob that was
1484 ** previously copied using OP_SCopy, the copies will continue to be valid.
1486 case OP_SoftNull: {
1487 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1488 pOut = &aMem[pOp->p1];
1489 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1490 break;
1493 /* Opcode: Blob P1 P2 * P4 *
1494 ** Synopsis: r[P2]=P4 (len=P1)
1496 ** P4 points to a blob of data P1 bytes long. Store this
1497 ** blob in register P2. If P4 is a NULL pointer, then construct
1498 ** a zero-filled blob that is P1 bytes long in P2.
1500 case OP_Blob: { /* out2 */
1501 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1502 pOut = out2Prerelease(p, pOp);
1503 if( pOp->p4.z==0 ){
1504 sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
1505 if( sqlite3VdbeMemExpandBlob(pOut) ) goto no_mem;
1506 }else{
1507 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1509 pOut->enc = encoding;
1510 UPDATE_MAX_BLOBSIZE(pOut);
1511 break;
1514 /* Opcode: Variable P1 P2 * P4 *
1515 ** Synopsis: r[P2]=parameter(P1,P4)
1517 ** Transfer the values of bound parameter P1 into register P2
1519 ** If the parameter is named, then its name appears in P4.
1520 ** The P4 value is used by sqlite3_bind_parameter_name().
1522 case OP_Variable: { /* out2 */
1523 Mem *pVar; /* Value being transferred */
1525 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1526 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1527 pVar = &p->aVar[pOp->p1 - 1];
1528 if( sqlite3VdbeMemTooBig(pVar) ){
1529 goto too_big;
1531 pOut = &aMem[pOp->p2];
1532 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
1533 memcpy(pOut, pVar, MEMCELLSIZE);
1534 pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
1535 pOut->flags |= MEM_Static|MEM_FromBind;
1536 UPDATE_MAX_BLOBSIZE(pOut);
1537 break;
1540 /* Opcode: Move P1 P2 P3 * *
1541 ** Synopsis: r[P2@P3]=r[P1@P3]
1543 ** Move the P3 values in register P1..P1+P3-1 over into
1544 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1545 ** left holding a NULL. It is an error for register ranges
1546 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1547 ** for P3 to be less than 1.
1549 case OP_Move: {
1550 int n; /* Number of registers left to copy */
1551 int p1; /* Register to copy from */
1552 int p2; /* Register to copy to */
1554 n = pOp->p3;
1555 p1 = pOp->p1;
1556 p2 = pOp->p2;
1557 assert( n>0 && p1>0 && p2>0 );
1558 assert( p1+n<=p2 || p2+n<=p1 );
1560 pIn1 = &aMem[p1];
1561 pOut = &aMem[p2];
1563 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1564 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1565 assert( memIsValid(pIn1) );
1566 memAboutToChange(p, pOut);
1567 sqlite3VdbeMemMove(pOut, pIn1);
1568 #ifdef SQLITE_DEBUG
1569 pIn1->pScopyFrom = 0;
1570 { int i;
1571 for(i=1; i<p->nMem; i++){
1572 if( aMem[i].pScopyFrom==pIn1 ){
1573 aMem[i].pScopyFrom = pOut;
1577 #endif
1578 Deephemeralize(pOut);
1579 REGISTER_TRACE(p2++, pOut);
1580 pIn1++;
1581 pOut++;
1582 }while( --n );
1583 break;
1586 /* Opcode: Copy P1 P2 P3 * P5
1587 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1589 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1591 ** If the 0x0002 bit of P5 is set then also clear the MEM_Subtype flag in the
1592 ** destination. The 0x0001 bit of P5 indicates that this Copy opcode cannot
1593 ** be merged. The 0x0001 bit is used by the query planner and does not
1594 ** come into play during query execution.
1596 ** This instruction makes a deep copy of the value. A duplicate
1597 ** is made of any string or blob constant. See also OP_SCopy.
1599 case OP_Copy: {
1600 int n;
1602 n = pOp->p3;
1603 pIn1 = &aMem[pOp->p1];
1604 pOut = &aMem[pOp->p2];
1605 assert( pOut!=pIn1 );
1606 while( 1 ){
1607 memAboutToChange(p, pOut);
1608 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1609 Deephemeralize(pOut);
1610 if( (pOut->flags & MEM_Subtype)!=0 && (pOp->p5 & 0x0002)!=0 ){
1611 pOut->flags &= ~MEM_Subtype;
1613 #ifdef SQLITE_DEBUG
1614 pOut->pScopyFrom = 0;
1615 #endif
1616 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1617 if( (n--)==0 ) break;
1618 pOut++;
1619 pIn1++;
1621 break;
1624 /* Opcode: SCopy P1 P2 * * *
1625 ** Synopsis: r[P2]=r[P1]
1627 ** Make a shallow copy of register P1 into register P2.
1629 ** This instruction makes a shallow copy of the value. If the value
1630 ** is a string or blob, then the copy is only a pointer to the
1631 ** original and hence if the original changes so will the copy.
1632 ** Worse, if the original is deallocated, the copy becomes invalid.
1633 ** Thus the program must guarantee that the original will not change
1634 ** during the lifetime of the copy. Use OP_Copy to make a complete
1635 ** copy.
1637 case OP_SCopy: { /* out2 */
1638 pIn1 = &aMem[pOp->p1];
1639 pOut = &aMem[pOp->p2];
1640 assert( pOut!=pIn1 );
1641 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1642 #ifdef SQLITE_DEBUG
1643 pOut->pScopyFrom = pIn1;
1644 pOut->mScopyFlags = pIn1->flags;
1645 #endif
1646 break;
1649 /* Opcode: IntCopy P1 P2 * * *
1650 ** Synopsis: r[P2]=r[P1]
1652 ** Transfer the integer value held in register P1 into register P2.
1654 ** This is an optimized version of SCopy that works only for integer
1655 ** values.
1657 case OP_IntCopy: { /* out2 */
1658 pIn1 = &aMem[pOp->p1];
1659 assert( (pIn1->flags & MEM_Int)!=0 );
1660 pOut = &aMem[pOp->p2];
1661 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1662 break;
1665 /* Opcode: FkCheck * * * * *
1667 ** Halt with an SQLITE_CONSTRAINT error if there are any unresolved
1668 ** foreign key constraint violations. If there are no foreign key
1669 ** constraint violations, this is a no-op.
1671 ** FK constraint violations are also checked when the prepared statement
1672 ** exits. This opcode is used to raise foreign key constraint errors prior
1673 ** to returning results such as a row change count or the result of a
1674 ** RETURNING clause.
1676 case OP_FkCheck: {
1677 if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){
1678 goto abort_due_to_error;
1680 break;
1683 /* Opcode: ResultRow P1 P2 * * *
1684 ** Synopsis: output=r[P1@P2]
1686 ** The registers P1 through P1+P2-1 contain a single row of
1687 ** results. This opcode causes the sqlite3_step() call to terminate
1688 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1689 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1690 ** the result row.
1692 case OP_ResultRow: {
1693 assert( p->nResColumn==pOp->p2 );
1694 assert( pOp->p1>0 || CORRUPT_DB );
1695 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1697 p->cacheCtr = (p->cacheCtr + 2)|1;
1698 p->pResultRow = &aMem[pOp->p1];
1699 #ifdef SQLITE_DEBUG
1701 Mem *pMem = p->pResultRow;
1702 int i;
1703 for(i=0; i<pOp->p2; i++){
1704 assert( memIsValid(&pMem[i]) );
1705 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1706 /* The registers in the result will not be used again when the
1707 ** prepared statement restarts. This is because sqlite3_column()
1708 ** APIs might have caused type conversions of made other changes to
1709 ** the register values. Therefore, we can go ahead and break any
1710 ** OP_SCopy dependencies. */
1711 pMem[i].pScopyFrom = 0;
1714 #endif
1715 if( db->mallocFailed ) goto no_mem;
1716 if( db->mTrace & SQLITE_TRACE_ROW ){
1717 db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1719 p->pc = (int)(pOp - aOp) + 1;
1720 rc = SQLITE_ROW;
1721 goto vdbe_return;
1724 /* Opcode: Concat P1 P2 P3 * *
1725 ** Synopsis: r[P3]=r[P2]+r[P1]
1727 ** Add the text in register P1 onto the end of the text in
1728 ** register P2 and store the result in register P3.
1729 ** If either the P1 or P2 text are NULL then store NULL in P3.
1731 ** P3 = P2 || P1
1733 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1734 ** if P3 is the same register as P2, the implementation is able
1735 ** to avoid a memcpy().
1737 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1738 i64 nByte; /* Total size of the output string or blob */
1739 u16 flags1; /* Initial flags for P1 */
1740 u16 flags2; /* Initial flags for P2 */
1742 pIn1 = &aMem[pOp->p1];
1743 pIn2 = &aMem[pOp->p2];
1744 pOut = &aMem[pOp->p3];
1745 testcase( pOut==pIn2 );
1746 assert( pIn1!=pOut );
1747 flags1 = pIn1->flags;
1748 testcase( flags1 & MEM_Null );
1749 testcase( pIn2->flags & MEM_Null );
1750 if( (flags1 | pIn2->flags) & MEM_Null ){
1751 sqlite3VdbeMemSetNull(pOut);
1752 break;
1754 if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
1755 if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
1756 flags1 = pIn1->flags & ~MEM_Str;
1757 }else if( (flags1 & MEM_Zero)!=0 ){
1758 if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
1759 flags1 = pIn1->flags & ~MEM_Str;
1761 flags2 = pIn2->flags;
1762 if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
1763 if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
1764 flags2 = pIn2->flags & ~MEM_Str;
1765 }else if( (flags2 & MEM_Zero)!=0 ){
1766 if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
1767 flags2 = pIn2->flags & ~MEM_Str;
1769 nByte = pIn1->n + pIn2->n;
1770 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1771 goto too_big;
1773 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1774 goto no_mem;
1776 MemSetTypeFlag(pOut, MEM_Str);
1777 if( pOut!=pIn2 ){
1778 memcpy(pOut->z, pIn2->z, pIn2->n);
1779 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
1780 pIn2->flags = flags2;
1782 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1783 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1784 pIn1->flags = flags1;
1785 if( encoding>SQLITE_UTF8 ) nByte &= ~1;
1786 pOut->z[nByte]=0;
1787 pOut->z[nByte+1] = 0;
1788 pOut->flags |= MEM_Term;
1789 pOut->n = (int)nByte;
1790 pOut->enc = encoding;
1791 UPDATE_MAX_BLOBSIZE(pOut);
1792 break;
1795 /* Opcode: Add P1 P2 P3 * *
1796 ** Synopsis: r[P3]=r[P1]+r[P2]
1798 ** Add the value in register P1 to the value in register P2
1799 ** and store the result in register P3.
1800 ** If either input is NULL, the result is NULL.
1802 /* Opcode: Multiply P1 P2 P3 * *
1803 ** Synopsis: r[P3]=r[P1]*r[P2]
1806 ** Multiply the value in register P1 by the value in register P2
1807 ** and store the result in register P3.
1808 ** If either input is NULL, the result is NULL.
1810 /* Opcode: Subtract P1 P2 P3 * *
1811 ** Synopsis: r[P3]=r[P2]-r[P1]
1813 ** Subtract the value in register P1 from the value in register P2
1814 ** and store the result in register P3.
1815 ** If either input is NULL, the result is NULL.
1817 /* Opcode: Divide P1 P2 P3 * *
1818 ** Synopsis: r[P3]=r[P2]/r[P1]
1820 ** Divide the value in register P1 by the value in register P2
1821 ** and store the result in register P3 (P3=P2/P1). If the value in
1822 ** register P1 is zero, then the result is NULL. If either input is
1823 ** NULL, the result is NULL.
1825 /* Opcode: Remainder P1 P2 P3 * *
1826 ** Synopsis: r[P3]=r[P2]%r[P1]
1828 ** Compute the remainder after integer register P2 is divided by
1829 ** register P1 and store the result in register P3.
1830 ** If the value in register P1 is zero the result is NULL.
1831 ** If either operand is NULL, the result is NULL.
1833 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1834 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1835 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1836 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1837 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1838 u16 type1; /* Numeric type of left operand */
1839 u16 type2; /* Numeric type of right operand */
1840 i64 iA; /* Integer value of left operand */
1841 i64 iB; /* Integer value of right operand */
1842 double rA; /* Real value of left operand */
1843 double rB; /* Real value of right operand */
1845 pIn1 = &aMem[pOp->p1];
1846 type1 = pIn1->flags;
1847 pIn2 = &aMem[pOp->p2];
1848 type2 = pIn2->flags;
1849 pOut = &aMem[pOp->p3];
1850 if( (type1 & type2 & MEM_Int)!=0 ){
1851 int_math:
1852 iA = pIn1->u.i;
1853 iB = pIn2->u.i;
1854 switch( pOp->opcode ){
1855 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1856 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1857 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1858 case OP_Divide: {
1859 if( iA==0 ) goto arithmetic_result_is_null;
1860 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1861 iB /= iA;
1862 break;
1864 default: {
1865 if( iA==0 ) goto arithmetic_result_is_null;
1866 if( iA==-1 ) iA = 1;
1867 iB %= iA;
1868 break;
1871 pOut->u.i = iB;
1872 MemSetTypeFlag(pOut, MEM_Int);
1873 }else if( ((type1 | type2) & MEM_Null)!=0 ){
1874 goto arithmetic_result_is_null;
1875 }else{
1876 type1 = numericType(pIn1);
1877 type2 = numericType(pIn2);
1878 if( (type1 & type2 & MEM_Int)!=0 ) goto int_math;
1879 fp_math:
1880 rA = sqlite3VdbeRealValue(pIn1);
1881 rB = sqlite3VdbeRealValue(pIn2);
1882 switch( pOp->opcode ){
1883 case OP_Add: rB += rA; break;
1884 case OP_Subtract: rB -= rA; break;
1885 case OP_Multiply: rB *= rA; break;
1886 case OP_Divide: {
1887 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1888 if( rA==(double)0 ) goto arithmetic_result_is_null;
1889 rB /= rA;
1890 break;
1892 default: {
1893 iA = sqlite3VdbeIntValue(pIn1);
1894 iB = sqlite3VdbeIntValue(pIn2);
1895 if( iA==0 ) goto arithmetic_result_is_null;
1896 if( iA==-1 ) iA = 1;
1897 rB = (double)(iB % iA);
1898 break;
1901 #ifdef SQLITE_OMIT_FLOATING_POINT
1902 pOut->u.i = rB;
1903 MemSetTypeFlag(pOut, MEM_Int);
1904 #else
1905 if( sqlite3IsNaN(rB) ){
1906 goto arithmetic_result_is_null;
1908 pOut->u.r = rB;
1909 MemSetTypeFlag(pOut, MEM_Real);
1910 #endif
1912 break;
1914 arithmetic_result_is_null:
1915 sqlite3VdbeMemSetNull(pOut);
1916 break;
1919 /* Opcode: CollSeq P1 * * P4
1921 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1922 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1923 ** be returned. This is used by the built-in min(), max() and nullif()
1924 ** functions.
1926 ** If P1 is not zero, then it is a register that a subsequent min() or
1927 ** max() aggregate will set to 1 if the current row is not the minimum or
1928 ** maximum. The P1 register is initialized to 0 by this instruction.
1930 ** The interface used by the implementation of the aforementioned functions
1931 ** to retrieve the collation sequence set by this opcode is not available
1932 ** publicly. Only built-in functions have access to this feature.
1934 case OP_CollSeq: {
1935 assert( pOp->p4type==P4_COLLSEQ );
1936 if( pOp->p1 ){
1937 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1939 break;
1942 /* Opcode: BitAnd P1 P2 P3 * *
1943 ** Synopsis: r[P3]=r[P1]&r[P2]
1945 ** Take the bit-wise AND of the values in register P1 and P2 and
1946 ** store the result in register P3.
1947 ** If either input is NULL, the result is NULL.
1949 /* Opcode: BitOr P1 P2 P3 * *
1950 ** Synopsis: r[P3]=r[P1]|r[P2]
1952 ** Take the bit-wise OR of the values in register P1 and P2 and
1953 ** store the result in register P3.
1954 ** If either input is NULL, the result is NULL.
1956 /* Opcode: ShiftLeft P1 P2 P3 * *
1957 ** Synopsis: r[P3]=r[P2]<<r[P1]
1959 ** Shift the integer value in register P2 to the left by the
1960 ** number of bits specified by the integer in register P1.
1961 ** Store the result in register P3.
1962 ** If either input is NULL, the result is NULL.
1964 /* Opcode: ShiftRight P1 P2 P3 * *
1965 ** Synopsis: r[P3]=r[P2]>>r[P1]
1967 ** Shift the integer value in register P2 to the right by the
1968 ** number of bits specified by the integer in register P1.
1969 ** Store the result in register P3.
1970 ** If either input is NULL, the result is NULL.
1972 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1973 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1974 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1975 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1976 i64 iA;
1977 u64 uA;
1978 i64 iB;
1979 u8 op;
1981 pIn1 = &aMem[pOp->p1];
1982 pIn2 = &aMem[pOp->p2];
1983 pOut = &aMem[pOp->p3];
1984 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1985 sqlite3VdbeMemSetNull(pOut);
1986 break;
1988 iA = sqlite3VdbeIntValue(pIn2);
1989 iB = sqlite3VdbeIntValue(pIn1);
1990 op = pOp->opcode;
1991 if( op==OP_BitAnd ){
1992 iA &= iB;
1993 }else if( op==OP_BitOr ){
1994 iA |= iB;
1995 }else if( iB!=0 ){
1996 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1998 /* If shifting by a negative amount, shift in the other direction */
1999 if( iB<0 ){
2000 assert( OP_ShiftRight==OP_ShiftLeft+1 );
2001 op = 2*OP_ShiftLeft + 1 - op;
2002 iB = iB>(-64) ? -iB : 64;
2005 if( iB>=64 ){
2006 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
2007 }else{
2008 memcpy(&uA, &iA, sizeof(uA));
2009 if( op==OP_ShiftLeft ){
2010 uA <<= iB;
2011 }else{
2012 uA >>= iB;
2013 /* Sign-extend on a right shift of a negative number */
2014 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
2016 memcpy(&iA, &uA, sizeof(iA));
2019 pOut->u.i = iA;
2020 MemSetTypeFlag(pOut, MEM_Int);
2021 break;
2024 /* Opcode: AddImm P1 P2 * * *
2025 ** Synopsis: r[P1]=r[P1]+P2
2027 ** Add the constant P2 to the value in register P1.
2028 ** The result is always an integer.
2030 ** To force any register to be an integer, just add 0.
2032 case OP_AddImm: { /* in1 */
2033 pIn1 = &aMem[pOp->p1];
2034 memAboutToChange(p, pIn1);
2035 sqlite3VdbeMemIntegerify(pIn1);
2036 pIn1->u.i += pOp->p2;
2037 break;
2040 /* Opcode: MustBeInt P1 P2 * * *
2042 ** Force the value in register P1 to be an integer. If the value
2043 ** in P1 is not an integer and cannot be converted into an integer
2044 ** without data loss, then jump immediately to P2, or if P2==0
2045 ** raise an SQLITE_MISMATCH exception.
2047 case OP_MustBeInt: { /* jump, in1 */
2048 pIn1 = &aMem[pOp->p1];
2049 if( (pIn1->flags & MEM_Int)==0 ){
2050 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
2051 if( (pIn1->flags & MEM_Int)==0 ){
2052 VdbeBranchTaken(1, 2);
2053 if( pOp->p2==0 ){
2054 rc = SQLITE_MISMATCH;
2055 goto abort_due_to_error;
2056 }else{
2057 goto jump_to_p2;
2061 VdbeBranchTaken(0, 2);
2062 MemSetTypeFlag(pIn1, MEM_Int);
2063 break;
2066 #ifndef SQLITE_OMIT_FLOATING_POINT
2067 /* Opcode: RealAffinity P1 * * * *
2069 ** If register P1 holds an integer convert it to a real value.
2071 ** This opcode is used when extracting information from a column that
2072 ** has REAL affinity. Such column values may still be stored as
2073 ** integers, for space efficiency, but after extraction we want them
2074 ** to have only a real value.
2076 case OP_RealAffinity: { /* in1 */
2077 pIn1 = &aMem[pOp->p1];
2078 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
2079 testcase( pIn1->flags & MEM_Int );
2080 testcase( pIn1->flags & MEM_IntReal );
2081 sqlite3VdbeMemRealify(pIn1);
2082 REGISTER_TRACE(pOp->p1, pIn1);
2084 break;
2086 #endif
2088 #ifndef SQLITE_OMIT_CAST
2089 /* Opcode: Cast P1 P2 * * *
2090 ** Synopsis: affinity(r[P1])
2092 ** Force the value in register P1 to be the type defined by P2.
2094 ** <ul>
2095 ** <li> P2=='A' &rarr; BLOB
2096 ** <li> P2=='B' &rarr; TEXT
2097 ** <li> P2=='C' &rarr; NUMERIC
2098 ** <li> P2=='D' &rarr; INTEGER
2099 ** <li> P2=='E' &rarr; REAL
2100 ** </ul>
2102 ** A NULL value is not changed by this routine. It remains NULL.
2104 case OP_Cast: { /* in1 */
2105 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
2106 testcase( pOp->p2==SQLITE_AFF_TEXT );
2107 testcase( pOp->p2==SQLITE_AFF_BLOB );
2108 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
2109 testcase( pOp->p2==SQLITE_AFF_INTEGER );
2110 testcase( pOp->p2==SQLITE_AFF_REAL );
2111 pIn1 = &aMem[pOp->p1];
2112 memAboutToChange(p, pIn1);
2113 rc = ExpandBlob(pIn1);
2114 if( rc ) goto abort_due_to_error;
2115 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
2116 if( rc ) goto abort_due_to_error;
2117 UPDATE_MAX_BLOBSIZE(pIn1);
2118 REGISTER_TRACE(pOp->p1, pIn1);
2119 break;
2121 #endif /* SQLITE_OMIT_CAST */
2123 /* Opcode: Eq P1 P2 P3 P4 P5
2124 ** Synopsis: IF r[P3]==r[P1]
2126 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
2127 ** jump to address P2.
2129 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2130 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2131 ** to coerce both inputs according to this affinity before the
2132 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2133 ** affinity is used. Note that the affinity conversions are stored
2134 ** back into the input registers P1 and P3. So this opcode can cause
2135 ** persistent changes to registers P1 and P3.
2137 ** Once any conversions have taken place, and neither value is NULL,
2138 ** the values are compared. If both values are blobs then memcmp() is
2139 ** used to determine the results of the comparison. If both values
2140 ** are text, then the appropriate collating function specified in
2141 ** P4 is used to do the comparison. If P4 is not specified then
2142 ** memcmp() is used to compare text string. If both values are
2143 ** numeric, then a numeric comparison is used. If the two values
2144 ** are of different types, then numbers are considered less than
2145 ** strings and strings are considered less than blobs.
2147 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
2148 ** true or false and is never NULL. If both operands are NULL then the result
2149 ** of comparison is true. If either operand is NULL then the result is false.
2150 ** If neither operand is NULL the result is the same as it would be if
2151 ** the SQLITE_NULLEQ flag were omitted from P5.
2153 ** This opcode saves the result of comparison for use by the new
2154 ** OP_Jump opcode.
2156 /* Opcode: Ne P1 P2 P3 P4 P5
2157 ** Synopsis: IF r[P3]!=r[P1]
2159 ** This works just like the Eq opcode except that the jump is taken if
2160 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
2161 ** additional information.
2163 /* Opcode: Lt P1 P2 P3 P4 P5
2164 ** Synopsis: IF r[P3]<r[P1]
2166 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
2167 ** jump to address P2.
2169 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
2170 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
2171 ** bit is clear then fall through if either operand is NULL.
2173 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2174 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2175 ** to coerce both inputs according to this affinity before the
2176 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2177 ** affinity is used. Note that the affinity conversions are stored
2178 ** back into the input registers P1 and P3. So this opcode can cause
2179 ** persistent changes to registers P1 and P3.
2181 ** Once any conversions have taken place, and neither value is NULL,
2182 ** the values are compared. If both values are blobs then memcmp() is
2183 ** used to determine the results of the comparison. If both values
2184 ** are text, then the appropriate collating function specified in
2185 ** P4 is used to do the comparison. If P4 is not specified then
2186 ** memcmp() is used to compare text string. If both values are
2187 ** numeric, then a numeric comparison is used. If the two values
2188 ** are of different types, then numbers are considered less than
2189 ** strings and strings are considered less than blobs.
2191 ** This opcode saves the result of comparison for use by the new
2192 ** OP_Jump opcode.
2194 /* Opcode: Le P1 P2 P3 P4 P5
2195 ** Synopsis: IF r[P3]<=r[P1]
2197 ** This works just like the Lt opcode except that the jump is taken if
2198 ** the content of register P3 is less than or equal to the content of
2199 ** register P1. See the Lt opcode for additional information.
2201 /* Opcode: Gt P1 P2 P3 P4 P5
2202 ** Synopsis: IF r[P3]>r[P1]
2204 ** This works just like the Lt opcode except that the jump is taken if
2205 ** the content of register P3 is greater than the content of
2206 ** register P1. See the Lt opcode for additional information.
2208 /* Opcode: Ge P1 P2 P3 P4 P5
2209 ** Synopsis: IF r[P3]>=r[P1]
2211 ** This works just like the Lt opcode except that the jump is taken if
2212 ** the content of register P3 is greater than or equal to the content of
2213 ** register P1. See the Lt opcode for additional information.
2215 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
2216 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
2217 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
2218 case OP_Le: /* same as TK_LE, jump, in1, in3 */
2219 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
2220 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
2221 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
2222 char affinity; /* Affinity to use for comparison */
2223 u16 flags1; /* Copy of initial value of pIn1->flags */
2224 u16 flags3; /* Copy of initial value of pIn3->flags */
2226 pIn1 = &aMem[pOp->p1];
2227 pIn3 = &aMem[pOp->p3];
2228 flags1 = pIn1->flags;
2229 flags3 = pIn3->flags;
2230 if( (flags1 & flags3 & MEM_Int)!=0 ){
2231 /* Common case of comparison of two integers */
2232 if( pIn3->u.i > pIn1->u.i ){
2233 if( sqlite3aGTb[pOp->opcode] ){
2234 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2235 goto jump_to_p2;
2237 iCompare = +1;
2238 VVA_ONLY( iCompareIsInit = 1; )
2239 }else if( pIn3->u.i < pIn1->u.i ){
2240 if( sqlite3aLTb[pOp->opcode] ){
2241 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2242 goto jump_to_p2;
2244 iCompare = -1;
2245 VVA_ONLY( iCompareIsInit = 1; )
2246 }else{
2247 if( sqlite3aEQb[pOp->opcode] ){
2248 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2249 goto jump_to_p2;
2251 iCompare = 0;
2252 VVA_ONLY( iCompareIsInit = 1; )
2254 VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2255 break;
2257 if( (flags1 | flags3)&MEM_Null ){
2258 /* One or both operands are NULL */
2259 if( pOp->p5 & SQLITE_NULLEQ ){
2260 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
2261 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
2262 ** or not both operands are null.
2264 assert( (flags1 & MEM_Cleared)==0 );
2265 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
2266 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
2267 if( (flags1&flags3&MEM_Null)!=0
2268 && (flags3&MEM_Cleared)==0
2270 res = 0; /* Operands are equal */
2271 }else{
2272 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
2274 }else{
2275 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
2276 ** then the result is always NULL.
2277 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
2279 VdbeBranchTaken(2,3);
2280 if( pOp->p5 & SQLITE_JUMPIFNULL ){
2281 goto jump_to_p2;
2283 iCompare = 1; /* Operands are not equal */
2284 VVA_ONLY( iCompareIsInit = 1; )
2285 break;
2287 }else{
2288 /* Neither operand is NULL and we couldn't do the special high-speed
2289 ** integer comparison case. So do a general-case comparison. */
2290 affinity = pOp->p5 & SQLITE_AFF_MASK;
2291 if( affinity>=SQLITE_AFF_NUMERIC ){
2292 if( (flags1 | flags3)&MEM_Str ){
2293 if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2294 applyNumericAffinity(pIn1,0);
2295 assert( flags3==pIn3->flags || CORRUPT_DB );
2296 flags3 = pIn3->flags;
2298 if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2299 applyNumericAffinity(pIn3,0);
2302 }else if( affinity==SQLITE_AFF_TEXT && ((flags1 | flags3) & MEM_Str)!=0 ){
2303 if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2304 testcase( pIn1->flags & MEM_Int );
2305 testcase( pIn1->flags & MEM_Real );
2306 testcase( pIn1->flags & MEM_IntReal );
2307 sqlite3VdbeMemStringify(pIn1, encoding, 1);
2308 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
2309 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
2310 if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
2312 if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2313 testcase( pIn3->flags & MEM_Int );
2314 testcase( pIn3->flags & MEM_Real );
2315 testcase( pIn3->flags & MEM_IntReal );
2316 sqlite3VdbeMemStringify(pIn3, encoding, 1);
2317 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
2318 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
2321 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
2322 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
2325 /* At this point, res is negative, zero, or positive if reg[P1] is
2326 ** less than, equal to, or greater than reg[P3], respectively. Compute
2327 ** the answer to this operator in res2, depending on what the comparison
2328 ** operator actually is. The next block of code depends on the fact
2329 ** that the 6 comparison operators are consecutive integers in this
2330 ** order: NE, EQ, GT, LE, LT, GE */
2331 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
2332 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
2333 if( res<0 ){
2334 res2 = sqlite3aLTb[pOp->opcode];
2335 }else if( res==0 ){
2336 res2 = sqlite3aEQb[pOp->opcode];
2337 }else{
2338 res2 = sqlite3aGTb[pOp->opcode];
2340 iCompare = res;
2341 VVA_ONLY( iCompareIsInit = 1; )
2343 /* Undo any changes made by applyAffinity() to the input registers. */
2344 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
2345 pIn3->flags = flags3;
2346 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
2347 pIn1->flags = flags1;
2349 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2350 if( res2 ){
2351 goto jump_to_p2;
2353 break;
2356 /* Opcode: ElseEq * P2 * * *
2358 ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
2359 ** can be zero or more OP_ReleaseReg opcodes intervening, but no other
2360 ** opcodes are allowed to occur between this instruction and the previous
2361 ** OP_Lt or OP_Gt.
2363 ** If the result of an OP_Eq comparison on the same two operands as
2364 ** the prior OP_Lt or OP_Gt would have been true, then jump to P2. If
2365 ** the result of an OP_Eq comparison on the two previous operands
2366 ** would have been false or NULL, then fall through.
2368 case OP_ElseEq: { /* same as TK_ESCAPE, jump */
2370 #ifdef SQLITE_DEBUG
2371 /* Verify the preconditions of this opcode - that it follows an OP_Lt or
2372 ** OP_Gt with zero or more intervening OP_ReleaseReg opcodes */
2373 int iAddr;
2374 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
2375 if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
2376 assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
2377 break;
2379 #endif /* SQLITE_DEBUG */
2380 assert( iCompareIsInit );
2381 VdbeBranchTaken(iCompare==0, 2);
2382 if( iCompare==0 ) goto jump_to_p2;
2383 break;
2387 /* Opcode: Permutation * * * P4 *
2389 ** Set the permutation used by the OP_Compare operator in the next
2390 ** instruction. The permutation is stored in the P4 operand.
2392 ** The permutation is only valid for the next opcode which must be
2393 ** an OP_Compare that has the OPFLAG_PERMUTE bit set in P5.
2395 ** The first integer in the P4 integer array is the length of the array
2396 ** and does not become part of the permutation.
2398 case OP_Permutation: {
2399 assert( pOp->p4type==P4_INTARRAY );
2400 assert( pOp->p4.ai );
2401 assert( pOp[1].opcode==OP_Compare );
2402 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2403 break;
2406 /* Opcode: Compare P1 P2 P3 P4 P5
2407 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2409 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2410 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2411 ** the comparison for use by the next OP_Jump instruct.
2413 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2414 ** determined by the most recent OP_Permutation operator. If the
2415 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2416 ** order.
2418 ** P4 is a KeyInfo structure that defines collating sequences and sort
2419 ** orders for the comparison. The permutation applies to registers
2420 ** only. The KeyInfo elements are used sequentially.
2422 ** The comparison is a sort comparison, so NULLs compare equal,
2423 ** NULLs are less than numbers, numbers are less than strings,
2424 ** and strings are less than blobs.
2426 ** This opcode must be immediately followed by an OP_Jump opcode.
2428 case OP_Compare: {
2429 int n;
2430 int i;
2431 int p1;
2432 int p2;
2433 const KeyInfo *pKeyInfo;
2434 u32 idx;
2435 CollSeq *pColl; /* Collating sequence to use on this term */
2436 int bRev; /* True for DESCENDING sort order */
2437 u32 *aPermute; /* The permutation */
2439 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2440 aPermute = 0;
2441 }else{
2442 assert( pOp>aOp );
2443 assert( pOp[-1].opcode==OP_Permutation );
2444 assert( pOp[-1].p4type==P4_INTARRAY );
2445 aPermute = pOp[-1].p4.ai + 1;
2446 assert( aPermute!=0 );
2448 n = pOp->p3;
2449 pKeyInfo = pOp->p4.pKeyInfo;
2450 assert( n>0 );
2451 assert( pKeyInfo!=0 );
2452 p1 = pOp->p1;
2453 p2 = pOp->p2;
2454 #ifdef SQLITE_DEBUG
2455 if( aPermute ){
2456 int k, mx = 0;
2457 for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
2458 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2459 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2460 }else{
2461 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2462 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2464 #endif /* SQLITE_DEBUG */
2465 for(i=0; i<n; i++){
2466 idx = aPermute ? aPermute[i] : (u32)i;
2467 assert( memIsValid(&aMem[p1+idx]) );
2468 assert( memIsValid(&aMem[p2+idx]) );
2469 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2470 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2471 assert( i<pKeyInfo->nKeyField );
2472 pColl = pKeyInfo->aColl[i];
2473 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
2474 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2475 VVA_ONLY( iCompareIsInit = 1; )
2476 if( iCompare ){
2477 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
2478 && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
2480 iCompare = -iCompare;
2482 if( bRev ) iCompare = -iCompare;
2483 break;
2486 assert( pOp[1].opcode==OP_Jump );
2487 break;
2490 /* Opcode: Jump P1 P2 P3 * *
2492 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2493 ** in the most recent OP_Compare instruction the P1 vector was less than,
2494 ** equal to, or greater than the P2 vector, respectively.
2496 ** This opcode must immediately follow an OP_Compare opcode.
2498 case OP_Jump: { /* jump */
2499 assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
2500 assert( iCompareIsInit );
2501 if( iCompare<0 ){
2502 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
2503 }else if( iCompare==0 ){
2504 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
2505 }else{
2506 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
2508 break;
2511 /* Opcode: And P1 P2 P3 * *
2512 ** Synopsis: r[P3]=(r[P1] && r[P2])
2514 ** Take the logical AND of the values in registers P1 and P2 and
2515 ** write the result into register P3.
2517 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2518 ** the other input is NULL. A NULL and true or two NULLs give
2519 ** a NULL output.
2521 /* Opcode: Or P1 P2 P3 * *
2522 ** Synopsis: r[P3]=(r[P1] || r[P2])
2524 ** Take the logical OR of the values in register P1 and P2 and
2525 ** store the answer in register P3.
2527 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2528 ** even if the other input is NULL. A NULL and false or two NULLs
2529 ** give a NULL output.
2531 case OP_And: /* same as TK_AND, in1, in2, out3 */
2532 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2533 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2534 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2536 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2537 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2538 if( pOp->opcode==OP_And ){
2539 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2540 v1 = and_logic[v1*3+v2];
2541 }else{
2542 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2543 v1 = or_logic[v1*3+v2];
2545 pOut = &aMem[pOp->p3];
2546 if( v1==2 ){
2547 MemSetTypeFlag(pOut, MEM_Null);
2548 }else{
2549 pOut->u.i = v1;
2550 MemSetTypeFlag(pOut, MEM_Int);
2552 break;
2555 /* Opcode: IsTrue P1 P2 P3 P4 *
2556 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2558 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2559 ** IS NOT FALSE operators.
2561 ** Interpret the value in register P1 as a boolean value. Store that
2562 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2563 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2564 ** is 1.
2566 ** The logic is summarized like this:
2568 ** <ul>
2569 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2570 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2571 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2572 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2573 ** </ul>
2575 case OP_IsTrue: { /* in1, out2 */
2576 assert( pOp->p4type==P4_INT32 );
2577 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2578 assert( pOp->p3==0 || pOp->p3==1 );
2579 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2580 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2581 break;
2584 /* Opcode: Not P1 P2 * * *
2585 ** Synopsis: r[P2]= !r[P1]
2587 ** Interpret the value in register P1 as a boolean value. Store the
2588 ** boolean complement in register P2. If the value in register P1 is
2589 ** NULL, then a NULL is stored in P2.
2591 case OP_Not: { /* same as TK_NOT, in1, out2 */
2592 pIn1 = &aMem[pOp->p1];
2593 pOut = &aMem[pOp->p2];
2594 if( (pIn1->flags & MEM_Null)==0 ){
2595 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2596 }else{
2597 sqlite3VdbeMemSetNull(pOut);
2599 break;
2602 /* Opcode: BitNot P1 P2 * * *
2603 ** Synopsis: r[P2]= ~r[P1]
2605 ** Interpret the content of register P1 as an integer. Store the
2606 ** ones-complement of the P1 value into register P2. If P1 holds
2607 ** a NULL then store a NULL in P2.
2609 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2610 pIn1 = &aMem[pOp->p1];
2611 pOut = &aMem[pOp->p2];
2612 sqlite3VdbeMemSetNull(pOut);
2613 if( (pIn1->flags & MEM_Null)==0 ){
2614 pOut->flags = MEM_Int;
2615 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2617 break;
2620 /* Opcode: Once P1 P2 * * *
2622 ** Fall through to the next instruction the first time this opcode is
2623 ** encountered on each invocation of the byte-code program. Jump to P2
2624 ** on the second and all subsequent encounters during the same invocation.
2626 ** Top-level programs determine first invocation by comparing the P1
2627 ** operand against the P1 operand on the OP_Init opcode at the beginning
2628 ** of the program. If the P1 values differ, then fall through and make
2629 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2630 ** the same then take the jump.
2632 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2633 ** whether or not the jump should be taken. The bitmask is necessary
2634 ** because the self-altering code trick does not work for recursive
2635 ** triggers.
2637 case OP_Once: { /* jump */
2638 u32 iAddr; /* Address of this instruction */
2639 assert( p->aOp[0].opcode==OP_Init );
2640 if( p->pFrame ){
2641 iAddr = (int)(pOp - p->aOp);
2642 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2643 VdbeBranchTaken(1, 2);
2644 goto jump_to_p2;
2646 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2647 }else{
2648 if( p->aOp[0].p1==pOp->p1 ){
2649 VdbeBranchTaken(1, 2);
2650 goto jump_to_p2;
2653 VdbeBranchTaken(0, 2);
2654 pOp->p1 = p->aOp[0].p1;
2655 break;
2658 /* Opcode: If P1 P2 P3 * *
2660 ** Jump to P2 if the value in register P1 is true. The value
2661 ** is considered true if it is numeric and non-zero. If the value
2662 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2664 case OP_If: { /* jump, in1 */
2665 int c;
2666 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2667 VdbeBranchTaken(c!=0, 2);
2668 if( c ) goto jump_to_p2;
2669 break;
2672 /* Opcode: IfNot P1 P2 P3 * *
2674 ** Jump to P2 if the value in register P1 is False. The value
2675 ** is considered false if it has a numeric value of zero. If the value
2676 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2678 case OP_IfNot: { /* jump, in1 */
2679 int c;
2680 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2681 VdbeBranchTaken(c!=0, 2);
2682 if( c ) goto jump_to_p2;
2683 break;
2686 /* Opcode: IsNull P1 P2 * * *
2687 ** Synopsis: if r[P1]==NULL goto P2
2689 ** Jump to P2 if the value in register P1 is NULL.
2691 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2692 pIn1 = &aMem[pOp->p1];
2693 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2694 if( (pIn1->flags & MEM_Null)!=0 ){
2695 goto jump_to_p2;
2697 break;
2700 /* Opcode: IsType P1 P2 P3 P4 P5
2701 ** Synopsis: if typeof(P1.P3) in P5 goto P2
2703 ** Jump to P2 if the type of a column in a btree is one of the types specified
2704 ** by the P5 bitmask.
2706 ** P1 is normally a cursor on a btree for which the row decode cache is
2707 ** valid through at least column P3. In other words, there should have been
2708 ** a prior OP_Column for column P3 or greater. If the cursor is not valid,
2709 ** then this opcode might give spurious results.
2710 ** The the btree row has fewer than P3 columns, then use P4 as the
2711 ** datatype.
2713 ** If P1 is -1, then P3 is a register number and the datatype is taken
2714 ** from the value in that register.
2716 ** P5 is a bitmask of data types. SQLITE_INTEGER is the least significant
2717 ** (0x01) bit. SQLITE_FLOAT is the 0x02 bit. SQLITE_TEXT is 0x04.
2718 ** SQLITE_BLOB is 0x08. SQLITE_NULL is 0x10.
2720 ** WARNING: This opcode does not reliably distinguish between NULL and REAL
2721 ** when P1>=0. If the database contains a NaN value, this opcode will think
2722 ** that the datatype is REAL when it should be NULL. When P1<0 and the value
2723 ** is already stored in register P3, then this opcode does reliably
2724 ** distinguish between NULL and REAL. The problem only arises then P1>=0.
2726 ** Take the jump to address P2 if and only if the datatype of the
2727 ** value determined by P1 and P3 corresponds to one of the bits in the
2728 ** P5 bitmask.
2731 case OP_IsType: { /* jump */
2732 VdbeCursor *pC;
2733 u16 typeMask;
2734 u32 serialType;
2736 assert( pOp->p1>=(-1) && pOp->p1<p->nCursor );
2737 assert( pOp->p1>=0 || (pOp->p3>=0 && pOp->p3<=(p->nMem+1 - p->nCursor)) );
2738 if( pOp->p1>=0 ){
2739 pC = p->apCsr[pOp->p1];
2740 assert( pC!=0 );
2741 assert( pOp->p3>=0 );
2742 if( pOp->p3<pC->nHdrParsed ){
2743 serialType = pC->aType[pOp->p3];
2744 if( serialType>=12 ){
2745 if( serialType&1 ){
2746 typeMask = 0x04; /* SQLITE_TEXT */
2747 }else{
2748 typeMask = 0x08; /* SQLITE_BLOB */
2750 }else{
2751 static const unsigned char aMask[] = {
2752 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2,
2753 0x01, 0x01, 0x10, 0x10
2755 testcase( serialType==0 );
2756 testcase( serialType==1 );
2757 testcase( serialType==2 );
2758 testcase( serialType==3 );
2759 testcase( serialType==4 );
2760 testcase( serialType==5 );
2761 testcase( serialType==6 );
2762 testcase( serialType==7 );
2763 testcase( serialType==8 );
2764 testcase( serialType==9 );
2765 testcase( serialType==10 );
2766 testcase( serialType==11 );
2767 typeMask = aMask[serialType];
2769 }else{
2770 typeMask = 1 << (pOp->p4.i - 1);
2771 testcase( typeMask==0x01 );
2772 testcase( typeMask==0x02 );
2773 testcase( typeMask==0x04 );
2774 testcase( typeMask==0x08 );
2775 testcase( typeMask==0x10 );
2777 }else{
2778 assert( memIsValid(&aMem[pOp->p3]) );
2779 typeMask = 1 << (sqlite3_value_type((sqlite3_value*)&aMem[pOp->p3])-1);
2780 testcase( typeMask==0x01 );
2781 testcase( typeMask==0x02 );
2782 testcase( typeMask==0x04 );
2783 testcase( typeMask==0x08 );
2784 testcase( typeMask==0x10 );
2786 VdbeBranchTaken( (typeMask & pOp->p5)!=0, 2);
2787 if( typeMask & pOp->p5 ){
2788 goto jump_to_p2;
2790 break;
2793 /* Opcode: ZeroOrNull P1 P2 P3 * *
2794 ** Synopsis: r[P2] = 0 OR NULL
2796 ** If both registers P1 and P3 are NOT NULL, then store a zero in
2797 ** register P2. If either registers P1 or P3 are NULL then put
2798 ** a NULL in register P2.
2800 case OP_ZeroOrNull: { /* in1, in2, out2, in3 */
2801 if( (aMem[pOp->p1].flags & MEM_Null)!=0
2802 || (aMem[pOp->p3].flags & MEM_Null)!=0
2804 sqlite3VdbeMemSetNull(aMem + pOp->p2);
2805 }else{
2806 sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
2808 break;
2811 /* Opcode: NotNull P1 P2 * * *
2812 ** Synopsis: if r[P1]!=NULL goto P2
2814 ** Jump to P2 if the value in register P1 is not NULL.
2816 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2817 pIn1 = &aMem[pOp->p1];
2818 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2819 if( (pIn1->flags & MEM_Null)==0 ){
2820 goto jump_to_p2;
2822 break;
2825 /* Opcode: IfNullRow P1 P2 P3 * *
2826 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2828 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2829 ** If it is, then set register P3 to NULL and jump immediately to P2.
2830 ** If P1 is not on a NULL row, then fall through without making any
2831 ** changes.
2833 ** If P1 is not an open cursor, then this opcode is a no-op.
2835 case OP_IfNullRow: { /* jump */
2836 VdbeCursor *pC;
2837 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2838 pC = p->apCsr[pOp->p1];
2839 if( pC && pC->nullRow ){
2840 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2841 goto jump_to_p2;
2843 break;
2846 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2847 /* Opcode: Offset P1 P2 P3 * *
2848 ** Synopsis: r[P3] = sqlite_offset(P1)
2850 ** Store in register r[P3] the byte offset into the database file that is the
2851 ** start of the payload for the record at which that cursor P1 is currently
2852 ** pointing.
2854 ** P2 is the column number for the argument to the sqlite_offset() function.
2855 ** This opcode does not use P2 itself, but the P2 value is used by the
2856 ** code generator. The P1, P2, and P3 operands to this opcode are the
2857 ** same as for OP_Column.
2859 ** This opcode is only available if SQLite is compiled with the
2860 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2862 case OP_Offset: { /* out3 */
2863 VdbeCursor *pC; /* The VDBE cursor */
2864 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2865 pC = p->apCsr[pOp->p1];
2866 pOut = &p->aMem[pOp->p3];
2867 if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
2868 sqlite3VdbeMemSetNull(pOut);
2869 }else{
2870 if( pC->deferredMoveto ){
2871 rc = sqlite3VdbeFinishMoveto(pC);
2872 if( rc ) goto abort_due_to_error;
2874 if( sqlite3BtreeEof(pC->uc.pCursor) ){
2875 sqlite3VdbeMemSetNull(pOut);
2876 }else{
2877 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2880 break;
2882 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2884 /* Opcode: Column P1 P2 P3 P4 P5
2885 ** Synopsis: r[P3]=PX cursor P1 column P2
2887 ** Interpret the data that cursor P1 points to as a structure built using
2888 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2889 ** information about the format of the data.) Extract the P2-th column
2890 ** from this record. If there are less than (P2+1)
2891 ** values in the record, extract a NULL.
2893 ** The value extracted is stored in register P3.
2895 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2896 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2897 ** the result.
2899 ** If the OPFLAG_LENGTHARG bit is set in P5 then the result is guaranteed
2900 ** to only be used by the length() function or the equivalent. The content
2901 ** of large blobs is not loaded, thus saving CPU cycles. If the
2902 ** OPFLAG_TYPEOFARG bit is set then the result will only be used by the
2903 ** typeof() function or the IS NULL or IS NOT NULL operators or the
2904 ** equivalent. In this case, all content loading can be omitted.
2906 case OP_Column: { /* ncycle */
2907 u32 p2; /* column number to retrieve */
2908 VdbeCursor *pC; /* The VDBE cursor */
2909 BtCursor *pCrsr; /* The B-Tree cursor corresponding to pC */
2910 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2911 int len; /* The length of the serialized data for the column */
2912 int i; /* Loop counter */
2913 Mem *pDest; /* Where to write the extracted value */
2914 Mem sMem; /* For storing the record being decoded */
2915 const u8 *zData; /* Part of the record being decoded */
2916 const u8 *zHdr; /* Next unparsed byte of the header */
2917 const u8 *zEndHdr; /* Pointer to first byte after the header */
2918 u64 offset64; /* 64-bit offset */
2919 u32 t; /* A type code from the record header */
2920 Mem *pReg; /* PseudoTable input register */
2922 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2923 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2924 pC = p->apCsr[pOp->p1];
2925 p2 = (u32)pOp->p2;
2927 op_column_restart:
2928 assert( pC!=0 );
2929 assert( p2<(u32)pC->nField
2930 || (pC->eCurType==CURTYPE_PSEUDO && pC->seekResult==0) );
2931 aOffset = pC->aOffset;
2932 assert( aOffset==pC->aType+pC->nField );
2933 assert( pC->eCurType!=CURTYPE_VTAB );
2934 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2935 assert( pC->eCurType!=CURTYPE_SORTER );
2937 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2938 if( pC->nullRow ){
2939 if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
2940 /* For the special case of as pseudo-cursor, the seekResult field
2941 ** identifies the register that holds the record */
2942 pReg = &aMem[pC->seekResult];
2943 assert( pReg->flags & MEM_Blob );
2944 assert( memIsValid(pReg) );
2945 pC->payloadSize = pC->szRow = pReg->n;
2946 pC->aRow = (u8*)pReg->z;
2947 }else{
2948 pDest = &aMem[pOp->p3];
2949 memAboutToChange(p, pDest);
2950 sqlite3VdbeMemSetNull(pDest);
2951 goto op_column_out;
2953 }else{
2954 pCrsr = pC->uc.pCursor;
2955 if( pC->deferredMoveto ){
2956 u32 iMap;
2957 assert( !pC->isEphemeral );
2958 if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0 ){
2959 pC = pC->pAltCursor;
2960 p2 = iMap - 1;
2961 goto op_column_restart;
2963 rc = sqlite3VdbeFinishMoveto(pC);
2964 if( rc ) goto abort_due_to_error;
2965 }else if( sqlite3BtreeCursorHasMoved(pCrsr) ){
2966 rc = sqlite3VdbeHandleMovedCursor(pC);
2967 if( rc ) goto abort_due_to_error;
2968 goto op_column_restart;
2970 assert( pC->eCurType==CURTYPE_BTREE );
2971 assert( pCrsr );
2972 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2973 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2974 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2975 assert( pC->szRow<=pC->payloadSize );
2976 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2978 pC->cacheStatus = p->cacheCtr;
2979 if( (aOffset[0] = pC->aRow[0])<0x80 ){
2980 pC->iHdrOffset = 1;
2981 }else{
2982 pC->iHdrOffset = sqlite3GetVarint32(pC->aRow, aOffset);
2984 pC->nHdrParsed = 0;
2986 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2987 /* pC->aRow does not have to hold the entire row, but it does at least
2988 ** need to cover the header of the record. If pC->aRow does not contain
2989 ** the complete header, then set it to zero, forcing the header to be
2990 ** dynamically allocated. */
2991 pC->aRow = 0;
2992 pC->szRow = 0;
2994 /* Make sure a corrupt database has not given us an oversize header.
2995 ** Do this now to avoid an oversize memory allocation.
2997 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2998 ** types use so much data space that there can only be 4096 and 32 of
2999 ** them, respectively. So the maximum header length results from a
3000 ** 3-byte type for each of the maximum of 32768 columns plus three
3001 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
3003 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
3004 goto op_column_corrupt;
3006 }else{
3007 /* This is an optimization. By skipping over the first few tests
3008 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
3009 ** measurable performance gain.
3011 ** This branch is taken even if aOffset[0]==0. Such a record is never
3012 ** generated by SQLite, and could be considered corruption, but we
3013 ** accept it for historical reasons. When aOffset[0]==0, the code this
3014 ** branch jumps to reads past the end of the record, but never more
3015 ** than a few bytes. Even if the record occurs at the end of the page
3016 ** content area, the "page header" comes after the page content and so
3017 ** this overread is harmless. Similar overreads can occur for a corrupt
3018 ** database file.
3020 zData = pC->aRow;
3021 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
3022 testcase( aOffset[0]==0 );
3023 goto op_column_read_header;
3025 }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
3026 rc = sqlite3VdbeHandleMovedCursor(pC);
3027 if( rc ) goto abort_due_to_error;
3028 goto op_column_restart;
3031 /* Make sure at least the first p2+1 entries of the header have been
3032 ** parsed and valid information is in aOffset[] and pC->aType[].
3034 if( pC->nHdrParsed<=p2 ){
3035 /* If there is more header available for parsing in the record, try
3036 ** to extract additional fields up through the p2+1-th field
3038 if( pC->iHdrOffset<aOffset[0] ){
3039 /* Make sure zData points to enough of the record to cover the header. */
3040 if( pC->aRow==0 ){
3041 memset(&sMem, 0, sizeof(sMem));
3042 rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
3043 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3044 zData = (u8*)sMem.z;
3045 }else{
3046 zData = pC->aRow;
3049 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
3050 op_column_read_header:
3051 i = pC->nHdrParsed;
3052 offset64 = aOffset[i];
3053 zHdr = zData + pC->iHdrOffset;
3054 zEndHdr = zData + aOffset[0];
3055 testcase( zHdr>=zEndHdr );
3057 if( (pC->aType[i] = t = zHdr[0])<0x80 ){
3058 zHdr++;
3059 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
3060 }else{
3061 zHdr += sqlite3GetVarint32(zHdr, &t);
3062 pC->aType[i] = t;
3063 offset64 += sqlite3VdbeSerialTypeLen(t);
3065 aOffset[++i] = (u32)(offset64 & 0xffffffff);
3066 }while( (u32)i<=p2 && zHdr<zEndHdr );
3068 /* The record is corrupt if any of the following are true:
3069 ** (1) the bytes of the header extend past the declared header size
3070 ** (2) the entire header was used but not all data was used
3071 ** (3) the end of the data extends beyond the end of the record.
3073 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
3074 || (offset64 > pC->payloadSize)
3076 if( aOffset[0]==0 ){
3077 i = 0;
3078 zHdr = zEndHdr;
3079 }else{
3080 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
3081 goto op_column_corrupt;
3085 pC->nHdrParsed = i;
3086 pC->iHdrOffset = (u32)(zHdr - zData);
3087 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
3088 }else{
3089 t = 0;
3092 /* If after trying to extract new entries from the header, nHdrParsed is
3093 ** still not up to p2, that means that the record has fewer than p2
3094 ** columns. So the result will be either the default value or a NULL.
3096 if( pC->nHdrParsed<=p2 ){
3097 pDest = &aMem[pOp->p3];
3098 memAboutToChange(p, pDest);
3099 if( pOp->p4type==P4_MEM ){
3100 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
3101 }else{
3102 sqlite3VdbeMemSetNull(pDest);
3104 goto op_column_out;
3106 }else{
3107 t = pC->aType[p2];
3110 /* Extract the content for the p2+1-th column. Control can only
3111 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
3112 ** all valid.
3114 assert( p2<pC->nHdrParsed );
3115 assert( rc==SQLITE_OK );
3116 pDest = &aMem[pOp->p3];
3117 memAboutToChange(p, pDest);
3118 assert( sqlite3VdbeCheckMemInvariants(pDest) );
3119 if( VdbeMemDynamic(pDest) ){
3120 sqlite3VdbeMemSetNull(pDest);
3122 assert( t==pC->aType[p2] );
3123 if( pC->szRow>=aOffset[p2+1] ){
3124 /* This is the common case where the desired content fits on the original
3125 ** page - where the content is not on an overflow page */
3126 zData = pC->aRow + aOffset[p2];
3127 if( t<12 ){
3128 sqlite3VdbeSerialGet(zData, t, pDest);
3129 }else{
3130 /* If the column value is a string, we need a persistent value, not
3131 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
3132 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
3134 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
3135 pDest->n = len = (t-12)/2;
3136 pDest->enc = encoding;
3137 if( pDest->szMalloc < len+2 ){
3138 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
3139 pDest->flags = MEM_Null;
3140 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
3141 }else{
3142 pDest->z = pDest->zMalloc;
3144 memcpy(pDest->z, zData, len);
3145 pDest->z[len] = 0;
3146 pDest->z[len+1] = 0;
3147 pDest->flags = aFlag[t&1];
3149 }else{
3150 u8 p5;
3151 pDest->enc = encoding;
3152 assert( pDest->db==db );
3153 /* This branch happens only when content is on overflow pages */
3154 if( ((p5 = (pOp->p5 & OPFLAG_BYTELENARG))!=0
3155 && (p5==OPFLAG_TYPEOFARG
3156 || (t>=12 && ((t&1)==0 || p5==OPFLAG_BYTELENARG))
3159 || sqlite3VdbeSerialTypeLen(t)==0
3161 /* Content is irrelevant for
3162 ** 1. the typeof() function,
3163 ** 2. the length(X) function if X is a blob, and
3164 ** 3. if the content length is zero.
3165 ** So we might as well use bogus content rather than reading
3166 ** content from disk.
3168 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
3169 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
3170 ** read more. Use the global constant sqlite3CtypeMap[] as the array,
3171 ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
3172 ** and it begins with a bunch of zeros.
3174 sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
3175 }else{
3176 rc = vdbeColumnFromOverflow(pC, p2, t, aOffset[p2],
3177 p->cacheCtr, colCacheCtr, pDest);
3178 if( rc ){
3179 if( rc==SQLITE_NOMEM ) goto no_mem;
3180 if( rc==SQLITE_TOOBIG ) goto too_big;
3181 goto abort_due_to_error;
3186 op_column_out:
3187 UPDATE_MAX_BLOBSIZE(pDest);
3188 REGISTER_TRACE(pOp->p3, pDest);
3189 break;
3191 op_column_corrupt:
3192 if( aOp[0].p3>0 ){
3193 pOp = &aOp[aOp[0].p3-1];
3194 break;
3195 }else{
3196 rc = SQLITE_CORRUPT_BKPT;
3197 goto abort_due_to_error;
3201 /* Opcode: TypeCheck P1 P2 P3 P4 *
3202 ** Synopsis: typecheck(r[P1@P2])
3204 ** Apply affinities to the range of P2 registers beginning with P1.
3205 ** Take the affinities from the Table object in P4. If any value
3206 ** cannot be coerced into the correct type, then raise an error.
3208 ** This opcode is similar to OP_Affinity except that this opcode
3209 ** forces the register type to the Table column type. This is used
3210 ** to implement "strict affinity".
3212 ** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
3213 ** is zero. When P3 is non-zero, no type checking occurs for
3214 ** static generated columns. Virtual columns are computed at query time
3215 ** and so they are never checked.
3217 ** Preconditions:
3219 ** <ul>
3220 ** <li> P2 should be the number of non-virtual columns in the
3221 ** table of P4.
3222 ** <li> Table P4 should be a STRICT table.
3223 ** </ul>
3225 ** If any precondition is false, an assertion fault occurs.
3227 case OP_TypeCheck: {
3228 Table *pTab;
3229 Column *aCol;
3230 int i;
3232 assert( pOp->p4type==P4_TABLE );
3233 pTab = pOp->p4.pTab;
3234 assert( pTab->tabFlags & TF_Strict );
3235 assert( pTab->nNVCol==pOp->p2 );
3236 aCol = pTab->aCol;
3237 pIn1 = &aMem[pOp->p1];
3238 for(i=0; i<pTab->nCol; i++){
3239 if( aCol[i].colFlags & COLFLAG_GENERATED ){
3240 if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
3241 if( pOp->p3 ){ pIn1++; continue; }
3243 assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
3244 applyAffinity(pIn1, aCol[i].affinity, encoding);
3245 if( (pIn1->flags & MEM_Null)==0 ){
3246 switch( aCol[i].eCType ){
3247 case COLTYPE_BLOB: {
3248 if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
3249 break;
3251 case COLTYPE_INTEGER:
3252 case COLTYPE_INT: {
3253 if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
3254 break;
3256 case COLTYPE_TEXT: {
3257 if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
3258 break;
3260 case COLTYPE_REAL: {
3261 testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
3262 assert( (pIn1->flags & MEM_IntReal)==0 );
3263 if( pIn1->flags & MEM_Int ){
3264 /* When applying REAL affinity, if the result is still an MEM_Int
3265 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3266 ** so that we keep the high-resolution integer value but know that
3267 ** the type really wants to be REAL. */
3268 testcase( pIn1->u.i==140737488355328LL );
3269 testcase( pIn1->u.i==140737488355327LL );
3270 testcase( pIn1->u.i==-140737488355328LL );
3271 testcase( pIn1->u.i==-140737488355329LL );
3272 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
3273 pIn1->flags |= MEM_IntReal;
3274 pIn1->flags &= ~MEM_Int;
3275 }else{
3276 pIn1->u.r = (double)pIn1->u.i;
3277 pIn1->flags |= MEM_Real;
3278 pIn1->flags &= ~MEM_Int;
3280 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
3281 goto vdbe_type_error;
3283 break;
3285 default: {
3286 /* COLTYPE_ANY. Accept anything. */
3287 break;
3291 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3292 pIn1++;
3294 assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
3295 break;
3297 vdbe_type_error:
3298 sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
3299 vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
3300 pTab->zName, aCol[i].zCnName);
3301 rc = SQLITE_CONSTRAINT_DATATYPE;
3302 goto abort_due_to_error;
3305 /* Opcode: Affinity P1 P2 * P4 *
3306 ** Synopsis: affinity(r[P1@P2])
3308 ** Apply affinities to a range of P2 registers starting with P1.
3310 ** P4 is a string that is P2 characters long. The N-th character of the
3311 ** string indicates the column affinity that should be used for the N-th
3312 ** memory cell in the range.
3314 case OP_Affinity: {
3315 const char *zAffinity; /* The affinity to be applied */
3317 zAffinity = pOp->p4.z;
3318 assert( zAffinity!=0 );
3319 assert( pOp->p2>0 );
3320 assert( zAffinity[pOp->p2]==0 );
3321 pIn1 = &aMem[pOp->p1];
3322 while( 1 /*exit-by-break*/ ){
3323 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
3324 assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
3325 applyAffinity(pIn1, zAffinity[0], encoding);
3326 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
3327 /* When applying REAL affinity, if the result is still an MEM_Int
3328 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3329 ** so that we keep the high-resolution integer value but know that
3330 ** the type really wants to be REAL. */
3331 testcase( pIn1->u.i==140737488355328LL );
3332 testcase( pIn1->u.i==140737488355327LL );
3333 testcase( pIn1->u.i==-140737488355328LL );
3334 testcase( pIn1->u.i==-140737488355329LL );
3335 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
3336 pIn1->flags |= MEM_IntReal;
3337 pIn1->flags &= ~MEM_Int;
3338 }else{
3339 pIn1->u.r = (double)pIn1->u.i;
3340 pIn1->flags |= MEM_Real;
3341 pIn1->flags &= ~(MEM_Int|MEM_Str);
3344 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3345 zAffinity++;
3346 if( zAffinity[0]==0 ) break;
3347 pIn1++;
3349 break;
3352 /* Opcode: MakeRecord P1 P2 P3 P4 *
3353 ** Synopsis: r[P3]=mkrec(r[P1@P2])
3355 ** Convert P2 registers beginning with P1 into the [record format]
3356 ** use as a data record in a database table or as a key
3357 ** in an index. The OP_Column opcode can decode the record later.
3359 ** P4 may be a string that is P2 characters long. The N-th character of the
3360 ** string indicates the column affinity that should be used for the N-th
3361 ** field of the index key.
3363 ** The mapping from character to affinity is given by the SQLITE_AFF_
3364 ** macros defined in sqliteInt.h.
3366 ** If P4 is NULL then all index fields have the affinity BLOB.
3368 ** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
3369 ** compile-time option is enabled:
3371 ** * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
3372 ** of the right-most table that can be null-trimmed.
3374 ** * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
3375 ** OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
3376 ** accept no-change records with serial_type 10. This value is
3377 ** only used inside an assert() and does not affect the end result.
3379 case OP_MakeRecord: {
3380 Mem *pRec; /* The new record */
3381 u64 nData; /* Number of bytes of data space */
3382 int nHdr; /* Number of bytes of header space */
3383 i64 nByte; /* Data space required for this record */
3384 i64 nZero; /* Number of zero bytes at the end of the record */
3385 int nVarint; /* Number of bytes in a varint */
3386 u32 serial_type; /* Type field */
3387 Mem *pData0; /* First field to be combined into the record */
3388 Mem *pLast; /* Last field of the record */
3389 int nField; /* Number of fields in the record */
3390 char *zAffinity; /* The affinity string for the record */
3391 u32 len; /* Length of a field */
3392 u8 *zHdr; /* Where to write next byte of the header */
3393 u8 *zPayload; /* Where to write next byte of the payload */
3395 /* Assuming the record contains N fields, the record format looks
3396 ** like this:
3398 ** ------------------------------------------------------------------------
3399 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
3400 ** ------------------------------------------------------------------------
3402 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
3403 ** and so forth.
3405 ** Each type field is a varint representing the serial type of the
3406 ** corresponding data element (see sqlite3VdbeSerialType()). The
3407 ** hdr-size field is also a varint which is the offset from the beginning
3408 ** of the record to data0.
3410 nData = 0; /* Number of bytes of data space */
3411 nHdr = 0; /* Number of bytes of header space */
3412 nZero = 0; /* Number of zero bytes at the end of the record */
3413 nField = pOp->p1;
3414 zAffinity = pOp->p4.z;
3415 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
3416 pData0 = &aMem[nField];
3417 nField = pOp->p2;
3418 pLast = &pData0[nField-1];
3420 /* Identify the output register */
3421 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
3422 pOut = &aMem[pOp->p3];
3423 memAboutToChange(p, pOut);
3425 /* Apply the requested affinity to all inputs
3427 assert( pData0<=pLast );
3428 if( zAffinity ){
3429 pRec = pData0;
3431 applyAffinity(pRec, zAffinity[0], encoding);
3432 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
3433 pRec->flags |= MEM_IntReal;
3434 pRec->flags &= ~(MEM_Int);
3436 REGISTER_TRACE((int)(pRec-aMem), pRec);
3437 zAffinity++;
3438 pRec++;
3439 assert( zAffinity[0]==0 || pRec<=pLast );
3440 }while( zAffinity[0] );
3443 #ifdef SQLITE_ENABLE_NULL_TRIM
3444 /* NULLs can be safely trimmed from the end of the record, as long as
3445 ** as the schema format is 2 or more and none of the omitted columns
3446 ** have a non-NULL default value. Also, the record must be left with
3447 ** at least one field. If P5>0 then it will be one more than the
3448 ** index of the right-most column with a non-NULL default value */
3449 if( pOp->p5 ){
3450 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
3451 pLast--;
3452 nField--;
3455 #endif
3457 /* Loop through the elements that will make up the record to figure
3458 ** out how much space is required for the new record. After this loop,
3459 ** the Mem.uTemp field of each term should hold the serial-type that will
3460 ** be used for that term in the generated record:
3462 ** Mem.uTemp value type
3463 ** --------------- ---------------
3464 ** 0 NULL
3465 ** 1 1-byte signed integer
3466 ** 2 2-byte signed integer
3467 ** 3 3-byte signed integer
3468 ** 4 4-byte signed integer
3469 ** 5 6-byte signed integer
3470 ** 6 8-byte signed integer
3471 ** 7 IEEE float
3472 ** 8 Integer constant 0
3473 ** 9 Integer constant 1
3474 ** 10,11 reserved for expansion
3475 ** N>=12 and even BLOB
3476 ** N>=13 and odd text
3478 ** The following additional values are computed:
3479 ** nHdr Number of bytes needed for the record header
3480 ** nData Number of bytes of data space needed for the record
3481 ** nZero Zero bytes at the end of the record
3483 pRec = pLast;
3485 assert( memIsValid(pRec) );
3486 if( pRec->flags & MEM_Null ){
3487 if( pRec->flags & MEM_Zero ){
3488 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
3489 ** table methods that never invoke sqlite3_result_xxxxx() while
3490 ** computing an unchanging column value in an UPDATE statement.
3491 ** Give such values a special internal-use-only serial-type of 10
3492 ** so that they can be passed through to xUpdate and have
3493 ** a true sqlite3_value_nochange(). */
3494 #ifndef SQLITE_ENABLE_NULL_TRIM
3495 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
3496 #endif
3497 pRec->uTemp = 10;
3498 }else{
3499 pRec->uTemp = 0;
3501 nHdr++;
3502 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
3503 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3504 i64 i = pRec->u.i;
3505 u64 uu;
3506 testcase( pRec->flags & MEM_Int );
3507 testcase( pRec->flags & MEM_IntReal );
3508 if( i<0 ){
3509 uu = ~i;
3510 }else{
3511 uu = i;
3513 nHdr++;
3514 testcase( uu==127 ); testcase( uu==128 );
3515 testcase( uu==32767 ); testcase( uu==32768 );
3516 testcase( uu==8388607 ); testcase( uu==8388608 );
3517 testcase( uu==2147483647 ); testcase( uu==2147483648LL );
3518 testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
3519 if( uu<=127 ){
3520 if( (i&1)==i && p->minWriteFileFormat>=4 ){
3521 pRec->uTemp = 8+(u32)uu;
3522 }else{
3523 nData++;
3524 pRec->uTemp = 1;
3526 }else if( uu<=32767 ){
3527 nData += 2;
3528 pRec->uTemp = 2;
3529 }else if( uu<=8388607 ){
3530 nData += 3;
3531 pRec->uTemp = 3;
3532 }else if( uu<=2147483647 ){
3533 nData += 4;
3534 pRec->uTemp = 4;
3535 }else if( uu<=140737488355327LL ){
3536 nData += 6;
3537 pRec->uTemp = 5;
3538 }else{
3539 nData += 8;
3540 if( pRec->flags & MEM_IntReal ){
3541 /* If the value is IntReal and is going to take up 8 bytes to store
3542 ** as an integer, then we might as well make it an 8-byte floating
3543 ** point value */
3544 pRec->u.r = (double)pRec->u.i;
3545 pRec->flags &= ~MEM_IntReal;
3546 pRec->flags |= MEM_Real;
3547 pRec->uTemp = 7;
3548 }else{
3549 pRec->uTemp = 6;
3552 }else if( pRec->flags & MEM_Real ){
3553 nHdr++;
3554 nData += 8;
3555 pRec->uTemp = 7;
3556 }else{
3557 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
3558 assert( pRec->n>=0 );
3559 len = (u32)pRec->n;
3560 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
3561 if( pRec->flags & MEM_Zero ){
3562 serial_type += pRec->u.nZero*2;
3563 if( nData ){
3564 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
3565 len += pRec->u.nZero;
3566 }else{
3567 nZero += pRec->u.nZero;
3570 nData += len;
3571 nHdr += sqlite3VarintLen(serial_type);
3572 pRec->uTemp = serial_type;
3574 if( pRec==pData0 ) break;
3575 pRec--;
3576 }while(1);
3578 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
3579 ** which determines the total number of bytes in the header. The varint
3580 ** value is the size of the header in bytes including the size varint
3581 ** itself. */
3582 testcase( nHdr==126 );
3583 testcase( nHdr==127 );
3584 if( nHdr<=126 ){
3585 /* The common case */
3586 nHdr += 1;
3587 }else{
3588 /* Rare case of a really large header */
3589 nVarint = sqlite3VarintLen(nHdr);
3590 nHdr += nVarint;
3591 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
3593 nByte = nHdr+nData;
3595 /* Make sure the output register has a buffer large enough to store
3596 ** the new record. The output register (pOp->p3) is not allowed to
3597 ** be one of the input registers (because the following call to
3598 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
3600 if( nByte+nZero<=pOut->szMalloc ){
3601 /* The output register is already large enough to hold the record.
3602 ** No error checks or buffer enlargement is required */
3603 pOut->z = pOut->zMalloc;
3604 }else{
3605 /* Need to make sure that the output is not too big and then enlarge
3606 ** the output register to hold the full result */
3607 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3608 goto too_big;
3610 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
3611 goto no_mem;
3614 pOut->n = (int)nByte;
3615 pOut->flags = MEM_Blob;
3616 if( nZero ){
3617 pOut->u.nZero = nZero;
3618 pOut->flags |= MEM_Zero;
3620 UPDATE_MAX_BLOBSIZE(pOut);
3621 zHdr = (u8 *)pOut->z;
3622 zPayload = zHdr + nHdr;
3624 /* Write the record */
3625 if( nHdr<0x80 ){
3626 *(zHdr++) = nHdr;
3627 }else{
3628 zHdr += sqlite3PutVarint(zHdr,nHdr);
3630 assert( pData0<=pLast );
3631 pRec = pData0;
3632 while( 1 /*exit-by-break*/ ){
3633 serial_type = pRec->uTemp;
3634 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
3635 ** additional varints, one per column.
3636 ** EVIDENCE-OF: R-64536-51728 The values for each column in the record
3637 ** immediately follow the header. */
3638 if( serial_type<=7 ){
3639 *(zHdr++) = serial_type;
3640 if( serial_type==0 ){
3641 /* NULL value. No change in zPayload */
3642 }else{
3643 u64 v;
3644 if( serial_type==7 ){
3645 assert( sizeof(v)==sizeof(pRec->u.r) );
3646 memcpy(&v, &pRec->u.r, sizeof(v));
3647 swapMixedEndianFloat(v);
3648 }else{
3649 v = pRec->u.i;
3651 len = sqlite3SmallTypeSizes[serial_type];
3652 assert( len>=1 && len<=8 && len!=5 && len!=7 );
3653 switch( len ){
3654 default: zPayload[7] = (u8)(v&0xff); v >>= 8;
3655 zPayload[6] = (u8)(v&0xff); v >>= 8;
3656 case 6: zPayload[5] = (u8)(v&0xff); v >>= 8;
3657 zPayload[4] = (u8)(v&0xff); v >>= 8;
3658 case 4: zPayload[3] = (u8)(v&0xff); v >>= 8;
3659 case 3: zPayload[2] = (u8)(v&0xff); v >>= 8;
3660 case 2: zPayload[1] = (u8)(v&0xff); v >>= 8;
3661 case 1: zPayload[0] = (u8)(v&0xff);
3663 zPayload += len;
3665 }else if( serial_type<0x80 ){
3666 *(zHdr++) = serial_type;
3667 if( serial_type>=14 && pRec->n>0 ){
3668 assert( pRec->z!=0 );
3669 memcpy(zPayload, pRec->z, pRec->n);
3670 zPayload += pRec->n;
3672 }else{
3673 zHdr += sqlite3PutVarint(zHdr, serial_type);
3674 if( pRec->n ){
3675 assert( pRec->z!=0 );
3676 memcpy(zPayload, pRec->z, pRec->n);
3677 zPayload += pRec->n;
3680 if( pRec==pLast ) break;
3681 pRec++;
3683 assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
3684 assert( nByte==(int)(zPayload - (u8*)pOut->z) );
3686 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
3687 REGISTER_TRACE(pOp->p3, pOut);
3688 break;
3691 /* Opcode: Count P1 P2 P3 * *
3692 ** Synopsis: r[P2]=count()
3694 ** Store the number of entries (an integer value) in the table or index
3695 ** opened by cursor P1 in register P2.
3697 ** If P3==0, then an exact count is obtained, which involves visiting
3698 ** every btree page of the table. But if P3 is non-zero, an estimate
3699 ** is returned based on the current cursor position.
3701 case OP_Count: { /* out2 */
3702 i64 nEntry;
3703 BtCursor *pCrsr;
3705 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
3706 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
3707 assert( pCrsr );
3708 if( pOp->p3 ){
3709 nEntry = sqlite3BtreeRowCountEst(pCrsr);
3710 }else{
3711 nEntry = 0; /* Not needed. Only used to silence a warning. */
3712 rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
3713 if( rc ) goto abort_due_to_error;
3715 pOut = out2Prerelease(p, pOp);
3716 pOut->u.i = nEntry;
3717 goto check_for_interrupt;
3720 /* Opcode: Savepoint P1 * * P4 *
3722 ** Open, release or rollback the savepoint named by parameter P4, depending
3723 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
3724 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
3725 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
3727 case OP_Savepoint: {
3728 int p1; /* Value of P1 operand */
3729 char *zName; /* Name of savepoint */
3730 int nName;
3731 Savepoint *pNew;
3732 Savepoint *pSavepoint;
3733 Savepoint *pTmp;
3734 int iSavepoint;
3735 int ii;
3737 p1 = pOp->p1;
3738 zName = pOp->p4.z;
3740 /* Assert that the p1 parameter is valid. Also that if there is no open
3741 ** transaction, then there cannot be any savepoints.
3743 assert( db->pSavepoint==0 || db->autoCommit==0 );
3744 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
3745 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
3746 assert( checkSavepointCount(db) );
3747 assert( p->bIsReader );
3749 if( p1==SAVEPOINT_BEGIN ){
3750 if( db->nVdbeWrite>0 ){
3751 /* A new savepoint cannot be created if there are active write
3752 ** statements (i.e. open read/write incremental blob handles).
3754 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
3755 rc = SQLITE_BUSY;
3756 }else{
3757 nName = sqlite3Strlen30(zName);
3759 #ifndef SQLITE_OMIT_VIRTUALTABLE
3760 /* This call is Ok even if this savepoint is actually a transaction
3761 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3762 ** If this is a transaction savepoint being opened, it is guaranteed
3763 ** that the db->aVTrans[] array is empty. */
3764 assert( db->autoCommit==0 || db->nVTrans==0 );
3765 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
3766 db->nStatement+db->nSavepoint);
3767 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3768 #endif
3770 /* Create a new savepoint structure. */
3771 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
3772 if( pNew ){
3773 pNew->zName = (char *)&pNew[1];
3774 memcpy(pNew->zName, zName, nName+1);
3776 /* If there is no open transaction, then mark this as a special
3777 ** "transaction savepoint". */
3778 if( db->autoCommit ){
3779 db->autoCommit = 0;
3780 db->isTransactionSavepoint = 1;
3781 }else{
3782 db->nSavepoint++;
3785 /* Link the new savepoint into the database handle's list. */
3786 pNew->pNext = db->pSavepoint;
3787 db->pSavepoint = pNew;
3788 pNew->nDeferredCons = db->nDeferredCons;
3789 pNew->nDeferredImmCons = db->nDeferredImmCons;
3792 }else{
3793 assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
3794 iSavepoint = 0;
3796 /* Find the named savepoint. If there is no such savepoint, then an
3797 ** an error is returned to the user. */
3798 for(
3799 pSavepoint = db->pSavepoint;
3800 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3801 pSavepoint = pSavepoint->pNext
3803 iSavepoint++;
3805 if( !pSavepoint ){
3806 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3807 rc = SQLITE_ERROR;
3808 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3809 /* It is not possible to release (commit) a savepoint if there are
3810 ** active write statements.
3812 sqlite3VdbeError(p, "cannot release savepoint - "
3813 "SQL statements in progress");
3814 rc = SQLITE_BUSY;
3815 }else{
3817 /* Determine whether or not this is a transaction savepoint. If so,
3818 ** and this is a RELEASE command, then the current transaction
3819 ** is committed.
3821 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3822 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3823 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3824 goto vdbe_return;
3826 db->autoCommit = 1;
3827 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3828 p->pc = (int)(pOp - aOp);
3829 db->autoCommit = 0;
3830 p->rc = rc = SQLITE_BUSY;
3831 goto vdbe_return;
3833 rc = p->rc;
3834 if( rc ){
3835 db->autoCommit = 0;
3836 }else{
3837 db->isTransactionSavepoint = 0;
3839 }else{
3840 int isSchemaChange;
3841 iSavepoint = db->nSavepoint - iSavepoint - 1;
3842 if( p1==SAVEPOINT_ROLLBACK ){
3843 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3844 for(ii=0; ii<db->nDb; ii++){
3845 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3846 SQLITE_ABORT_ROLLBACK,
3847 isSchemaChange==0);
3848 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3850 }else{
3851 assert( p1==SAVEPOINT_RELEASE );
3852 isSchemaChange = 0;
3854 for(ii=0; ii<db->nDb; ii++){
3855 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3856 if( rc!=SQLITE_OK ){
3857 goto abort_due_to_error;
3860 if( isSchemaChange ){
3861 sqlite3ExpirePreparedStatements(db, 0);
3862 sqlite3ResetAllSchemasOfConnection(db);
3863 db->mDbFlags |= DBFLAG_SchemaChange;
3866 if( rc ) goto abort_due_to_error;
3868 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3869 ** savepoints nested inside of the savepoint being operated on. */
3870 while( db->pSavepoint!=pSavepoint ){
3871 pTmp = db->pSavepoint;
3872 db->pSavepoint = pTmp->pNext;
3873 sqlite3DbFree(db, pTmp);
3874 db->nSavepoint--;
3877 /* If it is a RELEASE, then destroy the savepoint being operated on
3878 ** too. If it is a ROLLBACK TO, then set the number of deferred
3879 ** constraint violations present in the database to the value stored
3880 ** when the savepoint was created. */
3881 if( p1==SAVEPOINT_RELEASE ){
3882 assert( pSavepoint==db->pSavepoint );
3883 db->pSavepoint = pSavepoint->pNext;
3884 sqlite3DbFree(db, pSavepoint);
3885 if( !isTransaction ){
3886 db->nSavepoint--;
3888 }else{
3889 assert( p1==SAVEPOINT_ROLLBACK );
3890 db->nDeferredCons = pSavepoint->nDeferredCons;
3891 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3894 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3895 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3896 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3900 if( rc ) goto abort_due_to_error;
3901 if( p->eVdbeState==VDBE_HALT_STATE ){
3902 rc = SQLITE_DONE;
3903 goto vdbe_return;
3905 break;
3908 /* Opcode: AutoCommit P1 P2 * * *
3910 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3911 ** back any currently active btree transactions. If there are any active
3912 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3913 ** there are active writing VMs or active VMs that use shared cache.
3915 ** This instruction causes the VM to halt.
3917 case OP_AutoCommit: {
3918 int desiredAutoCommit;
3919 int iRollback;
3921 desiredAutoCommit = pOp->p1;
3922 iRollback = pOp->p2;
3923 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3924 assert( desiredAutoCommit==1 || iRollback==0 );
3925 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3926 assert( p->bIsReader );
3928 if( desiredAutoCommit!=db->autoCommit ){
3929 if( iRollback ){
3930 assert( desiredAutoCommit==1 );
3931 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3932 db->autoCommit = 1;
3933 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3934 /* If this instruction implements a COMMIT and other VMs are writing
3935 ** return an error indicating that the other VMs must complete first.
3937 sqlite3VdbeError(p, "cannot commit transaction - "
3938 "SQL statements in progress");
3939 rc = SQLITE_BUSY;
3940 goto abort_due_to_error;
3941 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3942 goto vdbe_return;
3943 }else{
3944 db->autoCommit = (u8)desiredAutoCommit;
3946 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3947 p->pc = (int)(pOp - aOp);
3948 db->autoCommit = (u8)(1-desiredAutoCommit);
3949 p->rc = rc = SQLITE_BUSY;
3950 goto vdbe_return;
3952 sqlite3CloseSavepoints(db);
3953 if( p->rc==SQLITE_OK ){
3954 rc = SQLITE_DONE;
3955 }else{
3956 rc = SQLITE_ERROR;
3958 goto vdbe_return;
3959 }else{
3960 sqlite3VdbeError(p,
3961 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3962 (iRollback)?"cannot rollback - no transaction is active":
3963 "cannot commit - no transaction is active"));
3965 rc = SQLITE_ERROR;
3966 goto abort_due_to_error;
3968 /*NOTREACHED*/ assert(0);
3971 /* Opcode: Transaction P1 P2 P3 P4 P5
3973 ** Begin a transaction on database P1 if a transaction is not already
3974 ** active.
3975 ** If P2 is non-zero, then a write-transaction is started, or if a
3976 ** read-transaction is already active, it is upgraded to a write-transaction.
3977 ** If P2 is zero, then a read-transaction is started. If P2 is 2 or more
3978 ** then an exclusive transaction is started.
3980 ** P1 is the index of the database file on which the transaction is
3981 ** started. Index 0 is the main database file and index 1 is the
3982 ** file used for temporary tables. Indices of 2 or more are used for
3983 ** attached databases.
3985 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3986 ** true (this flag is set if the Vdbe may modify more than one row and may
3987 ** throw an ABORT exception), a statement transaction may also be opened.
3988 ** More specifically, a statement transaction is opened iff the database
3989 ** connection is currently not in autocommit mode, or if there are other
3990 ** active statements. A statement transaction allows the changes made by this
3991 ** VDBE to be rolled back after an error without having to roll back the
3992 ** entire transaction. If no error is encountered, the statement transaction
3993 ** will automatically commit when the VDBE halts.
3995 ** If P5!=0 then this opcode also checks the schema cookie against P3
3996 ** and the schema generation counter against P4.
3997 ** The cookie changes its value whenever the database schema changes.
3998 ** This operation is used to detect when that the cookie has changed
3999 ** and that the current process needs to reread the schema. If the schema
4000 ** cookie in P3 differs from the schema cookie in the database header or
4001 ** if the schema generation counter in P4 differs from the current
4002 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
4003 ** halts. The sqlite3_step() wrapper function might then reprepare the
4004 ** statement and rerun it from the beginning.
4006 case OP_Transaction: {
4007 Btree *pBt;
4008 Db *pDb;
4009 int iMeta = 0;
4011 assert( p->bIsReader );
4012 assert( p->readOnly==0 || pOp->p2==0 );
4013 assert( pOp->p2>=0 && pOp->p2<=2 );
4014 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4015 assert( DbMaskTest(p->btreeMask, pOp->p1) );
4016 assert( rc==SQLITE_OK );
4017 if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
4018 if( db->flags & SQLITE_QueryOnly ){
4019 /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
4020 rc = SQLITE_READONLY;
4021 }else{
4022 /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
4023 ** transaction */
4024 rc = SQLITE_CORRUPT;
4026 goto abort_due_to_error;
4028 pDb = &db->aDb[pOp->p1];
4029 pBt = pDb->pBt;
4031 if( pBt ){
4032 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
4033 testcase( rc==SQLITE_BUSY_SNAPSHOT );
4034 testcase( rc==SQLITE_BUSY_RECOVERY );
4035 if( rc!=SQLITE_OK ){
4036 if( (rc&0xff)==SQLITE_BUSY ){
4037 p->pc = (int)(pOp - aOp);
4038 p->rc = rc;
4039 goto vdbe_return;
4041 goto abort_due_to_error;
4044 if( p->usesStmtJournal
4045 && pOp->p2
4046 && (db->autoCommit==0 || db->nVdbeRead>1)
4048 assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
4049 if( p->iStatement==0 ){
4050 assert( db->nStatement>=0 && db->nSavepoint>=0 );
4051 db->nStatement++;
4052 p->iStatement = db->nSavepoint + db->nStatement;
4055 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
4056 if( rc==SQLITE_OK ){
4057 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
4060 /* Store the current value of the database handles deferred constraint
4061 ** counter. If the statement transaction needs to be rolled back,
4062 ** the value of this counter needs to be restored too. */
4063 p->nStmtDefCons = db->nDeferredCons;
4064 p->nStmtDefImmCons = db->nDeferredImmCons;
4067 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
4068 if( rc==SQLITE_OK
4069 && pOp->p5
4070 && (iMeta!=pOp->p3 || pDb->pSchema->iGeneration!=pOp->p4.i)
4073 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
4074 ** version is checked to ensure that the schema has not changed since the
4075 ** SQL statement was prepared.
4077 sqlite3DbFree(db, p->zErrMsg);
4078 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
4079 /* If the schema-cookie from the database file matches the cookie
4080 ** stored with the in-memory representation of the schema, do
4081 ** not reload the schema from the database file.
4083 ** If virtual-tables are in use, this is not just an optimization.
4084 ** Often, v-tables store their data in other SQLite tables, which
4085 ** are queried from within xNext() and other v-table methods using
4086 ** prepared queries. If such a query is out-of-date, we do not want to
4087 ** discard the database schema, as the user code implementing the
4088 ** v-table would have to be ready for the sqlite3_vtab structure itself
4089 ** to be invalidated whenever sqlite3_step() is called from within
4090 ** a v-table method.
4092 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
4093 sqlite3ResetOneSchema(db, pOp->p1);
4095 p->expired = 1;
4096 rc = SQLITE_SCHEMA;
4098 /* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
4099 ** from being modified in sqlite3VdbeHalt(). If this statement is
4100 ** reprepared, changeCntOn will be set again. */
4101 p->changeCntOn = 0;
4103 if( rc ) goto abort_due_to_error;
4104 break;
4107 /* Opcode: ReadCookie P1 P2 P3 * *
4109 ** Read cookie number P3 from database P1 and write it into register P2.
4110 ** P3==1 is the schema version. P3==2 is the database format.
4111 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
4112 ** the main database file and P1==1 is the database file used to store
4113 ** temporary tables.
4115 ** There must be a read-lock on the database (either a transaction
4116 ** must be started or there must be an open cursor) before
4117 ** executing this instruction.
4119 case OP_ReadCookie: { /* out2 */
4120 int iMeta;
4121 int iDb;
4122 int iCookie;
4124 assert( p->bIsReader );
4125 iDb = pOp->p1;
4126 iCookie = pOp->p3;
4127 assert( pOp->p3<SQLITE_N_BTREE_META );
4128 assert( iDb>=0 && iDb<db->nDb );
4129 assert( db->aDb[iDb].pBt!=0 );
4130 assert( DbMaskTest(p->btreeMask, iDb) );
4132 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
4133 pOut = out2Prerelease(p, pOp);
4134 pOut->u.i = iMeta;
4135 break;
4138 /* Opcode: SetCookie P1 P2 P3 * P5
4140 ** Write the integer value P3 into cookie number P2 of database P1.
4141 ** P2==1 is the schema version. P2==2 is the database format.
4142 ** P2==3 is the recommended pager cache
4143 ** size, and so forth. P1==0 is the main database file and P1==1 is the
4144 ** database file used to store temporary tables.
4146 ** A transaction must be started before executing this opcode.
4148 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
4149 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
4150 ** has P5 set to 1, so that the internal schema version will be different
4151 ** from the database schema version, resulting in a schema reset.
4153 case OP_SetCookie: {
4154 Db *pDb;
4156 sqlite3VdbeIncrWriteCounter(p, 0);
4157 assert( pOp->p2<SQLITE_N_BTREE_META );
4158 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4159 assert( DbMaskTest(p->btreeMask, pOp->p1) );
4160 assert( p->readOnly==0 );
4161 pDb = &db->aDb[pOp->p1];
4162 assert( pDb->pBt!=0 );
4163 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
4164 /* See note about index shifting on OP_ReadCookie */
4165 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
4166 if( pOp->p2==BTREE_SCHEMA_VERSION ){
4167 /* When the schema cookie changes, record the new cookie internally */
4168 *(u32*)&pDb->pSchema->schema_cookie = *(u32*)&pOp->p3 - pOp->p5;
4169 db->mDbFlags |= DBFLAG_SchemaChange;
4170 sqlite3FkClearTriggerCache(db, pOp->p1);
4171 }else if( pOp->p2==BTREE_FILE_FORMAT ){
4172 /* Record changes in the file format */
4173 pDb->pSchema->file_format = pOp->p3;
4175 if( pOp->p1==1 ){
4176 /* Invalidate all prepared statements whenever the TEMP database
4177 ** schema is changed. Ticket #1644 */
4178 sqlite3ExpirePreparedStatements(db, 0);
4179 p->expired = 0;
4181 if( rc ) goto abort_due_to_error;
4182 break;
4185 /* Opcode: OpenRead P1 P2 P3 P4 P5
4186 ** Synopsis: root=P2 iDb=P3
4188 ** Open a read-only cursor for the database table whose root page is
4189 ** P2 in a database file. The database file is determined by P3.
4190 ** P3==0 means the main database, P3==1 means the database used for
4191 ** temporary tables, and P3>1 means used the corresponding attached
4192 ** database. Give the new cursor an identifier of P1. The P1
4193 ** values need not be contiguous but all P1 values should be small integers.
4194 ** It is an error for P1 to be negative.
4196 ** Allowed P5 bits:
4197 ** <ul>
4198 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4199 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4200 ** of OP_SeekLE/OP_IdxLT)
4201 ** </ul>
4203 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4204 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4205 ** object, then table being opened must be an [index b-tree] where the
4206 ** KeyInfo object defines the content and collating
4207 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4208 ** value, then the table being opened must be a [table b-tree] with a
4209 ** number of columns no less than the value of P4.
4211 ** See also: OpenWrite, ReopenIdx
4213 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
4214 ** Synopsis: root=P2 iDb=P3
4216 ** The ReopenIdx opcode works like OP_OpenRead except that it first
4217 ** checks to see if the cursor on P1 is already open on the same
4218 ** b-tree and if it is this opcode becomes a no-op. In other words,
4219 ** if the cursor is already open, do not reopen it.
4221 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
4222 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
4223 ** be the same as every other ReopenIdx or OpenRead for the same cursor
4224 ** number.
4226 ** Allowed P5 bits:
4227 ** <ul>
4228 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4229 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4230 ** of OP_SeekLE/OP_IdxLT)
4231 ** </ul>
4233 ** See also: OP_OpenRead, OP_OpenWrite
4235 /* Opcode: OpenWrite P1 P2 P3 P4 P5
4236 ** Synopsis: root=P2 iDb=P3
4238 ** Open a read/write cursor named P1 on the table or index whose root
4239 ** page is P2 (or whose root page is held in register P2 if the
4240 ** OPFLAG_P2ISREG bit is set in P5 - see below).
4242 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4243 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4244 ** object, then table being opened must be an [index b-tree] where the
4245 ** KeyInfo object defines the content and collating
4246 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4247 ** value, then the table being opened must be a [table b-tree] with a
4248 ** number of columns no less than the value of P4.
4250 ** Allowed P5 bits:
4251 ** <ul>
4252 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4253 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4254 ** of OP_SeekLE/OP_IdxLT)
4255 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
4256 ** and subsequently delete entries in an index btree. This is a
4257 ** hint to the storage engine that the storage engine is allowed to
4258 ** ignore. The hint is not used by the official SQLite b*tree storage
4259 ** engine, but is used by COMDB2.
4260 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
4261 ** as the root page, not the value of P2 itself.
4262 ** </ul>
4264 ** This instruction works like OpenRead except that it opens the cursor
4265 ** in read/write mode.
4267 ** See also: OP_OpenRead, OP_ReopenIdx
4269 case OP_ReopenIdx: { /* ncycle */
4270 int nField;
4271 KeyInfo *pKeyInfo;
4272 u32 p2;
4273 int iDb;
4274 int wrFlag;
4275 Btree *pX;
4276 VdbeCursor *pCur;
4277 Db *pDb;
4279 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4280 assert( pOp->p4type==P4_KEYINFO );
4281 pCur = p->apCsr[pOp->p1];
4282 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
4283 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
4284 assert( pCur->eCurType==CURTYPE_BTREE );
4285 sqlite3BtreeClearCursor(pCur->uc.pCursor);
4286 goto open_cursor_set_hints;
4288 /* If the cursor is not currently open or is open on a different
4289 ** index, then fall through into OP_OpenRead to force a reopen */
4290 case OP_OpenRead: /* ncycle */
4291 case OP_OpenWrite:
4293 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4294 assert( p->bIsReader );
4295 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
4296 || p->readOnly==0 );
4298 if( p->expired==1 ){
4299 rc = SQLITE_ABORT_ROLLBACK;
4300 goto abort_due_to_error;
4303 nField = 0;
4304 pKeyInfo = 0;
4305 p2 = (u32)pOp->p2;
4306 iDb = pOp->p3;
4307 assert( iDb>=0 && iDb<db->nDb );
4308 assert( DbMaskTest(p->btreeMask, iDb) );
4309 pDb = &db->aDb[iDb];
4310 pX = pDb->pBt;
4311 assert( pX!=0 );
4312 if( pOp->opcode==OP_OpenWrite ){
4313 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
4314 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
4315 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4316 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
4317 p->minWriteFileFormat = pDb->pSchema->file_format;
4319 }else{
4320 wrFlag = 0;
4322 if( pOp->p5 & OPFLAG_P2ISREG ){
4323 assert( p2>0 );
4324 assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
4325 assert( pOp->opcode==OP_OpenWrite );
4326 pIn2 = &aMem[p2];
4327 assert( memIsValid(pIn2) );
4328 assert( (pIn2->flags & MEM_Int)!=0 );
4329 sqlite3VdbeMemIntegerify(pIn2);
4330 p2 = (int)pIn2->u.i;
4331 /* The p2 value always comes from a prior OP_CreateBtree opcode and
4332 ** that opcode will always set the p2 value to 2 or more or else fail.
4333 ** If there were a failure, the prepared statement would have halted
4334 ** before reaching this instruction. */
4335 assert( p2>=2 );
4337 if( pOp->p4type==P4_KEYINFO ){
4338 pKeyInfo = pOp->p4.pKeyInfo;
4339 assert( pKeyInfo->enc==ENC(db) );
4340 assert( pKeyInfo->db==db );
4341 nField = pKeyInfo->nAllField;
4342 }else if( pOp->p4type==P4_INT32 ){
4343 nField = pOp->p4.i;
4345 assert( pOp->p1>=0 );
4346 assert( nField>=0 );
4347 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
4348 pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
4349 if( pCur==0 ) goto no_mem;
4350 pCur->iDb = iDb;
4351 pCur->nullRow = 1;
4352 pCur->isOrdered = 1;
4353 pCur->pgnoRoot = p2;
4354 #ifdef SQLITE_DEBUG
4355 pCur->wrFlag = wrFlag;
4356 #endif
4357 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
4358 pCur->pKeyInfo = pKeyInfo;
4359 /* Set the VdbeCursor.isTable variable. Previous versions of
4360 ** SQLite used to check if the root-page flags were sane at this point
4361 ** and report database corruption if they were not, but this check has
4362 ** since moved into the btree layer. */
4363 pCur->isTable = pOp->p4type!=P4_KEYINFO;
4365 open_cursor_set_hints:
4366 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
4367 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
4368 testcase( pOp->p5 & OPFLAG_BULKCSR );
4369 testcase( pOp->p2 & OPFLAG_SEEKEQ );
4370 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
4371 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
4372 if( rc ) goto abort_due_to_error;
4373 break;
4376 /* Opcode: OpenDup P1 P2 * * *
4378 ** Open a new cursor P1 that points to the same ephemeral table as
4379 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
4380 ** opcode. Only ephemeral cursors may be duplicated.
4382 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
4384 case OP_OpenDup: { /* ncycle */
4385 VdbeCursor *pOrig; /* The original cursor to be duplicated */
4386 VdbeCursor *pCx; /* The new cursor */
4388 pOrig = p->apCsr[pOp->p2];
4389 assert( pOrig );
4390 assert( pOrig->isEphemeral ); /* Only ephemeral cursors can be duplicated */
4392 pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
4393 if( pCx==0 ) goto no_mem;
4394 pCx->nullRow = 1;
4395 pCx->isEphemeral = 1;
4396 pCx->pKeyInfo = pOrig->pKeyInfo;
4397 pCx->isTable = pOrig->isTable;
4398 pCx->pgnoRoot = pOrig->pgnoRoot;
4399 pCx->isOrdered = pOrig->isOrdered;
4400 pCx->ub.pBtx = pOrig->ub.pBtx;
4401 pCx->noReuse = 1;
4402 pOrig->noReuse = 1;
4403 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4404 pCx->pKeyInfo, pCx->uc.pCursor);
4405 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
4406 ** opened for a database. Since there is already an open cursor when this
4407 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
4408 assert( rc==SQLITE_OK );
4409 break;
4413 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5
4414 ** Synopsis: nColumn=P2
4416 ** Open a new cursor P1 to a transient table.
4417 ** The cursor is always opened read/write even if
4418 ** the main database is read-only. The ephemeral
4419 ** table is deleted automatically when the cursor is closed.
4421 ** If the cursor P1 is already opened on an ephemeral table, the table
4422 ** is cleared (all content is erased).
4424 ** P2 is the number of columns in the ephemeral table.
4425 ** The cursor points to a BTree table if P4==0 and to a BTree index
4426 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
4427 ** that defines the format of keys in the index.
4429 ** The P5 parameter can be a mask of the BTREE_* flags defined
4430 ** in btree.h. These flags control aspects of the operation of
4431 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
4432 ** added automatically.
4434 ** If P3 is positive, then reg[P3] is modified slightly so that it
4435 ** can be used as zero-length data for OP_Insert. This is an optimization
4436 ** that avoids an extra OP_Blob opcode to initialize that register.
4438 /* Opcode: OpenAutoindex P1 P2 * P4 *
4439 ** Synopsis: nColumn=P2
4441 ** This opcode works the same as OP_OpenEphemeral. It has a
4442 ** different name to distinguish its use. Tables created using
4443 ** by this opcode will be used for automatically created transient
4444 ** indices in joins.
4446 case OP_OpenAutoindex: /* ncycle */
4447 case OP_OpenEphemeral: { /* ncycle */
4448 VdbeCursor *pCx;
4449 KeyInfo *pKeyInfo;
4451 static const int vfsFlags =
4452 SQLITE_OPEN_READWRITE |
4453 SQLITE_OPEN_CREATE |
4454 SQLITE_OPEN_EXCLUSIVE |
4455 SQLITE_OPEN_DELETEONCLOSE |
4456 SQLITE_OPEN_TRANSIENT_DB;
4457 assert( pOp->p1>=0 );
4458 assert( pOp->p2>=0 );
4459 if( pOp->p3>0 ){
4460 /* Make register reg[P3] into a value that can be used as the data
4461 ** form sqlite3BtreeInsert() where the length of the data is zero. */
4462 assert( pOp->p2==0 ); /* Only used when number of columns is zero */
4463 assert( pOp->opcode==OP_OpenEphemeral );
4464 assert( aMem[pOp->p3].flags & MEM_Null );
4465 aMem[pOp->p3].n = 0;
4466 aMem[pOp->p3].z = "";
4468 pCx = p->apCsr[pOp->p1];
4469 if( pCx && !pCx->noReuse && ALWAYS(pOp->p2<=pCx->nField) ){
4470 /* If the ephemeral table is already open and has no duplicates from
4471 ** OP_OpenDup, then erase all existing content so that the table is
4472 ** empty again, rather than creating a new table. */
4473 assert( pCx->isEphemeral );
4474 pCx->seqCount = 0;
4475 pCx->cacheStatus = CACHE_STALE;
4476 rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
4477 }else{
4478 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
4479 if( pCx==0 ) goto no_mem;
4480 pCx->isEphemeral = 1;
4481 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
4482 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
4483 vfsFlags);
4484 if( rc==SQLITE_OK ){
4485 rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
4486 if( rc==SQLITE_OK ){
4487 /* If a transient index is required, create it by calling
4488 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
4489 ** opening it. If a transient table is required, just use the
4490 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
4492 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
4493 assert( pOp->p4type==P4_KEYINFO );
4494 rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
4495 BTREE_BLOBKEY | pOp->p5);
4496 if( rc==SQLITE_OK ){
4497 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
4498 assert( pKeyInfo->db==db );
4499 assert( pKeyInfo->enc==ENC(db) );
4500 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4501 pKeyInfo, pCx->uc.pCursor);
4503 pCx->isTable = 0;
4504 }else{
4505 pCx->pgnoRoot = SCHEMA_ROOT;
4506 rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
4507 0, pCx->uc.pCursor);
4508 pCx->isTable = 1;
4511 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
4512 if( rc ){
4513 sqlite3BtreeClose(pCx->ub.pBtx);
4517 if( rc ) goto abort_due_to_error;
4518 pCx->nullRow = 1;
4519 break;
4522 /* Opcode: SorterOpen P1 P2 P3 P4 *
4524 ** This opcode works like OP_OpenEphemeral except that it opens
4525 ** a transient index that is specifically designed to sort large
4526 ** tables using an external merge-sort algorithm.
4528 ** If argument P3 is non-zero, then it indicates that the sorter may
4529 ** assume that a stable sort considering the first P3 fields of each
4530 ** key is sufficient to produce the required results.
4532 case OP_SorterOpen: {
4533 VdbeCursor *pCx;
4535 assert( pOp->p1>=0 );
4536 assert( pOp->p2>=0 );
4537 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
4538 if( pCx==0 ) goto no_mem;
4539 pCx->pKeyInfo = pOp->p4.pKeyInfo;
4540 assert( pCx->pKeyInfo->db==db );
4541 assert( pCx->pKeyInfo->enc==ENC(db) );
4542 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4543 if( rc ) goto abort_due_to_error;
4544 break;
4547 /* Opcode: SequenceTest P1 P2 * * *
4548 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4550 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4551 ** to P2. Regardless of whether or not the jump is taken, increment the
4552 ** the sequence value.
4554 case OP_SequenceTest: {
4555 VdbeCursor *pC;
4556 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4557 pC = p->apCsr[pOp->p1];
4558 assert( isSorter(pC) );
4559 if( (pC->seqCount++)==0 ){
4560 goto jump_to_p2;
4562 break;
4565 /* Opcode: OpenPseudo P1 P2 P3 * *
4566 ** Synopsis: P3 columns in r[P2]
4568 ** Open a new cursor that points to a fake table that contains a single
4569 ** row of data. The content of that one row is the content of memory
4570 ** register P2. In other words, cursor P1 becomes an alias for the
4571 ** MEM_Blob content contained in register P2.
4573 ** A pseudo-table created by this opcode is used to hold a single
4574 ** row output from the sorter so that the row can be decomposed into
4575 ** individual columns using the OP_Column opcode. The OP_Column opcode
4576 ** is the only cursor opcode that works with a pseudo-table.
4578 ** P3 is the number of fields in the records that will be stored by
4579 ** the pseudo-table.
4581 case OP_OpenPseudo: {
4582 VdbeCursor *pCx;
4584 assert( pOp->p1>=0 );
4585 assert( pOp->p3>=0 );
4586 pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
4587 if( pCx==0 ) goto no_mem;
4588 pCx->nullRow = 1;
4589 pCx->seekResult = pOp->p2;
4590 pCx->isTable = 1;
4591 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4592 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
4593 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4594 ** which is a performance optimization */
4595 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4596 assert( pOp->p5==0 );
4597 break;
4600 /* Opcode: Close P1 * * * *
4602 ** Close a cursor previously opened as P1. If P1 is not
4603 ** currently open, this instruction is a no-op.
4605 case OP_Close: { /* ncycle */
4606 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4607 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4608 p->apCsr[pOp->p1] = 0;
4609 break;
4612 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4613 /* Opcode: ColumnsUsed P1 * * P4 *
4615 ** This opcode (which only exists if SQLite was compiled with
4616 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4617 ** table or index for cursor P1 are used. P4 is a 64-bit integer
4618 ** (P4_INT64) in which the first 63 bits are one for each of the
4619 ** first 63 columns of the table or index that are actually used
4620 ** by the cursor. The high-order bit is set if any column after
4621 ** the 64th is used.
4623 case OP_ColumnsUsed: {
4624 VdbeCursor *pC;
4625 pC = p->apCsr[pOp->p1];
4626 assert( pC->eCurType==CURTYPE_BTREE );
4627 pC->maskUsed = *(u64*)pOp->p4.pI64;
4628 break;
4630 #endif
4632 /* Opcode: SeekGE P1 P2 P3 P4 *
4633 ** Synopsis: key=r[P3@P4]
4635 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4636 ** use the value in register P3 as the key. If cursor P1 refers
4637 ** to an SQL index, then P3 is the first in an array of P4 registers
4638 ** that are used as an unpacked index key.
4640 ** Reposition cursor P1 so that it points to the smallest entry that
4641 ** is greater than or equal to the key value. If there are no records
4642 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4644 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4645 ** opcode will either land on a record that exactly matches the key, or
4646 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4647 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4648 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4649 ** IdxGT opcode will be used on subsequent loop iterations. The
4650 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4651 ** is an equality search.
4653 ** This opcode leaves the cursor configured to move in forward order,
4654 ** from the beginning toward the end. In other words, the cursor is
4655 ** configured to use Next, not Prev.
4657 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4659 /* Opcode: SeekGT P1 P2 P3 P4 *
4660 ** Synopsis: key=r[P3@P4]
4662 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4663 ** use the value in register P3 as a key. If cursor P1 refers
4664 ** to an SQL index, then P3 is the first in an array of P4 registers
4665 ** that are used as an unpacked index key.
4667 ** Reposition cursor P1 so that it points to the smallest entry that
4668 ** is greater than the key value. If there are no records greater than
4669 ** the key and P2 is not zero, then jump to P2.
4671 ** This opcode leaves the cursor configured to move in forward order,
4672 ** from the beginning toward the end. In other words, the cursor is
4673 ** configured to use Next, not Prev.
4675 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4677 /* Opcode: SeekLT P1 P2 P3 P4 *
4678 ** Synopsis: key=r[P3@P4]
4680 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4681 ** use the value in register P3 as a key. If cursor P1 refers
4682 ** to an SQL index, then P3 is the first in an array of P4 registers
4683 ** that are used as an unpacked index key.
4685 ** Reposition cursor P1 so that it points to the largest entry that
4686 ** is less than the key value. If there are no records less than
4687 ** the key and P2 is not zero, then jump to P2.
4689 ** This opcode leaves the cursor configured to move in reverse order,
4690 ** from the end toward the beginning. In other words, the cursor is
4691 ** configured to use Prev, not Next.
4693 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4695 /* Opcode: SeekLE P1 P2 P3 P4 *
4696 ** Synopsis: key=r[P3@P4]
4698 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4699 ** use the value in register P3 as a key. If cursor P1 refers
4700 ** to an SQL index, then P3 is the first in an array of P4 registers
4701 ** that are used as an unpacked index key.
4703 ** Reposition cursor P1 so that it points to the largest entry that
4704 ** is less than or equal to the key value. If there are no records
4705 ** less than or equal to the key and P2 is not zero, then jump to P2.
4707 ** This opcode leaves the cursor configured to move in reverse order,
4708 ** from the end toward the beginning. In other words, the cursor is
4709 ** configured to use Prev, not Next.
4711 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4712 ** opcode will either land on a record that exactly matches the key, or
4713 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4714 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4715 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4716 ** IdxGE opcode will be used on subsequent loop iterations. The
4717 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4718 ** is an equality search.
4720 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4722 case OP_SeekLT: /* jump, in3, group, ncycle */
4723 case OP_SeekLE: /* jump, in3, group, ncycle */
4724 case OP_SeekGE: /* jump, in3, group, ncycle */
4725 case OP_SeekGT: { /* jump, in3, group, ncycle */
4726 int res; /* Comparison result */
4727 int oc; /* Opcode */
4728 VdbeCursor *pC; /* The cursor to seek */
4729 UnpackedRecord r; /* The key to seek for */
4730 int nField; /* Number of columns or fields in the key */
4731 i64 iKey; /* The rowid we are to seek to */
4732 int eqOnly; /* Only interested in == results */
4734 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4735 assert( pOp->p2!=0 );
4736 pC = p->apCsr[pOp->p1];
4737 assert( pC!=0 );
4738 assert( pC->eCurType==CURTYPE_BTREE );
4739 assert( OP_SeekLE == OP_SeekLT+1 );
4740 assert( OP_SeekGE == OP_SeekLT+2 );
4741 assert( OP_SeekGT == OP_SeekLT+3 );
4742 assert( pC->isOrdered );
4743 assert( pC->uc.pCursor!=0 );
4744 oc = pOp->opcode;
4745 eqOnly = 0;
4746 pC->nullRow = 0;
4747 #ifdef SQLITE_DEBUG
4748 pC->seekOp = pOp->opcode;
4749 #endif
4751 pC->deferredMoveto = 0;
4752 pC->cacheStatus = CACHE_STALE;
4753 if( pC->isTable ){
4754 u16 flags3, newType;
4755 /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4756 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4757 || CORRUPT_DB );
4759 /* The input value in P3 might be of any type: integer, real, string,
4760 ** blob, or NULL. But it needs to be an integer before we can do
4761 ** the seek, so convert it. */
4762 pIn3 = &aMem[pOp->p3];
4763 flags3 = pIn3->flags;
4764 if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4765 applyNumericAffinity(pIn3, 0);
4767 iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4768 newType = pIn3->flags; /* Record the type after applying numeric affinity */
4769 pIn3->flags = flags3; /* But convert the type back to its original */
4771 /* If the P3 value could not be converted into an integer without
4772 ** loss of information, then special processing is required... */
4773 if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4774 int c;
4775 if( (newType & MEM_Real)==0 ){
4776 if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4777 VdbeBranchTaken(1,2);
4778 goto jump_to_p2;
4779 }else{
4780 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4781 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4782 goto seek_not_found;
4785 c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
4787 /* If the approximation iKey is larger than the actual real search
4788 ** term, substitute >= for > and < for <=. e.g. if the search term
4789 ** is 4.9 and the integer approximation 5:
4791 ** (x > 4.9) -> (x >= 5)
4792 ** (x <= 4.9) -> (x < 5)
4794 if( c>0 ){
4795 assert( OP_SeekGE==(OP_SeekGT-1) );
4796 assert( OP_SeekLT==(OP_SeekLE-1) );
4797 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4798 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4801 /* If the approximation iKey is smaller than the actual real search
4802 ** term, substitute <= for < and > for >=. */
4803 else if( c<0 ){
4804 assert( OP_SeekLE==(OP_SeekLT+1) );
4805 assert( OP_SeekGT==(OP_SeekGE+1) );
4806 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4807 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4810 rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
4811 pC->movetoTarget = iKey; /* Used by OP_Delete */
4812 if( rc!=SQLITE_OK ){
4813 goto abort_due_to_error;
4815 }else{
4816 /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4817 ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4818 ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4819 ** with the same key.
4821 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4822 eqOnly = 1;
4823 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4824 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4825 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4826 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4827 assert( pOp[1].p1==pOp[0].p1 );
4828 assert( pOp[1].p2==pOp[0].p2 );
4829 assert( pOp[1].p3==pOp[0].p3 );
4830 assert( pOp[1].p4.i==pOp[0].p4.i );
4833 nField = pOp->p4.i;
4834 assert( pOp->p4type==P4_INT32 );
4835 assert( nField>0 );
4836 r.pKeyInfo = pC->pKeyInfo;
4837 r.nField = (u16)nField;
4839 /* The next line of code computes as follows, only faster:
4840 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
4841 ** r.default_rc = -1;
4842 ** }else{
4843 ** r.default_rc = +1;
4844 ** }
4846 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4847 assert( oc!=OP_SeekGT || r.default_rc==-1 );
4848 assert( oc!=OP_SeekLE || r.default_rc==-1 );
4849 assert( oc!=OP_SeekGE || r.default_rc==+1 );
4850 assert( oc!=OP_SeekLT || r.default_rc==+1 );
4852 r.aMem = &aMem[pOp->p3];
4853 #ifdef SQLITE_DEBUG
4855 int i;
4856 for(i=0; i<r.nField; i++){
4857 assert( memIsValid(&r.aMem[i]) );
4858 if( i>0 ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
4861 #endif
4862 r.eqSeen = 0;
4863 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
4864 if( rc!=SQLITE_OK ){
4865 goto abort_due_to_error;
4867 if( eqOnly && r.eqSeen==0 ){
4868 assert( res!=0 );
4869 goto seek_not_found;
4872 #ifdef SQLITE_TEST
4873 sqlite3_search_count++;
4874 #endif
4875 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
4876 if( res<0 || (res==0 && oc==OP_SeekGT) ){
4877 res = 0;
4878 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4879 if( rc!=SQLITE_OK ){
4880 if( rc==SQLITE_DONE ){
4881 rc = SQLITE_OK;
4882 res = 1;
4883 }else{
4884 goto abort_due_to_error;
4887 }else{
4888 res = 0;
4890 }else{
4891 assert( oc==OP_SeekLT || oc==OP_SeekLE );
4892 if( res>0 || (res==0 && oc==OP_SeekLT) ){
4893 res = 0;
4894 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4895 if( rc!=SQLITE_OK ){
4896 if( rc==SQLITE_DONE ){
4897 rc = SQLITE_OK;
4898 res = 1;
4899 }else{
4900 goto abort_due_to_error;
4903 }else{
4904 /* res might be negative because the table is empty. Check to
4905 ** see if this is the case.
4907 res = sqlite3BtreeEof(pC->uc.pCursor);
4910 seek_not_found:
4911 assert( pOp->p2>0 );
4912 VdbeBranchTaken(res!=0,2);
4913 if( res ){
4914 goto jump_to_p2;
4915 }else if( eqOnly ){
4916 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4917 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4919 break;
4923 /* Opcode: SeekScan P1 P2 * * P5
4924 ** Synopsis: Scan-ahead up to P1 rows
4926 ** This opcode is a prefix opcode to OP_SeekGE. In other words, this
4927 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4928 ** checked by assert() statements.
4930 ** This opcode uses the P1 through P4 operands of the subsequent
4931 ** OP_SeekGE. In the text that follows, the operands of the subsequent
4932 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4. Only
4933 ** the P1, P2 and P5 operands of this opcode are also used, and are called
4934 ** This.P1, This.P2 and This.P5.
4936 ** This opcode helps to optimize IN operators on a multi-column index
4937 ** where the IN operator is on the later terms of the index by avoiding
4938 ** unnecessary seeks on the btree, substituting steps to the next row
4939 ** of the b-tree instead. A correct answer is obtained if this opcode
4940 ** is omitted or is a no-op.
4942 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4943 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4944 ** to. Call this SeekGE.P3/P4 row the "target".
4946 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4947 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4949 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4950 ** might be the target row, or it might be near and slightly before the
4951 ** target row, or it might be after the target row. If the cursor is
4952 ** currently before the target row, then this opcode attempts to position
4953 ** the cursor on or after the target row by invoking sqlite3BtreeStep()
4954 ** on the cursor between 1 and This.P1 times.
4956 ** The This.P5 parameter is a flag that indicates what to do if the
4957 ** cursor ends up pointing at a valid row that is past the target
4958 ** row. If This.P5 is false (0) then a jump is made to SeekGE.P2. If
4959 ** This.P5 is true (non-zero) then a jump is made to This.P2. The P5==0
4960 ** case occurs when there are no inequality constraints to the right of
4961 ** the IN constraint. The jump to SeekGE.P2 ends the loop. The P5!=0 case
4962 ** occurs when there are inequality constraints to the right of the IN
4963 ** operator. In that case, the This.P2 will point either directly to or
4964 ** to setup code prior to the OP_IdxGT or OP_IdxGE opcode that checks for
4965 ** loop terminate.
4967 ** Possible outcomes from this opcode:<ol>
4969 ** <li> If the cursor is initially not pointed to any valid row, then
4970 ** fall through into the subsequent OP_SeekGE opcode.
4972 ** <li> If the cursor is left pointing to a row that is before the target
4973 ** row, even after making as many as This.P1 calls to
4974 ** sqlite3BtreeNext(), then also fall through into OP_SeekGE.
4976 ** <li> If the cursor is left pointing at the target row, either because it
4977 ** was at the target row to begin with or because one or more
4978 ** sqlite3BtreeNext() calls moved the cursor to the target row,
4979 ** then jump to This.P2..,
4981 ** <li> If the cursor started out before the target row and a call to
4982 ** to sqlite3BtreeNext() moved the cursor off the end of the index
4983 ** (indicating that the target row definitely does not exist in the
4984 ** btree) then jump to SeekGE.P2, ending the loop.
4986 ** <li> If the cursor ends up on a valid row that is past the target row
4987 ** (indicating that the target row does not exist in the btree) then
4988 ** jump to SeekOP.P2 if This.P5==0 or to This.P2 if This.P5>0.
4989 ** </ol>
4991 case OP_SeekScan: { /* ncycle */
4992 VdbeCursor *pC;
4993 int res;
4994 int nStep;
4995 UnpackedRecord r;
4997 assert( pOp[1].opcode==OP_SeekGE );
4999 /* If pOp->p5 is clear, then pOp->p2 points to the first instruction past the
5000 ** OP_IdxGT that follows the OP_SeekGE. Otherwise, it points to the first
5001 ** opcode past the OP_SeekGE itself. */
5002 assert( pOp->p2>=(int)(pOp-aOp)+2 );
5003 #ifdef SQLITE_DEBUG
5004 if( pOp->p5==0 ){
5005 /* There are no inequality constraints following the IN constraint. */
5006 assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
5007 assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
5008 assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
5009 assert( aOp[pOp->p2-1].opcode==OP_IdxGT
5010 || aOp[pOp->p2-1].opcode==OP_IdxGE );
5011 testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
5012 }else{
5013 /* There are inequality constraints. */
5014 assert( pOp->p2==(int)(pOp-aOp)+2 );
5015 assert( aOp[pOp->p2-1].opcode==OP_SeekGE );
5017 #endif
5019 assert( pOp->p1>0 );
5020 pC = p->apCsr[pOp[1].p1];
5021 assert( pC!=0 );
5022 assert( pC->eCurType==CURTYPE_BTREE );
5023 assert( !pC->isTable );
5024 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
5025 #ifdef SQLITE_DEBUG
5026 if( db->flags&SQLITE_VdbeTrace ){
5027 printf("... cursor not valid - fall through\n");
5029 #endif
5030 break;
5032 nStep = pOp->p1;
5033 assert( nStep>=1 );
5034 r.pKeyInfo = pC->pKeyInfo;
5035 r.nField = (u16)pOp[1].p4.i;
5036 r.default_rc = 0;
5037 r.aMem = &aMem[pOp[1].p3];
5038 #ifdef SQLITE_DEBUG
5040 int i;
5041 for(i=0; i<r.nField; i++){
5042 assert( memIsValid(&r.aMem[i]) );
5043 REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
5046 #endif
5047 res = 0; /* Not needed. Only used to silence a warning. */
5048 while(1){
5049 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5050 if( rc ) goto abort_due_to_error;
5051 if( res>0 && pOp->p5==0 ){
5052 seekscan_search_fail:
5053 /* Jump to SeekGE.P2, ending the loop */
5054 #ifdef SQLITE_DEBUG
5055 if( db->flags&SQLITE_VdbeTrace ){
5056 printf("... %d steps and then skip\n", pOp->p1 - nStep);
5058 #endif
5059 VdbeBranchTaken(1,3);
5060 pOp++;
5061 goto jump_to_p2;
5063 if( res>=0 ){
5064 /* Jump to This.P2, bypassing the OP_SeekGE opcode */
5065 #ifdef SQLITE_DEBUG
5066 if( db->flags&SQLITE_VdbeTrace ){
5067 printf("... %d steps and then success\n", pOp->p1 - nStep);
5069 #endif
5070 VdbeBranchTaken(2,3);
5071 goto jump_to_p2;
5072 break;
5074 if( nStep<=0 ){
5075 #ifdef SQLITE_DEBUG
5076 if( db->flags&SQLITE_VdbeTrace ){
5077 printf("... fall through after %d steps\n", pOp->p1);
5079 #endif
5080 VdbeBranchTaken(0,3);
5081 break;
5083 nStep--;
5084 pC->cacheStatus = CACHE_STALE;
5085 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
5086 if( rc ){
5087 if( rc==SQLITE_DONE ){
5088 rc = SQLITE_OK;
5089 goto seekscan_search_fail;
5090 }else{
5091 goto abort_due_to_error;
5096 break;
5100 /* Opcode: SeekHit P1 P2 P3 * *
5101 ** Synopsis: set P2<=seekHit<=P3
5103 ** Increase or decrease the seekHit value for cursor P1, if necessary,
5104 ** so that it is no less than P2 and no greater than P3.
5106 ** The seekHit integer represents the maximum of terms in an index for which
5107 ** there is known to be at least one match. If the seekHit value is smaller
5108 ** than the total number of equality terms in an index lookup, then the
5109 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
5110 ** early, thus saving work. This is part of the IN-early-out optimization.
5112 ** P1 must be a valid b-tree cursor.
5114 case OP_SeekHit: { /* ncycle */
5115 VdbeCursor *pC;
5116 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5117 pC = p->apCsr[pOp->p1];
5118 assert( pC!=0 );
5119 assert( pOp->p3>=pOp->p2 );
5120 if( pC->seekHit<pOp->p2 ){
5121 #ifdef SQLITE_DEBUG
5122 if( db->flags&SQLITE_VdbeTrace ){
5123 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
5125 #endif
5126 pC->seekHit = pOp->p2;
5127 }else if( pC->seekHit>pOp->p3 ){
5128 #ifdef SQLITE_DEBUG
5129 if( db->flags&SQLITE_VdbeTrace ){
5130 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
5132 #endif
5133 pC->seekHit = pOp->p3;
5135 break;
5138 /* Opcode: IfNotOpen P1 P2 * * *
5139 ** Synopsis: if( !csr[P1] ) goto P2
5141 ** If cursor P1 is not open or if P1 is set to a NULL row using the
5142 ** OP_NullRow opcode, then jump to instruction P2. Otherwise, fall through.
5144 case OP_IfNotOpen: { /* jump */
5145 VdbeCursor *pCur;
5147 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5148 pCur = p->apCsr[pOp->p1];
5149 VdbeBranchTaken(pCur==0 || pCur->nullRow, 2);
5150 if( pCur==0 || pCur->nullRow ){
5151 goto jump_to_p2_and_check_for_interrupt;
5153 break;
5156 /* Opcode: Found P1 P2 P3 P4 *
5157 ** Synopsis: key=r[P3@P4]
5159 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5160 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5161 ** record.
5163 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5164 ** is a prefix of any entry in P1 then a jump is made to P2 and
5165 ** P1 is left pointing at the matching entry.
5167 ** This operation leaves the cursor in a state where it can be
5168 ** advanced in the forward direction. The Next instruction will work,
5169 ** but not the Prev instruction.
5171 ** See also: NotFound, NoConflict, NotExists. SeekGe
5173 /* Opcode: NotFound P1 P2 P3 P4 *
5174 ** Synopsis: key=r[P3@P4]
5176 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5177 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5178 ** record.
5180 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5181 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
5182 ** does contain an entry whose prefix matches the P3/P4 record then control
5183 ** falls through to the next instruction and P1 is left pointing at the
5184 ** matching entry.
5186 ** This operation leaves the cursor in a state where it cannot be
5187 ** advanced in either direction. In other words, the Next and Prev
5188 ** opcodes do not work after this operation.
5190 ** See also: Found, NotExists, NoConflict, IfNoHope
5192 /* Opcode: IfNoHope P1 P2 P3 P4 *
5193 ** Synopsis: key=r[P3@P4]
5195 ** Register P3 is the first of P4 registers that form an unpacked
5196 ** record. Cursor P1 is an index btree. P2 is a jump destination.
5197 ** In other words, the operands to this opcode are the same as the
5198 ** operands to OP_NotFound and OP_IdxGT.
5200 ** This opcode is an optimization attempt only. If this opcode always
5201 ** falls through, the correct answer is still obtained, but extra work
5202 ** is performed.
5204 ** A value of N in the seekHit flag of cursor P1 means that there exists
5205 ** a key P3:N that will match some record in the index. We want to know
5206 ** if it is possible for a record P3:P4 to match some record in the
5207 ** index. If it is not possible, we can skip some work. So if seekHit
5208 ** is less than P4, attempt to find out if a match is possible by running
5209 ** OP_NotFound.
5211 ** This opcode is used in IN clause processing for a multi-column key.
5212 ** If an IN clause is attached to an element of the key other than the
5213 ** left-most element, and if there are no matches on the most recent
5214 ** seek over the whole key, then it might be that one of the key element
5215 ** to the left is prohibiting a match, and hence there is "no hope" of
5216 ** any match regardless of how many IN clause elements are checked.
5217 ** In such a case, we abandon the IN clause search early, using this
5218 ** opcode. The opcode name comes from the fact that the
5219 ** jump is taken if there is "no hope" of achieving a match.
5221 ** See also: NotFound, SeekHit
5223 /* Opcode: NoConflict P1 P2 P3 P4 *
5224 ** Synopsis: key=r[P3@P4]
5226 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5227 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5228 ** record.
5230 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5231 ** contains any NULL value, jump immediately to P2. If all terms of the
5232 ** record are not-NULL then a check is done to determine if any row in the
5233 ** P1 index btree has a matching key prefix. If there are no matches, jump
5234 ** immediately to P2. If there is a match, fall through and leave the P1
5235 ** cursor pointing to the matching row.
5237 ** This opcode is similar to OP_NotFound with the exceptions that the
5238 ** branch is always taken if any part of the search key input is NULL.
5240 ** This operation leaves the cursor in a state where it cannot be
5241 ** advanced in either direction. In other words, the Next and Prev
5242 ** opcodes do not work after this operation.
5244 ** See also: NotFound, Found, NotExists
5246 case OP_IfNoHope: { /* jump, in3, ncycle */
5247 VdbeCursor *pC;
5248 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5249 pC = p->apCsr[pOp->p1];
5250 assert( pC!=0 );
5251 #ifdef SQLITE_DEBUG
5252 if( db->flags&SQLITE_VdbeTrace ){
5253 printf("seekHit is %d\n", pC->seekHit);
5255 #endif
5256 if( pC->seekHit>=pOp->p4.i ) break;
5257 /* Fall through into OP_NotFound */
5258 /* no break */ deliberate_fall_through
5260 case OP_NoConflict: /* jump, in3, ncycle */
5261 case OP_NotFound: /* jump, in3, ncycle */
5262 case OP_Found: { /* jump, in3, ncycle */
5263 int alreadyExists;
5264 int ii;
5265 VdbeCursor *pC;
5266 UnpackedRecord *pIdxKey;
5267 UnpackedRecord r;
5269 #ifdef SQLITE_TEST
5270 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
5271 #endif
5273 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5274 assert( pOp->p4type==P4_INT32 );
5275 pC = p->apCsr[pOp->p1];
5276 assert( pC!=0 );
5277 #ifdef SQLITE_DEBUG
5278 pC->seekOp = pOp->opcode;
5279 #endif
5280 r.aMem = &aMem[pOp->p3];
5281 assert( pC->eCurType==CURTYPE_BTREE );
5282 assert( pC->uc.pCursor!=0 );
5283 assert( pC->isTable==0 );
5284 r.nField = (u16)pOp->p4.i;
5285 if( r.nField>0 ){
5286 /* Key values in an array of registers */
5287 r.pKeyInfo = pC->pKeyInfo;
5288 r.default_rc = 0;
5289 #ifdef SQLITE_DEBUG
5290 for(ii=0; ii<r.nField; ii++){
5291 assert( memIsValid(&r.aMem[ii]) );
5292 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
5293 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
5295 #endif
5296 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &pC->seekResult);
5297 }else{
5298 /* Composite key generated by OP_MakeRecord */
5299 assert( r.aMem->flags & MEM_Blob );
5300 assert( pOp->opcode!=OP_NoConflict );
5301 rc = ExpandBlob(r.aMem);
5302 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
5303 if( rc ) goto no_mem;
5304 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
5305 if( pIdxKey==0 ) goto no_mem;
5306 sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);
5307 pIdxKey->default_rc = 0;
5308 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);
5309 sqlite3DbFreeNN(db, pIdxKey);
5311 if( rc!=SQLITE_OK ){
5312 goto abort_due_to_error;
5314 alreadyExists = (pC->seekResult==0);
5315 pC->nullRow = 1-alreadyExists;
5316 pC->deferredMoveto = 0;
5317 pC->cacheStatus = CACHE_STALE;
5318 if( pOp->opcode==OP_Found ){
5319 VdbeBranchTaken(alreadyExists!=0,2);
5320 if( alreadyExists ) goto jump_to_p2;
5321 }else{
5322 if( !alreadyExists ){
5323 VdbeBranchTaken(1,2);
5324 goto jump_to_p2;
5326 if( pOp->opcode==OP_NoConflict ){
5327 /* For the OP_NoConflict opcode, take the jump if any of the
5328 ** input fields are NULL, since any key with a NULL will not
5329 ** conflict */
5330 for(ii=0; ii<r.nField; ii++){
5331 if( r.aMem[ii].flags & MEM_Null ){
5332 VdbeBranchTaken(1,2);
5333 goto jump_to_p2;
5337 VdbeBranchTaken(0,2);
5338 if( pOp->opcode==OP_IfNoHope ){
5339 pC->seekHit = pOp->p4.i;
5342 break;
5345 /* Opcode: SeekRowid P1 P2 P3 * *
5346 ** Synopsis: intkey=r[P3]
5348 ** P1 is the index of a cursor open on an SQL table btree (with integer
5349 ** keys). If register P3 does not contain an integer or if P1 does not
5350 ** contain a record with rowid P3 then jump immediately to P2.
5351 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
5352 ** a record with rowid P3 then
5353 ** leave the cursor pointing at that record and fall through to the next
5354 ** instruction.
5356 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
5357 ** the P3 register must be guaranteed to contain an integer value. With this
5358 ** opcode, register P3 might not contain an integer.
5360 ** The OP_NotFound opcode performs the same operation on index btrees
5361 ** (with arbitrary multi-value keys).
5363 ** This opcode leaves the cursor in a state where it cannot be advanced
5364 ** in either direction. In other words, the Next and Prev opcodes will
5365 ** not work following this opcode.
5367 ** See also: Found, NotFound, NoConflict, SeekRowid
5369 /* Opcode: NotExists P1 P2 P3 * *
5370 ** Synopsis: intkey=r[P3]
5372 ** P1 is the index of a cursor open on an SQL table btree (with integer
5373 ** keys). P3 is an integer rowid. If P1 does not contain a record with
5374 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
5375 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
5376 ** leave the cursor pointing at that record and fall through to the next
5377 ** instruction.
5379 ** The OP_SeekRowid opcode performs the same operation but also allows the
5380 ** P3 register to contain a non-integer value, in which case the jump is
5381 ** always taken. This opcode requires that P3 always contain an integer.
5383 ** The OP_NotFound opcode performs the same operation on index btrees
5384 ** (with arbitrary multi-value keys).
5386 ** This opcode leaves the cursor in a state where it cannot be advanced
5387 ** in either direction. In other words, the Next and Prev opcodes will
5388 ** not work following this opcode.
5390 ** See also: Found, NotFound, NoConflict, SeekRowid
5392 case OP_SeekRowid: { /* jump, in3, ncycle */
5393 VdbeCursor *pC;
5394 BtCursor *pCrsr;
5395 int res;
5396 u64 iKey;
5398 pIn3 = &aMem[pOp->p3];
5399 testcase( pIn3->flags & MEM_Int );
5400 testcase( pIn3->flags & MEM_IntReal );
5401 testcase( pIn3->flags & MEM_Real );
5402 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
5403 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
5404 /* If pIn3->u.i does not contain an integer, compute iKey as the
5405 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
5406 ** into an integer without loss of information. Take care to avoid
5407 ** changing the datatype of pIn3, however, as it is used by other
5408 ** parts of the prepared statement. */
5409 Mem x = pIn3[0];
5410 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
5411 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
5412 iKey = x.u.i;
5413 goto notExistsWithKey;
5415 /* Fall through into OP_NotExists */
5416 /* no break */ deliberate_fall_through
5417 case OP_NotExists: /* jump, in3, ncycle */
5418 pIn3 = &aMem[pOp->p3];
5419 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
5420 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5421 iKey = pIn3->u.i;
5422 notExistsWithKey:
5423 pC = p->apCsr[pOp->p1];
5424 assert( pC!=0 );
5425 #ifdef SQLITE_DEBUG
5426 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
5427 #endif
5428 assert( pC->isTable );
5429 assert( pC->eCurType==CURTYPE_BTREE );
5430 pCrsr = pC->uc.pCursor;
5431 assert( pCrsr!=0 );
5432 res = 0;
5433 rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
5434 assert( rc==SQLITE_OK || res==0 );
5435 pC->movetoTarget = iKey; /* Used by OP_Delete */
5436 pC->nullRow = 0;
5437 pC->cacheStatus = CACHE_STALE;
5438 pC->deferredMoveto = 0;
5439 VdbeBranchTaken(res!=0,2);
5440 pC->seekResult = res;
5441 if( res!=0 ){
5442 assert( rc==SQLITE_OK );
5443 if( pOp->p2==0 ){
5444 rc = SQLITE_CORRUPT_BKPT;
5445 }else{
5446 goto jump_to_p2;
5449 if( rc ) goto abort_due_to_error;
5450 break;
5453 /* Opcode: Sequence P1 P2 * * *
5454 ** Synopsis: r[P2]=cursor[P1].ctr++
5456 ** Find the next available sequence number for cursor P1.
5457 ** Write the sequence number into register P2.
5458 ** The sequence number on the cursor is incremented after this
5459 ** instruction.
5461 case OP_Sequence: { /* out2 */
5462 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5463 assert( p->apCsr[pOp->p1]!=0 );
5464 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
5465 pOut = out2Prerelease(p, pOp);
5466 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
5467 break;
5471 /* Opcode: NewRowid P1 P2 P3 * *
5472 ** Synopsis: r[P2]=rowid
5474 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
5475 ** The record number is not previously used as a key in the database
5476 ** table that cursor P1 points to. The new record number is written
5477 ** written to register P2.
5479 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
5480 ** the largest previously generated record number. No new record numbers are
5481 ** allowed to be less than this value. When this value reaches its maximum,
5482 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
5483 ** generated record number. This P3 mechanism is used to help implement the
5484 ** AUTOINCREMENT feature.
5486 case OP_NewRowid: { /* out2 */
5487 i64 v; /* The new rowid */
5488 VdbeCursor *pC; /* Cursor of table to get the new rowid */
5489 int res; /* Result of an sqlite3BtreeLast() */
5490 int cnt; /* Counter to limit the number of searches */
5491 #ifndef SQLITE_OMIT_AUTOINCREMENT
5492 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
5493 VdbeFrame *pFrame; /* Root frame of VDBE */
5494 #endif
5496 v = 0;
5497 res = 0;
5498 pOut = out2Prerelease(p, pOp);
5499 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5500 pC = p->apCsr[pOp->p1];
5501 assert( pC!=0 );
5502 assert( pC->isTable );
5503 assert( pC->eCurType==CURTYPE_BTREE );
5504 assert( pC->uc.pCursor!=0 );
5506 /* The next rowid or record number (different terms for the same
5507 ** thing) is obtained in a two-step algorithm.
5509 ** First we attempt to find the largest existing rowid and add one
5510 ** to that. But if the largest existing rowid is already the maximum
5511 ** positive integer, we have to fall through to the second
5512 ** probabilistic algorithm
5514 ** The second algorithm is to select a rowid at random and see if
5515 ** it already exists in the table. If it does not exist, we have
5516 ** succeeded. If the random rowid does exist, we select a new one
5517 ** and try again, up to 100 times.
5519 assert( pC->isTable );
5521 #ifdef SQLITE_32BIT_ROWID
5522 # define MAX_ROWID 0x7fffffff
5523 #else
5524 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
5525 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
5526 ** to provide the constant while making all compilers happy.
5528 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
5529 #endif
5531 if( !pC->useRandomRowid ){
5532 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
5533 if( rc!=SQLITE_OK ){
5534 goto abort_due_to_error;
5536 if( res ){
5537 v = 1; /* IMP: R-61914-48074 */
5538 }else{
5539 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
5540 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5541 if( v>=MAX_ROWID ){
5542 pC->useRandomRowid = 1;
5543 }else{
5544 v++; /* IMP: R-29538-34987 */
5549 #ifndef SQLITE_OMIT_AUTOINCREMENT
5550 if( pOp->p3 ){
5551 /* Assert that P3 is a valid memory cell. */
5552 assert( pOp->p3>0 );
5553 if( p->pFrame ){
5554 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5555 /* Assert that P3 is a valid memory cell. */
5556 assert( pOp->p3<=pFrame->nMem );
5557 pMem = &pFrame->aMem[pOp->p3];
5558 }else{
5559 /* Assert that P3 is a valid memory cell. */
5560 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
5561 pMem = &aMem[pOp->p3];
5562 memAboutToChange(p, pMem);
5564 assert( memIsValid(pMem) );
5566 REGISTER_TRACE(pOp->p3, pMem);
5567 sqlite3VdbeMemIntegerify(pMem);
5568 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
5569 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
5570 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
5571 goto abort_due_to_error;
5573 if( v<pMem->u.i+1 ){
5574 v = pMem->u.i + 1;
5576 pMem->u.i = v;
5578 #endif
5579 if( pC->useRandomRowid ){
5580 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
5581 ** largest possible integer (9223372036854775807) then the database
5582 ** engine starts picking positive candidate ROWIDs at random until
5583 ** it finds one that is not previously used. */
5584 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
5585 ** an AUTOINCREMENT table. */
5586 cnt = 0;
5588 sqlite3_randomness(sizeof(v), &v);
5589 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
5590 }while( ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
5591 0, &res))==SQLITE_OK)
5592 && (res==0)
5593 && (++cnt<100));
5594 if( rc ) goto abort_due_to_error;
5595 if( res==0 ){
5596 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
5597 goto abort_due_to_error;
5599 assert( v>0 ); /* EV: R-40812-03570 */
5601 pC->deferredMoveto = 0;
5602 pC->cacheStatus = CACHE_STALE;
5604 pOut->u.i = v;
5605 break;
5608 /* Opcode: Insert P1 P2 P3 P4 P5
5609 ** Synopsis: intkey=r[P3] data=r[P2]
5611 ** Write an entry into the table of cursor P1. A new entry is
5612 ** created if it doesn't already exist or the data for an existing
5613 ** entry is overwritten. The data is the value MEM_Blob stored in register
5614 ** number P2. The key is stored in register P3. The key must
5615 ** be a MEM_Int.
5617 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5618 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
5619 ** then rowid is stored for subsequent return by the
5620 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5622 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5623 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5624 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5625 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5627 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5628 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
5629 ** is part of an INSERT operation. The difference is only important to
5630 ** the update hook.
5632 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5633 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5634 ** following a successful insert.
5636 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5637 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5638 ** and register P2 becomes ephemeral. If the cursor is changed, the
5639 ** value of register P2 will then change. Make sure this does not
5640 ** cause any problems.)
5642 ** This instruction only works on tables. The equivalent instruction
5643 ** for indices is OP_IdxInsert.
5645 case OP_Insert: {
5646 Mem *pData; /* MEM cell holding data for the record to be inserted */
5647 Mem *pKey; /* MEM cell holding key for the record */
5648 VdbeCursor *pC; /* Cursor to table into which insert is written */
5649 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
5650 const char *zDb; /* database name - used by the update hook */
5651 Table *pTab; /* Table structure - used by update and pre-update hooks */
5652 BtreePayload x; /* Payload to be inserted */
5654 pData = &aMem[pOp->p2];
5655 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5656 assert( memIsValid(pData) );
5657 pC = p->apCsr[pOp->p1];
5658 assert( pC!=0 );
5659 assert( pC->eCurType==CURTYPE_BTREE );
5660 assert( pC->deferredMoveto==0 );
5661 assert( pC->uc.pCursor!=0 );
5662 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5663 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5664 REGISTER_TRACE(pOp->p2, pData);
5665 sqlite3VdbeIncrWriteCounter(p, pC);
5667 pKey = &aMem[pOp->p3];
5668 assert( pKey->flags & MEM_Int );
5669 assert( memIsValid(pKey) );
5670 REGISTER_TRACE(pOp->p3, pKey);
5671 x.nKey = pKey->u.i;
5673 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5674 assert( pC->iDb>=0 );
5675 zDb = db->aDb[pC->iDb].zDbSName;
5676 pTab = pOp->p4.pTab;
5677 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5678 }else{
5679 pTab = 0;
5680 zDb = 0;
5683 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5684 /* Invoke the pre-update hook, if any */
5685 if( pTab ){
5686 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5687 sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
5689 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5690 /* Prevent post-update hook from running in cases when it should not */
5691 pTab = 0;
5694 if( pOp->p5 & OPFLAG_ISNOOP ) break;
5695 #endif
5697 assert( (pOp->p5 & OPFLAG_LASTROWID)==0 || (pOp->p5 & OPFLAG_NCHANGE)!=0 );
5698 if( pOp->p5 & OPFLAG_NCHANGE ){
5699 p->nChange++;
5700 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5702 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5703 x.pData = pData->z;
5704 x.nData = pData->n;
5705 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5706 if( pData->flags & MEM_Zero ){
5707 x.nZero = pData->u.nZero;
5708 }else{
5709 x.nZero = 0;
5711 x.pKey = 0;
5712 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
5713 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5714 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5715 seekResult
5717 pC->deferredMoveto = 0;
5718 pC->cacheStatus = CACHE_STALE;
5719 colCacheCtr++;
5721 /* Invoke the update-hook if required. */
5722 if( rc ) goto abort_due_to_error;
5723 if( pTab ){
5724 assert( db->xUpdateCallback!=0 );
5725 assert( pTab->aCol!=0 );
5726 db->xUpdateCallback(db->pUpdateArg,
5727 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5728 zDb, pTab->zName, x.nKey);
5730 break;
5733 /* Opcode: RowCell P1 P2 P3 * *
5735 ** P1 and P2 are both open cursors. Both must be opened on the same type
5736 ** of table - intkey or index. This opcode is used as part of copying
5737 ** the current row from P2 into P1. If the cursors are opened on intkey
5738 ** tables, register P3 contains the rowid to use with the new record in
5739 ** P1. If they are opened on index tables, P3 is not used.
5741 ** This opcode must be followed by either an Insert or InsertIdx opcode
5742 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
5744 case OP_RowCell: {
5745 VdbeCursor *pDest; /* Cursor to write to */
5746 VdbeCursor *pSrc; /* Cursor to read from */
5747 i64 iKey; /* Rowid value to insert with */
5748 assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
5749 assert( pOp[1].opcode==OP_Insert || pOp->p3==0 );
5750 assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
5751 assert( pOp[1].p5 & OPFLAG_PREFORMAT );
5752 pDest = p->apCsr[pOp->p1];
5753 pSrc = p->apCsr[pOp->p2];
5754 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
5755 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
5756 if( rc!=SQLITE_OK ) goto abort_due_to_error;
5757 break;
5760 /* Opcode: Delete P1 P2 P3 P4 P5
5762 ** Delete the record at which the P1 cursor is currently pointing.
5764 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5765 ** the cursor will be left pointing at either the next or the previous
5766 ** record in the table. If it is left pointing at the next record, then
5767 ** the next Next instruction will be a no-op. As a result, in this case
5768 ** it is ok to delete a record from within a Next loop. If
5769 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5770 ** left in an undefined state.
5772 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5773 ** delete is one of several associated with deleting a table row and
5774 ** all its associated index entries. Exactly one of those deletes is
5775 ** the "primary" delete. The others are all on OPFLAG_FORDELETE
5776 ** cursors or else are marked with the AUXDELETE flag.
5778 ** If the OPFLAG_NCHANGE (0x01) flag of P2 (NB: P2 not P5) is set, then
5779 ** the row change count is incremented (otherwise not).
5781 ** If the OPFLAG_ISNOOP (0x40) flag of P2 (not P5!) is set, then the
5782 ** pre-update-hook for deletes is run, but the btree is otherwise unchanged.
5783 ** This happens when the OP_Delete is to be shortly followed by an OP_Insert
5784 ** with the same key, causing the btree entry to be overwritten.
5786 ** P1 must not be pseudo-table. It has to be a real table with
5787 ** multiple rows.
5789 ** If P4 is not NULL then it points to a Table object. In this case either
5790 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5791 ** have been positioned using OP_NotFound prior to invoking this opcode in
5792 ** this case. Specifically, if one is configured, the pre-update hook is
5793 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5794 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5796 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5797 ** of the memory cell that contains the value that the rowid of the row will
5798 ** be set to by the update.
5800 case OP_Delete: {
5801 VdbeCursor *pC;
5802 const char *zDb;
5803 Table *pTab;
5804 int opflags;
5806 opflags = pOp->p2;
5807 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5808 pC = p->apCsr[pOp->p1];
5809 assert( pC!=0 );
5810 assert( pC->eCurType==CURTYPE_BTREE );
5811 assert( pC->uc.pCursor!=0 );
5812 assert( pC->deferredMoveto==0 );
5813 sqlite3VdbeIncrWriteCounter(p, pC);
5815 #ifdef SQLITE_DEBUG
5816 if( pOp->p4type==P4_TABLE
5817 && HasRowid(pOp->p4.pTab)
5818 && pOp->p5==0
5819 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5821 /* If p5 is zero, the seek operation that positioned the cursor prior to
5822 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5823 ** the row that is being deleted */
5824 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5825 assert( CORRUPT_DB || pC->movetoTarget==iKey );
5827 #endif
5829 /* If the update-hook or pre-update-hook will be invoked, set zDb to
5830 ** the name of the db to pass as to it. Also set local pTab to a copy
5831 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5832 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5833 ** VdbeCursor.movetoTarget to the current rowid. */
5834 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5835 assert( pC->iDb>=0 );
5836 assert( pOp->p4.pTab!=0 );
5837 zDb = db->aDb[pC->iDb].zDbSName;
5838 pTab = pOp->p4.pTab;
5839 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5840 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5842 }else{
5843 zDb = 0;
5844 pTab = 0;
5847 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5848 /* Invoke the pre-update-hook if required. */
5849 assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
5850 if( db->xPreUpdateCallback && pTab ){
5851 assert( !(opflags & OPFLAG_ISUPDATE)
5852 || HasRowid(pTab)==0
5853 || (aMem[pOp->p3].flags & MEM_Int)
5855 sqlite3VdbePreUpdateHook(p, pC,
5856 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5857 zDb, pTab, pC->movetoTarget,
5858 pOp->p3, -1
5861 if( opflags & OPFLAG_ISNOOP ) break;
5862 #endif
5864 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5865 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5866 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5867 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5869 #ifdef SQLITE_DEBUG
5870 if( p->pFrame==0 ){
5871 if( pC->isEphemeral==0
5872 && (pOp->p5 & OPFLAG_AUXDELETE)==0
5873 && (pC->wrFlag & OPFLAG_FORDELETE)==0
5875 nExtraDelete++;
5877 if( pOp->p2 & OPFLAG_NCHANGE ){
5878 nExtraDelete--;
5881 #endif
5883 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5884 pC->cacheStatus = CACHE_STALE;
5885 colCacheCtr++;
5886 pC->seekResult = 0;
5887 if( rc ) goto abort_due_to_error;
5889 /* Invoke the update-hook if required. */
5890 if( opflags & OPFLAG_NCHANGE ){
5891 p->nChange++;
5892 if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
5893 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5894 pC->movetoTarget);
5895 assert( pC->iDb>=0 );
5899 break;
5901 /* Opcode: ResetCount * * * * *
5903 ** The value of the change counter is copied to the database handle
5904 ** change counter (returned by subsequent calls to sqlite3_changes()).
5905 ** Then the VMs internal change counter resets to 0.
5906 ** This is used by trigger programs.
5908 case OP_ResetCount: {
5909 sqlite3VdbeSetChanges(db, p->nChange);
5910 p->nChange = 0;
5911 break;
5914 /* Opcode: SorterCompare P1 P2 P3 P4
5915 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5917 ** P1 is a sorter cursor. This instruction compares a prefix of the
5918 ** record blob in register P3 against a prefix of the entry that
5919 ** the sorter cursor currently points to. Only the first P4 fields
5920 ** of r[P3] and the sorter record are compared.
5922 ** If either P3 or the sorter contains a NULL in one of their significant
5923 ** fields (not counting the P4 fields at the end which are ignored) then
5924 ** the comparison is assumed to be equal.
5926 ** Fall through to next instruction if the two records compare equal to
5927 ** each other. Jump to P2 if they are different.
5929 case OP_SorterCompare: {
5930 VdbeCursor *pC;
5931 int res;
5932 int nKeyCol;
5934 pC = p->apCsr[pOp->p1];
5935 assert( isSorter(pC) );
5936 assert( pOp->p4type==P4_INT32 );
5937 pIn3 = &aMem[pOp->p3];
5938 nKeyCol = pOp->p4.i;
5939 res = 0;
5940 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5941 VdbeBranchTaken(res!=0,2);
5942 if( rc ) goto abort_due_to_error;
5943 if( res ) goto jump_to_p2;
5944 break;
5947 /* Opcode: SorterData P1 P2 P3 * *
5948 ** Synopsis: r[P2]=data
5950 ** Write into register P2 the current sorter data for sorter cursor P1.
5951 ** Then clear the column header cache on cursor P3.
5953 ** This opcode is normally used to move a record out of the sorter and into
5954 ** a register that is the source for a pseudo-table cursor created using
5955 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
5956 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
5957 ** us from having to issue a separate NullRow instruction to clear that cache.
5959 case OP_SorterData: { /* ncycle */
5960 VdbeCursor *pC;
5962 pOut = &aMem[pOp->p2];
5963 pC = p->apCsr[pOp->p1];
5964 assert( isSorter(pC) );
5965 rc = sqlite3VdbeSorterRowkey(pC, pOut);
5966 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5967 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5968 if( rc ) goto abort_due_to_error;
5969 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5970 break;
5973 /* Opcode: RowData P1 P2 P3 * *
5974 ** Synopsis: r[P2]=data
5976 ** Write into register P2 the complete row content for the row at
5977 ** which cursor P1 is currently pointing.
5978 ** There is no interpretation of the data.
5979 ** It is just copied onto the P2 register exactly as
5980 ** it is found in the database file.
5982 ** If cursor P1 is an index, then the content is the key of the row.
5983 ** If cursor P2 is a table, then the content extracted is the data.
5985 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5986 ** of a real table, not a pseudo-table.
5988 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5989 ** into the database page. That means that the content of the output
5990 ** register will be invalidated as soon as the cursor moves - including
5991 ** moves caused by other cursors that "save" the current cursors
5992 ** position in order that they can write to the same table. If P3==0
5993 ** then a copy of the data is made into memory. P3!=0 is faster, but
5994 ** P3==0 is safer.
5996 ** If P3!=0 then the content of the P2 register is unsuitable for use
5997 ** in OP_Result and any OP_Result will invalidate the P2 register content.
5998 ** The P2 register content is invalidated by opcodes like OP_Function or
5999 ** by any use of another cursor pointing to the same table.
6001 case OP_RowData: {
6002 VdbeCursor *pC;
6003 BtCursor *pCrsr;
6004 u32 n;
6006 pOut = out2Prerelease(p, pOp);
6008 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6009 pC = p->apCsr[pOp->p1];
6010 assert( pC!=0 );
6011 assert( pC->eCurType==CURTYPE_BTREE );
6012 assert( isSorter(pC)==0 );
6013 assert( pC->nullRow==0 );
6014 assert( pC->uc.pCursor!=0 );
6015 pCrsr = pC->uc.pCursor;
6017 /* The OP_RowData opcodes always follow OP_NotExists or
6018 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
6019 ** that might invalidate the cursor.
6020 ** If this where not the case, on of the following assert()s
6021 ** would fail. Should this ever change (because of changes in the code
6022 ** generator) then the fix would be to insert a call to
6023 ** sqlite3VdbeCursorMoveto().
6025 assert( pC->deferredMoveto==0 );
6026 assert( sqlite3BtreeCursorIsValid(pCrsr) );
6028 n = sqlite3BtreePayloadSize(pCrsr);
6029 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
6030 goto too_big;
6032 testcase( n==0 );
6033 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
6034 if( rc ) goto abort_due_to_error;
6035 if( !pOp->p3 ) Deephemeralize(pOut);
6036 UPDATE_MAX_BLOBSIZE(pOut);
6037 REGISTER_TRACE(pOp->p2, pOut);
6038 break;
6041 /* Opcode: Rowid P1 P2 * * *
6042 ** Synopsis: r[P2]=PX rowid of P1
6044 ** Store in register P2 an integer which is the key of the table entry that
6045 ** P1 is currently point to.
6047 ** P1 can be either an ordinary table or a virtual table. There used to
6048 ** be a separate OP_VRowid opcode for use with virtual tables, but this
6049 ** one opcode now works for both table types.
6051 case OP_Rowid: { /* out2, ncycle */
6052 VdbeCursor *pC;
6053 i64 v;
6054 sqlite3_vtab *pVtab;
6055 const sqlite3_module *pModule;
6057 pOut = out2Prerelease(p, pOp);
6058 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6059 pC = p->apCsr[pOp->p1];
6060 assert( pC!=0 );
6061 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
6062 if( pC->nullRow ){
6063 pOut->flags = MEM_Null;
6064 break;
6065 }else if( pC->deferredMoveto ){
6066 v = pC->movetoTarget;
6067 #ifndef SQLITE_OMIT_VIRTUALTABLE
6068 }else if( pC->eCurType==CURTYPE_VTAB ){
6069 assert( pC->uc.pVCur!=0 );
6070 pVtab = pC->uc.pVCur->pVtab;
6071 pModule = pVtab->pModule;
6072 assert( pModule->xRowid );
6073 rc = pModule->xRowid(pC->uc.pVCur, &v);
6074 sqlite3VtabImportErrmsg(p, pVtab);
6075 if( rc ) goto abort_due_to_error;
6076 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6077 }else{
6078 assert( pC->eCurType==CURTYPE_BTREE );
6079 assert( pC->uc.pCursor!=0 );
6080 rc = sqlite3VdbeCursorRestore(pC);
6081 if( rc ) goto abort_due_to_error;
6082 if( pC->nullRow ){
6083 pOut->flags = MEM_Null;
6084 break;
6086 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
6088 pOut->u.i = v;
6089 break;
6092 /* Opcode: NullRow P1 * * * *
6094 ** Move the cursor P1 to a null row. Any OP_Column operations
6095 ** that occur while the cursor is on the null row will always
6096 ** write a NULL.
6098 ** If cursor P1 is not previously opened, open it now to a special
6099 ** pseudo-cursor that always returns NULL for every column.
6101 case OP_NullRow: {
6102 VdbeCursor *pC;
6104 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6105 pC = p->apCsr[pOp->p1];
6106 if( pC==0 ){
6107 /* If the cursor is not already open, create a special kind of
6108 ** pseudo-cursor that always gives null rows. */
6109 pC = allocateCursor(p, pOp->p1, 1, CURTYPE_PSEUDO);
6110 if( pC==0 ) goto no_mem;
6111 pC->seekResult = 0;
6112 pC->isTable = 1;
6113 pC->noReuse = 1;
6114 pC->uc.pCursor = sqlite3BtreeFakeValidCursor();
6116 pC->nullRow = 1;
6117 pC->cacheStatus = CACHE_STALE;
6118 if( pC->eCurType==CURTYPE_BTREE ){
6119 assert( pC->uc.pCursor!=0 );
6120 sqlite3BtreeClearCursor(pC->uc.pCursor);
6122 #ifdef SQLITE_DEBUG
6123 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
6124 #endif
6125 break;
6128 /* Opcode: SeekEnd P1 * * * *
6130 ** Position cursor P1 at the end of the btree for the purpose of
6131 ** appending a new entry onto the btree.
6133 ** It is assumed that the cursor is used only for appending and so
6134 ** if the cursor is valid, then the cursor must already be pointing
6135 ** at the end of the btree and so no changes are made to
6136 ** the cursor.
6138 /* Opcode: Last P1 P2 * * *
6140 ** The next use of the Rowid or Column or Prev instruction for P1
6141 ** will refer to the last entry in the database table or index.
6142 ** If the table or index is empty and P2>0, then jump immediately to P2.
6143 ** If P2 is 0 or if the table or index is not empty, fall through
6144 ** to the following instruction.
6146 ** This opcode leaves the cursor configured to move in reverse order,
6147 ** from the end toward the beginning. In other words, the cursor is
6148 ** configured to use Prev, not Next.
6150 case OP_SeekEnd: /* ncycle */
6151 case OP_Last: { /* jump, ncycle */
6152 VdbeCursor *pC;
6153 BtCursor *pCrsr;
6154 int res;
6156 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6157 pC = p->apCsr[pOp->p1];
6158 assert( pC!=0 );
6159 assert( pC->eCurType==CURTYPE_BTREE );
6160 pCrsr = pC->uc.pCursor;
6161 res = 0;
6162 assert( pCrsr!=0 );
6163 #ifdef SQLITE_DEBUG
6164 pC->seekOp = pOp->opcode;
6165 #endif
6166 if( pOp->opcode==OP_SeekEnd ){
6167 assert( pOp->p2==0 );
6168 pC->seekResult = -1;
6169 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
6170 break;
6173 rc = sqlite3BtreeLast(pCrsr, &res);
6174 pC->nullRow = (u8)res;
6175 pC->deferredMoveto = 0;
6176 pC->cacheStatus = CACHE_STALE;
6177 if( rc ) goto abort_due_to_error;
6178 if( pOp->p2>0 ){
6179 VdbeBranchTaken(res!=0,2);
6180 if( res ) goto jump_to_p2;
6182 break;
6185 /* Opcode: IfSmaller P1 P2 P3 * *
6187 ** Estimate the number of rows in the table P1. Jump to P2 if that
6188 ** estimate is less than approximately 2**(0.1*P3).
6190 case OP_IfSmaller: { /* jump */
6191 VdbeCursor *pC;
6192 BtCursor *pCrsr;
6193 int res;
6194 i64 sz;
6196 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6197 pC = p->apCsr[pOp->p1];
6198 assert( pC!=0 );
6199 pCrsr = pC->uc.pCursor;
6200 assert( pCrsr );
6201 rc = sqlite3BtreeFirst(pCrsr, &res);
6202 if( rc ) goto abort_due_to_error;
6203 if( res==0 ){
6204 sz = sqlite3BtreeRowCountEst(pCrsr);
6205 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
6207 VdbeBranchTaken(res!=0,2);
6208 if( res ) goto jump_to_p2;
6209 break;
6213 /* Opcode: SorterSort P1 P2 * * *
6215 ** After all records have been inserted into the Sorter object
6216 ** identified by P1, invoke this opcode to actually do the sorting.
6217 ** Jump to P2 if there are no records to be sorted.
6219 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
6220 ** for Sorter objects.
6222 /* Opcode: Sort P1 P2 * * *
6224 ** This opcode does exactly the same thing as OP_Rewind except that
6225 ** it increments an undocumented global variable used for testing.
6227 ** Sorting is accomplished by writing records into a sorting index,
6228 ** then rewinding that index and playing it back from beginning to
6229 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
6230 ** rewinding so that the global variable will be incremented and
6231 ** regression tests can determine whether or not the optimizer is
6232 ** correctly optimizing out sorts.
6234 case OP_SorterSort: /* jump ncycle */
6235 case OP_Sort: { /* jump ncycle */
6236 #ifdef SQLITE_TEST
6237 sqlite3_sort_count++;
6238 sqlite3_search_count--;
6239 #endif
6240 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
6241 /* Fall through into OP_Rewind */
6242 /* no break */ deliberate_fall_through
6244 /* Opcode: Rewind P1 P2 * * *
6246 ** The next use of the Rowid or Column or Next instruction for P1
6247 ** will refer to the first entry in the database table or index.
6248 ** If the table or index is empty, jump immediately to P2.
6249 ** If the table or index is not empty, fall through to the following
6250 ** instruction.
6252 ** If P2 is zero, that is an assertion that the P1 table is never
6253 ** empty and hence the jump will never be taken.
6255 ** This opcode leaves the cursor configured to move in forward order,
6256 ** from the beginning toward the end. In other words, the cursor is
6257 ** configured to use Next, not Prev.
6259 case OP_Rewind: { /* jump, ncycle */
6260 VdbeCursor *pC;
6261 BtCursor *pCrsr;
6262 int res;
6264 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6265 assert( pOp->p5==0 );
6266 assert( pOp->p2>=0 && pOp->p2<p->nOp );
6268 pC = p->apCsr[pOp->p1];
6269 assert( pC!=0 );
6270 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
6271 res = 1;
6272 #ifdef SQLITE_DEBUG
6273 pC->seekOp = OP_Rewind;
6274 #endif
6275 if( isSorter(pC) ){
6276 rc = sqlite3VdbeSorterRewind(pC, &res);
6277 }else{
6278 assert( pC->eCurType==CURTYPE_BTREE );
6279 pCrsr = pC->uc.pCursor;
6280 assert( pCrsr );
6281 rc = sqlite3BtreeFirst(pCrsr, &res);
6282 pC->deferredMoveto = 0;
6283 pC->cacheStatus = CACHE_STALE;
6285 if( rc ) goto abort_due_to_error;
6286 pC->nullRow = (u8)res;
6287 if( pOp->p2>0 ){
6288 VdbeBranchTaken(res!=0,2);
6289 if( res ) goto jump_to_p2;
6291 break;
6294 /* Opcode: Next P1 P2 P3 * P5
6296 ** Advance cursor P1 so that it points to the next key/data pair in its
6297 ** table or index. If there are no more key/value pairs then fall through
6298 ** to the following instruction. But if the cursor advance was successful,
6299 ** jump immediately to P2.
6301 ** The Next opcode is only valid following an SeekGT, SeekGE, or
6302 ** OP_Rewind opcode used to position the cursor. Next is not allowed
6303 ** to follow SeekLT, SeekLE, or OP_Last.
6305 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
6306 ** been opened prior to this opcode or the program will segfault.
6308 ** The P3 value is a hint to the btree implementation. If P3==1, that
6309 ** means P1 is an SQL index and that this instruction could have been
6310 ** omitted if that index had been unique. P3 is usually 0. P3 is
6311 ** always either 0 or 1.
6313 ** If P5 is positive and the jump is taken, then event counter
6314 ** number P5-1 in the prepared statement is incremented.
6316 ** See also: Prev
6318 /* Opcode: Prev P1 P2 P3 * P5
6320 ** Back up cursor P1 so that it points to the previous key/data pair in its
6321 ** table or index. If there is no previous key/value pairs then fall through
6322 ** to the following instruction. But if the cursor backup was successful,
6323 ** jump immediately to P2.
6326 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
6327 ** OP_Last opcode used to position the cursor. Prev is not allowed
6328 ** to follow SeekGT, SeekGE, or OP_Rewind.
6330 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
6331 ** not open then the behavior is undefined.
6333 ** The P3 value is a hint to the btree implementation. If P3==1, that
6334 ** means P1 is an SQL index and that this instruction could have been
6335 ** omitted if that index had been unique. P3 is usually 0. P3 is
6336 ** always either 0 or 1.
6338 ** If P5 is positive and the jump is taken, then event counter
6339 ** number P5-1 in the prepared statement is incremented.
6341 /* Opcode: SorterNext P1 P2 * * P5
6343 ** This opcode works just like OP_Next except that P1 must be a
6344 ** sorter object for which the OP_SorterSort opcode has been
6345 ** invoked. This opcode advances the cursor to the next sorted
6346 ** record, or jumps to P2 if there are no more sorted records.
6348 case OP_SorterNext: { /* jump */
6349 VdbeCursor *pC;
6351 pC = p->apCsr[pOp->p1];
6352 assert( isSorter(pC) );
6353 rc = sqlite3VdbeSorterNext(db, pC);
6354 goto next_tail;
6356 case OP_Prev: /* jump, ncycle */
6357 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6358 assert( pOp->p5==0
6359 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6360 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6361 pC = p->apCsr[pOp->p1];
6362 assert( pC!=0 );
6363 assert( pC->deferredMoveto==0 );
6364 assert( pC->eCurType==CURTYPE_BTREE );
6365 assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
6366 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
6367 || pC->seekOp==OP_NullRow);
6368 rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
6369 goto next_tail;
6371 case OP_Next: /* jump, ncycle */
6372 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6373 assert( pOp->p5==0
6374 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6375 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6376 pC = p->apCsr[pOp->p1];
6377 assert( pC!=0 );
6378 assert( pC->deferredMoveto==0 );
6379 assert( pC->eCurType==CURTYPE_BTREE );
6380 assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
6381 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
6382 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
6383 || pC->seekOp==OP_IfNoHope);
6384 rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
6386 next_tail:
6387 pC->cacheStatus = CACHE_STALE;
6388 VdbeBranchTaken(rc==SQLITE_OK,2);
6389 if( rc==SQLITE_OK ){
6390 pC->nullRow = 0;
6391 p->aCounter[pOp->p5]++;
6392 #ifdef SQLITE_TEST
6393 sqlite3_search_count++;
6394 #endif
6395 goto jump_to_p2_and_check_for_interrupt;
6397 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6398 rc = SQLITE_OK;
6399 pC->nullRow = 1;
6400 goto check_for_interrupt;
6403 /* Opcode: IdxInsert P1 P2 P3 P4 P5
6404 ** Synopsis: key=r[P2]
6406 ** Register P2 holds an SQL index key made using the
6407 ** MakeRecord instructions. This opcode writes that key
6408 ** into the index P1. Data for the entry is nil.
6410 ** If P4 is not zero, then it is the number of values in the unpacked
6411 ** key of reg(P2). In that case, P3 is the index of the first register
6412 ** for the unpacked key. The availability of the unpacked key can sometimes
6413 ** be an optimization.
6415 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
6416 ** that this insert is likely to be an append.
6418 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
6419 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
6420 ** then the change counter is unchanged.
6422 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
6423 ** run faster by avoiding an unnecessary seek on cursor P1. However,
6424 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
6425 ** seeks on the cursor or if the most recent seek used a key equivalent
6426 ** to P2.
6428 ** This instruction only works for indices. The equivalent instruction
6429 ** for tables is OP_Insert.
6431 case OP_IdxInsert: { /* in2 */
6432 VdbeCursor *pC;
6433 BtreePayload x;
6435 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6436 pC = p->apCsr[pOp->p1];
6437 sqlite3VdbeIncrWriteCounter(p, pC);
6438 assert( pC!=0 );
6439 assert( !isSorter(pC) );
6440 pIn2 = &aMem[pOp->p2];
6441 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
6442 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
6443 assert( pC->eCurType==CURTYPE_BTREE );
6444 assert( pC->isTable==0 );
6445 rc = ExpandBlob(pIn2);
6446 if( rc ) goto abort_due_to_error;
6447 x.nKey = pIn2->n;
6448 x.pKey = pIn2->z;
6449 x.aMem = aMem + pOp->p3;
6450 x.nMem = (u16)pOp->p4.i;
6451 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
6452 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
6453 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
6455 assert( pC->deferredMoveto==0 );
6456 pC->cacheStatus = CACHE_STALE;
6457 if( rc) goto abort_due_to_error;
6458 break;
6461 /* Opcode: SorterInsert P1 P2 * * *
6462 ** Synopsis: key=r[P2]
6464 ** Register P2 holds an SQL index key made using the
6465 ** MakeRecord instructions. This opcode writes that key
6466 ** into the sorter P1. Data for the entry is nil.
6468 case OP_SorterInsert: { /* in2 */
6469 VdbeCursor *pC;
6471 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6472 pC = p->apCsr[pOp->p1];
6473 sqlite3VdbeIncrWriteCounter(p, pC);
6474 assert( pC!=0 );
6475 assert( isSorter(pC) );
6476 pIn2 = &aMem[pOp->p2];
6477 assert( pIn2->flags & MEM_Blob );
6478 assert( pC->isTable==0 );
6479 rc = ExpandBlob(pIn2);
6480 if( rc ) goto abort_due_to_error;
6481 rc = sqlite3VdbeSorterWrite(pC, pIn2);
6482 if( rc) goto abort_due_to_error;
6483 break;
6486 /* Opcode: IdxDelete P1 P2 P3 * P5
6487 ** Synopsis: key=r[P2@P3]
6489 ** The content of P3 registers starting at register P2 form
6490 ** an unpacked index key. This opcode removes that entry from the
6491 ** index opened by cursor P1.
6493 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
6494 ** if no matching index entry is found. This happens when running
6495 ** an UPDATE or DELETE statement and the index entry to be updated
6496 ** or deleted is not found. For some uses of IdxDelete
6497 ** (example: the EXCEPT operator) it does not matter that no matching
6498 ** entry is found. For those cases, P5 is zero. Also, do not raise
6499 ** this (self-correcting and non-critical) error if in writable_schema mode.
6501 case OP_IdxDelete: {
6502 VdbeCursor *pC;
6503 BtCursor *pCrsr;
6504 int res;
6505 UnpackedRecord r;
6507 assert( pOp->p3>0 );
6508 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
6509 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6510 pC = p->apCsr[pOp->p1];
6511 assert( pC!=0 );
6512 assert( pC->eCurType==CURTYPE_BTREE );
6513 sqlite3VdbeIncrWriteCounter(p, pC);
6514 pCrsr = pC->uc.pCursor;
6515 assert( pCrsr!=0 );
6516 r.pKeyInfo = pC->pKeyInfo;
6517 r.nField = (u16)pOp->p3;
6518 r.default_rc = 0;
6519 r.aMem = &aMem[pOp->p2];
6520 rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
6521 if( rc ) goto abort_due_to_error;
6522 if( res==0 ){
6523 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
6524 if( rc ) goto abort_due_to_error;
6525 }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
6526 rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
6527 goto abort_due_to_error;
6529 assert( pC->deferredMoveto==0 );
6530 pC->cacheStatus = CACHE_STALE;
6531 pC->seekResult = 0;
6532 break;
6535 /* Opcode: DeferredSeek P1 * P3 P4 *
6536 ** Synopsis: Move P3 to P1.rowid if needed
6538 ** P1 is an open index cursor and P3 is a cursor on the corresponding
6539 ** table. This opcode does a deferred seek of the P3 table cursor
6540 ** to the row that corresponds to the current row of P1.
6542 ** This is a deferred seek. Nothing actually happens until
6543 ** the cursor is used to read a record. That way, if no reads
6544 ** occur, no unnecessary I/O happens.
6546 ** P4 may be an array of integers (type P4_INTARRAY) containing
6547 ** one entry for each column in the P3 table. If array entry a(i)
6548 ** is non-zero, then reading column a(i)-1 from cursor P3 is
6549 ** equivalent to performing the deferred seek and then reading column i
6550 ** from P1. This information is stored in P3 and used to redirect
6551 ** reads against P3 over to P1, thus possibly avoiding the need to
6552 ** seek and read cursor P3.
6554 /* Opcode: IdxRowid P1 P2 * * *
6555 ** Synopsis: r[P2]=rowid
6557 ** Write into register P2 an integer which is the last entry in the record at
6558 ** the end of the index key pointed to by cursor P1. This integer should be
6559 ** the rowid of the table entry to which this index entry points.
6561 ** See also: Rowid, MakeRecord.
6563 case OP_DeferredSeek: /* ncycle */
6564 case OP_IdxRowid: { /* out2, ncycle */
6565 VdbeCursor *pC; /* The P1 index cursor */
6566 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
6567 i64 rowid; /* Rowid that P1 current points to */
6569 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6570 pC = p->apCsr[pOp->p1];
6571 assert( pC!=0 );
6572 assert( pC->eCurType==CURTYPE_BTREE || IsNullCursor(pC) );
6573 assert( pC->uc.pCursor!=0 );
6574 assert( pC->isTable==0 || IsNullCursor(pC) );
6575 assert( pC->deferredMoveto==0 );
6576 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
6578 /* The IdxRowid and Seek opcodes are combined because of the commonality
6579 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
6580 rc = sqlite3VdbeCursorRestore(pC);
6582 /* sqlite3VdbeCursorRestore() may fail if the cursor has been disturbed
6583 ** since it was last positioned and an error (e.g. OOM or an IO error)
6584 ** occurs while trying to reposition it. */
6585 if( rc!=SQLITE_OK ) goto abort_due_to_error;
6587 if( !pC->nullRow ){
6588 rowid = 0; /* Not needed. Only used to silence a warning. */
6589 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
6590 if( rc!=SQLITE_OK ){
6591 goto abort_due_to_error;
6593 if( pOp->opcode==OP_DeferredSeek ){
6594 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
6595 pTabCur = p->apCsr[pOp->p3];
6596 assert( pTabCur!=0 );
6597 assert( pTabCur->eCurType==CURTYPE_BTREE );
6598 assert( pTabCur->uc.pCursor!=0 );
6599 assert( pTabCur->isTable );
6600 pTabCur->nullRow = 0;
6601 pTabCur->movetoTarget = rowid;
6602 pTabCur->deferredMoveto = 1;
6603 pTabCur->cacheStatus = CACHE_STALE;
6604 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
6605 assert( !pTabCur->isEphemeral );
6606 pTabCur->ub.aAltMap = pOp->p4.ai;
6607 assert( !pC->isEphemeral );
6608 pTabCur->pAltCursor = pC;
6609 }else{
6610 pOut = out2Prerelease(p, pOp);
6611 pOut->u.i = rowid;
6613 }else{
6614 assert( pOp->opcode==OP_IdxRowid );
6615 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
6617 break;
6620 /* Opcode: FinishSeek P1 * * * *
6622 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
6623 ** seek operation now, without further delay. If the cursor seek has
6624 ** already occurred, this instruction is a no-op.
6626 case OP_FinishSeek: { /* ncycle */
6627 VdbeCursor *pC; /* The P1 index cursor */
6629 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6630 pC = p->apCsr[pOp->p1];
6631 if( pC->deferredMoveto ){
6632 rc = sqlite3VdbeFinishMoveto(pC);
6633 if( rc ) goto abort_due_to_error;
6635 break;
6638 /* Opcode: IdxGE P1 P2 P3 P4 *
6639 ** Synopsis: key=r[P3@P4]
6641 ** The P4 register values beginning with P3 form an unpacked index
6642 ** key that omits the PRIMARY KEY. Compare this key value against the index
6643 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6644 ** fields at the end.
6646 ** If the P1 index entry is greater than or equal to the key value
6647 ** then jump to P2. Otherwise fall through to the next instruction.
6649 /* Opcode: IdxGT P1 P2 P3 P4 *
6650 ** Synopsis: key=r[P3@P4]
6652 ** The P4 register values beginning with P3 form an unpacked index
6653 ** key that omits the PRIMARY KEY. Compare this key value against the index
6654 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6655 ** fields at the end.
6657 ** If the P1 index entry is greater than the key value
6658 ** then jump to P2. Otherwise fall through to the next instruction.
6660 /* Opcode: IdxLT P1 P2 P3 P4 *
6661 ** Synopsis: key=r[P3@P4]
6663 ** The P4 register values beginning with P3 form an unpacked index
6664 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6665 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6666 ** ROWID on the P1 index.
6668 ** If the P1 index entry is less than the key value then jump to P2.
6669 ** Otherwise fall through to the next instruction.
6671 /* Opcode: IdxLE P1 P2 P3 P4 *
6672 ** Synopsis: key=r[P3@P4]
6674 ** The P4 register values beginning with P3 form an unpacked index
6675 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6676 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6677 ** ROWID on the P1 index.
6679 ** If the P1 index entry is less than or equal to the key value then jump
6680 ** to P2. Otherwise fall through to the next instruction.
6682 case OP_IdxLE: /* jump, ncycle */
6683 case OP_IdxGT: /* jump, ncycle */
6684 case OP_IdxLT: /* jump, ncycle */
6685 case OP_IdxGE: { /* jump, ncycle */
6686 VdbeCursor *pC;
6687 int res;
6688 UnpackedRecord r;
6690 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6691 pC = p->apCsr[pOp->p1];
6692 assert( pC!=0 );
6693 assert( pC->isOrdered );
6694 assert( pC->eCurType==CURTYPE_BTREE );
6695 assert( pC->uc.pCursor!=0);
6696 assert( pC->deferredMoveto==0 );
6697 assert( pOp->p4type==P4_INT32 );
6698 r.pKeyInfo = pC->pKeyInfo;
6699 r.nField = (u16)pOp->p4.i;
6700 if( pOp->opcode<OP_IdxLT ){
6701 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6702 r.default_rc = -1;
6703 }else{
6704 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6705 r.default_rc = 0;
6707 r.aMem = &aMem[pOp->p3];
6708 #ifdef SQLITE_DEBUG
6710 int i;
6711 for(i=0; i<r.nField; i++){
6712 assert( memIsValid(&r.aMem[i]) );
6713 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6716 #endif
6718 /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6720 i64 nCellKey = 0;
6721 BtCursor *pCur;
6722 Mem m;
6724 assert( pC->eCurType==CURTYPE_BTREE );
6725 pCur = pC->uc.pCursor;
6726 assert( sqlite3BtreeCursorIsValid(pCur) );
6727 nCellKey = sqlite3BtreePayloadSize(pCur);
6728 /* nCellKey will always be between 0 and 0xffffffff because of the way
6729 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6730 if( nCellKey<=0 || nCellKey>0x7fffffff ){
6731 rc = SQLITE_CORRUPT_BKPT;
6732 goto abort_due_to_error;
6734 sqlite3VdbeMemInit(&m, db, 0);
6735 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6736 if( rc ) goto abort_due_to_error;
6737 res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6738 sqlite3VdbeMemReleaseMalloc(&m);
6740 /* End of inlined sqlite3VdbeIdxKeyCompare() */
6742 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6743 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6744 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6745 res = -res;
6746 }else{
6747 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6748 res++;
6750 VdbeBranchTaken(res>0,2);
6751 assert( rc==SQLITE_OK );
6752 if( res>0 ) goto jump_to_p2;
6753 break;
6756 /* Opcode: Destroy P1 P2 P3 * *
6758 ** Delete an entire database table or index whose root page in the database
6759 ** file is given by P1.
6761 ** The table being destroyed is in the main database file if P3==0. If
6762 ** P3==1 then the table to be destroyed is in the auxiliary database file
6763 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6765 ** If AUTOVACUUM is enabled then it is possible that another root page
6766 ** might be moved into the newly deleted root page in order to keep all
6767 ** root pages contiguous at the beginning of the database. The former
6768 ** value of the root page that moved - its value before the move occurred -
6769 ** is stored in register P2. If no page movement was required (because the
6770 ** table being dropped was already the last one in the database) then a
6771 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
6772 ** is stored in register P2.
6774 ** This opcode throws an error if there are any active reader VMs when
6775 ** it is invoked. This is done to avoid the difficulty associated with
6776 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6777 ** database. This error is thrown even if the database is not an AUTOVACUUM
6778 ** db in order to avoid introducing an incompatibility between autovacuum
6779 ** and non-autovacuum modes.
6781 ** See also: Clear
6783 case OP_Destroy: { /* out2 */
6784 int iMoved;
6785 int iDb;
6787 sqlite3VdbeIncrWriteCounter(p, 0);
6788 assert( p->readOnly==0 );
6789 assert( pOp->p1>1 );
6790 pOut = out2Prerelease(p, pOp);
6791 pOut->flags = MEM_Null;
6792 if( db->nVdbeRead > db->nVDestroy+1 ){
6793 rc = SQLITE_LOCKED;
6794 p->errorAction = OE_Abort;
6795 goto abort_due_to_error;
6796 }else{
6797 iDb = pOp->p3;
6798 assert( DbMaskTest(p->btreeMask, iDb) );
6799 iMoved = 0; /* Not needed. Only to silence a warning. */
6800 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6801 pOut->flags = MEM_Int;
6802 pOut->u.i = iMoved;
6803 if( rc ) goto abort_due_to_error;
6804 #ifndef SQLITE_OMIT_AUTOVACUUM
6805 if( iMoved!=0 ){
6806 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6807 /* All OP_Destroy operations occur on the same btree */
6808 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6809 resetSchemaOnFault = iDb+1;
6811 #endif
6813 break;
6816 /* Opcode: Clear P1 P2 P3
6818 ** Delete all contents of the database table or index whose root page
6819 ** in the database file is given by P1. But, unlike Destroy, do not
6820 ** remove the table or index from the database file.
6822 ** The table being cleared is in the main database file if P2==0. If
6823 ** P2==1 then the table to be cleared is in the auxiliary database file
6824 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6826 ** If the P3 value is non-zero, then the row change count is incremented
6827 ** by the number of rows in the table being cleared. If P3 is greater
6828 ** than zero, then the value stored in register P3 is also incremented
6829 ** by the number of rows in the table being cleared.
6831 ** See also: Destroy
6833 case OP_Clear: {
6834 i64 nChange;
6836 sqlite3VdbeIncrWriteCounter(p, 0);
6837 nChange = 0;
6838 assert( p->readOnly==0 );
6839 assert( DbMaskTest(p->btreeMask, pOp->p2) );
6840 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
6841 if( pOp->p3 ){
6842 p->nChange += nChange;
6843 if( pOp->p3>0 ){
6844 assert( memIsValid(&aMem[pOp->p3]) );
6845 memAboutToChange(p, &aMem[pOp->p3]);
6846 aMem[pOp->p3].u.i += nChange;
6849 if( rc ) goto abort_due_to_error;
6850 break;
6853 /* Opcode: ResetSorter P1 * * * *
6855 ** Delete all contents from the ephemeral table or sorter
6856 ** that is open on cursor P1.
6858 ** This opcode only works for cursors used for sorting and
6859 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6861 case OP_ResetSorter: {
6862 VdbeCursor *pC;
6864 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6865 pC = p->apCsr[pOp->p1];
6866 assert( pC!=0 );
6867 if( isSorter(pC) ){
6868 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6869 }else{
6870 assert( pC->eCurType==CURTYPE_BTREE );
6871 assert( pC->isEphemeral );
6872 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6873 if( rc ) goto abort_due_to_error;
6875 break;
6878 /* Opcode: CreateBtree P1 P2 P3 * *
6879 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6881 ** Allocate a new b-tree in the main database file if P1==0 or in the
6882 ** TEMP database file if P1==1 or in an attached database if
6883 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6884 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6885 ** The root page number of the new b-tree is stored in register P2.
6887 case OP_CreateBtree: { /* out2 */
6888 Pgno pgno;
6889 Db *pDb;
6891 sqlite3VdbeIncrWriteCounter(p, 0);
6892 pOut = out2Prerelease(p, pOp);
6893 pgno = 0;
6894 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6895 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6896 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6897 assert( p->readOnly==0 );
6898 pDb = &db->aDb[pOp->p1];
6899 assert( pDb->pBt!=0 );
6900 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6901 if( rc ) goto abort_due_to_error;
6902 pOut->u.i = pgno;
6903 break;
6906 /* Opcode: SqlExec * * * P4 *
6908 ** Run the SQL statement or statements specified in the P4 string.
6909 ** Disable Auth and Trace callbacks while those statements are running if
6910 ** P1 is true.
6912 case OP_SqlExec: {
6913 char *zErr;
6914 #ifndef SQLITE_OMIT_AUTHORIZATION
6915 sqlite3_xauth xAuth;
6916 #endif
6917 u8 mTrace;
6919 sqlite3VdbeIncrWriteCounter(p, 0);
6920 db->nSqlExec++;
6921 zErr = 0;
6922 #ifndef SQLITE_OMIT_AUTHORIZATION
6923 xAuth = db->xAuth;
6924 #endif
6925 mTrace = db->mTrace;
6926 if( pOp->p1 ){
6927 #ifndef SQLITE_OMIT_AUTHORIZATION
6928 db->xAuth = 0;
6929 #endif
6930 db->mTrace = 0;
6932 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, &zErr);
6933 db->nSqlExec--;
6934 #ifndef SQLITE_OMIT_AUTHORIZATION
6935 db->xAuth = xAuth;
6936 #endif
6937 db->mTrace = mTrace;
6938 if( zErr || rc ){
6939 sqlite3VdbeError(p, "%s", zErr);
6940 sqlite3_free(zErr);
6941 if( rc==SQLITE_NOMEM ) goto no_mem;
6942 goto abort_due_to_error;
6944 break;
6947 /* Opcode: ParseSchema P1 * * P4 *
6949 ** Read and parse all entries from the schema table of database P1
6950 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
6951 ** entire schema for P1 is reparsed.
6953 ** This opcode invokes the parser to create a new virtual machine,
6954 ** then runs the new virtual machine. It is thus a re-entrant opcode.
6956 case OP_ParseSchema: {
6957 int iDb;
6958 const char *zSchema;
6959 char *zSql;
6960 InitData initData;
6962 /* Any prepared statement that invokes this opcode will hold mutexes
6963 ** on every btree. This is a prerequisite for invoking
6964 ** sqlite3InitCallback().
6966 #ifdef SQLITE_DEBUG
6967 for(iDb=0; iDb<db->nDb; iDb++){
6968 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
6970 #endif
6972 iDb = pOp->p1;
6973 assert( iDb>=0 && iDb<db->nDb );
6974 assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
6975 || db->mallocFailed
6976 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
6978 #ifndef SQLITE_OMIT_ALTERTABLE
6979 if( pOp->p4.z==0 ){
6980 sqlite3SchemaClear(db->aDb[iDb].pSchema);
6981 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
6982 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
6983 db->mDbFlags |= DBFLAG_SchemaChange;
6984 p->expired = 0;
6985 }else
6986 #endif
6988 zSchema = LEGACY_SCHEMA_TABLE;
6989 initData.db = db;
6990 initData.iDb = iDb;
6991 initData.pzErrMsg = &p->zErrMsg;
6992 initData.mInitFlags = 0;
6993 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
6994 zSql = sqlite3MPrintf(db,
6995 "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
6996 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
6997 if( zSql==0 ){
6998 rc = SQLITE_NOMEM_BKPT;
6999 }else{
7000 assert( db->init.busy==0 );
7001 db->init.busy = 1;
7002 initData.rc = SQLITE_OK;
7003 initData.nInitRow = 0;
7004 assert( !db->mallocFailed );
7005 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
7006 if( rc==SQLITE_OK ) rc = initData.rc;
7007 if( rc==SQLITE_OK && initData.nInitRow==0 ){
7008 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
7009 ** at least one SQL statement. Any less than that indicates that
7010 ** the sqlite_schema table is corrupt. */
7011 rc = SQLITE_CORRUPT_BKPT;
7013 sqlite3DbFreeNN(db, zSql);
7014 db->init.busy = 0;
7017 if( rc ){
7018 sqlite3ResetAllSchemasOfConnection(db);
7019 if( rc==SQLITE_NOMEM ){
7020 goto no_mem;
7022 goto abort_due_to_error;
7024 break;
7027 #if !defined(SQLITE_OMIT_ANALYZE)
7028 /* Opcode: LoadAnalysis P1 * * * *
7030 ** Read the sqlite_stat1 table for database P1 and load the content
7031 ** of that table into the internal index hash table. This will cause
7032 ** the analysis to be used when preparing all subsequent queries.
7034 case OP_LoadAnalysis: {
7035 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7036 rc = sqlite3AnalysisLoad(db, pOp->p1);
7037 if( rc ) goto abort_due_to_error;
7038 break;
7040 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
7042 /* Opcode: DropTable P1 * * P4 *
7044 ** Remove the internal (in-memory) data structures that describe
7045 ** the table named P4 in database P1. This is called after a table
7046 ** is dropped from disk (using the Destroy opcode) in order to keep
7047 ** the internal representation of the
7048 ** schema consistent with what is on disk.
7050 case OP_DropTable: {
7051 sqlite3VdbeIncrWriteCounter(p, 0);
7052 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
7053 break;
7056 /* Opcode: DropIndex P1 * * P4 *
7058 ** Remove the internal (in-memory) data structures that describe
7059 ** the index named P4 in database P1. This is called after an index
7060 ** is dropped from disk (using the Destroy opcode)
7061 ** in order to keep the internal representation of the
7062 ** schema consistent with what is on disk.
7064 case OP_DropIndex: {
7065 sqlite3VdbeIncrWriteCounter(p, 0);
7066 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
7067 break;
7070 /* Opcode: DropTrigger P1 * * P4 *
7072 ** Remove the internal (in-memory) data structures that describe
7073 ** the trigger named P4 in database P1. This is called after a trigger
7074 ** is dropped from disk (using the Destroy opcode) in order to keep
7075 ** the internal representation of the
7076 ** schema consistent with what is on disk.
7078 case OP_DropTrigger: {
7079 sqlite3VdbeIncrWriteCounter(p, 0);
7080 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
7081 break;
7085 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
7086 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
7088 ** Do an analysis of the currently open database. Store in
7089 ** register P1 the text of an error message describing any problems.
7090 ** If no problems are found, store a NULL in register P1.
7092 ** The register P3 contains one less than the maximum number of allowed errors.
7093 ** At most reg(P3) errors will be reported.
7094 ** In other words, the analysis stops as soon as reg(P1) errors are
7095 ** seen. Reg(P1) is updated with the number of errors remaining.
7097 ** The root page numbers of all tables in the database are integers
7098 ** stored in P4_INTARRAY argument.
7100 ** If P5 is not zero, the check is done on the auxiliary database
7101 ** file, not the main database file.
7103 ** This opcode is used to implement the integrity_check pragma.
7105 case OP_IntegrityCk: {
7106 int nRoot; /* Number of tables to check. (Number of root pages.) */
7107 Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */
7108 int nErr; /* Number of errors reported */
7109 char *z; /* Text of the error report */
7110 Mem *pnErr; /* Register keeping track of errors remaining */
7112 assert( p->bIsReader );
7113 nRoot = pOp->p2;
7114 aRoot = pOp->p4.ai;
7115 assert( nRoot>0 );
7116 assert( aRoot[0]==(Pgno)nRoot );
7117 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7118 pnErr = &aMem[pOp->p3];
7119 assert( (pnErr->flags & MEM_Int)!=0 );
7120 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
7121 pIn1 = &aMem[pOp->p1];
7122 assert( pOp->p5<db->nDb );
7123 assert( DbMaskTest(p->btreeMask, pOp->p5) );
7124 rc = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
7125 (int)pnErr->u.i+1, &nErr, &z);
7126 sqlite3VdbeMemSetNull(pIn1);
7127 if( nErr==0 ){
7128 assert( z==0 );
7129 }else if( rc ){
7130 sqlite3_free(z);
7131 goto abort_due_to_error;
7132 }else{
7133 pnErr->u.i -= nErr-1;
7134 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
7136 UPDATE_MAX_BLOBSIZE(pIn1);
7137 sqlite3VdbeChangeEncoding(pIn1, encoding);
7138 goto check_for_interrupt;
7140 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
7142 /* Opcode: RowSetAdd P1 P2 * * *
7143 ** Synopsis: rowset(P1)=r[P2]
7145 ** Insert the integer value held by register P2 into a RowSet object
7146 ** held in register P1.
7148 ** An assertion fails if P2 is not an integer.
7150 case OP_RowSetAdd: { /* in1, in2 */
7151 pIn1 = &aMem[pOp->p1];
7152 pIn2 = &aMem[pOp->p2];
7153 assert( (pIn2->flags & MEM_Int)!=0 );
7154 if( (pIn1->flags & MEM_Blob)==0 ){
7155 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7157 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7158 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
7159 break;
7162 /* Opcode: RowSetRead P1 P2 P3 * *
7163 ** Synopsis: r[P3]=rowset(P1)
7165 ** Extract the smallest value from the RowSet object in P1
7166 ** and put that value into register P3.
7167 ** Or, if RowSet object P1 is initially empty, leave P3
7168 ** unchanged and jump to instruction P2.
7170 case OP_RowSetRead: { /* jump, in1, out3 */
7171 i64 val;
7173 pIn1 = &aMem[pOp->p1];
7174 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
7175 if( (pIn1->flags & MEM_Blob)==0
7176 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
7178 /* The boolean index is empty */
7179 sqlite3VdbeMemSetNull(pIn1);
7180 VdbeBranchTaken(1,2);
7181 goto jump_to_p2_and_check_for_interrupt;
7182 }else{
7183 /* A value was pulled from the index */
7184 VdbeBranchTaken(0,2);
7185 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
7187 goto check_for_interrupt;
7190 /* Opcode: RowSetTest P1 P2 P3 P4
7191 ** Synopsis: if r[P3] in rowset(P1) goto P2
7193 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
7194 ** contains a RowSet object and that RowSet object contains
7195 ** the value held in P3, jump to register P2. Otherwise, insert the
7196 ** integer in P3 into the RowSet and continue on to the
7197 ** next opcode.
7199 ** The RowSet object is optimized for the case where sets of integers
7200 ** are inserted in distinct phases, which each set contains no duplicates.
7201 ** Each set is identified by a unique P4 value. The first set
7202 ** must have P4==0, the final set must have P4==-1, and for all other sets
7203 ** must have P4>0.
7205 ** This allows optimizations: (a) when P4==0 there is no need to test
7206 ** the RowSet object for P3, as it is guaranteed not to contain it,
7207 ** (b) when P4==-1 there is no need to insert the value, as it will
7208 ** never be tested for, and (c) when a value that is part of set X is
7209 ** inserted, there is no need to search to see if the same value was
7210 ** previously inserted as part of set X (only if it was previously
7211 ** inserted as part of some other set).
7213 case OP_RowSetTest: { /* jump, in1, in3 */
7214 int iSet;
7215 int exists;
7217 pIn1 = &aMem[pOp->p1];
7218 pIn3 = &aMem[pOp->p3];
7219 iSet = pOp->p4.i;
7220 assert( pIn3->flags&MEM_Int );
7222 /* If there is anything other than a rowset object in memory cell P1,
7223 ** delete it now and initialize P1 with an empty rowset
7225 if( (pIn1->flags & MEM_Blob)==0 ){
7226 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7228 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7229 assert( pOp->p4type==P4_INT32 );
7230 assert( iSet==-1 || iSet>=0 );
7231 if( iSet ){
7232 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
7233 VdbeBranchTaken(exists!=0,2);
7234 if( exists ) goto jump_to_p2;
7236 if( iSet>=0 ){
7237 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
7239 break;
7243 #ifndef SQLITE_OMIT_TRIGGER
7245 /* Opcode: Program P1 P2 P3 P4 P5
7247 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
7249 ** P1 contains the address of the memory cell that contains the first memory
7250 ** cell in an array of values used as arguments to the sub-program. P2
7251 ** contains the address to jump to if the sub-program throws an IGNORE
7252 ** exception using the RAISE() function. Register P3 contains the address
7253 ** of a memory cell in this (the parent) VM that is used to allocate the
7254 ** memory required by the sub-vdbe at runtime.
7256 ** P4 is a pointer to the VM containing the trigger program.
7258 ** If P5 is non-zero, then recursive program invocation is enabled.
7260 case OP_Program: { /* jump */
7261 int nMem; /* Number of memory registers for sub-program */
7262 int nByte; /* Bytes of runtime space required for sub-program */
7263 Mem *pRt; /* Register to allocate runtime space */
7264 Mem *pMem; /* Used to iterate through memory cells */
7265 Mem *pEnd; /* Last memory cell in new array */
7266 VdbeFrame *pFrame; /* New vdbe frame to execute in */
7267 SubProgram *pProgram; /* Sub-program to execute */
7268 void *t; /* Token identifying trigger */
7270 pProgram = pOp->p4.pProgram;
7271 pRt = &aMem[pOp->p3];
7272 assert( pProgram->nOp>0 );
7274 /* If the p5 flag is clear, then recursive invocation of triggers is
7275 ** disabled for backwards compatibility (p5 is set if this sub-program
7276 ** is really a trigger, not a foreign key action, and the flag set
7277 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
7279 ** It is recursive invocation of triggers, at the SQL level, that is
7280 ** disabled. In some cases a single trigger may generate more than one
7281 ** SubProgram (if the trigger may be executed with more than one different
7282 ** ON CONFLICT algorithm). SubProgram structures associated with a
7283 ** single trigger all have the same value for the SubProgram.token
7284 ** variable. */
7285 if( pOp->p5 ){
7286 t = pProgram->token;
7287 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
7288 if( pFrame ) break;
7291 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
7292 rc = SQLITE_ERROR;
7293 sqlite3VdbeError(p, "too many levels of trigger recursion");
7294 goto abort_due_to_error;
7297 /* Register pRt is used to store the memory required to save the state
7298 ** of the current program, and the memory required at runtime to execute
7299 ** the trigger program. If this trigger has been fired before, then pRt
7300 ** is already allocated. Otherwise, it must be initialized. */
7301 if( (pRt->flags&MEM_Blob)==0 ){
7302 /* SubProgram.nMem is set to the number of memory cells used by the
7303 ** program stored in SubProgram.aOp. As well as these, one memory
7304 ** cell is required for each cursor used by the program. Set local
7305 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
7307 nMem = pProgram->nMem + pProgram->nCsr;
7308 assert( nMem>0 );
7309 if( pProgram->nCsr==0 ) nMem++;
7310 nByte = ROUND8(sizeof(VdbeFrame))
7311 + nMem * sizeof(Mem)
7312 + pProgram->nCsr * sizeof(VdbeCursor*)
7313 + (pProgram->nOp + 7)/8;
7314 pFrame = sqlite3DbMallocZero(db, nByte);
7315 if( !pFrame ){
7316 goto no_mem;
7318 sqlite3VdbeMemRelease(pRt);
7319 pRt->flags = MEM_Blob|MEM_Dyn;
7320 pRt->z = (char*)pFrame;
7321 pRt->n = nByte;
7322 pRt->xDel = sqlite3VdbeFrameMemDel;
7324 pFrame->v = p;
7325 pFrame->nChildMem = nMem;
7326 pFrame->nChildCsr = pProgram->nCsr;
7327 pFrame->pc = (int)(pOp - aOp);
7328 pFrame->aMem = p->aMem;
7329 pFrame->nMem = p->nMem;
7330 pFrame->apCsr = p->apCsr;
7331 pFrame->nCursor = p->nCursor;
7332 pFrame->aOp = p->aOp;
7333 pFrame->nOp = p->nOp;
7334 pFrame->token = pProgram->token;
7335 #ifdef SQLITE_DEBUG
7336 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
7337 #endif
7339 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
7340 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
7341 pMem->flags = MEM_Undefined;
7342 pMem->db = db;
7344 }else{
7345 pFrame = (VdbeFrame*)pRt->z;
7346 assert( pRt->xDel==sqlite3VdbeFrameMemDel );
7347 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
7348 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
7349 assert( pProgram->nCsr==pFrame->nChildCsr );
7350 assert( (int)(pOp - aOp)==pFrame->pc );
7353 p->nFrame++;
7354 pFrame->pParent = p->pFrame;
7355 pFrame->lastRowid = db->lastRowid;
7356 pFrame->nChange = p->nChange;
7357 pFrame->nDbChange = p->db->nChange;
7358 assert( pFrame->pAuxData==0 );
7359 pFrame->pAuxData = p->pAuxData;
7360 p->pAuxData = 0;
7361 p->nChange = 0;
7362 p->pFrame = pFrame;
7363 p->aMem = aMem = VdbeFrameMem(pFrame);
7364 p->nMem = pFrame->nChildMem;
7365 p->nCursor = (u16)pFrame->nChildCsr;
7366 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
7367 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
7368 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
7369 p->aOp = aOp = pProgram->aOp;
7370 p->nOp = pProgram->nOp;
7371 #ifdef SQLITE_DEBUG
7372 /* Verify that second and subsequent executions of the same trigger do not
7373 ** try to reuse register values from the first use. */
7375 int i;
7376 for(i=0; i<p->nMem; i++){
7377 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
7378 MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
7381 #endif
7382 pOp = &aOp[-1];
7383 goto check_for_interrupt;
7386 /* Opcode: Param P1 P2 * * *
7388 ** This opcode is only ever present in sub-programs called via the
7389 ** OP_Program instruction. Copy a value currently stored in a memory
7390 ** cell of the calling (parent) frame to cell P2 in the current frames
7391 ** address space. This is used by trigger programs to access the new.*
7392 ** and old.* values.
7394 ** The address of the cell in the parent frame is determined by adding
7395 ** the value of the P1 argument to the value of the P1 argument to the
7396 ** calling OP_Program instruction.
7398 case OP_Param: { /* out2 */
7399 VdbeFrame *pFrame;
7400 Mem *pIn;
7401 pOut = out2Prerelease(p, pOp);
7402 pFrame = p->pFrame;
7403 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
7404 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
7405 break;
7408 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
7410 #ifndef SQLITE_OMIT_FOREIGN_KEY
7411 /* Opcode: FkCounter P1 P2 * * *
7412 ** Synopsis: fkctr[P1]+=P2
7414 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
7415 ** If P1 is non-zero, the database constraint counter is incremented
7416 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
7417 ** statement counter is incremented (immediate foreign key constraints).
7419 case OP_FkCounter: {
7420 if( db->flags & SQLITE_DeferFKs ){
7421 db->nDeferredImmCons += pOp->p2;
7422 }else if( pOp->p1 ){
7423 db->nDeferredCons += pOp->p2;
7424 }else{
7425 p->nFkConstraint += pOp->p2;
7427 break;
7430 /* Opcode: FkIfZero P1 P2 * * *
7431 ** Synopsis: if fkctr[P1]==0 goto P2
7433 ** This opcode tests if a foreign key constraint-counter is currently zero.
7434 ** If so, jump to instruction P2. Otherwise, fall through to the next
7435 ** instruction.
7437 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
7438 ** is zero (the one that counts deferred constraint violations). If P1 is
7439 ** zero, the jump is taken if the statement constraint-counter is zero
7440 ** (immediate foreign key constraint violations).
7442 case OP_FkIfZero: { /* jump */
7443 if( pOp->p1 ){
7444 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
7445 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7446 }else{
7447 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
7448 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7450 break;
7452 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
7454 #ifndef SQLITE_OMIT_AUTOINCREMENT
7455 /* Opcode: MemMax P1 P2 * * *
7456 ** Synopsis: r[P1]=max(r[P1],r[P2])
7458 ** P1 is a register in the root frame of this VM (the root frame is
7459 ** different from the current frame if this instruction is being executed
7460 ** within a sub-program). Set the value of register P1 to the maximum of
7461 ** its current value and the value in register P2.
7463 ** This instruction throws an error if the memory cell is not initially
7464 ** an integer.
7466 case OP_MemMax: { /* in2 */
7467 VdbeFrame *pFrame;
7468 if( p->pFrame ){
7469 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
7470 pIn1 = &pFrame->aMem[pOp->p1];
7471 }else{
7472 pIn1 = &aMem[pOp->p1];
7474 assert( memIsValid(pIn1) );
7475 sqlite3VdbeMemIntegerify(pIn1);
7476 pIn2 = &aMem[pOp->p2];
7477 sqlite3VdbeMemIntegerify(pIn2);
7478 if( pIn1->u.i<pIn2->u.i){
7479 pIn1->u.i = pIn2->u.i;
7481 break;
7483 #endif /* SQLITE_OMIT_AUTOINCREMENT */
7485 /* Opcode: IfPos P1 P2 P3 * *
7486 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
7488 ** Register P1 must contain an integer.
7489 ** If the value of register P1 is 1 or greater, subtract P3 from the
7490 ** value in P1 and jump to P2.
7492 ** If the initial value of register P1 is less than 1, then the
7493 ** value is unchanged and control passes through to the next instruction.
7495 case OP_IfPos: { /* jump, in1 */
7496 pIn1 = &aMem[pOp->p1];
7497 assert( pIn1->flags&MEM_Int );
7498 VdbeBranchTaken( pIn1->u.i>0, 2);
7499 if( pIn1->u.i>0 ){
7500 pIn1->u.i -= pOp->p3;
7501 goto jump_to_p2;
7503 break;
7506 /* Opcode: OffsetLimit P1 P2 P3 * *
7507 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
7509 ** This opcode performs a commonly used computation associated with
7510 ** LIMIT and OFFSET processing. r[P1] holds the limit counter. r[P3]
7511 ** holds the offset counter. The opcode computes the combined value
7512 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
7513 ** value computed is the total number of rows that will need to be
7514 ** visited in order to complete the query.
7516 ** If r[P3] is zero or negative, that means there is no OFFSET
7517 ** and r[P2] is set to be the value of the LIMIT, r[P1].
7519 ** if r[P1] is zero or negative, that means there is no LIMIT
7520 ** and r[P2] is set to -1.
7522 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
7524 case OP_OffsetLimit: { /* in1, out2, in3 */
7525 i64 x;
7526 pIn1 = &aMem[pOp->p1];
7527 pIn3 = &aMem[pOp->p3];
7528 pOut = out2Prerelease(p, pOp);
7529 assert( pIn1->flags & MEM_Int );
7530 assert( pIn3->flags & MEM_Int );
7531 x = pIn1->u.i;
7532 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
7533 /* If the LIMIT is less than or equal to zero, loop forever. This
7534 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
7535 ** also loop forever. This is undocumented. In fact, one could argue
7536 ** that the loop should terminate. But assuming 1 billion iterations
7537 ** per second (far exceeding the capabilities of any current hardware)
7538 ** it would take nearly 300 years to actually reach the limit. So
7539 ** looping forever is a reasonable approximation. */
7540 pOut->u.i = -1;
7541 }else{
7542 pOut->u.i = x;
7544 break;
7547 /* Opcode: IfNotZero P1 P2 * * *
7548 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
7550 ** Register P1 must contain an integer. If the content of register P1 is
7551 ** initially greater than zero, then decrement the value in register P1.
7552 ** If it is non-zero (negative or positive) and then also jump to P2.
7553 ** If register P1 is initially zero, leave it unchanged and fall through.
7555 case OP_IfNotZero: { /* jump, in1 */
7556 pIn1 = &aMem[pOp->p1];
7557 assert( pIn1->flags&MEM_Int );
7558 VdbeBranchTaken(pIn1->u.i<0, 2);
7559 if( pIn1->u.i ){
7560 if( pIn1->u.i>0 ) pIn1->u.i--;
7561 goto jump_to_p2;
7563 break;
7566 /* Opcode: DecrJumpZero P1 P2 * * *
7567 ** Synopsis: if (--r[P1])==0 goto P2
7569 ** Register P1 must hold an integer. Decrement the value in P1
7570 ** and jump to P2 if the new value is exactly zero.
7572 case OP_DecrJumpZero: { /* jump, in1 */
7573 pIn1 = &aMem[pOp->p1];
7574 assert( pIn1->flags&MEM_Int );
7575 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
7576 VdbeBranchTaken(pIn1->u.i==0, 2);
7577 if( pIn1->u.i==0 ) goto jump_to_p2;
7578 break;
7582 /* Opcode: AggStep * P2 P3 P4 P5
7583 ** Synopsis: accum=r[P3] step(r[P2@P5])
7585 ** Execute the xStep function for an aggregate.
7586 ** The function has P5 arguments. P4 is a pointer to the
7587 ** FuncDef structure that specifies the function. Register P3 is the
7588 ** accumulator.
7590 ** The P5 arguments are taken from register P2 and its
7591 ** successors.
7593 /* Opcode: AggInverse * P2 P3 P4 P5
7594 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
7596 ** Execute the xInverse function for an aggregate.
7597 ** The function has P5 arguments. P4 is a pointer to the
7598 ** FuncDef structure that specifies the function. Register P3 is the
7599 ** accumulator.
7601 ** The P5 arguments are taken from register P2 and its
7602 ** successors.
7604 /* Opcode: AggStep1 P1 P2 P3 P4 P5
7605 ** Synopsis: accum=r[P3] step(r[P2@P5])
7607 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
7608 ** aggregate. The function has P5 arguments. P4 is a pointer to the
7609 ** FuncDef structure that specifies the function. Register P3 is the
7610 ** accumulator.
7612 ** The P5 arguments are taken from register P2 and its
7613 ** successors.
7615 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
7616 ** the FuncDef stored in P4 is converted into an sqlite3_context and
7617 ** the opcode is changed. In this way, the initialization of the
7618 ** sqlite3_context only happens once, instead of on each call to the
7619 ** step function.
7621 case OP_AggInverse:
7622 case OP_AggStep: {
7623 int n;
7624 sqlite3_context *pCtx;
7626 assert( pOp->p4type==P4_FUNCDEF );
7627 n = pOp->p5;
7628 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7629 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7630 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7631 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
7632 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
7633 if( pCtx==0 ) goto no_mem;
7634 pCtx->pMem = 0;
7635 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
7636 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
7637 pCtx->pFunc = pOp->p4.pFunc;
7638 pCtx->iOp = (int)(pOp - aOp);
7639 pCtx->pVdbe = p;
7640 pCtx->skipFlag = 0;
7641 pCtx->isError = 0;
7642 pCtx->enc = encoding;
7643 pCtx->argc = n;
7644 pOp->p4type = P4_FUNCCTX;
7645 pOp->p4.pCtx = pCtx;
7647 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
7648 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
7650 pOp->opcode = OP_AggStep1;
7651 /* Fall through into OP_AggStep */
7652 /* no break */ deliberate_fall_through
7654 case OP_AggStep1: {
7655 int i;
7656 sqlite3_context *pCtx;
7657 Mem *pMem;
7659 assert( pOp->p4type==P4_FUNCCTX );
7660 pCtx = pOp->p4.pCtx;
7661 pMem = &aMem[pOp->p3];
7663 #ifdef SQLITE_DEBUG
7664 if( pOp->p1 ){
7665 /* This is an OP_AggInverse call. Verify that xStep has always
7666 ** been called at least once prior to any xInverse call. */
7667 assert( pMem->uTemp==0x1122e0e3 );
7668 }else{
7669 /* This is an OP_AggStep call. Mark it as such. */
7670 pMem->uTemp = 0x1122e0e3;
7672 #endif
7674 /* If this function is inside of a trigger, the register array in aMem[]
7675 ** might change from one evaluation to the next. The next block of code
7676 ** checks to see if the register array has changed, and if so it
7677 ** reinitializes the relevant parts of the sqlite3_context object */
7678 if( pCtx->pMem != pMem ){
7679 pCtx->pMem = pMem;
7680 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7683 #ifdef SQLITE_DEBUG
7684 for(i=0; i<pCtx->argc; i++){
7685 assert( memIsValid(pCtx->argv[i]) );
7686 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7688 #endif
7690 pMem->n++;
7691 assert( pCtx->pOut->flags==MEM_Null );
7692 assert( pCtx->isError==0 );
7693 assert( pCtx->skipFlag==0 );
7694 #ifndef SQLITE_OMIT_WINDOWFUNC
7695 if( pOp->p1 ){
7696 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7697 }else
7698 #endif
7699 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7701 if( pCtx->isError ){
7702 if( pCtx->isError>0 ){
7703 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7704 rc = pCtx->isError;
7706 if( pCtx->skipFlag ){
7707 assert( pOp[-1].opcode==OP_CollSeq );
7708 i = pOp[-1].p1;
7709 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7710 pCtx->skipFlag = 0;
7712 sqlite3VdbeMemRelease(pCtx->pOut);
7713 pCtx->pOut->flags = MEM_Null;
7714 pCtx->isError = 0;
7715 if( rc ) goto abort_due_to_error;
7717 assert( pCtx->pOut->flags==MEM_Null );
7718 assert( pCtx->skipFlag==0 );
7719 break;
7722 /* Opcode: AggFinal P1 P2 * P4 *
7723 ** Synopsis: accum=r[P1] N=P2
7725 ** P1 is the memory location that is the accumulator for an aggregate
7726 ** or window function. Execute the finalizer function
7727 ** for an aggregate and store the result in P1.
7729 ** P2 is the number of arguments that the step function takes and
7730 ** P4 is a pointer to the FuncDef for this function. The P2
7731 ** argument is not used by this opcode. It is only there to disambiguate
7732 ** functions that can take varying numbers of arguments. The
7733 ** P4 argument is only needed for the case where
7734 ** the step function was not previously called.
7736 /* Opcode: AggValue * P2 P3 P4 *
7737 ** Synopsis: r[P3]=value N=P2
7739 ** Invoke the xValue() function and store the result in register P3.
7741 ** P2 is the number of arguments that the step function takes and
7742 ** P4 is a pointer to the FuncDef for this function. The P2
7743 ** argument is not used by this opcode. It is only there to disambiguate
7744 ** functions that can take varying numbers of arguments. The
7745 ** P4 argument is only needed for the case where
7746 ** the step function was not previously called.
7748 case OP_AggValue:
7749 case OP_AggFinal: {
7750 Mem *pMem;
7751 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7752 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7753 pMem = &aMem[pOp->p1];
7754 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7755 #ifndef SQLITE_OMIT_WINDOWFUNC
7756 if( pOp->p3 ){
7757 memAboutToChange(p, &aMem[pOp->p3]);
7758 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7759 pMem = &aMem[pOp->p3];
7760 }else
7761 #endif
7763 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7766 if( rc ){
7767 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7768 goto abort_due_to_error;
7770 sqlite3VdbeChangeEncoding(pMem, encoding);
7771 UPDATE_MAX_BLOBSIZE(pMem);
7772 REGISTER_TRACE((int)(pMem-aMem), pMem);
7773 break;
7776 #ifndef SQLITE_OMIT_WAL
7777 /* Opcode: Checkpoint P1 P2 P3 * *
7779 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7780 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7781 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
7782 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
7783 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7784 ** in the WAL that have been checkpointed after the checkpoint
7785 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
7786 ** mem[P3+2] are initialized to -1.
7788 case OP_Checkpoint: {
7789 int i; /* Loop counter */
7790 int aRes[3]; /* Results */
7791 Mem *pMem; /* Write results here */
7793 assert( p->readOnly==0 );
7794 aRes[0] = 0;
7795 aRes[1] = aRes[2] = -1;
7796 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7797 || pOp->p2==SQLITE_CHECKPOINT_FULL
7798 || pOp->p2==SQLITE_CHECKPOINT_RESTART
7799 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7801 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7802 if( rc ){
7803 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7804 rc = SQLITE_OK;
7805 aRes[0] = 1;
7807 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7808 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7810 break;
7812 #endif
7814 #ifndef SQLITE_OMIT_PRAGMA
7815 /* Opcode: JournalMode P1 P2 P3 * *
7817 ** Change the journal mode of database P1 to P3. P3 must be one of the
7818 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7819 ** modes (delete, truncate, persist, off and memory), this is a simple
7820 ** operation. No IO is required.
7822 ** If changing into or out of WAL mode the procedure is more complicated.
7824 ** Write a string containing the final journal-mode to register P2.
7826 case OP_JournalMode: { /* out2 */
7827 Btree *pBt; /* Btree to change journal mode of */
7828 Pager *pPager; /* Pager associated with pBt */
7829 int eNew; /* New journal mode */
7830 int eOld; /* The old journal mode */
7831 #ifndef SQLITE_OMIT_WAL
7832 const char *zFilename; /* Name of database file for pPager */
7833 #endif
7835 pOut = out2Prerelease(p, pOp);
7836 eNew = pOp->p3;
7837 assert( eNew==PAGER_JOURNALMODE_DELETE
7838 || eNew==PAGER_JOURNALMODE_TRUNCATE
7839 || eNew==PAGER_JOURNALMODE_PERSIST
7840 || eNew==PAGER_JOURNALMODE_OFF
7841 || eNew==PAGER_JOURNALMODE_MEMORY
7842 || eNew==PAGER_JOURNALMODE_WAL
7843 || eNew==PAGER_JOURNALMODE_QUERY
7845 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7846 assert( p->readOnly==0 );
7848 pBt = db->aDb[pOp->p1].pBt;
7849 pPager = sqlite3BtreePager(pBt);
7850 eOld = sqlite3PagerGetJournalMode(pPager);
7851 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7852 assert( sqlite3BtreeHoldsMutex(pBt) );
7853 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7855 #ifndef SQLITE_OMIT_WAL
7856 zFilename = sqlite3PagerFilename(pPager, 1);
7858 /* Do not allow a transition to journal_mode=WAL for a database
7859 ** in temporary storage or if the VFS does not support shared memory
7861 if( eNew==PAGER_JOURNALMODE_WAL
7862 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
7863 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
7865 eNew = eOld;
7868 if( (eNew!=eOld)
7869 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7871 if( !db->autoCommit || db->nVdbeRead>1 ){
7872 rc = SQLITE_ERROR;
7873 sqlite3VdbeError(p,
7874 "cannot change %s wal mode from within a transaction",
7875 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7877 goto abort_due_to_error;
7878 }else{
7880 if( eOld==PAGER_JOURNALMODE_WAL ){
7881 /* If leaving WAL mode, close the log file. If successful, the call
7882 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7883 ** file. An EXCLUSIVE lock may still be held on the database file
7884 ** after a successful return.
7886 rc = sqlite3PagerCloseWal(pPager, db);
7887 if( rc==SQLITE_OK ){
7888 sqlite3PagerSetJournalMode(pPager, eNew);
7890 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7891 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
7892 ** as an intermediate */
7893 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7896 /* Open a transaction on the database file. Regardless of the journal
7897 ** mode, this transaction always uses a rollback journal.
7899 assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7900 if( rc==SQLITE_OK ){
7901 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7905 #endif /* ifndef SQLITE_OMIT_WAL */
7907 if( rc ) eNew = eOld;
7908 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7910 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7911 pOut->z = (char *)sqlite3JournalModename(eNew);
7912 pOut->n = sqlite3Strlen30(pOut->z);
7913 pOut->enc = SQLITE_UTF8;
7914 sqlite3VdbeChangeEncoding(pOut, encoding);
7915 if( rc ) goto abort_due_to_error;
7916 break;
7918 #endif /* SQLITE_OMIT_PRAGMA */
7920 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7921 /* Opcode: Vacuum P1 P2 * * *
7923 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
7924 ** for an attached database. The "temp" database may not be vacuumed.
7926 ** If P2 is not zero, then it is a register holding a string which is
7927 ** the file into which the result of vacuum should be written. When
7928 ** P2 is zero, the vacuum overwrites the original database.
7930 case OP_Vacuum: {
7931 assert( p->readOnly==0 );
7932 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7933 pOp->p2 ? &aMem[pOp->p2] : 0);
7934 if( rc ) goto abort_due_to_error;
7935 break;
7937 #endif
7939 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7940 /* Opcode: IncrVacuum P1 P2 * * *
7942 ** Perform a single step of the incremental vacuum procedure on
7943 ** the P1 database. If the vacuum has finished, jump to instruction
7944 ** P2. Otherwise, fall through to the next instruction.
7946 case OP_IncrVacuum: { /* jump */
7947 Btree *pBt;
7949 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7950 assert( DbMaskTest(p->btreeMask, pOp->p1) );
7951 assert( p->readOnly==0 );
7952 pBt = db->aDb[pOp->p1].pBt;
7953 rc = sqlite3BtreeIncrVacuum(pBt);
7954 VdbeBranchTaken(rc==SQLITE_DONE,2);
7955 if( rc ){
7956 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7957 rc = SQLITE_OK;
7958 goto jump_to_p2;
7960 break;
7962 #endif
7964 /* Opcode: Expire P1 P2 * * *
7966 ** Cause precompiled statements to expire. When an expired statement
7967 ** is executed using sqlite3_step() it will either automatically
7968 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
7969 ** or it will fail with SQLITE_SCHEMA.
7971 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
7972 ** then only the currently executing statement is expired.
7974 ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
7975 ** then running SQL statements are allowed to continue to run to completion.
7976 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
7977 ** that might help the statement run faster but which does not affect the
7978 ** correctness of operation.
7980 case OP_Expire: {
7981 assert( pOp->p2==0 || pOp->p2==1 );
7982 if( !pOp->p1 ){
7983 sqlite3ExpirePreparedStatements(db, pOp->p2);
7984 }else{
7985 p->expired = pOp->p2+1;
7987 break;
7990 /* Opcode: CursorLock P1 * * * *
7992 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
7993 ** written by an other cursor.
7995 case OP_CursorLock: {
7996 VdbeCursor *pC;
7997 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7998 pC = p->apCsr[pOp->p1];
7999 assert( pC!=0 );
8000 assert( pC->eCurType==CURTYPE_BTREE );
8001 sqlite3BtreeCursorPin(pC->uc.pCursor);
8002 break;
8005 /* Opcode: CursorUnlock P1 * * * *
8007 ** Unlock the btree to which cursor P1 is pointing so that it can be
8008 ** written by other cursors.
8010 case OP_CursorUnlock: {
8011 VdbeCursor *pC;
8012 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8013 pC = p->apCsr[pOp->p1];
8014 assert( pC!=0 );
8015 assert( pC->eCurType==CURTYPE_BTREE );
8016 sqlite3BtreeCursorUnpin(pC->uc.pCursor);
8017 break;
8020 #ifndef SQLITE_OMIT_SHARED_CACHE
8021 /* Opcode: TableLock P1 P2 P3 P4 *
8022 ** Synopsis: iDb=P1 root=P2 write=P3
8024 ** Obtain a lock on a particular table. This instruction is only used when
8025 ** the shared-cache feature is enabled.
8027 ** P1 is the index of the database in sqlite3.aDb[] of the database
8028 ** on which the lock is acquired. A readlock is obtained if P3==0 or
8029 ** a write lock if P3==1.
8031 ** P2 contains the root-page of the table to lock.
8033 ** P4 contains a pointer to the name of the table being locked. This is only
8034 ** used to generate an error message if the lock cannot be obtained.
8036 case OP_TableLock: {
8037 u8 isWriteLock = (u8)pOp->p3;
8038 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
8039 int p1 = pOp->p1;
8040 assert( p1>=0 && p1<db->nDb );
8041 assert( DbMaskTest(p->btreeMask, p1) );
8042 assert( isWriteLock==0 || isWriteLock==1 );
8043 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
8044 if( rc ){
8045 if( (rc&0xFF)==SQLITE_LOCKED ){
8046 const char *z = pOp->p4.z;
8047 sqlite3VdbeError(p, "database table is locked: %s", z);
8049 goto abort_due_to_error;
8052 break;
8054 #endif /* SQLITE_OMIT_SHARED_CACHE */
8056 #ifndef SQLITE_OMIT_VIRTUALTABLE
8057 /* Opcode: VBegin * * * P4 *
8059 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
8060 ** xBegin method for that table.
8062 ** Also, whether or not P4 is set, check that this is not being called from
8063 ** within a callback to a virtual table xSync() method. If it is, the error
8064 ** code will be set to SQLITE_LOCKED.
8066 case OP_VBegin: {
8067 VTable *pVTab;
8068 pVTab = pOp->p4.pVtab;
8069 rc = sqlite3VtabBegin(db, pVTab);
8070 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
8071 if( rc ) goto abort_due_to_error;
8072 break;
8074 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8076 #ifndef SQLITE_OMIT_VIRTUALTABLE
8077 /* Opcode: VCreate P1 P2 * * *
8079 ** P2 is a register that holds the name of a virtual table in database
8080 ** P1. Call the xCreate method for that table.
8082 case OP_VCreate: {
8083 Mem sMem; /* For storing the record being decoded */
8084 const char *zTab; /* Name of the virtual table */
8086 memset(&sMem, 0, sizeof(sMem));
8087 sMem.db = db;
8088 /* Because P2 is always a static string, it is impossible for the
8089 ** sqlite3VdbeMemCopy() to fail */
8090 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
8091 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
8092 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
8093 assert( rc==SQLITE_OK );
8094 zTab = (const char*)sqlite3_value_text(&sMem);
8095 assert( zTab || db->mallocFailed );
8096 if( zTab ){
8097 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
8099 sqlite3VdbeMemRelease(&sMem);
8100 if( rc ) goto abort_due_to_error;
8101 break;
8103 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8105 #ifndef SQLITE_OMIT_VIRTUALTABLE
8106 /* Opcode: VDestroy P1 * * P4 *
8108 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
8109 ** of that table.
8111 case OP_VDestroy: {
8112 db->nVDestroy++;
8113 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
8114 db->nVDestroy--;
8115 assert( p->errorAction==OE_Abort && p->usesStmtJournal );
8116 if( rc ) goto abort_due_to_error;
8117 break;
8119 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8121 #ifndef SQLITE_OMIT_VIRTUALTABLE
8122 /* Opcode: VOpen P1 * * P4 *
8124 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8125 ** P1 is a cursor number. This opcode opens a cursor to the virtual
8126 ** table and stores that cursor in P1.
8128 case OP_VOpen: { /* ncycle */
8129 VdbeCursor *pCur;
8130 sqlite3_vtab_cursor *pVCur;
8131 sqlite3_vtab *pVtab;
8132 const sqlite3_module *pModule;
8134 assert( p->bIsReader );
8135 pCur = 0;
8136 pVCur = 0;
8137 pVtab = pOp->p4.pVtab->pVtab;
8138 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8139 rc = SQLITE_LOCKED;
8140 goto abort_due_to_error;
8142 pModule = pVtab->pModule;
8143 rc = pModule->xOpen(pVtab, &pVCur);
8144 sqlite3VtabImportErrmsg(p, pVtab);
8145 if( rc ) goto abort_due_to_error;
8147 /* Initialize sqlite3_vtab_cursor base class */
8148 pVCur->pVtab = pVtab;
8150 /* Initialize vdbe cursor object */
8151 pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
8152 if( pCur ){
8153 pCur->uc.pVCur = pVCur;
8154 pVtab->nRef++;
8155 }else{
8156 assert( db->mallocFailed );
8157 pModule->xClose(pVCur);
8158 goto no_mem;
8160 break;
8162 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8164 #ifndef SQLITE_OMIT_VIRTUALTABLE
8165 /* Opcode: VCheck P1 P2 P3 P4 *
8167 ** P4 is a pointer to a Table object that is a virtual table in schema P1
8168 ** that supports the xIntegrity() method. This opcode runs the xIntegrity()
8169 ** method for that virtual table, using P3 as the integer argument. If
8170 ** an error is reported back, the table name is prepended to the error
8171 ** message and that message is stored in P2. If no errors are seen,
8172 ** register P2 is set to NULL.
8174 case OP_VCheck: { /* out2 */
8175 Table *pTab;
8176 sqlite3_vtab *pVtab;
8177 const sqlite3_module *pModule;
8178 char *zErr = 0;
8180 pOut = &aMem[pOp->p2];
8181 sqlite3VdbeMemSetNull(pOut); /* Innocent until proven guilty */
8182 assert( pOp->p4type==P4_TABLE );
8183 pTab = pOp->p4.pTab;
8184 assert( pTab!=0 );
8185 assert( IsVirtual(pTab) );
8186 assert( pTab->u.vtab.p!=0 );
8187 pVtab = pTab->u.vtab.p->pVtab;
8188 assert( pVtab!=0 );
8189 pModule = pVtab->pModule;
8190 assert( pModule!=0 );
8191 assert( pModule->iVersion>=4 );
8192 assert( pModule->xIntegrity!=0 );
8193 pTab->nTabRef++;
8194 sqlite3VtabLock(pTab->u.vtab.p);
8195 assert( pOp->p1>=0 && pOp->p1<db->nDb );
8196 rc = pModule->xIntegrity(pVtab, db->aDb[pOp->p1].zDbSName, pTab->zName,
8197 pOp->p3, &zErr);
8198 sqlite3VtabUnlock(pTab->u.vtab.p);
8199 sqlite3DeleteTable(db, pTab);
8200 if( rc ){
8201 sqlite3_free(zErr);
8202 goto abort_due_to_error;
8204 if( zErr ){
8205 sqlite3VdbeMemSetStr(pOut, zErr, -1, SQLITE_UTF8, sqlite3_free);
8207 break;
8209 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8211 #ifndef SQLITE_OMIT_VIRTUALTABLE
8212 /* Opcode: VInitIn P1 P2 P3 * *
8213 ** Synopsis: r[P2]=ValueList(P1,P3)
8215 ** Set register P2 to be a pointer to a ValueList object for cursor P1
8216 ** with cache register P3 and output register P3+1. This ValueList object
8217 ** can be used as the first argument to sqlite3_vtab_in_first() and
8218 ** sqlite3_vtab_in_next() to extract all of the values stored in the P1
8219 ** cursor. Register P3 is used to hold the values returned by
8220 ** sqlite3_vtab_in_first() and sqlite3_vtab_in_next().
8222 case OP_VInitIn: { /* out2, ncycle */
8223 VdbeCursor *pC; /* The cursor containing the RHS values */
8224 ValueList *pRhs; /* New ValueList object to put in reg[P2] */
8226 pC = p->apCsr[pOp->p1];
8227 pRhs = sqlite3_malloc64( sizeof(*pRhs) );
8228 if( pRhs==0 ) goto no_mem;
8229 pRhs->pCsr = pC->uc.pCursor;
8230 pRhs->pOut = &aMem[pOp->p3];
8231 pOut = out2Prerelease(p, pOp);
8232 pOut->flags = MEM_Null;
8233 sqlite3VdbeMemSetPointer(pOut, pRhs, "ValueList", sqlite3VdbeValueListFree);
8234 break;
8236 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8239 #ifndef SQLITE_OMIT_VIRTUALTABLE
8240 /* Opcode: VFilter P1 P2 P3 P4 *
8241 ** Synopsis: iplan=r[P3] zplan='P4'
8243 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
8244 ** the filtered result set is empty.
8246 ** P4 is either NULL or a string that was generated by the xBestIndex
8247 ** method of the module. The interpretation of the P4 string is left
8248 ** to the module implementation.
8250 ** This opcode invokes the xFilter method on the virtual table specified
8251 ** by P1. The integer query plan parameter to xFilter is stored in register
8252 ** P3. Register P3+1 stores the argc parameter to be passed to the
8253 ** xFilter method. Registers P3+2..P3+1+argc are the argc
8254 ** additional parameters which are passed to
8255 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
8257 ** A jump is made to P2 if the result set after filtering would be empty.
8259 case OP_VFilter: { /* jump, ncycle */
8260 int nArg;
8261 int iQuery;
8262 const sqlite3_module *pModule;
8263 Mem *pQuery;
8264 Mem *pArgc;
8265 sqlite3_vtab_cursor *pVCur;
8266 sqlite3_vtab *pVtab;
8267 VdbeCursor *pCur;
8268 int res;
8269 int i;
8270 Mem **apArg;
8272 pQuery = &aMem[pOp->p3];
8273 pArgc = &pQuery[1];
8274 pCur = p->apCsr[pOp->p1];
8275 assert( memIsValid(pQuery) );
8276 REGISTER_TRACE(pOp->p3, pQuery);
8277 assert( pCur!=0 );
8278 assert( pCur->eCurType==CURTYPE_VTAB );
8279 pVCur = pCur->uc.pVCur;
8280 pVtab = pVCur->pVtab;
8281 pModule = pVtab->pModule;
8283 /* Grab the index number and argc parameters */
8284 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
8285 nArg = (int)pArgc->u.i;
8286 iQuery = (int)pQuery->u.i;
8288 /* Invoke the xFilter method */
8289 apArg = p->apArg;
8290 for(i = 0; i<nArg; i++){
8291 apArg[i] = &pArgc[i+1];
8293 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
8294 sqlite3VtabImportErrmsg(p, pVtab);
8295 if( rc ) goto abort_due_to_error;
8296 res = pModule->xEof(pVCur);
8297 pCur->nullRow = 0;
8298 VdbeBranchTaken(res!=0,2);
8299 if( res ) goto jump_to_p2;
8300 break;
8302 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8304 #ifndef SQLITE_OMIT_VIRTUALTABLE
8305 /* Opcode: VColumn P1 P2 P3 * P5
8306 ** Synopsis: r[P3]=vcolumn(P2)
8308 ** Store in register P3 the value of the P2-th column of
8309 ** the current row of the virtual-table of cursor P1.
8311 ** If the VColumn opcode is being used to fetch the value of
8312 ** an unchanging column during an UPDATE operation, then the P5
8313 ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
8314 ** function to return true inside the xColumn method of the virtual
8315 ** table implementation. The P5 column might also contain other
8316 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
8317 ** unused by OP_VColumn.
8319 case OP_VColumn: { /* ncycle */
8320 sqlite3_vtab *pVtab;
8321 const sqlite3_module *pModule;
8322 Mem *pDest;
8323 sqlite3_context sContext;
8325 VdbeCursor *pCur = p->apCsr[pOp->p1];
8326 assert( pCur!=0 );
8327 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
8328 pDest = &aMem[pOp->p3];
8329 memAboutToChange(p, pDest);
8330 if( pCur->nullRow ){
8331 sqlite3VdbeMemSetNull(pDest);
8332 break;
8334 assert( pCur->eCurType==CURTYPE_VTAB );
8335 pVtab = pCur->uc.pVCur->pVtab;
8336 pModule = pVtab->pModule;
8337 assert( pModule->xColumn );
8338 memset(&sContext, 0, sizeof(sContext));
8339 sContext.pOut = pDest;
8340 sContext.enc = encoding;
8341 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
8342 if( pOp->p5 & OPFLAG_NOCHNG ){
8343 sqlite3VdbeMemSetNull(pDest);
8344 pDest->flags = MEM_Null|MEM_Zero;
8345 pDest->u.nZero = 0;
8346 }else{
8347 MemSetTypeFlag(pDest, MEM_Null);
8349 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
8350 sqlite3VtabImportErrmsg(p, pVtab);
8351 if( sContext.isError>0 ){
8352 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
8353 rc = sContext.isError;
8355 sqlite3VdbeChangeEncoding(pDest, encoding);
8356 REGISTER_TRACE(pOp->p3, pDest);
8357 UPDATE_MAX_BLOBSIZE(pDest);
8359 if( rc ) goto abort_due_to_error;
8360 break;
8362 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8364 #ifndef SQLITE_OMIT_VIRTUALTABLE
8365 /* Opcode: VNext P1 P2 * * *
8367 ** Advance virtual table P1 to the next row in its result set and
8368 ** jump to instruction P2. Or, if the virtual table has reached
8369 ** the end of its result set, then fall through to the next instruction.
8371 case OP_VNext: { /* jump, ncycle */
8372 sqlite3_vtab *pVtab;
8373 const sqlite3_module *pModule;
8374 int res;
8375 VdbeCursor *pCur;
8377 pCur = p->apCsr[pOp->p1];
8378 assert( pCur!=0 );
8379 assert( pCur->eCurType==CURTYPE_VTAB );
8380 if( pCur->nullRow ){
8381 break;
8383 pVtab = pCur->uc.pVCur->pVtab;
8384 pModule = pVtab->pModule;
8385 assert( pModule->xNext );
8387 /* Invoke the xNext() method of the module. There is no way for the
8388 ** underlying implementation to return an error if one occurs during
8389 ** xNext(). Instead, if an error occurs, true is returned (indicating that
8390 ** data is available) and the error code returned when xColumn or
8391 ** some other method is next invoked on the save virtual table cursor.
8393 rc = pModule->xNext(pCur->uc.pVCur);
8394 sqlite3VtabImportErrmsg(p, pVtab);
8395 if( rc ) goto abort_due_to_error;
8396 res = pModule->xEof(pCur->uc.pVCur);
8397 VdbeBranchTaken(!res,2);
8398 if( !res ){
8399 /* If there is data, jump to P2 */
8400 goto jump_to_p2_and_check_for_interrupt;
8402 goto check_for_interrupt;
8404 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8406 #ifndef SQLITE_OMIT_VIRTUALTABLE
8407 /* Opcode: VRename P1 * * P4 *
8409 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8410 ** This opcode invokes the corresponding xRename method. The value
8411 ** in register P1 is passed as the zName argument to the xRename method.
8413 case OP_VRename: {
8414 sqlite3_vtab *pVtab;
8415 Mem *pName;
8416 int isLegacy;
8418 isLegacy = (db->flags & SQLITE_LegacyAlter);
8419 db->flags |= SQLITE_LegacyAlter;
8420 pVtab = pOp->p4.pVtab->pVtab;
8421 pName = &aMem[pOp->p1];
8422 assert( pVtab->pModule->xRename );
8423 assert( memIsValid(pName) );
8424 assert( p->readOnly==0 );
8425 REGISTER_TRACE(pOp->p1, pName);
8426 assert( pName->flags & MEM_Str );
8427 testcase( pName->enc==SQLITE_UTF8 );
8428 testcase( pName->enc==SQLITE_UTF16BE );
8429 testcase( pName->enc==SQLITE_UTF16LE );
8430 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
8431 if( rc ) goto abort_due_to_error;
8432 rc = pVtab->pModule->xRename(pVtab, pName->z);
8433 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
8434 sqlite3VtabImportErrmsg(p, pVtab);
8435 p->expired = 0;
8436 if( rc ) goto abort_due_to_error;
8437 break;
8439 #endif
8441 #ifndef SQLITE_OMIT_VIRTUALTABLE
8442 /* Opcode: VUpdate P1 P2 P3 P4 P5
8443 ** Synopsis: data=r[P3@P2]
8445 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8446 ** This opcode invokes the corresponding xUpdate method. P2 values
8447 ** are contiguous memory cells starting at P3 to pass to the xUpdate
8448 ** invocation. The value in register (P3+P2-1) corresponds to the
8449 ** p2th element of the argv array passed to xUpdate.
8451 ** The xUpdate method will do a DELETE or an INSERT or both.
8452 ** The argv[0] element (which corresponds to memory cell P3)
8453 ** is the rowid of a row to delete. If argv[0] is NULL then no
8454 ** deletion occurs. The argv[1] element is the rowid of the new
8455 ** row. This can be NULL to have the virtual table select the new
8456 ** rowid for itself. The subsequent elements in the array are
8457 ** the values of columns in the new row.
8459 ** If P2==1 then no insert is performed. argv[0] is the rowid of
8460 ** a row to delete.
8462 ** P1 is a boolean flag. If it is set to true and the xUpdate call
8463 ** is successful, then the value returned by sqlite3_last_insert_rowid()
8464 ** is set to the value of the rowid for the row just inserted.
8466 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
8467 ** apply in the case of a constraint failure on an insert or update.
8469 case OP_VUpdate: {
8470 sqlite3_vtab *pVtab;
8471 const sqlite3_module *pModule;
8472 int nArg;
8473 int i;
8474 sqlite_int64 rowid = 0;
8475 Mem **apArg;
8476 Mem *pX;
8478 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
8479 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
8481 assert( p->readOnly==0 );
8482 if( db->mallocFailed ) goto no_mem;
8483 sqlite3VdbeIncrWriteCounter(p, 0);
8484 pVtab = pOp->p4.pVtab->pVtab;
8485 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8486 rc = SQLITE_LOCKED;
8487 goto abort_due_to_error;
8489 pModule = pVtab->pModule;
8490 nArg = pOp->p2;
8491 assert( pOp->p4type==P4_VTAB );
8492 if( ALWAYS(pModule->xUpdate) ){
8493 u8 vtabOnConflict = db->vtabOnConflict;
8494 apArg = p->apArg;
8495 pX = &aMem[pOp->p3];
8496 for(i=0; i<nArg; i++){
8497 assert( memIsValid(pX) );
8498 memAboutToChange(p, pX);
8499 apArg[i] = pX;
8500 pX++;
8502 db->vtabOnConflict = pOp->p5;
8503 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
8504 db->vtabOnConflict = vtabOnConflict;
8505 sqlite3VtabImportErrmsg(p, pVtab);
8506 if( rc==SQLITE_OK && pOp->p1 ){
8507 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
8508 db->lastRowid = rowid;
8510 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
8511 if( pOp->p5==OE_Ignore ){
8512 rc = SQLITE_OK;
8513 }else{
8514 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
8516 }else{
8517 p->nChange++;
8519 if( rc ) goto abort_due_to_error;
8521 break;
8523 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8525 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8526 /* Opcode: Pagecount P1 P2 * * *
8528 ** Write the current number of pages in database P1 to memory cell P2.
8530 case OP_Pagecount: { /* out2 */
8531 pOut = out2Prerelease(p, pOp);
8532 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
8533 break;
8535 #endif
8538 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8539 /* Opcode: MaxPgcnt P1 P2 P3 * *
8541 ** Try to set the maximum page count for database P1 to the value in P3.
8542 ** Do not let the maximum page count fall below the current page count and
8543 ** do not change the maximum page count value if P3==0.
8545 ** Store the maximum page count after the change in register P2.
8547 case OP_MaxPgcnt: { /* out2 */
8548 unsigned int newMax;
8549 Btree *pBt;
8551 pOut = out2Prerelease(p, pOp);
8552 pBt = db->aDb[pOp->p1].pBt;
8553 newMax = 0;
8554 if( pOp->p3 ){
8555 newMax = sqlite3BtreeLastPage(pBt);
8556 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
8558 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
8559 break;
8561 #endif
8563 /* Opcode: Function P1 P2 P3 P4 *
8564 ** Synopsis: r[P3]=func(r[P2@NP])
8566 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8567 ** contains a pointer to the function to be run) with arguments taken
8568 ** from register P2 and successors. The number of arguments is in
8569 ** the sqlite3_context object that P4 points to.
8570 ** The result of the function is stored
8571 ** in register P3. Register P3 must not be one of the function inputs.
8573 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8574 ** function was determined to be constant at compile time. If the first
8575 ** argument was constant then bit 0 of P1 is set. This is used to determine
8576 ** whether meta data associated with a user function argument using the
8577 ** sqlite3_set_auxdata() API may be safely retained until the next
8578 ** invocation of this opcode.
8580 ** See also: AggStep, AggFinal, PureFunc
8582 /* Opcode: PureFunc P1 P2 P3 P4 *
8583 ** Synopsis: r[P3]=func(r[P2@NP])
8585 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8586 ** contains a pointer to the function to be run) with arguments taken
8587 ** from register P2 and successors. The number of arguments is in
8588 ** the sqlite3_context object that P4 points to.
8589 ** The result of the function is stored
8590 ** in register P3. Register P3 must not be one of the function inputs.
8592 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8593 ** function was determined to be constant at compile time. If the first
8594 ** argument was constant then bit 0 of P1 is set. This is used to determine
8595 ** whether meta data associated with a user function argument using the
8596 ** sqlite3_set_auxdata() API may be safely retained until the next
8597 ** invocation of this opcode.
8599 ** This opcode works exactly like OP_Function. The only difference is in
8600 ** its name. This opcode is used in places where the function must be
8601 ** purely non-deterministic. Some built-in date/time functions can be
8602 ** either deterministic of non-deterministic, depending on their arguments.
8603 ** When those function are used in a non-deterministic way, they will check
8604 ** to see if they were called using OP_PureFunc instead of OP_Function, and
8605 ** if they were, they throw an error.
8607 ** See also: AggStep, AggFinal, Function
8609 case OP_PureFunc: /* group */
8610 case OP_Function: { /* group */
8611 int i;
8612 sqlite3_context *pCtx;
8614 assert( pOp->p4type==P4_FUNCCTX );
8615 pCtx = pOp->p4.pCtx;
8617 /* If this function is inside of a trigger, the register array in aMem[]
8618 ** might change from one evaluation to the next. The next block of code
8619 ** checks to see if the register array has changed, and if so it
8620 ** reinitializes the relevant parts of the sqlite3_context object */
8621 pOut = &aMem[pOp->p3];
8622 if( pCtx->pOut != pOut ){
8623 pCtx->pVdbe = p;
8624 pCtx->pOut = pOut;
8625 pCtx->enc = encoding;
8626 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
8628 assert( pCtx->pVdbe==p );
8630 memAboutToChange(p, pOut);
8631 #ifdef SQLITE_DEBUG
8632 for(i=0; i<pCtx->argc; i++){
8633 assert( memIsValid(pCtx->argv[i]) );
8634 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
8636 #endif
8637 MemSetTypeFlag(pOut, MEM_Null);
8638 assert( pCtx->isError==0 );
8639 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
8641 /* If the function returned an error, throw an exception */
8642 if( pCtx->isError ){
8643 if( pCtx->isError>0 ){
8644 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
8645 rc = pCtx->isError;
8647 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
8648 pCtx->isError = 0;
8649 if( rc ) goto abort_due_to_error;
8652 assert( (pOut->flags&MEM_Str)==0
8653 || pOut->enc==encoding
8654 || db->mallocFailed );
8655 assert( !sqlite3VdbeMemTooBig(pOut) );
8657 REGISTER_TRACE(pOp->p3, pOut);
8658 UPDATE_MAX_BLOBSIZE(pOut);
8659 break;
8662 /* Opcode: ClrSubtype P1 * * * *
8663 ** Synopsis: r[P1].subtype = 0
8665 ** Clear the subtype from register P1.
8667 case OP_ClrSubtype: { /* in1 */
8668 pIn1 = &aMem[pOp->p1];
8669 pIn1->flags &= ~MEM_Subtype;
8670 break;
8673 /* Opcode: FilterAdd P1 * P3 P4 *
8674 ** Synopsis: filter(P1) += key(P3@P4)
8676 ** Compute a hash on the P4 registers starting with r[P3] and
8677 ** add that hash to the bloom filter contained in r[P1].
8679 case OP_FilterAdd: {
8680 u64 h;
8682 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8683 pIn1 = &aMem[pOp->p1];
8684 assert( pIn1->flags & MEM_Blob );
8685 assert( pIn1->n>0 );
8686 h = filterHash(aMem, pOp);
8687 #ifdef SQLITE_DEBUG
8688 if( db->flags&SQLITE_VdbeTrace ){
8689 int ii;
8690 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8691 registerTrace(ii, &aMem[ii]);
8693 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8695 #endif
8696 h %= (pIn1->n*8);
8697 pIn1->z[h/8] |= 1<<(h&7);
8698 break;
8701 /* Opcode: Filter P1 P2 P3 P4 *
8702 ** Synopsis: if key(P3@P4) not in filter(P1) goto P2
8704 ** Compute a hash on the key contained in the P4 registers starting
8705 ** with r[P3]. Check to see if that hash is found in the
8706 ** bloom filter hosted by register P1. If it is not present then
8707 ** maybe jump to P2. Otherwise fall through.
8709 ** False negatives are harmless. It is always safe to fall through,
8710 ** even if the value is in the bloom filter. A false negative causes
8711 ** more CPU cycles to be used, but it should still yield the correct
8712 ** answer. However, an incorrect answer may well arise from a
8713 ** false positive - if the jump is taken when it should fall through.
8715 case OP_Filter: { /* jump */
8716 u64 h;
8718 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8719 pIn1 = &aMem[pOp->p1];
8720 assert( (pIn1->flags & MEM_Blob)!=0 );
8721 assert( pIn1->n >= 1 );
8722 h = filterHash(aMem, pOp);
8723 #ifdef SQLITE_DEBUG
8724 if( db->flags&SQLITE_VdbeTrace ){
8725 int ii;
8726 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8727 registerTrace(ii, &aMem[ii]);
8729 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8731 #endif
8732 h %= (pIn1->n*8);
8733 if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
8734 VdbeBranchTaken(1, 2);
8735 p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
8736 goto jump_to_p2;
8737 }else{
8738 p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
8739 VdbeBranchTaken(0, 2);
8741 break;
8744 /* Opcode: Trace P1 P2 * P4 *
8746 ** Write P4 on the statement trace output if statement tracing is
8747 ** enabled.
8749 ** Operand P1 must be 0x7fffffff and P2 must positive.
8751 /* Opcode: Init P1 P2 P3 P4 *
8752 ** Synopsis: Start at P2
8754 ** Programs contain a single instance of this opcode as the very first
8755 ** opcode.
8757 ** If tracing is enabled (by the sqlite3_trace()) interface, then
8758 ** the UTF-8 string contained in P4 is emitted on the trace callback.
8759 ** Or if P4 is blank, use the string returned by sqlite3_sql().
8761 ** If P2 is not zero, jump to instruction P2.
8763 ** Increment the value of P1 so that OP_Once opcodes will jump the
8764 ** first time they are evaluated for this run.
8766 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
8767 ** error is encountered.
8769 case OP_Trace:
8770 case OP_Init: { /* jump */
8771 int i;
8772 #ifndef SQLITE_OMIT_TRACE
8773 char *zTrace;
8774 #endif
8776 /* If the P4 argument is not NULL, then it must be an SQL comment string.
8777 ** The "--" string is broken up to prevent false-positives with srcck1.c.
8779 ** This assert() provides evidence for:
8780 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
8781 ** would have been returned by the legacy sqlite3_trace() interface by
8782 ** using the X argument when X begins with "--" and invoking
8783 ** sqlite3_expanded_sql(P) otherwise.
8785 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
8787 /* OP_Init is always instruction 0 */
8788 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
8790 #ifndef SQLITE_OMIT_TRACE
8791 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
8792 && p->minWriteFileFormat!=254 /* tag-20220401a */
8793 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8795 #ifndef SQLITE_OMIT_DEPRECATED
8796 if( db->mTrace & SQLITE_TRACE_LEGACY ){
8797 char *z = sqlite3VdbeExpandSql(p, zTrace);
8798 db->trace.xLegacy(db->pTraceArg, z);
8799 sqlite3_free(z);
8800 }else
8801 #endif
8802 if( db->nVdbeExec>1 ){
8803 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
8804 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
8805 sqlite3DbFree(db, z);
8806 }else{
8807 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
8810 #ifdef SQLITE_USE_FCNTL_TRACE
8811 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
8812 if( zTrace ){
8813 int j;
8814 for(j=0; j<db->nDb; j++){
8815 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
8816 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
8819 #endif /* SQLITE_USE_FCNTL_TRACE */
8820 #ifdef SQLITE_DEBUG
8821 if( (db->flags & SQLITE_SqlTrace)!=0
8822 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8824 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8826 #endif /* SQLITE_DEBUG */
8827 #endif /* SQLITE_OMIT_TRACE */
8828 assert( pOp->p2>0 );
8829 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8830 if( pOp->opcode==OP_Trace ) break;
8831 for(i=1; i<p->nOp; i++){
8832 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8834 pOp->p1 = 0;
8836 pOp->p1++;
8837 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8838 goto jump_to_p2;
8841 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8842 /* Opcode: CursorHint P1 * * P4 *
8844 ** Provide a hint to cursor P1 that it only needs to return rows that
8845 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
8846 ** to values currently held in registers. TK_COLUMN terms in the P4
8847 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8849 case OP_CursorHint: {
8850 VdbeCursor *pC;
8852 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8853 assert( pOp->p4type==P4_EXPR );
8854 pC = p->apCsr[pOp->p1];
8855 if( pC ){
8856 assert( pC->eCurType==CURTYPE_BTREE );
8857 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8858 pOp->p4.pExpr, aMem);
8860 break;
8862 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8864 #ifdef SQLITE_DEBUG
8865 /* Opcode: Abortable * * * * *
8867 ** Verify that an Abort can happen. Assert if an Abort at this point
8868 ** might cause database corruption. This opcode only appears in debugging
8869 ** builds.
8871 ** An Abort is safe if either there have been no writes, or if there is
8872 ** an active statement journal.
8874 case OP_Abortable: {
8875 sqlite3VdbeAssertAbortable(p);
8876 break;
8878 #endif
8880 #ifdef SQLITE_DEBUG
8881 /* Opcode: ReleaseReg P1 P2 P3 * P5
8882 ** Synopsis: release r[P1@P2] mask P3
8884 ** Release registers from service. Any content that was in the
8885 ** the registers is unreliable after this opcode completes.
8887 ** The registers released will be the P2 registers starting at P1,
8888 ** except if bit ii of P3 set, then do not release register P1+ii.
8889 ** In other words, P3 is a mask of registers to preserve.
8891 ** Releasing a register clears the Mem.pScopyFrom pointer. That means
8892 ** that if the content of the released register was set using OP_SCopy,
8893 ** a change to the value of the source register for the OP_SCopy will no longer
8894 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8896 ** If P5 is set, then all released registers have their type set
8897 ** to MEM_Undefined so that any subsequent attempt to read the released
8898 ** register (before it is reinitialized) will generate an assertion fault.
8900 ** P5 ought to be set on every call to this opcode.
8901 ** However, there are places in the code generator will release registers
8902 ** before their are used, under the (valid) assumption that the registers
8903 ** will not be reallocated for some other purpose before they are used and
8904 ** hence are safe to release.
8906 ** This opcode is only available in testing and debugging builds. It is
8907 ** not generated for release builds. The purpose of this opcode is to help
8908 ** validate the generated bytecode. This opcode does not actually contribute
8909 ** to computing an answer.
8911 case OP_ReleaseReg: {
8912 Mem *pMem;
8913 int i;
8914 u32 constMask;
8915 assert( pOp->p1>0 );
8916 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8917 pMem = &aMem[pOp->p1];
8918 constMask = pOp->p3;
8919 for(i=0; i<pOp->p2; i++, pMem++){
8920 if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8921 pMem->pScopyFrom = 0;
8922 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
8925 break;
8927 #endif
8929 /* Opcode: Noop * * * * *
8931 ** Do nothing. This instruction is often useful as a jump
8932 ** destination.
8935 ** The magic Explain opcode are only inserted when explain==2 (which
8936 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
8937 ** This opcode records information from the optimizer. It is the
8938 ** the same as a no-op. This opcodesnever appears in a real VM program.
8940 default: { /* This is really OP_Noop, OP_Explain */
8941 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
8943 break;
8946 /*****************************************************************************
8947 ** The cases of the switch statement above this line should all be indented
8948 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
8949 ** readability. From this point on down, the normal indentation rules are
8950 ** restored.
8951 *****************************************************************************/
8954 #if defined(VDBE_PROFILE)
8955 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
8956 pnCycle = 0;
8957 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
8958 if( pnCycle ){
8959 *pnCycle += sqlite3Hwtime();
8960 pnCycle = 0;
8962 #endif
8964 /* The following code adds nothing to the actual functionality
8965 ** of the program. It is only here for testing and debugging.
8966 ** On the other hand, it does burn CPU cycles every time through
8967 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
8969 #ifndef NDEBUG
8970 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
8972 #ifdef SQLITE_DEBUG
8973 if( db->flags & SQLITE_VdbeTrace ){
8974 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
8975 if( rc!=0 ) printf("rc=%d\n",rc);
8976 if( opProperty & (OPFLG_OUT2) ){
8977 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
8979 if( opProperty & OPFLG_OUT3 ){
8980 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
8982 if( opProperty==0xff ){
8983 /* Never happens. This code exists to avoid a harmless linkage
8984 ** warning about sqlite3VdbeRegisterDump() being defined but not
8985 ** used. */
8986 sqlite3VdbeRegisterDump(p);
8989 #endif /* SQLITE_DEBUG */
8990 #endif /* NDEBUG */
8991 } /* The end of the for(;;) loop the loops through opcodes */
8993 /* If we reach this point, it means that execution is finished with
8994 ** an error of some kind.
8996 abort_due_to_error:
8997 if( db->mallocFailed ){
8998 rc = SQLITE_NOMEM_BKPT;
8999 }else if( rc==SQLITE_IOERR_CORRUPTFS ){
9000 rc = SQLITE_CORRUPT_BKPT;
9002 assert( rc );
9003 #ifdef SQLITE_DEBUG
9004 if( db->flags & SQLITE_VdbeTrace ){
9005 const char *zTrace = p->zSql;
9006 if( zTrace==0 ){
9007 if( aOp[0].opcode==OP_Trace ){
9008 zTrace = aOp[0].p4.z;
9010 if( zTrace==0 ) zTrace = "???";
9012 printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
9014 #endif
9015 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
9016 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
9018 p->rc = rc;
9019 sqlite3SystemError(db, rc);
9020 testcase( sqlite3GlobalConfig.xLog!=0 );
9021 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
9022 (int)(pOp - aOp), p->zSql, p->zErrMsg);
9023 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
9024 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
9025 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
9026 db->flags |= SQLITE_CorruptRdOnly;
9028 rc = SQLITE_ERROR;
9029 if( resetSchemaOnFault>0 ){
9030 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
9033 /* This is the only way out of this procedure. We have to
9034 ** release the mutexes on btrees that were acquired at the
9035 ** top. */
9036 vdbe_return:
9037 #if defined(VDBE_PROFILE)
9038 if( pnCycle ){
9039 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
9040 pnCycle = 0;
9042 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9043 if( pnCycle ){
9044 *pnCycle += sqlite3Hwtime();
9045 pnCycle = 0;
9047 #endif
9049 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9050 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
9051 nProgressLimit += db->nProgressOps;
9052 if( db->xProgress(db->pProgressArg) ){
9053 nProgressLimit = LARGEST_UINT64;
9054 rc = SQLITE_INTERRUPT;
9055 goto abort_due_to_error;
9058 #endif
9059 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
9060 if( DbMaskNonZero(p->lockMask) ){
9061 sqlite3VdbeLeave(p);
9063 assert( rc!=SQLITE_OK || nExtraDelete==0
9064 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
9066 return rc;
9068 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
9069 ** is encountered.
9071 too_big:
9072 sqlite3VdbeError(p, "string or blob too big");
9073 rc = SQLITE_TOOBIG;
9074 goto abort_due_to_error;
9076 /* Jump to here if a malloc() fails.
9078 no_mem:
9079 sqlite3OomFault(db);
9080 sqlite3VdbeError(p, "out of memory");
9081 rc = SQLITE_NOMEM_BKPT;
9082 goto abort_due_to_error;
9084 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
9085 ** flag.
9087 abort_due_to_interrupt:
9088 assert( AtomicLoad(&db->u1.isInterrupted) );
9089 rc = SQLITE_INTERRUPT;
9090 goto abort_due_to_error;