Fix a segfault caused by having identical window functions in the select-list
[sqlite.git] / src / vdbe.c
blob6eb5f95024b521f78cc2e30abce688b1d3e53512
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 ** Given a cursor number and a column for a table or index, compute a
41 ** hash value for use in the Mem.iTabColHash value. The iTabColHash
42 ** column is only used for verification - it is omitted from production
43 ** builds. Collisions are harmless in the sense that the correct answer
44 ** still results. The only harm of collisions is that they can potential
45 ** reduce column-cache error detection during SQLITE_DEBUG builds.
47 ** No valid hash should be 0.
49 #define TableColumnHash(T,C) (((u32)(T)<<16)^(u32)(C+2))
52 ** The following global variable is incremented every time a cursor
53 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
54 ** procedures use this information to make sure that indices are
55 ** working correctly. This variable has no function other than to
56 ** help verify the correct operation of the library.
58 #ifdef SQLITE_TEST
59 int sqlite3_search_count = 0;
60 #endif
63 ** When this global variable is positive, it gets decremented once before
64 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
65 ** field of the sqlite3 structure is set in order to simulate an interrupt.
67 ** This facility is used for testing purposes only. It does not function
68 ** in an ordinary build.
70 #ifdef SQLITE_TEST
71 int sqlite3_interrupt_count = 0;
72 #endif
75 ** The next global variable is incremented each type the OP_Sort opcode
76 ** is executed. The test procedures use this information to make sure that
77 ** sorting is occurring or not occurring at appropriate times. This variable
78 ** has no function other than to help verify the correct operation of the
79 ** library.
81 #ifdef SQLITE_TEST
82 int sqlite3_sort_count = 0;
83 #endif
86 ** The next global variable records the size of the largest MEM_Blob
87 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
88 ** use this information to make sure that the zero-blob functionality
89 ** is working correctly. This variable has no function other than to
90 ** help verify the correct operation of the library.
92 #ifdef SQLITE_TEST
93 int sqlite3_max_blobsize = 0;
94 static void updateMaxBlobsize(Mem *p){
95 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
96 sqlite3_max_blobsize = p->n;
99 #endif
102 ** This macro evaluates to true if either the update hook or the preupdate
103 ** hook are enabled for database connect DB.
105 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
106 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
107 #else
108 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
109 #endif
112 ** The next global variable is incremented each time the OP_Found opcode
113 ** is executed. This is used to test whether or not the foreign key
114 ** operation implemented using OP_FkIsZero is working. This variable
115 ** has no function other than to help verify the correct operation of the
116 ** library.
118 #ifdef SQLITE_TEST
119 int sqlite3_found_count = 0;
120 #endif
123 ** Test a register to see if it exceeds the current maximum blob size.
124 ** If it does, record the new maximum blob size.
126 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
127 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
128 #else
129 # define UPDATE_MAX_BLOBSIZE(P)
130 #endif
133 ** Invoke the VDBE coverage callback, if that callback is defined. This
134 ** feature is used for test suite validation only and does not appear an
135 ** production builds.
137 ** M is an integer, 2 or 3, that indices how many different ways the
138 ** branch can go. It is usually 2. "I" is the direction the branch
139 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
140 ** second alternative branch is taken.
142 ** iSrcLine is the source code line (from the __LINE__ macro) that
143 ** generated the VDBE instruction. This instrumentation assumes that all
144 ** source code is in a single file (the amalgamation). Special values 1
145 ** and 2 for the iSrcLine parameter mean that this particular branch is
146 ** always taken or never taken, respectively.
148 #if !defined(SQLITE_VDBE_COVERAGE)
149 # define VdbeBranchTaken(I,M)
150 #else
151 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
152 static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
153 if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
154 M = iSrcLine;
155 /* Assert the truth of VdbeCoverageAlwaysTaken() and
156 ** VdbeCoverageNeverTaken() */
157 assert( (M & I)==I );
158 }else{
159 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
160 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
161 iSrcLine,I,M);
164 #endif
167 ** Convert the given register into a string if it isn't one
168 ** already. Return non-zero if a malloc() fails.
170 #define Stringify(P, enc) \
171 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
172 { goto no_mem; }
175 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
176 ** a pointer to a dynamically allocated string where some other entity
177 ** is responsible for deallocating that string. Because the register
178 ** does not control the string, it might be deleted without the register
179 ** knowing it.
181 ** This routine converts an ephemeral string into a dynamically allocated
182 ** string that the register itself controls. In other words, it
183 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
185 #define Deephemeralize(P) \
186 if( ((P)->flags&MEM_Ephem)!=0 \
187 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
189 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
190 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
193 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
194 ** if we run out of memory.
196 static VdbeCursor *allocateCursor(
197 Vdbe *p, /* The virtual machine */
198 int iCur, /* Index of the new VdbeCursor */
199 int nField, /* Number of fields in the table or index */
200 int iDb, /* Database the cursor belongs to, or -1 */
201 u8 eCurType /* Type of the new cursor */
203 /* Find the memory cell that will be used to store the blob of memory
204 ** required for this VdbeCursor structure. It is convenient to use a
205 ** vdbe memory cell to manage the memory allocation required for a
206 ** VdbeCursor structure for the following reasons:
208 ** * Sometimes cursor numbers are used for a couple of different
209 ** purposes in a vdbe program. The different uses might require
210 ** different sized allocations. Memory cells provide growable
211 ** allocations.
213 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
214 ** be freed lazily via the sqlite3_release_memory() API. This
215 ** minimizes the number of malloc calls made by the system.
217 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
218 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
219 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
221 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
223 int nByte;
224 VdbeCursor *pCx = 0;
225 nByte =
226 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
227 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
229 assert( iCur>=0 && iCur<p->nCursor );
230 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
231 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
232 p->apCsr[iCur] = 0;
234 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
235 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
236 memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
237 pCx->eCurType = eCurType;
238 pCx->iDb = iDb;
239 pCx->nField = nField;
240 pCx->aOffset = &pCx->aType[nField];
241 if( eCurType==CURTYPE_BTREE ){
242 pCx->uc.pCursor = (BtCursor*)
243 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
244 sqlite3BtreeCursorZero(pCx->uc.pCursor);
247 return pCx;
251 ** Try to convert a value into a numeric representation if we can
252 ** do so without loss of information. In other words, if the string
253 ** looks like a number, convert it into a number. If it does not
254 ** look like a number, leave it alone.
256 ** If the bTryForInt flag is true, then extra effort is made to give
257 ** an integer representation. Strings that look like floating point
258 ** values but which have no fractional component (example: '48.00')
259 ** will have a MEM_Int representation when bTryForInt is true.
261 ** If bTryForInt is false, then if the input string contains a decimal
262 ** point or exponential notation, the result is only MEM_Real, even
263 ** if there is an exact integer representation of the quantity.
265 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
266 double rValue;
267 i64 iValue;
268 u8 enc = pRec->enc;
269 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
270 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
271 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
272 pRec->u.i = iValue;
273 pRec->flags |= MEM_Int;
274 }else{
275 pRec->u.r = rValue;
276 pRec->flags |= MEM_Real;
277 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
279 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
280 ** string representation after computing a numeric equivalent, because the
281 ** string representation might not be the canonical representation for the
282 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
283 pRec->flags &= ~MEM_Str;
287 ** Processing is determine by the affinity parameter:
289 ** SQLITE_AFF_INTEGER:
290 ** SQLITE_AFF_REAL:
291 ** SQLITE_AFF_NUMERIC:
292 ** Try to convert pRec to an integer representation or a
293 ** floating-point representation if an integer representation
294 ** is not possible. Note that the integer representation is
295 ** always preferred, even if the affinity is REAL, because
296 ** an integer representation is more space efficient on disk.
298 ** SQLITE_AFF_TEXT:
299 ** Convert pRec to a text representation.
301 ** SQLITE_AFF_BLOB:
302 ** No-op. pRec is unchanged.
304 static void applyAffinity(
305 Mem *pRec, /* The value to apply affinity to */
306 char affinity, /* The affinity to be applied */
307 u8 enc /* Use this text encoding */
309 if( affinity>=SQLITE_AFF_NUMERIC ){
310 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
311 || affinity==SQLITE_AFF_NUMERIC );
312 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
313 if( (pRec->flags & MEM_Real)==0 ){
314 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
315 }else{
316 sqlite3VdbeIntegerAffinity(pRec);
319 }else if( affinity==SQLITE_AFF_TEXT ){
320 /* Only attempt the conversion to TEXT if there is an integer or real
321 ** representation (blob and NULL do not get converted) but no string
322 ** representation. It would be harmless to repeat the conversion if
323 ** there is already a string rep, but it is pointless to waste those
324 ** CPU cycles. */
325 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
326 if( (pRec->flags&(MEM_Real|MEM_Int)) ){
327 sqlite3VdbeMemStringify(pRec, enc, 1);
330 pRec->flags &= ~(MEM_Real|MEM_Int);
335 ** Try to convert the type of a function argument or a result column
336 ** into a numeric representation. Use either INTEGER or REAL whichever
337 ** is appropriate. But only do the conversion if it is possible without
338 ** loss of information and return the revised type of the argument.
340 int sqlite3_value_numeric_type(sqlite3_value *pVal){
341 int eType = sqlite3_value_type(pVal);
342 if( eType==SQLITE_TEXT ){
343 Mem *pMem = (Mem*)pVal;
344 applyNumericAffinity(pMem, 0);
345 eType = sqlite3_value_type(pVal);
347 return eType;
351 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
352 ** not the internal Mem* type.
354 void sqlite3ValueApplyAffinity(
355 sqlite3_value *pVal,
356 u8 affinity,
357 u8 enc
359 applyAffinity((Mem *)pVal, affinity, enc);
363 ** pMem currently only holds a string type (or maybe a BLOB that we can
364 ** interpret as a string if we want to). Compute its corresponding
365 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
366 ** accordingly.
368 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
369 assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
370 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
371 if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
372 return 0;
374 if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
375 return MEM_Int;
377 return MEM_Real;
381 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
382 ** none.
384 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
385 ** But it does set pMem->u.r and pMem->u.i appropriately.
387 static u16 numericType(Mem *pMem){
388 if( pMem->flags & (MEM_Int|MEM_Real) ){
389 return pMem->flags & (MEM_Int|MEM_Real);
391 if( pMem->flags & (MEM_Str|MEM_Blob) ){
392 return computeNumericType(pMem);
394 return 0;
397 #ifdef SQLITE_DEBUG
399 ** Write a nice string representation of the contents of cell pMem
400 ** into buffer zBuf, length nBuf.
402 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
403 char *zCsr = zBuf;
404 int f = pMem->flags;
406 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
408 if( f&MEM_Blob ){
409 int i;
410 char c;
411 if( f & MEM_Dyn ){
412 c = 'z';
413 assert( (f & (MEM_Static|MEM_Ephem))==0 );
414 }else if( f & MEM_Static ){
415 c = 't';
416 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
417 }else if( f & MEM_Ephem ){
418 c = 'e';
419 assert( (f & (MEM_Static|MEM_Dyn))==0 );
420 }else{
421 c = 's';
423 *(zCsr++) = c;
424 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
425 zCsr += sqlite3Strlen30(zCsr);
426 for(i=0; i<16 && i<pMem->n; i++){
427 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
428 zCsr += sqlite3Strlen30(zCsr);
430 for(i=0; i<16 && i<pMem->n; i++){
431 char z = pMem->z[i];
432 if( z<32 || z>126 ) *zCsr++ = '.';
433 else *zCsr++ = z;
435 *(zCsr++) = ']';
436 if( f & MEM_Zero ){
437 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
438 zCsr += sqlite3Strlen30(zCsr);
440 *zCsr = '\0';
441 }else if( f & MEM_Str ){
442 int j, k;
443 zBuf[0] = ' ';
444 if( f & MEM_Dyn ){
445 zBuf[1] = 'z';
446 assert( (f & (MEM_Static|MEM_Ephem))==0 );
447 }else if( f & MEM_Static ){
448 zBuf[1] = 't';
449 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
450 }else if( f & MEM_Ephem ){
451 zBuf[1] = 'e';
452 assert( (f & (MEM_Static|MEM_Dyn))==0 );
453 }else{
454 zBuf[1] = 's';
456 k = 2;
457 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
458 k += sqlite3Strlen30(&zBuf[k]);
459 zBuf[k++] = '[';
460 for(j=0; j<15 && j<pMem->n; j++){
461 u8 c = pMem->z[j];
462 if( c>=0x20 && c<0x7f ){
463 zBuf[k++] = c;
464 }else{
465 zBuf[k++] = '.';
468 zBuf[k++] = ']';
469 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
470 k += sqlite3Strlen30(&zBuf[k]);
471 zBuf[k++] = 0;
474 #endif
476 #ifdef SQLITE_DEBUG
478 ** Print the value of a register for tracing purposes:
480 static void memTracePrint(Mem *p){
481 if( p->flags & MEM_Undefined ){
482 printf(" undefined");
483 }else if( p->flags & MEM_Null ){
484 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
485 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
486 printf(" si:%lld", p->u.i);
487 }else if( p->flags & MEM_Int ){
488 printf(" i:%lld", p->u.i);
489 #ifndef SQLITE_OMIT_FLOATING_POINT
490 }else if( p->flags & MEM_Real ){
491 printf(" r:%g", p->u.r);
492 #endif
493 }else if( p->flags & MEM_RowSet ){
494 printf(" (rowset)");
495 }else{
496 char zBuf[200];
497 sqlite3VdbeMemPrettyPrint(p, zBuf);
498 printf(" %s", zBuf);
500 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
502 static void registerTrace(int iReg, Mem *p){
503 printf("REG[%d] = ", iReg);
504 memTracePrint(p);
505 printf("\n");
506 sqlite3VdbeCheckMemInvariants(p);
508 #endif
510 #ifdef SQLITE_DEBUG
511 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
512 #else
513 # define REGISTER_TRACE(R,M)
514 #endif
517 #ifdef VDBE_PROFILE
520 ** hwtime.h contains inline assembler code for implementing
521 ** high-performance timing routines.
523 #include "hwtime.h"
525 #endif
527 #ifndef NDEBUG
529 ** This function is only called from within an assert() expression. It
530 ** checks that the sqlite3.nTransaction variable is correctly set to
531 ** the number of non-transaction savepoints currently in the
532 ** linked list starting at sqlite3.pSavepoint.
534 ** Usage:
536 ** assert( checkSavepointCount(db) );
538 static int checkSavepointCount(sqlite3 *db){
539 int n = 0;
540 Savepoint *p;
541 for(p=db->pSavepoint; p; p=p->pNext) n++;
542 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
543 return 1;
545 #endif
548 ** Return the register of pOp->p2 after first preparing it to be
549 ** overwritten with an integer value.
551 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
552 sqlite3VdbeMemSetNull(pOut);
553 pOut->flags = MEM_Int;
554 return pOut;
556 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
557 Mem *pOut;
558 assert( pOp->p2>0 );
559 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
560 pOut = &p->aMem[pOp->p2];
561 memAboutToChange(p, pOut);
562 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
563 return out2PrereleaseWithClear(pOut);
564 }else{
565 pOut->flags = MEM_Int;
566 return pOut;
572 ** Execute as much of a VDBE program as we can.
573 ** This is the core of sqlite3_step().
575 int sqlite3VdbeExec(
576 Vdbe *p /* The VDBE */
578 Op *aOp = p->aOp; /* Copy of p->aOp */
579 Op *pOp = aOp; /* Current operation */
580 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
581 Op *pOrigOp; /* Value of pOp at the top of the loop */
582 #endif
583 #ifdef SQLITE_DEBUG
584 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
585 #endif
586 int rc = SQLITE_OK; /* Value to return */
587 sqlite3 *db = p->db; /* The database */
588 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
589 u8 encoding = ENC(db); /* The database encoding */
590 int iCompare = 0; /* Result of last comparison */
591 unsigned nVmStep = 0; /* Number of virtual machine steps */
592 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
593 unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
594 #endif
595 Mem *aMem = p->aMem; /* Copy of p->aMem */
596 Mem *pIn1 = 0; /* 1st input operand */
597 Mem *pIn2 = 0; /* 2nd input operand */
598 Mem *pIn3 = 0; /* 3rd input operand */
599 Mem *pOut = 0; /* Output operand */
600 #ifdef VDBE_PROFILE
601 u64 start; /* CPU clock count at start of opcode */
602 #endif
603 /*** INSERT STACK UNION HERE ***/
605 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
606 sqlite3VdbeEnter(p);
607 if( p->rc==SQLITE_NOMEM ){
608 /* This happens if a malloc() inside a call to sqlite3_column_text() or
609 ** sqlite3_column_text16() failed. */
610 goto no_mem;
612 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
613 assert( p->bIsReader || p->readOnly!=0 );
614 p->iCurrentTime = 0;
615 assert( p->explain==0 );
616 p->pResultSet = 0;
617 db->busyHandler.nBusy = 0;
618 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
619 sqlite3VdbeIOTraceSql(p);
620 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
621 if( db->xProgress ){
622 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
623 assert( 0 < db->nProgressOps );
624 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
625 }else{
626 nProgressLimit = 0xffffffff;
628 #endif
629 #ifdef SQLITE_DEBUG
630 sqlite3BeginBenignMalloc();
631 if( p->pc==0
632 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
634 int i;
635 int once = 1;
636 sqlite3VdbePrintSql(p);
637 if( p->db->flags & SQLITE_VdbeListing ){
638 printf("VDBE Program Listing:\n");
639 for(i=0; i<p->nOp; i++){
640 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
643 if( p->db->flags & SQLITE_VdbeEQP ){
644 for(i=0; i<p->nOp; i++){
645 if( aOp[i].opcode==OP_Explain ){
646 if( once ) printf("VDBE Query Plan:\n");
647 printf("%s\n", aOp[i].p4.z);
648 once = 0;
652 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
654 sqlite3EndBenignMalloc();
655 #endif
656 for(pOp=&aOp[p->pc]; 1; pOp++){
657 /* Errors are detected by individual opcodes, with an immediate
658 ** jumps to abort_due_to_error. */
659 assert( rc==SQLITE_OK );
661 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
662 #ifdef VDBE_PROFILE
663 start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
664 #endif
665 nVmStep++;
666 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
667 if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
668 #endif
670 /* Only allow tracing if SQLITE_DEBUG is defined.
672 #ifdef SQLITE_DEBUG
673 if( db->flags & SQLITE_VdbeTrace ){
674 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
676 #endif
679 /* Check to see if we need to simulate an interrupt. This only happens
680 ** if we have a special test build.
682 #ifdef SQLITE_TEST
683 if( sqlite3_interrupt_count>0 ){
684 sqlite3_interrupt_count--;
685 if( sqlite3_interrupt_count==0 ){
686 sqlite3_interrupt(db);
689 #endif
691 /* Sanity checking on other operands */
692 #ifdef SQLITE_DEBUG
694 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
695 if( (opProperty & OPFLG_IN1)!=0 ){
696 assert( pOp->p1>0 );
697 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
698 assert( memIsValid(&aMem[pOp->p1]) );
699 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
700 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
702 if( (opProperty & OPFLG_IN2)!=0 ){
703 assert( pOp->p2>0 );
704 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
705 assert( memIsValid(&aMem[pOp->p2]) );
706 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
707 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
709 if( (opProperty & OPFLG_IN3)!=0 ){
710 assert( pOp->p3>0 );
711 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
712 assert( memIsValid(&aMem[pOp->p3]) );
713 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
714 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
716 if( (opProperty & OPFLG_OUT2)!=0 ){
717 assert( pOp->p2>0 );
718 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
719 memAboutToChange(p, &aMem[pOp->p2]);
721 if( (opProperty & OPFLG_OUT3)!=0 ){
722 assert( pOp->p3>0 );
723 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
724 memAboutToChange(p, &aMem[pOp->p3]);
727 #endif
728 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
729 pOrigOp = pOp;
730 #endif
732 switch( pOp->opcode ){
734 /*****************************************************************************
735 ** What follows is a massive switch statement where each case implements a
736 ** separate instruction in the virtual machine. If we follow the usual
737 ** indentation conventions, each case should be indented by 6 spaces. But
738 ** that is a lot of wasted space on the left margin. So the code within
739 ** the switch statement will break with convention and be flush-left. Another
740 ** big comment (similar to this one) will mark the point in the code where
741 ** we transition back to normal indentation.
743 ** The formatting of each case is important. The makefile for SQLite
744 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
745 ** file looking for lines that begin with "case OP_". The opcodes.h files
746 ** will be filled with #defines that give unique integer values to each
747 ** opcode and the opcodes.c file is filled with an array of strings where
748 ** each string is the symbolic name for the corresponding opcode. If the
749 ** case statement is followed by a comment of the form "/# same as ... #/"
750 ** that comment is used to determine the particular value of the opcode.
752 ** Other keywords in the comment that follows each case are used to
753 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
754 ** Keywords include: in1, in2, in3, out2, out3. See
755 ** the mkopcodeh.awk script for additional information.
757 ** Documentation about VDBE opcodes is generated by scanning this file
758 ** for lines of that contain "Opcode:". That line and all subsequent
759 ** comment lines are used in the generation of the opcode.html documentation
760 ** file.
762 ** SUMMARY:
764 ** Formatting is important to scripts that scan this file.
765 ** Do not deviate from the formatting style currently in use.
767 *****************************************************************************/
769 /* Opcode: Goto * P2 * * *
771 ** An unconditional jump to address P2.
772 ** The next instruction executed will be
773 ** the one at index P2 from the beginning of
774 ** the program.
776 ** The P1 parameter is not actually used by this opcode. However, it
777 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
778 ** that this Goto is the bottom of a loop and that the lines from P2 down
779 ** to the current line should be indented for EXPLAIN output.
781 case OP_Goto: { /* jump */
782 jump_to_p2_and_check_for_interrupt:
783 pOp = &aOp[pOp->p2 - 1];
785 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
786 ** OP_VNext, or OP_SorterNext) all jump here upon
787 ** completion. Check to see if sqlite3_interrupt() has been called
788 ** or if the progress callback needs to be invoked.
790 ** This code uses unstructured "goto" statements and does not look clean.
791 ** But that is not due to sloppy coding habits. The code is written this
792 ** way for performance, to avoid having to run the interrupt and progress
793 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
794 ** faster according to "valgrind --tool=cachegrind" */
795 check_for_interrupt:
796 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
797 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
798 /* Call the progress callback if it is configured and the required number
799 ** of VDBE ops have been executed (either since this invocation of
800 ** sqlite3VdbeExec() or since last time the progress callback was called).
801 ** If the progress callback returns non-zero, exit the virtual machine with
802 ** a return code SQLITE_ABORT.
804 if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
805 assert( db->nProgressOps!=0 );
806 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
807 if( db->xProgress(db->pProgressArg) ){
808 rc = SQLITE_INTERRUPT;
809 goto abort_due_to_error;
812 #endif
814 break;
817 /* Opcode: Gosub P1 P2 * * *
819 ** Write the current address onto register P1
820 ** and then jump to address P2.
822 case OP_Gosub: { /* jump */
823 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
824 pIn1 = &aMem[pOp->p1];
825 assert( VdbeMemDynamic(pIn1)==0 );
826 memAboutToChange(p, pIn1);
827 pIn1->flags = MEM_Int;
828 pIn1->u.i = (int)(pOp-aOp);
829 REGISTER_TRACE(pOp->p1, pIn1);
831 /* Most jump operations do a goto to this spot in order to update
832 ** the pOp pointer. */
833 jump_to_p2:
834 pOp = &aOp[pOp->p2 - 1];
835 break;
838 /* Opcode: Return P1 * * * *
840 ** Jump to the next instruction after the address in register P1. After
841 ** the jump, register P1 becomes undefined.
843 case OP_Return: { /* in1 */
844 pIn1 = &aMem[pOp->p1];
845 assert( pIn1->flags==MEM_Int );
846 pOp = &aOp[pIn1->u.i];
847 pIn1->flags = MEM_Undefined;
848 break;
851 /* Opcode: InitCoroutine P1 P2 P3 * *
853 ** Set up register P1 so that it will Yield to the coroutine
854 ** located at address P3.
856 ** If P2!=0 then the coroutine implementation immediately follows
857 ** this opcode. So jump over the coroutine implementation to
858 ** address P2.
860 ** See also: EndCoroutine
862 case OP_InitCoroutine: { /* jump */
863 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
864 assert( pOp->p2>=0 && pOp->p2<p->nOp );
865 assert( pOp->p3>=0 && pOp->p3<p->nOp );
866 pOut = &aMem[pOp->p1];
867 assert( !VdbeMemDynamic(pOut) );
868 pOut->u.i = pOp->p3 - 1;
869 pOut->flags = MEM_Int;
870 if( pOp->p2 ) goto jump_to_p2;
871 break;
874 /* Opcode: EndCoroutine P1 * * * *
876 ** The instruction at the address in register P1 is a Yield.
877 ** Jump to the P2 parameter of that Yield.
878 ** After the jump, register P1 becomes undefined.
880 ** See also: InitCoroutine
882 case OP_EndCoroutine: { /* in1 */
883 VdbeOp *pCaller;
884 pIn1 = &aMem[pOp->p1];
885 assert( pIn1->flags==MEM_Int );
886 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
887 pCaller = &aOp[pIn1->u.i];
888 assert( pCaller->opcode==OP_Yield );
889 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
890 pOp = &aOp[pCaller->p2 - 1];
891 pIn1->flags = MEM_Undefined;
892 break;
895 /* Opcode: Yield P1 P2 * * *
897 ** Swap the program counter with the value in register P1. This
898 ** has the effect of yielding to a coroutine.
900 ** If the coroutine that is launched by this instruction ends with
901 ** Yield or Return then continue to the next instruction. But if
902 ** the coroutine launched by this instruction ends with
903 ** EndCoroutine, then jump to P2 rather than continuing with the
904 ** next instruction.
906 ** See also: InitCoroutine
908 case OP_Yield: { /* in1, jump */
909 int pcDest;
910 pIn1 = &aMem[pOp->p1];
911 assert( VdbeMemDynamic(pIn1)==0 );
912 pIn1->flags = MEM_Int;
913 pcDest = (int)pIn1->u.i;
914 pIn1->u.i = (int)(pOp - aOp);
915 REGISTER_TRACE(pOp->p1, pIn1);
916 pOp = &aOp[pcDest];
917 break;
920 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
921 ** Synopsis: if r[P3]=null halt
923 ** Check the value in register P3. If it is NULL then Halt using
924 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
925 ** value in register P3 is not NULL, then this routine is a no-op.
926 ** The P5 parameter should be 1.
928 case OP_HaltIfNull: { /* in3 */
929 pIn3 = &aMem[pOp->p3];
930 #ifdef SQLITE_DEBUG
931 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
932 #endif
933 if( (pIn3->flags & MEM_Null)==0 ) break;
934 /* Fall through into OP_Halt */
937 /* Opcode: Halt P1 P2 * P4 P5
939 ** Exit immediately. All open cursors, etc are closed
940 ** automatically.
942 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
943 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
944 ** For errors, it can be some other value. If P1!=0 then P2 will determine
945 ** whether or not to rollback the current transaction. Do not rollback
946 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
947 ** then back out all changes that have occurred during this execution of the
948 ** VDBE, but do not rollback the transaction.
950 ** If P4 is not null then it is an error message string.
952 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
954 ** 0: (no change)
955 ** 1: NOT NULL contraint failed: P4
956 ** 2: UNIQUE constraint failed: P4
957 ** 3: CHECK constraint failed: P4
958 ** 4: FOREIGN KEY constraint failed: P4
960 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
961 ** omitted.
963 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
964 ** every program. So a jump past the last instruction of the program
965 ** is the same as executing Halt.
967 case OP_Halt: {
968 VdbeFrame *pFrame;
969 int pcx;
971 pcx = (int)(pOp - aOp);
972 #ifdef SQLITE_DEBUG
973 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
974 #endif
975 if( pOp->p1==SQLITE_OK && p->pFrame ){
976 /* Halt the sub-program. Return control to the parent frame. */
977 pFrame = p->pFrame;
978 p->pFrame = pFrame->pParent;
979 p->nFrame--;
980 sqlite3VdbeSetChanges(db, p->nChange);
981 pcx = sqlite3VdbeFrameRestore(pFrame);
982 if( pOp->p2==OE_Ignore ){
983 /* Instruction pcx is the OP_Program that invoked the sub-program
984 ** currently being halted. If the p2 instruction of this OP_Halt
985 ** instruction is set to OE_Ignore, then the sub-program is throwing
986 ** an IGNORE exception. In this case jump to the address specified
987 ** as the p2 of the calling OP_Program. */
988 pcx = p->aOp[pcx].p2-1;
990 aOp = p->aOp;
991 aMem = p->aMem;
992 pOp = &aOp[pcx];
993 break;
995 p->rc = pOp->p1;
996 p->errorAction = (u8)pOp->p2;
997 p->pc = pcx;
998 assert( pOp->p5<=4 );
999 if( p->rc ){
1000 if( pOp->p5 ){
1001 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
1002 "FOREIGN KEY" };
1003 testcase( pOp->p5==1 );
1004 testcase( pOp->p5==2 );
1005 testcase( pOp->p5==3 );
1006 testcase( pOp->p5==4 );
1007 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
1008 if( pOp->p4.z ){
1009 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
1011 }else{
1012 sqlite3VdbeError(p, "%s", pOp->p4.z);
1014 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
1016 rc = sqlite3VdbeHalt(p);
1017 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1018 if( rc==SQLITE_BUSY ){
1019 p->rc = SQLITE_BUSY;
1020 }else{
1021 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1022 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1023 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1025 goto vdbe_return;
1028 /* Opcode: Integer P1 P2 * * *
1029 ** Synopsis: r[P2]=P1
1031 ** The 32-bit integer value P1 is written into register P2.
1033 case OP_Integer: { /* out2 */
1034 pOut = out2Prerelease(p, pOp);
1035 pOut->u.i = pOp->p1;
1036 break;
1039 /* Opcode: Int64 * P2 * P4 *
1040 ** Synopsis: r[P2]=P4
1042 ** P4 is a pointer to a 64-bit integer value.
1043 ** Write that value into register P2.
1045 case OP_Int64: { /* out2 */
1046 pOut = out2Prerelease(p, pOp);
1047 assert( pOp->p4.pI64!=0 );
1048 pOut->u.i = *pOp->p4.pI64;
1049 break;
1052 #ifndef SQLITE_OMIT_FLOATING_POINT
1053 /* Opcode: Real * P2 * P4 *
1054 ** Synopsis: r[P2]=P4
1056 ** P4 is a pointer to a 64-bit floating point value.
1057 ** Write that value into register P2.
1059 case OP_Real: { /* same as TK_FLOAT, out2 */
1060 pOut = out2Prerelease(p, pOp);
1061 pOut->flags = MEM_Real;
1062 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1063 pOut->u.r = *pOp->p4.pReal;
1064 break;
1066 #endif
1068 /* Opcode: String8 * P2 * P4 *
1069 ** Synopsis: r[P2]='P4'
1071 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1072 ** into a String opcode before it is executed for the first time. During
1073 ** this transformation, the length of string P4 is computed and stored
1074 ** as the P1 parameter.
1076 case OP_String8: { /* same as TK_STRING, out2 */
1077 assert( pOp->p4.z!=0 );
1078 pOut = out2Prerelease(p, pOp);
1079 pOp->opcode = OP_String;
1080 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1082 #ifndef SQLITE_OMIT_UTF16
1083 if( encoding!=SQLITE_UTF8 ){
1084 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1085 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1086 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1087 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1088 assert( VdbeMemDynamic(pOut)==0 );
1089 pOut->szMalloc = 0;
1090 pOut->flags |= MEM_Static;
1091 if( pOp->p4type==P4_DYNAMIC ){
1092 sqlite3DbFree(db, pOp->p4.z);
1094 pOp->p4type = P4_DYNAMIC;
1095 pOp->p4.z = pOut->z;
1096 pOp->p1 = pOut->n;
1098 testcase( rc==SQLITE_TOOBIG );
1099 #endif
1100 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1101 goto too_big;
1103 assert( rc==SQLITE_OK );
1104 /* Fall through to the next case, OP_String */
1107 /* Opcode: String P1 P2 P3 P4 P5
1108 ** Synopsis: r[P2]='P4' (len=P1)
1110 ** The string value P4 of length P1 (bytes) is stored in register P2.
1112 ** If P3 is not zero and the content of register P3 is equal to P5, then
1113 ** the datatype of the register P2 is converted to BLOB. The content is
1114 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1115 ** of a string, as if it had been CAST. In other words:
1117 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1119 case OP_String: { /* out2 */
1120 assert( pOp->p4.z!=0 );
1121 pOut = out2Prerelease(p, pOp);
1122 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1123 pOut->z = pOp->p4.z;
1124 pOut->n = pOp->p1;
1125 pOut->enc = encoding;
1126 UPDATE_MAX_BLOBSIZE(pOut);
1127 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1128 if( pOp->p3>0 ){
1129 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1130 pIn3 = &aMem[pOp->p3];
1131 assert( pIn3->flags & MEM_Int );
1132 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1134 #endif
1135 break;
1138 /* Opcode: Null P1 P2 P3 * *
1139 ** Synopsis: r[P2..P3]=NULL
1141 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1142 ** NULL into register P3 and every register in between P2 and P3. If P3
1143 ** is less than P2 (typically P3 is zero) then only register P2 is
1144 ** set to NULL.
1146 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1147 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1148 ** OP_Ne or OP_Eq.
1150 case OP_Null: { /* out2 */
1151 int cnt;
1152 u16 nullFlag;
1153 pOut = out2Prerelease(p, pOp);
1154 cnt = pOp->p3-pOp->p2;
1155 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1156 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1157 pOut->n = 0;
1158 while( cnt>0 ){
1159 pOut++;
1160 memAboutToChange(p, pOut);
1161 sqlite3VdbeMemSetNull(pOut);
1162 pOut->flags = nullFlag;
1163 pOut->n = 0;
1164 cnt--;
1166 break;
1169 /* Opcode: SoftNull P1 * * * *
1170 ** Synopsis: r[P1]=NULL
1172 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1173 ** instruction, but do not free any string or blob memory associated with
1174 ** the register, so that if the value was a string or blob that was
1175 ** previously copied using OP_SCopy, the copies will continue to be valid.
1177 case OP_SoftNull: {
1178 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1179 pOut = &aMem[pOp->p1];
1180 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1181 break;
1184 /* Opcode: Blob P1 P2 * P4 *
1185 ** Synopsis: r[P2]=P4 (len=P1)
1187 ** P4 points to a blob of data P1 bytes long. Store this
1188 ** blob in register P2.
1190 case OP_Blob: { /* out2 */
1191 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1192 pOut = out2Prerelease(p, pOp);
1193 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1194 pOut->enc = encoding;
1195 UPDATE_MAX_BLOBSIZE(pOut);
1196 break;
1199 /* Opcode: Variable P1 P2 * P4 *
1200 ** Synopsis: r[P2]=parameter(P1,P4)
1202 ** Transfer the values of bound parameter P1 into register P2
1204 ** If the parameter is named, then its name appears in P4.
1205 ** The P4 value is used by sqlite3_bind_parameter_name().
1207 case OP_Variable: { /* out2 */
1208 Mem *pVar; /* Value being transferred */
1210 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1211 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1212 pVar = &p->aVar[pOp->p1 - 1];
1213 if( sqlite3VdbeMemTooBig(pVar) ){
1214 goto too_big;
1216 pOut = &aMem[pOp->p2];
1217 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
1218 UPDATE_MAX_BLOBSIZE(pOut);
1219 break;
1222 /* Opcode: Move P1 P2 P3 * *
1223 ** Synopsis: r[P2@P3]=r[P1@P3]
1225 ** Move the P3 values in register P1..P1+P3-1 over into
1226 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1227 ** left holding a NULL. It is an error for register ranges
1228 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1229 ** for P3 to be less than 1.
1231 case OP_Move: {
1232 int n; /* Number of registers left to copy */
1233 int p1; /* Register to copy from */
1234 int p2; /* Register to copy to */
1236 n = pOp->p3;
1237 p1 = pOp->p1;
1238 p2 = pOp->p2;
1239 assert( n>0 && p1>0 && p2>0 );
1240 assert( p1+n<=p2 || p2+n<=p1 );
1242 pIn1 = &aMem[p1];
1243 pOut = &aMem[p2];
1245 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1246 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1247 assert( memIsValid(pIn1) );
1248 memAboutToChange(p, pOut);
1249 sqlite3VdbeMemMove(pOut, pIn1);
1250 #ifdef SQLITE_DEBUG
1251 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
1252 pOut->pScopyFrom += pOp->p2 - p1;
1254 #endif
1255 Deephemeralize(pOut);
1256 REGISTER_TRACE(p2++, pOut);
1257 pIn1++;
1258 pOut++;
1259 }while( --n );
1260 break;
1263 /* Opcode: Copy P1 P2 P3 * *
1264 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1266 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1268 ** This instruction makes a deep copy of the value. A duplicate
1269 ** is made of any string or blob constant. See also OP_SCopy.
1271 case OP_Copy: {
1272 int n;
1274 n = pOp->p3;
1275 pIn1 = &aMem[pOp->p1];
1276 pOut = &aMem[pOp->p2];
1277 assert( pOut!=pIn1 );
1278 while( 1 ){
1279 memAboutToChange(p, pOut);
1280 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1281 Deephemeralize(pOut);
1282 #ifdef SQLITE_DEBUG
1283 pOut->pScopyFrom = 0;
1284 pOut->iTabColHash = 0;
1285 #endif
1286 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1287 if( (n--)==0 ) break;
1288 pOut++;
1289 pIn1++;
1291 break;
1294 /* Opcode: SCopy P1 P2 * * *
1295 ** Synopsis: r[P2]=r[P1]
1297 ** Make a shallow copy of register P1 into register P2.
1299 ** This instruction makes a shallow copy of the value. If the value
1300 ** is a string or blob, then the copy is only a pointer to the
1301 ** original and hence if the original changes so will the copy.
1302 ** Worse, if the original is deallocated, the copy becomes invalid.
1303 ** Thus the program must guarantee that the original will not change
1304 ** during the lifetime of the copy. Use OP_Copy to make a complete
1305 ** copy.
1307 case OP_SCopy: { /* out2 */
1308 pIn1 = &aMem[pOp->p1];
1309 pOut = &aMem[pOp->p2];
1310 assert( pOut!=pIn1 );
1311 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1312 #ifdef SQLITE_DEBUG
1313 pOut->pScopyFrom = pIn1;
1314 pOut->mScopyFlags = pIn1->flags;
1315 #endif
1316 break;
1319 /* Opcode: IntCopy P1 P2 * * *
1320 ** Synopsis: r[P2]=r[P1]
1322 ** Transfer the integer value held in register P1 into register P2.
1324 ** This is an optimized version of SCopy that works only for integer
1325 ** values.
1327 case OP_IntCopy: { /* out2 */
1328 pIn1 = &aMem[pOp->p1];
1329 assert( (pIn1->flags & MEM_Int)!=0 );
1330 pOut = &aMem[pOp->p2];
1331 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1332 break;
1335 /* Opcode: ResultRow P1 P2 * * *
1336 ** Synopsis: output=r[P1@P2]
1338 ** The registers P1 through P1+P2-1 contain a single row of
1339 ** results. This opcode causes the sqlite3_step() call to terminate
1340 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1341 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1342 ** the result row.
1344 case OP_ResultRow: {
1345 Mem *pMem;
1346 int i;
1347 assert( p->nResColumn==pOp->p2 );
1348 assert( pOp->p1>0 );
1349 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1351 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1352 /* Run the progress counter just before returning.
1354 if( db->xProgress!=0
1355 && nVmStep>=nProgressLimit
1356 && db->xProgress(db->pProgressArg)!=0
1358 rc = SQLITE_INTERRUPT;
1359 goto abort_due_to_error;
1361 #endif
1363 /* If this statement has violated immediate foreign key constraints, do
1364 ** not return the number of rows modified. And do not RELEASE the statement
1365 ** transaction. It needs to be rolled back. */
1366 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
1367 assert( db->flags&SQLITE_CountRows );
1368 assert( p->usesStmtJournal );
1369 goto abort_due_to_error;
1372 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1373 ** DML statements invoke this opcode to return the number of rows
1374 ** modified to the user. This is the only way that a VM that
1375 ** opens a statement transaction may invoke this opcode.
1377 ** In case this is such a statement, close any statement transaction
1378 ** opened by this VM before returning control to the user. This is to
1379 ** ensure that statement-transactions are always nested, not overlapping.
1380 ** If the open statement-transaction is not closed here, then the user
1381 ** may step another VM that opens its own statement transaction. This
1382 ** may lead to overlapping statement transactions.
1384 ** The statement transaction is never a top-level transaction. Hence
1385 ** the RELEASE call below can never fail.
1387 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
1388 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
1389 assert( rc==SQLITE_OK );
1391 /* Invalidate all ephemeral cursor row caches */
1392 p->cacheCtr = (p->cacheCtr + 2)|1;
1394 /* Make sure the results of the current row are \000 terminated
1395 ** and have an assigned type. The results are de-ephemeralized as
1396 ** a side effect.
1398 pMem = p->pResultSet = &aMem[pOp->p1];
1399 for(i=0; i<pOp->p2; i++){
1400 assert( memIsValid(&pMem[i]) );
1401 Deephemeralize(&pMem[i]);
1402 assert( (pMem[i].flags & MEM_Ephem)==0
1403 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1404 sqlite3VdbeMemNulTerminate(&pMem[i]);
1405 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1407 if( db->mallocFailed ) goto no_mem;
1409 if( db->mTrace & SQLITE_TRACE_ROW ){
1410 db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1413 /* Return SQLITE_ROW
1415 p->pc = (int)(pOp - aOp) + 1;
1416 rc = SQLITE_ROW;
1417 goto vdbe_return;
1420 /* Opcode: Concat P1 P2 P3 * *
1421 ** Synopsis: r[P3]=r[P2]+r[P1]
1423 ** Add the text in register P1 onto the end of the text in
1424 ** register P2 and store the result in register P3.
1425 ** If either the P1 or P2 text are NULL then store NULL in P3.
1427 ** P3 = P2 || P1
1429 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1430 ** if P3 is the same register as P2, the implementation is able
1431 ** to avoid a memcpy().
1433 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1434 i64 nByte;
1436 pIn1 = &aMem[pOp->p1];
1437 pIn2 = &aMem[pOp->p2];
1438 pOut = &aMem[pOp->p3];
1439 assert( pIn1!=pOut );
1440 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1441 sqlite3VdbeMemSetNull(pOut);
1442 break;
1444 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
1445 Stringify(pIn1, encoding);
1446 Stringify(pIn2, encoding);
1447 nByte = pIn1->n + pIn2->n;
1448 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1449 goto too_big;
1451 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1452 goto no_mem;
1454 MemSetTypeFlag(pOut, MEM_Str);
1455 if( pOut!=pIn2 ){
1456 memcpy(pOut->z, pIn2->z, pIn2->n);
1458 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1459 pOut->z[nByte]=0;
1460 pOut->z[nByte+1] = 0;
1461 pOut->flags |= MEM_Term;
1462 pOut->n = (int)nByte;
1463 pOut->enc = encoding;
1464 UPDATE_MAX_BLOBSIZE(pOut);
1465 break;
1468 /* Opcode: Add P1 P2 P3 * *
1469 ** Synopsis: r[P3]=r[P1]+r[P2]
1471 ** Add the value in register P1 to the value in register P2
1472 ** and store the result in register P3.
1473 ** If either input is NULL, the result is NULL.
1475 /* Opcode: Multiply P1 P2 P3 * *
1476 ** Synopsis: r[P3]=r[P1]*r[P2]
1479 ** Multiply the value in register P1 by the value in register P2
1480 ** and store the result in register P3.
1481 ** If either input is NULL, the result is NULL.
1483 /* Opcode: Subtract P1 P2 P3 * *
1484 ** Synopsis: r[P3]=r[P2]-r[P1]
1486 ** Subtract the value in register P1 from the value in register P2
1487 ** and store the result in register P3.
1488 ** If either input is NULL, the result is NULL.
1490 /* Opcode: Divide P1 P2 P3 * *
1491 ** Synopsis: r[P3]=r[P2]/r[P1]
1493 ** Divide the value in register P1 by the value in register P2
1494 ** and store the result in register P3 (P3=P2/P1). If the value in
1495 ** register P1 is zero, then the result is NULL. If either input is
1496 ** NULL, the result is NULL.
1498 /* Opcode: Remainder P1 P2 P3 * *
1499 ** Synopsis: r[P3]=r[P2]%r[P1]
1501 ** Compute the remainder after integer register P2 is divided by
1502 ** register P1 and store the result in register P3.
1503 ** If the value in register P1 is zero the result is NULL.
1504 ** If either operand is NULL, the result is NULL.
1506 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1507 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1508 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1509 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1510 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1511 char bIntint; /* Started out as two integer operands */
1512 u16 flags; /* Combined MEM_* flags from both inputs */
1513 u16 type1; /* Numeric type of left operand */
1514 u16 type2; /* Numeric type of right operand */
1515 i64 iA; /* Integer value of left operand */
1516 i64 iB; /* Integer value of right operand */
1517 double rA; /* Real value of left operand */
1518 double rB; /* Real value of right operand */
1520 pIn1 = &aMem[pOp->p1];
1521 type1 = numericType(pIn1);
1522 pIn2 = &aMem[pOp->p2];
1523 type2 = numericType(pIn2);
1524 pOut = &aMem[pOp->p3];
1525 flags = pIn1->flags | pIn2->flags;
1526 if( (type1 & type2 & MEM_Int)!=0 ){
1527 iA = pIn1->u.i;
1528 iB = pIn2->u.i;
1529 bIntint = 1;
1530 switch( pOp->opcode ){
1531 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1532 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1533 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1534 case OP_Divide: {
1535 if( iA==0 ) goto arithmetic_result_is_null;
1536 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1537 iB /= iA;
1538 break;
1540 default: {
1541 if( iA==0 ) goto arithmetic_result_is_null;
1542 if( iA==-1 ) iA = 1;
1543 iB %= iA;
1544 break;
1547 pOut->u.i = iB;
1548 MemSetTypeFlag(pOut, MEM_Int);
1549 }else if( (flags & MEM_Null)!=0 ){
1550 goto arithmetic_result_is_null;
1551 }else{
1552 bIntint = 0;
1553 fp_math:
1554 rA = sqlite3VdbeRealValue(pIn1);
1555 rB = sqlite3VdbeRealValue(pIn2);
1556 switch( pOp->opcode ){
1557 case OP_Add: rB += rA; break;
1558 case OP_Subtract: rB -= rA; break;
1559 case OP_Multiply: rB *= rA; break;
1560 case OP_Divide: {
1561 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1562 if( rA==(double)0 ) goto arithmetic_result_is_null;
1563 rB /= rA;
1564 break;
1566 default: {
1567 iA = (i64)rA;
1568 iB = (i64)rB;
1569 if( iA==0 ) goto arithmetic_result_is_null;
1570 if( iA==-1 ) iA = 1;
1571 rB = (double)(iB % iA);
1572 break;
1575 #ifdef SQLITE_OMIT_FLOATING_POINT
1576 pOut->u.i = rB;
1577 MemSetTypeFlag(pOut, MEM_Int);
1578 #else
1579 if( sqlite3IsNaN(rB) ){
1580 goto arithmetic_result_is_null;
1582 pOut->u.r = rB;
1583 MemSetTypeFlag(pOut, MEM_Real);
1584 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
1585 sqlite3VdbeIntegerAffinity(pOut);
1587 #endif
1589 break;
1591 arithmetic_result_is_null:
1592 sqlite3VdbeMemSetNull(pOut);
1593 break;
1596 /* Opcode: CollSeq P1 * * P4
1598 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1599 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1600 ** be returned. This is used by the built-in min(), max() and nullif()
1601 ** functions.
1603 ** If P1 is not zero, then it is a register that a subsequent min() or
1604 ** max() aggregate will set to 1 if the current row is not the minimum or
1605 ** maximum. The P1 register is initialized to 0 by this instruction.
1607 ** The interface used by the implementation of the aforementioned functions
1608 ** to retrieve the collation sequence set by this opcode is not available
1609 ** publicly. Only built-in functions have access to this feature.
1611 case OP_CollSeq: {
1612 assert( pOp->p4type==P4_COLLSEQ );
1613 if( pOp->p1 ){
1614 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1616 break;
1619 /* Opcode: BitAnd P1 P2 P3 * *
1620 ** Synopsis: r[P3]=r[P1]&r[P2]
1622 ** Take the bit-wise AND of the values in register P1 and P2 and
1623 ** store the result in register P3.
1624 ** If either input is NULL, the result is NULL.
1626 /* Opcode: BitOr P1 P2 P3 * *
1627 ** Synopsis: r[P3]=r[P1]|r[P2]
1629 ** Take the bit-wise OR of the values in register P1 and P2 and
1630 ** store the result in register P3.
1631 ** If either input is NULL, the result is NULL.
1633 /* Opcode: ShiftLeft P1 P2 P3 * *
1634 ** Synopsis: r[P3]=r[P2]<<r[P1]
1636 ** Shift the integer value in register P2 to the left by the
1637 ** number of bits specified by the integer in register P1.
1638 ** Store the result in register P3.
1639 ** If either input is NULL, the result is NULL.
1641 /* Opcode: ShiftRight P1 P2 P3 * *
1642 ** Synopsis: r[P3]=r[P2]>>r[P1]
1644 ** Shift the integer value in register P2 to the right by the
1645 ** number of bits specified by the integer in register P1.
1646 ** Store the result in register P3.
1647 ** If either input is NULL, the result is NULL.
1649 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1650 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1651 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1652 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1653 i64 iA;
1654 u64 uA;
1655 i64 iB;
1656 u8 op;
1658 pIn1 = &aMem[pOp->p1];
1659 pIn2 = &aMem[pOp->p2];
1660 pOut = &aMem[pOp->p3];
1661 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1662 sqlite3VdbeMemSetNull(pOut);
1663 break;
1665 iA = sqlite3VdbeIntValue(pIn2);
1666 iB = sqlite3VdbeIntValue(pIn1);
1667 op = pOp->opcode;
1668 if( op==OP_BitAnd ){
1669 iA &= iB;
1670 }else if( op==OP_BitOr ){
1671 iA |= iB;
1672 }else if( iB!=0 ){
1673 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1675 /* If shifting by a negative amount, shift in the other direction */
1676 if( iB<0 ){
1677 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1678 op = 2*OP_ShiftLeft + 1 - op;
1679 iB = iB>(-64) ? -iB : 64;
1682 if( iB>=64 ){
1683 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1684 }else{
1685 memcpy(&uA, &iA, sizeof(uA));
1686 if( op==OP_ShiftLeft ){
1687 uA <<= iB;
1688 }else{
1689 uA >>= iB;
1690 /* Sign-extend on a right shift of a negative number */
1691 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1693 memcpy(&iA, &uA, sizeof(iA));
1696 pOut->u.i = iA;
1697 MemSetTypeFlag(pOut, MEM_Int);
1698 break;
1701 /* Opcode: AddImm P1 P2 * * *
1702 ** Synopsis: r[P1]=r[P1]+P2
1704 ** Add the constant P2 to the value in register P1.
1705 ** The result is always an integer.
1707 ** To force any register to be an integer, just add 0.
1709 case OP_AddImm: { /* in1 */
1710 pIn1 = &aMem[pOp->p1];
1711 memAboutToChange(p, pIn1);
1712 sqlite3VdbeMemIntegerify(pIn1);
1713 pIn1->u.i += pOp->p2;
1714 break;
1717 /* Opcode: MustBeInt P1 P2 * * *
1719 ** Force the value in register P1 to be an integer. If the value
1720 ** in P1 is not an integer and cannot be converted into an integer
1721 ** without data loss, then jump immediately to P2, or if P2==0
1722 ** raise an SQLITE_MISMATCH exception.
1724 case OP_MustBeInt: { /* jump, in1 */
1725 pIn1 = &aMem[pOp->p1];
1726 if( (pIn1->flags & MEM_Int)==0 ){
1727 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1728 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
1729 if( (pIn1->flags & MEM_Int)==0 ){
1730 if( pOp->p2==0 ){
1731 rc = SQLITE_MISMATCH;
1732 goto abort_due_to_error;
1733 }else{
1734 goto jump_to_p2;
1738 MemSetTypeFlag(pIn1, MEM_Int);
1739 break;
1742 #ifndef SQLITE_OMIT_FLOATING_POINT
1743 /* Opcode: RealAffinity P1 * * * *
1745 ** If register P1 holds an integer convert it to a real value.
1747 ** This opcode is used when extracting information from a column that
1748 ** has REAL affinity. Such column values may still be stored as
1749 ** integers, for space efficiency, but after extraction we want them
1750 ** to have only a real value.
1752 case OP_RealAffinity: { /* in1 */
1753 pIn1 = &aMem[pOp->p1];
1754 if( pIn1->flags & MEM_Int ){
1755 sqlite3VdbeMemRealify(pIn1);
1757 break;
1759 #endif
1761 #ifndef SQLITE_OMIT_CAST
1762 /* Opcode: Cast P1 P2 * * *
1763 ** Synopsis: affinity(r[P1])
1765 ** Force the value in register P1 to be the type defined by P2.
1767 ** <ul>
1768 ** <li> P2=='A' &rarr; BLOB
1769 ** <li> P2=='B' &rarr; TEXT
1770 ** <li> P2=='C' &rarr; NUMERIC
1771 ** <li> P2=='D' &rarr; INTEGER
1772 ** <li> P2=='E' &rarr; REAL
1773 ** </ul>
1775 ** A NULL value is not changed by this routine. It remains NULL.
1777 case OP_Cast: { /* in1 */
1778 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
1779 testcase( pOp->p2==SQLITE_AFF_TEXT );
1780 testcase( pOp->p2==SQLITE_AFF_BLOB );
1781 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
1782 testcase( pOp->p2==SQLITE_AFF_INTEGER );
1783 testcase( pOp->p2==SQLITE_AFF_REAL );
1784 pIn1 = &aMem[pOp->p1];
1785 memAboutToChange(p, pIn1);
1786 rc = ExpandBlob(pIn1);
1787 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
1788 UPDATE_MAX_BLOBSIZE(pIn1);
1789 if( rc ) goto abort_due_to_error;
1790 break;
1792 #endif /* SQLITE_OMIT_CAST */
1794 /* Opcode: Eq P1 P2 P3 P4 P5
1795 ** Synopsis: IF r[P3]==r[P1]
1797 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
1798 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
1799 ** store the result of comparison in register P2.
1801 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1802 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1803 ** to coerce both inputs according to this affinity before the
1804 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1805 ** affinity is used. Note that the affinity conversions are stored
1806 ** back into the input registers P1 and P3. So this opcode can cause
1807 ** persistent changes to registers P1 and P3.
1809 ** Once any conversions have taken place, and neither value is NULL,
1810 ** the values are compared. If both values are blobs then memcmp() is
1811 ** used to determine the results of the comparison. If both values
1812 ** are text, then the appropriate collating function specified in
1813 ** P4 is used to do the comparison. If P4 is not specified then
1814 ** memcmp() is used to compare text string. If both values are
1815 ** numeric, then a numeric comparison is used. If the two values
1816 ** are of different types, then numbers are considered less than
1817 ** strings and strings are considered less than blobs.
1819 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1820 ** true or false and is never NULL. If both operands are NULL then the result
1821 ** of comparison is true. If either operand is NULL then the result is false.
1822 ** If neither operand is NULL the result is the same as it would be if
1823 ** the SQLITE_NULLEQ flag were omitted from P5.
1825 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1826 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
1827 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
1829 /* Opcode: Ne P1 P2 P3 P4 P5
1830 ** Synopsis: IF r[P3]!=r[P1]
1832 ** This works just like the Eq opcode except that the jump is taken if
1833 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
1834 ** additional information.
1836 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1837 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
1838 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
1840 /* Opcode: Lt P1 P2 P3 P4 P5
1841 ** Synopsis: IF r[P3]<r[P1]
1843 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1844 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
1845 ** the result of comparison (0 or 1 or NULL) into register P2.
1847 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1848 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
1849 ** bit is clear then fall through if either operand is NULL.
1851 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1852 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1853 ** to coerce both inputs according to this affinity before the
1854 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1855 ** affinity is used. Note that the affinity conversions are stored
1856 ** back into the input registers P1 and P3. So this opcode can cause
1857 ** persistent changes to registers P1 and P3.
1859 ** Once any conversions have taken place, and neither value is NULL,
1860 ** the values are compared. If both values are blobs then memcmp() is
1861 ** used to determine the results of the comparison. If both values
1862 ** are text, then the appropriate collating function specified in
1863 ** P4 is used to do the comparison. If P4 is not specified then
1864 ** memcmp() is used to compare text string. If both values are
1865 ** numeric, then a numeric comparison is used. If the two values
1866 ** are of different types, then numbers are considered less than
1867 ** strings and strings are considered less than blobs.
1869 /* Opcode: Le P1 P2 P3 P4 P5
1870 ** Synopsis: IF r[P3]<=r[P1]
1872 ** This works just like the Lt opcode except that the jump is taken if
1873 ** the content of register P3 is less than or equal to the content of
1874 ** register P1. See the Lt opcode for additional information.
1876 /* Opcode: Gt P1 P2 P3 P4 P5
1877 ** Synopsis: IF r[P3]>r[P1]
1879 ** This works just like the Lt opcode except that the jump is taken if
1880 ** the content of register P3 is greater than the content of
1881 ** register P1. See the Lt opcode for additional information.
1883 /* Opcode: Ge P1 P2 P3 P4 P5
1884 ** Synopsis: IF r[P3]>=r[P1]
1886 ** This works just like the Lt opcode except that the jump is taken if
1887 ** the content of register P3 is greater than or equal to the content of
1888 ** register P1. See the Lt opcode for additional information.
1890 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
1891 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
1892 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
1893 case OP_Le: /* same as TK_LE, jump, in1, in3 */
1894 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
1895 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
1896 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
1897 char affinity; /* Affinity to use for comparison */
1898 u16 flags1; /* Copy of initial value of pIn1->flags */
1899 u16 flags3; /* Copy of initial value of pIn3->flags */
1901 pIn1 = &aMem[pOp->p1];
1902 pIn3 = &aMem[pOp->p3];
1903 flags1 = pIn1->flags;
1904 flags3 = pIn3->flags;
1905 if( (flags1 | flags3)&MEM_Null ){
1906 /* One or both operands are NULL */
1907 if( pOp->p5 & SQLITE_NULLEQ ){
1908 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1909 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1910 ** or not both operands are null.
1912 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
1913 assert( (flags1 & MEM_Cleared)==0 );
1914 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
1915 if( (flags1&flags3&MEM_Null)!=0
1916 && (flags3&MEM_Cleared)==0
1918 res = 0; /* Operands are equal */
1919 }else{
1920 res = 1; /* Operands are not equal */
1922 }else{
1923 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1924 ** then the result is always NULL.
1925 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1927 if( pOp->p5 & SQLITE_STOREP2 ){
1928 pOut = &aMem[pOp->p2];
1929 iCompare = 1; /* Operands are not equal */
1930 memAboutToChange(p, pOut);
1931 MemSetTypeFlag(pOut, MEM_Null);
1932 REGISTER_TRACE(pOp->p2, pOut);
1933 }else{
1934 VdbeBranchTaken(2,3);
1935 if( pOp->p5 & SQLITE_JUMPIFNULL ){
1936 goto jump_to_p2;
1939 break;
1941 }else{
1942 /* Neither operand is NULL. Do a comparison. */
1943 affinity = pOp->p5 & SQLITE_AFF_MASK;
1944 if( affinity>=SQLITE_AFF_NUMERIC ){
1945 if( (flags1 | flags3)&MEM_Str ){
1946 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1947 applyNumericAffinity(pIn1,0);
1948 testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
1949 flags3 = pIn3->flags;
1951 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1952 applyNumericAffinity(pIn3,0);
1955 /* Handle the common case of integer comparison here, as an
1956 ** optimization, to avoid a call to sqlite3MemCompare() */
1957 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
1958 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
1959 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
1960 res = 0;
1961 goto compare_op;
1963 }else if( affinity==SQLITE_AFF_TEXT ){
1964 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
1965 testcase( pIn1->flags & MEM_Int );
1966 testcase( pIn1->flags & MEM_Real );
1967 sqlite3VdbeMemStringify(pIn1, encoding, 1);
1968 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
1969 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
1970 assert( pIn1!=pIn3 );
1972 if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
1973 testcase( pIn3->flags & MEM_Int );
1974 testcase( pIn3->flags & MEM_Real );
1975 sqlite3VdbeMemStringify(pIn3, encoding, 1);
1976 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
1977 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
1980 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1981 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1983 compare_op:
1984 /* At this point, res is negative, zero, or positive if reg[P1] is
1985 ** less than, equal to, or greater than reg[P3], respectively. Compute
1986 ** the answer to this operator in res2, depending on what the comparison
1987 ** operator actually is. The next block of code depends on the fact
1988 ** that the 6 comparison operators are consecutive integers in this
1989 ** order: NE, EQ, GT, LE, LT, GE */
1990 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
1991 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
1992 if( res<0 ){ /* ne, eq, gt, le, lt, ge */
1993 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
1994 res2 = aLTb[pOp->opcode - OP_Ne];
1995 }else if( res==0 ){
1996 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
1997 res2 = aEQb[pOp->opcode - OP_Ne];
1998 }else{
1999 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
2000 res2 = aGTb[pOp->opcode - OP_Ne];
2003 /* Undo any changes made by applyAffinity() to the input registers. */
2004 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
2005 pIn1->flags = flags1;
2006 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
2007 pIn3->flags = flags3;
2009 if( pOp->p5 & SQLITE_STOREP2 ){
2010 pOut = &aMem[pOp->p2];
2011 iCompare = res;
2012 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
2013 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
2014 ** and prevents OP_Ne from overwriting NULL with 0. This flag
2015 ** is only used in contexts where either:
2016 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
2017 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
2018 ** Therefore it is not necessary to check the content of r[P2] for
2019 ** NULL. */
2020 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
2021 assert( res2==0 || res2==1 );
2022 testcase( res2==0 && pOp->opcode==OP_Eq );
2023 testcase( res2==1 && pOp->opcode==OP_Eq );
2024 testcase( res2==0 && pOp->opcode==OP_Ne );
2025 testcase( res2==1 && pOp->opcode==OP_Ne );
2026 if( (pOp->opcode==OP_Eq)==res2 ) break;
2028 memAboutToChange(p, pOut);
2029 MemSetTypeFlag(pOut, MEM_Int);
2030 pOut->u.i = res2;
2031 REGISTER_TRACE(pOp->p2, pOut);
2032 }else{
2033 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2034 if( res2 ){
2035 goto jump_to_p2;
2038 break;
2041 /* Opcode: ElseNotEq * P2 * * *
2043 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
2044 ** If result of an OP_Eq comparison on the same two operands
2045 ** would have be NULL or false (0), then then jump to P2.
2046 ** If the result of an OP_Eq comparison on the two previous operands
2047 ** would have been true (1), then fall through.
2049 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
2050 assert( pOp>aOp );
2051 assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
2052 assert( pOp[-1].p5 & SQLITE_STOREP2 );
2053 VdbeBranchTaken(iCompare!=0, 2);
2054 if( iCompare!=0 ) goto jump_to_p2;
2055 break;
2059 /* Opcode: Permutation * * * P4 *
2061 ** Set the permutation used by the OP_Compare operator in the next
2062 ** instruction. The permutation is stored in the P4 operand.
2064 ** The permutation is only valid until the next OP_Compare that has
2065 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2066 ** occur immediately prior to the OP_Compare.
2068 ** The first integer in the P4 integer array is the length of the array
2069 ** and does not become part of the permutation.
2071 case OP_Permutation: {
2072 assert( pOp->p4type==P4_INTARRAY );
2073 assert( pOp->p4.ai );
2074 assert( pOp[1].opcode==OP_Compare );
2075 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2076 break;
2079 /* Opcode: Compare P1 P2 P3 P4 P5
2080 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2082 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2083 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2084 ** the comparison for use by the next OP_Jump instruct.
2086 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2087 ** determined by the most recent OP_Permutation operator. If the
2088 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2089 ** order.
2091 ** P4 is a KeyInfo structure that defines collating sequences and sort
2092 ** orders for the comparison. The permutation applies to registers
2093 ** only. The KeyInfo elements are used sequentially.
2095 ** The comparison is a sort comparison, so NULLs compare equal,
2096 ** NULLs are less than numbers, numbers are less than strings,
2097 ** and strings are less than blobs.
2099 case OP_Compare: {
2100 int n;
2101 int i;
2102 int p1;
2103 int p2;
2104 const KeyInfo *pKeyInfo;
2105 int idx;
2106 CollSeq *pColl; /* Collating sequence to use on this term */
2107 int bRev; /* True for DESCENDING sort order */
2108 int *aPermute; /* The permutation */
2110 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2111 aPermute = 0;
2112 }else{
2113 assert( pOp>aOp );
2114 assert( pOp[-1].opcode==OP_Permutation );
2115 assert( pOp[-1].p4type==P4_INTARRAY );
2116 aPermute = pOp[-1].p4.ai + 1;
2117 assert( aPermute!=0 );
2119 n = pOp->p3;
2120 pKeyInfo = pOp->p4.pKeyInfo;
2121 assert( n>0 );
2122 assert( pKeyInfo!=0 );
2123 p1 = pOp->p1;
2124 p2 = pOp->p2;
2125 #ifdef SQLITE_DEBUG
2126 if( aPermute ){
2127 int k, mx = 0;
2128 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
2129 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2130 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2131 }else{
2132 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2133 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2135 #endif /* SQLITE_DEBUG */
2136 for(i=0; i<n; i++){
2137 idx = aPermute ? aPermute[i] : i;
2138 assert( memIsValid(&aMem[p1+idx]) );
2139 assert( memIsValid(&aMem[p2+idx]) );
2140 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2141 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2142 assert( i<pKeyInfo->nKeyField );
2143 pColl = pKeyInfo->aColl[i];
2144 bRev = pKeyInfo->aSortOrder[i];
2145 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2146 if( iCompare ){
2147 if( bRev ) iCompare = -iCompare;
2148 break;
2151 break;
2154 /* Opcode: Jump P1 P2 P3 * *
2156 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2157 ** in the most recent OP_Compare instruction the P1 vector was less than
2158 ** equal to, or greater than the P2 vector, respectively.
2160 case OP_Jump: { /* jump */
2161 if( iCompare<0 ){
2162 VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
2163 }else if( iCompare==0 ){
2164 VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
2165 }else{
2166 VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
2168 break;
2171 /* Opcode: And P1 P2 P3 * *
2172 ** Synopsis: r[P3]=(r[P1] && r[P2])
2174 ** Take the logical AND of the values in registers P1 and P2 and
2175 ** write the result into register P3.
2177 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2178 ** the other input is NULL. A NULL and true or two NULLs give
2179 ** a NULL output.
2181 /* Opcode: Or P1 P2 P3 * *
2182 ** Synopsis: r[P3]=(r[P1] || r[P2])
2184 ** Take the logical OR of the values in register P1 and P2 and
2185 ** store the answer in register P3.
2187 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2188 ** even if the other input is NULL. A NULL and false or two NULLs
2189 ** give a NULL output.
2191 case OP_And: /* same as TK_AND, in1, in2, out3 */
2192 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2193 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2194 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2196 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2197 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2198 if( pOp->opcode==OP_And ){
2199 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2200 v1 = and_logic[v1*3+v2];
2201 }else{
2202 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2203 v1 = or_logic[v1*3+v2];
2205 pOut = &aMem[pOp->p3];
2206 if( v1==2 ){
2207 MemSetTypeFlag(pOut, MEM_Null);
2208 }else{
2209 pOut->u.i = v1;
2210 MemSetTypeFlag(pOut, MEM_Int);
2212 break;
2215 /* Opcode: IsTrue P1 P2 P3 P4 *
2216 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2218 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2219 ** IS NOT FALSE operators.
2221 ** Interpret the value in register P1 as a boolean value. Store that
2222 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2223 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2224 ** is 1.
2226 ** The logic is summarized like this:
2228 ** <ul>
2229 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2230 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2231 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2232 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2233 ** </ul>
2235 case OP_IsTrue: { /* in1, out2 */
2236 assert( pOp->p4type==P4_INT32 );
2237 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2238 assert( pOp->p3==0 || pOp->p3==1 );
2239 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2240 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2241 break;
2244 /* Opcode: Not P1 P2 * * *
2245 ** Synopsis: r[P2]= !r[P1]
2247 ** Interpret the value in register P1 as a boolean value. Store the
2248 ** boolean complement in register P2. If the value in register P1 is
2249 ** NULL, then a NULL is stored in P2.
2251 case OP_Not: { /* same as TK_NOT, in1, out2 */
2252 pIn1 = &aMem[pOp->p1];
2253 pOut = &aMem[pOp->p2];
2254 if( (pIn1->flags & MEM_Null)==0 ){
2255 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2256 }else{
2257 sqlite3VdbeMemSetNull(pOut);
2259 break;
2262 /* Opcode: BitNot P1 P2 * * *
2263 ** Synopsis: r[P2]= ~r[P1]
2265 ** Interpret the content of register P1 as an integer. Store the
2266 ** ones-complement of the P1 value into register P2. If P1 holds
2267 ** a NULL then store a NULL in P2.
2269 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2270 pIn1 = &aMem[pOp->p1];
2271 pOut = &aMem[pOp->p2];
2272 sqlite3VdbeMemSetNull(pOut);
2273 if( (pIn1->flags & MEM_Null)==0 ){
2274 pOut->flags = MEM_Int;
2275 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2277 break;
2280 /* Opcode: Once P1 P2 * * *
2282 ** Fall through to the next instruction the first time this opcode is
2283 ** encountered on each invocation of the byte-code program. Jump to P2
2284 ** on the second and all subsequent encounters during the same invocation.
2286 ** Top-level programs determine first invocation by comparing the P1
2287 ** operand against the P1 operand on the OP_Init opcode at the beginning
2288 ** of the program. If the P1 values differ, then fall through and make
2289 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2290 ** the same then take the jump.
2292 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2293 ** whether or not the jump should be taken. The bitmask is necessary
2294 ** because the self-altering code trick does not work for recursive
2295 ** triggers.
2297 case OP_Once: { /* jump */
2298 u32 iAddr; /* Address of this instruction */
2299 assert( p->aOp[0].opcode==OP_Init );
2300 if( p->pFrame ){
2301 iAddr = (int)(pOp - p->aOp);
2302 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2303 VdbeBranchTaken(1, 2);
2304 goto jump_to_p2;
2306 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2307 }else{
2308 if( p->aOp[0].p1==pOp->p1 ){
2309 VdbeBranchTaken(1, 2);
2310 goto jump_to_p2;
2313 VdbeBranchTaken(0, 2);
2314 pOp->p1 = p->aOp[0].p1;
2315 break;
2318 /* Opcode: If P1 P2 P3 * *
2320 ** Jump to P2 if the value in register P1 is true. The value
2321 ** is considered true if it is numeric and non-zero. If the value
2322 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2324 case OP_If: { /* jump, in1 */
2325 int c;
2326 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2327 VdbeBranchTaken(c!=0, 2);
2328 if( c ) goto jump_to_p2;
2329 break;
2332 /* Opcode: IfNot P1 P2 P3 * *
2334 ** Jump to P2 if the value in register P1 is False. The value
2335 ** is considered false if it has a numeric value of zero. If the value
2336 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2338 case OP_IfNot: { /* jump, in1 */
2339 int c;
2340 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2341 VdbeBranchTaken(c!=0, 2);
2342 if( c ) goto jump_to_p2;
2343 break;
2346 /* Opcode: IsNull P1 P2 * * *
2347 ** Synopsis: if r[P1]==NULL goto P2
2349 ** Jump to P2 if the value in register P1 is NULL.
2351 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2352 pIn1 = &aMem[pOp->p1];
2353 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2354 if( (pIn1->flags & MEM_Null)!=0 ){
2355 goto jump_to_p2;
2357 break;
2360 /* Opcode: NotNull P1 P2 * * *
2361 ** Synopsis: if r[P1]!=NULL goto P2
2363 ** Jump to P2 if the value in register P1 is not NULL.
2365 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2366 pIn1 = &aMem[pOp->p1];
2367 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2368 if( (pIn1->flags & MEM_Null)==0 ){
2369 goto jump_to_p2;
2371 break;
2374 /* Opcode: IfNullRow P1 P2 P3 * *
2375 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2377 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2378 ** If it is, then set register P3 to NULL and jump immediately to P2.
2379 ** If P1 is not on a NULL row, then fall through without making any
2380 ** changes.
2382 case OP_IfNullRow: { /* jump */
2383 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2384 assert( p->apCsr[pOp->p1]!=0 );
2385 if( p->apCsr[pOp->p1]->nullRow ){
2386 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2387 goto jump_to_p2;
2389 break;
2392 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2393 /* Opcode: Offset P1 P2 P3 * *
2394 ** Synopsis: r[P3] = sqlite_offset(P1)
2396 ** Store in register r[P3] the byte offset into the database file that is the
2397 ** start of the payload for the record at which that cursor P1 is currently
2398 ** pointing.
2400 ** P2 is the column number for the argument to the sqlite_offset() function.
2401 ** This opcode does not use P2 itself, but the P2 value is used by the
2402 ** code generator. The P1, P2, and P3 operands to this opcode are the
2403 ** same as for OP_Column.
2405 ** This opcode is only available if SQLite is compiled with the
2406 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2408 case OP_Offset: { /* out3 */
2409 VdbeCursor *pC; /* The VDBE cursor */
2410 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2411 pC = p->apCsr[pOp->p1];
2412 pOut = &p->aMem[pOp->p3];
2413 if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
2414 sqlite3VdbeMemSetNull(pOut);
2415 }else{
2416 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2418 break;
2420 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2422 /* Opcode: Column P1 P2 P3 P4 P5
2423 ** Synopsis: r[P3]=PX
2425 ** Interpret the data that cursor P1 points to as a structure built using
2426 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2427 ** information about the format of the data.) Extract the P2-th column
2428 ** from this record. If there are less that (P2+1)
2429 ** values in the record, extract a NULL.
2431 ** The value extracted is stored in register P3.
2433 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2434 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2435 ** the result.
2437 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2438 ** then the cache of the cursor is reset prior to extracting the column.
2439 ** The first OP_Column against a pseudo-table after the value of the content
2440 ** register has changed should have this bit set.
2442 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2443 ** the result is guaranteed to only be used as the argument of a length()
2444 ** or typeof() function, respectively. The loading of large blobs can be
2445 ** skipped for length() and all content loading can be skipped for typeof().
2447 case OP_Column: {
2448 int p2; /* column number to retrieve */
2449 VdbeCursor *pC; /* The VDBE cursor */
2450 BtCursor *pCrsr; /* The BTree cursor */
2451 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2452 int len; /* The length of the serialized data for the column */
2453 int i; /* Loop counter */
2454 Mem *pDest; /* Where to write the extracted value */
2455 Mem sMem; /* For storing the record being decoded */
2456 const u8 *zData; /* Part of the record being decoded */
2457 const u8 *zHdr; /* Next unparsed byte of the header */
2458 const u8 *zEndHdr; /* Pointer to first byte after the header */
2459 u64 offset64; /* 64-bit offset */
2460 u32 t; /* A type code from the record header */
2461 Mem *pReg; /* PseudoTable input register */
2463 pC = p->apCsr[pOp->p1];
2464 p2 = pOp->p2;
2466 /* If the cursor cache is stale (meaning it is not currently point at
2467 ** the correct row) then bring it up-to-date by doing the necessary
2468 ** B-Tree seek. */
2469 rc = sqlite3VdbeCursorMoveto(&pC, &p2);
2470 if( rc ) goto abort_due_to_error;
2472 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2473 pDest = &aMem[pOp->p3];
2474 memAboutToChange(p, pDest);
2475 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2476 assert( pC!=0 );
2477 assert( p2<pC->nField );
2478 aOffset = pC->aOffset;
2479 assert( pC->eCurType!=CURTYPE_VTAB );
2480 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2481 assert( pC->eCurType!=CURTYPE_SORTER );
2483 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2484 if( pC->nullRow ){
2485 if( pC->eCurType==CURTYPE_PSEUDO ){
2486 /* For the special case of as pseudo-cursor, the seekResult field
2487 ** identifies the register that holds the record */
2488 assert( pC->seekResult>0 );
2489 pReg = &aMem[pC->seekResult];
2490 assert( pReg->flags & MEM_Blob );
2491 assert( memIsValid(pReg) );
2492 pC->payloadSize = pC->szRow = pReg->n;
2493 pC->aRow = (u8*)pReg->z;
2494 }else{
2495 sqlite3VdbeMemSetNull(pDest);
2496 goto op_column_out;
2498 }else{
2499 pCrsr = pC->uc.pCursor;
2500 assert( pC->eCurType==CURTYPE_BTREE );
2501 assert( pCrsr );
2502 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2503 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2504 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2505 assert( pC->szRow<=pC->payloadSize );
2506 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2507 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2508 goto too_big;
2511 pC->cacheStatus = p->cacheCtr;
2512 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
2513 pC->nHdrParsed = 0;
2516 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2517 /* pC->aRow does not have to hold the entire row, but it does at least
2518 ** need to cover the header of the record. If pC->aRow does not contain
2519 ** the complete header, then set it to zero, forcing the header to be
2520 ** dynamically allocated. */
2521 pC->aRow = 0;
2522 pC->szRow = 0;
2524 /* Make sure a corrupt database has not given us an oversize header.
2525 ** Do this now to avoid an oversize memory allocation.
2527 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2528 ** types use so much data space that there can only be 4096 and 32 of
2529 ** them, respectively. So the maximum header length results from a
2530 ** 3-byte type for each of the maximum of 32768 columns plus three
2531 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2533 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2534 goto op_column_corrupt;
2536 }else{
2537 /* This is an optimization. By skipping over the first few tests
2538 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2539 ** measurable performance gain.
2541 ** This branch is taken even if aOffset[0]==0. Such a record is never
2542 ** generated by SQLite, and could be considered corruption, but we
2543 ** accept it for historical reasons. When aOffset[0]==0, the code this
2544 ** branch jumps to reads past the end of the record, but never more
2545 ** than a few bytes. Even if the record occurs at the end of the page
2546 ** content area, the "page header" comes after the page content and so
2547 ** this overread is harmless. Similar overreads can occur for a corrupt
2548 ** database file.
2550 zData = pC->aRow;
2551 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2552 testcase( aOffset[0]==0 );
2553 goto op_column_read_header;
2557 /* Make sure at least the first p2+1 entries of the header have been
2558 ** parsed and valid information is in aOffset[] and pC->aType[].
2560 if( pC->nHdrParsed<=p2 ){
2561 /* If there is more header available for parsing in the record, try
2562 ** to extract additional fields up through the p2+1-th field
2564 if( pC->iHdrOffset<aOffset[0] ){
2565 /* Make sure zData points to enough of the record to cover the header. */
2566 if( pC->aRow==0 ){
2567 memset(&sMem, 0, sizeof(sMem));
2568 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
2569 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2570 zData = (u8*)sMem.z;
2571 }else{
2572 zData = pC->aRow;
2575 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2576 op_column_read_header:
2577 i = pC->nHdrParsed;
2578 offset64 = aOffset[i];
2579 zHdr = zData + pC->iHdrOffset;
2580 zEndHdr = zData + aOffset[0];
2581 testcase( zHdr>=zEndHdr );
2583 if( (t = zHdr[0])<0x80 ){
2584 zHdr++;
2585 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2586 }else{
2587 zHdr += sqlite3GetVarint32(zHdr, &t);
2588 offset64 += sqlite3VdbeSerialTypeLen(t);
2590 pC->aType[i++] = t;
2591 aOffset[i] = (u32)(offset64 & 0xffffffff);
2592 }while( i<=p2 && zHdr<zEndHdr );
2594 /* The record is corrupt if any of the following are true:
2595 ** (1) the bytes of the header extend past the declared header size
2596 ** (2) the entire header was used but not all data was used
2597 ** (3) the end of the data extends beyond the end of the record.
2599 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2600 || (offset64 > pC->payloadSize)
2602 if( aOffset[0]==0 ){
2603 i = 0;
2604 zHdr = zEndHdr;
2605 }else{
2606 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2607 goto op_column_corrupt;
2611 pC->nHdrParsed = i;
2612 pC->iHdrOffset = (u32)(zHdr - zData);
2613 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2614 }else{
2615 t = 0;
2618 /* If after trying to extract new entries from the header, nHdrParsed is
2619 ** still not up to p2, that means that the record has fewer than p2
2620 ** columns. So the result will be either the default value or a NULL.
2622 if( pC->nHdrParsed<=p2 ){
2623 if( pOp->p4type==P4_MEM ){
2624 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2625 }else{
2626 sqlite3VdbeMemSetNull(pDest);
2628 goto op_column_out;
2630 }else{
2631 t = pC->aType[p2];
2634 /* Extract the content for the p2+1-th column. Control can only
2635 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2636 ** all valid.
2638 assert( p2<pC->nHdrParsed );
2639 assert( rc==SQLITE_OK );
2640 assert( sqlite3VdbeCheckMemInvariants(pDest) );
2641 if( VdbeMemDynamic(pDest) ){
2642 sqlite3VdbeMemSetNull(pDest);
2644 assert( t==pC->aType[p2] );
2645 if( pC->szRow>=aOffset[p2+1] ){
2646 /* This is the common case where the desired content fits on the original
2647 ** page - where the content is not on an overflow page */
2648 zData = pC->aRow + aOffset[p2];
2649 if( t<12 ){
2650 sqlite3VdbeSerialGet(zData, t, pDest);
2651 }else{
2652 /* If the column value is a string, we need a persistent value, not
2653 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2654 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2656 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
2657 pDest->n = len = (t-12)/2;
2658 pDest->enc = encoding;
2659 if( pDest->szMalloc < len+2 ){
2660 pDest->flags = MEM_Null;
2661 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
2662 }else{
2663 pDest->z = pDest->zMalloc;
2665 memcpy(pDest->z, zData, len);
2666 pDest->z[len] = 0;
2667 pDest->z[len+1] = 0;
2668 pDest->flags = aFlag[t&1];
2670 }else{
2671 pDest->enc = encoding;
2672 /* This branch happens only when content is on overflow pages */
2673 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2674 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2675 || (len = sqlite3VdbeSerialTypeLen(t))==0
2677 /* Content is irrelevant for
2678 ** 1. the typeof() function,
2679 ** 2. the length(X) function if X is a blob, and
2680 ** 3. if the content length is zero.
2681 ** So we might as well use bogus content rather than reading
2682 ** content from disk.
2684 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2685 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2686 ** read up to 16. So 16 bytes of bogus content is supplied.
2688 static u8 aZero[16]; /* This is the bogus content */
2689 sqlite3VdbeSerialGet(aZero, t, pDest);
2690 }else{
2691 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
2692 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2693 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2694 pDest->flags &= ~MEM_Ephem;
2698 op_column_out:
2699 UPDATE_MAX_BLOBSIZE(pDest);
2700 REGISTER_TRACE(pOp->p3, pDest);
2701 break;
2703 op_column_corrupt:
2704 if( aOp[0].p3>0 ){
2705 pOp = &aOp[aOp[0].p3-1];
2706 break;
2707 }else{
2708 rc = SQLITE_CORRUPT_BKPT;
2709 goto abort_due_to_error;
2713 /* Opcode: Affinity P1 P2 * P4 *
2714 ** Synopsis: affinity(r[P1@P2])
2716 ** Apply affinities to a range of P2 registers starting with P1.
2718 ** P4 is a string that is P2 characters long. The N-th character of the
2719 ** string indicates the column affinity that should be used for the N-th
2720 ** memory cell in the range.
2722 case OP_Affinity: {
2723 const char *zAffinity; /* The affinity to be applied */
2725 zAffinity = pOp->p4.z;
2726 assert( zAffinity!=0 );
2727 assert( pOp->p2>0 );
2728 assert( zAffinity[pOp->p2]==0 );
2729 pIn1 = &aMem[pOp->p1];
2731 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
2732 assert( memIsValid(pIn1) );
2733 applyAffinity(pIn1, *(zAffinity++), encoding);
2734 pIn1++;
2735 }while( zAffinity[0] );
2736 break;
2739 /* Opcode: MakeRecord P1 P2 P3 P4 *
2740 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2742 ** Convert P2 registers beginning with P1 into the [record format]
2743 ** use as a data record in a database table or as a key
2744 ** in an index. The OP_Column opcode can decode the record later.
2746 ** P4 may be a string that is P2 characters long. The N-th character of the
2747 ** string indicates the column affinity that should be used for the N-th
2748 ** field of the index key.
2750 ** The mapping from character to affinity is given by the SQLITE_AFF_
2751 ** macros defined in sqliteInt.h.
2753 ** If P4 is NULL then all index fields have the affinity BLOB.
2755 case OP_MakeRecord: {
2756 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2757 Mem *pRec; /* The new record */
2758 u64 nData; /* Number of bytes of data space */
2759 int nHdr; /* Number of bytes of header space */
2760 i64 nByte; /* Data space required for this record */
2761 i64 nZero; /* Number of zero bytes at the end of the record */
2762 int nVarint; /* Number of bytes in a varint */
2763 u32 serial_type; /* Type field */
2764 Mem *pData0; /* First field to be combined into the record */
2765 Mem *pLast; /* Last field of the record */
2766 int nField; /* Number of fields in the record */
2767 char *zAffinity; /* The affinity string for the record */
2768 int file_format; /* File format to use for encoding */
2769 int i; /* Space used in zNewRecord[] header */
2770 int j; /* Space used in zNewRecord[] content */
2771 u32 len; /* Length of a field */
2773 /* Assuming the record contains N fields, the record format looks
2774 ** like this:
2776 ** ------------------------------------------------------------------------
2777 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2778 ** ------------------------------------------------------------------------
2780 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2781 ** and so forth.
2783 ** Each type field is a varint representing the serial type of the
2784 ** corresponding data element (see sqlite3VdbeSerialType()). The
2785 ** hdr-size field is also a varint which is the offset from the beginning
2786 ** of the record to data0.
2788 nData = 0; /* Number of bytes of data space */
2789 nHdr = 0; /* Number of bytes of header space */
2790 nZero = 0; /* Number of zero bytes at the end of the record */
2791 nField = pOp->p1;
2792 zAffinity = pOp->p4.z;
2793 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
2794 pData0 = &aMem[nField];
2795 nField = pOp->p2;
2796 pLast = &pData0[nField-1];
2797 file_format = p->minWriteFileFormat;
2799 /* Identify the output register */
2800 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2801 pOut = &aMem[pOp->p3];
2802 memAboutToChange(p, pOut);
2804 /* Apply the requested affinity to all inputs
2806 assert( pData0<=pLast );
2807 if( zAffinity ){
2808 pRec = pData0;
2810 applyAffinity(pRec++, *(zAffinity++), encoding);
2811 assert( zAffinity[0]==0 || pRec<=pLast );
2812 }while( zAffinity[0] );
2815 #ifdef SQLITE_ENABLE_NULL_TRIM
2816 /* NULLs can be safely trimmed from the end of the record, as long as
2817 ** as the schema format is 2 or more and none of the omitted columns
2818 ** have a non-NULL default value. Also, the record must be left with
2819 ** at least one field. If P5>0 then it will be one more than the
2820 ** index of the right-most column with a non-NULL default value */
2821 if( pOp->p5 ){
2822 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
2823 pLast--;
2824 nField--;
2827 #endif
2829 /* Loop through the elements that will make up the record to figure
2830 ** out how much space is required for the new record.
2832 pRec = pLast;
2834 assert( memIsValid(pRec) );
2835 serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
2836 if( pRec->flags & MEM_Zero ){
2837 if( serial_type==0 ){
2838 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
2839 ** table methods that never invoke sqlite3_result_xxxxx() while
2840 ** computing an unchanging column value in an UPDATE statement.
2841 ** Give such values a special internal-use-only serial-type of 10
2842 ** so that they can be passed through to xUpdate and have
2843 ** a true sqlite3_value_nochange(). */
2844 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
2845 serial_type = 10;
2846 }else if( nData ){
2847 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
2848 }else{
2849 nZero += pRec->u.nZero;
2850 len -= pRec->u.nZero;
2853 nData += len;
2854 testcase( serial_type==127 );
2855 testcase( serial_type==128 );
2856 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
2857 pRec->uTemp = serial_type;
2858 if( pRec==pData0 ) break;
2859 pRec--;
2860 }while(1);
2862 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
2863 ** which determines the total number of bytes in the header. The varint
2864 ** value is the size of the header in bytes including the size varint
2865 ** itself. */
2866 testcase( nHdr==126 );
2867 testcase( nHdr==127 );
2868 if( nHdr<=126 ){
2869 /* The common case */
2870 nHdr += 1;
2871 }else{
2872 /* Rare case of a really large header */
2873 nVarint = sqlite3VarintLen(nHdr);
2874 nHdr += nVarint;
2875 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
2877 nByte = nHdr+nData;
2878 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2879 goto too_big;
2882 /* Make sure the output register has a buffer large enough to store
2883 ** the new record. The output register (pOp->p3) is not allowed to
2884 ** be one of the input registers (because the following call to
2885 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2887 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
2888 goto no_mem;
2890 zNewRecord = (u8 *)pOut->z;
2892 /* Write the record */
2893 i = putVarint32(zNewRecord, nHdr);
2894 j = nHdr;
2895 assert( pData0<=pLast );
2896 pRec = pData0;
2898 serial_type = pRec->uTemp;
2899 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
2900 ** additional varints, one per column. */
2901 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
2902 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
2903 ** immediately follow the header. */
2904 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
2905 }while( (++pRec)<=pLast );
2906 assert( i==nHdr );
2907 assert( j==nByte );
2909 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2910 pOut->n = (int)nByte;
2911 pOut->flags = MEM_Blob;
2912 if( nZero ){
2913 pOut->u.nZero = nZero;
2914 pOut->flags |= MEM_Zero;
2916 REGISTER_TRACE(pOp->p3, pOut);
2917 UPDATE_MAX_BLOBSIZE(pOut);
2918 break;
2921 /* Opcode: Count P1 P2 * * *
2922 ** Synopsis: r[P2]=count()
2924 ** Store the number of entries (an integer value) in the table or index
2925 ** opened by cursor P1 in register P2
2927 #ifndef SQLITE_OMIT_BTREECOUNT
2928 case OP_Count: { /* out2 */
2929 i64 nEntry;
2930 BtCursor *pCrsr;
2932 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
2933 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
2934 assert( pCrsr );
2935 nEntry = 0; /* Not needed. Only used to silence a warning. */
2936 rc = sqlite3BtreeCount(pCrsr, &nEntry);
2937 if( rc ) goto abort_due_to_error;
2938 pOut = out2Prerelease(p, pOp);
2939 pOut->u.i = nEntry;
2940 break;
2942 #endif
2944 /* Opcode: Savepoint P1 * * P4 *
2946 ** Open, release or rollback the savepoint named by parameter P4, depending
2947 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2948 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2950 case OP_Savepoint: {
2951 int p1; /* Value of P1 operand */
2952 char *zName; /* Name of savepoint */
2953 int nName;
2954 Savepoint *pNew;
2955 Savepoint *pSavepoint;
2956 Savepoint *pTmp;
2957 int iSavepoint;
2958 int ii;
2960 p1 = pOp->p1;
2961 zName = pOp->p4.z;
2963 /* Assert that the p1 parameter is valid. Also that if there is no open
2964 ** transaction, then there cannot be any savepoints.
2966 assert( db->pSavepoint==0 || db->autoCommit==0 );
2967 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
2968 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
2969 assert( checkSavepointCount(db) );
2970 assert( p->bIsReader );
2972 if( p1==SAVEPOINT_BEGIN ){
2973 if( db->nVdbeWrite>0 ){
2974 /* A new savepoint cannot be created if there are active write
2975 ** statements (i.e. open read/write incremental blob handles).
2977 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
2978 rc = SQLITE_BUSY;
2979 }else{
2980 nName = sqlite3Strlen30(zName);
2982 #ifndef SQLITE_OMIT_VIRTUALTABLE
2983 /* This call is Ok even if this savepoint is actually a transaction
2984 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2985 ** If this is a transaction savepoint being opened, it is guaranteed
2986 ** that the db->aVTrans[] array is empty. */
2987 assert( db->autoCommit==0 || db->nVTrans==0 );
2988 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
2989 db->nStatement+db->nSavepoint);
2990 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2991 #endif
2993 /* Create a new savepoint structure. */
2994 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
2995 if( pNew ){
2996 pNew->zName = (char *)&pNew[1];
2997 memcpy(pNew->zName, zName, nName+1);
2999 /* If there is no open transaction, then mark this as a special
3000 ** "transaction savepoint". */
3001 if( db->autoCommit ){
3002 db->autoCommit = 0;
3003 db->isTransactionSavepoint = 1;
3004 }else{
3005 db->nSavepoint++;
3008 /* Link the new savepoint into the database handle's list. */
3009 pNew->pNext = db->pSavepoint;
3010 db->pSavepoint = pNew;
3011 pNew->nDeferredCons = db->nDeferredCons;
3012 pNew->nDeferredImmCons = db->nDeferredImmCons;
3015 }else{
3016 iSavepoint = 0;
3018 /* Find the named savepoint. If there is no such savepoint, then an
3019 ** an error is returned to the user. */
3020 for(
3021 pSavepoint = db->pSavepoint;
3022 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3023 pSavepoint = pSavepoint->pNext
3025 iSavepoint++;
3027 if( !pSavepoint ){
3028 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3029 rc = SQLITE_ERROR;
3030 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3031 /* It is not possible to release (commit) a savepoint if there are
3032 ** active write statements.
3034 sqlite3VdbeError(p, "cannot release savepoint - "
3035 "SQL statements in progress");
3036 rc = SQLITE_BUSY;
3037 }else{
3039 /* Determine whether or not this is a transaction savepoint. If so,
3040 ** and this is a RELEASE command, then the current transaction
3041 ** is committed.
3043 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3044 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3045 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3046 goto vdbe_return;
3048 db->autoCommit = 1;
3049 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3050 p->pc = (int)(pOp - aOp);
3051 db->autoCommit = 0;
3052 p->rc = rc = SQLITE_BUSY;
3053 goto vdbe_return;
3055 db->isTransactionSavepoint = 0;
3056 rc = p->rc;
3057 }else{
3058 int isSchemaChange;
3059 iSavepoint = db->nSavepoint - iSavepoint - 1;
3060 if( p1==SAVEPOINT_ROLLBACK ){
3061 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3062 for(ii=0; ii<db->nDb; ii++){
3063 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3064 SQLITE_ABORT_ROLLBACK,
3065 isSchemaChange==0);
3066 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3068 }else{
3069 isSchemaChange = 0;
3071 for(ii=0; ii<db->nDb; ii++){
3072 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3073 if( rc!=SQLITE_OK ){
3074 goto abort_due_to_error;
3077 if( isSchemaChange ){
3078 sqlite3ExpirePreparedStatements(db);
3079 sqlite3ResetAllSchemasOfConnection(db);
3080 db->mDbFlags |= DBFLAG_SchemaChange;
3084 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3085 ** savepoints nested inside of the savepoint being operated on. */
3086 while( db->pSavepoint!=pSavepoint ){
3087 pTmp = db->pSavepoint;
3088 db->pSavepoint = pTmp->pNext;
3089 sqlite3DbFree(db, pTmp);
3090 db->nSavepoint--;
3093 /* If it is a RELEASE, then destroy the savepoint being operated on
3094 ** too. If it is a ROLLBACK TO, then set the number of deferred
3095 ** constraint violations present in the database to the value stored
3096 ** when the savepoint was created. */
3097 if( p1==SAVEPOINT_RELEASE ){
3098 assert( pSavepoint==db->pSavepoint );
3099 db->pSavepoint = pSavepoint->pNext;
3100 sqlite3DbFree(db, pSavepoint);
3101 if( !isTransaction ){
3102 db->nSavepoint--;
3104 }else{
3105 db->nDeferredCons = pSavepoint->nDeferredCons;
3106 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3109 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3110 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3111 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3115 if( rc ) goto abort_due_to_error;
3117 break;
3120 /* Opcode: AutoCommit P1 P2 * * *
3122 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3123 ** back any currently active btree transactions. If there are any active
3124 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3125 ** there are active writing VMs or active VMs that use shared cache.
3127 ** This instruction causes the VM to halt.
3129 case OP_AutoCommit: {
3130 int desiredAutoCommit;
3131 int iRollback;
3133 desiredAutoCommit = pOp->p1;
3134 iRollback = pOp->p2;
3135 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3136 assert( desiredAutoCommit==1 || iRollback==0 );
3137 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3138 assert( p->bIsReader );
3140 if( desiredAutoCommit!=db->autoCommit ){
3141 if( iRollback ){
3142 assert( desiredAutoCommit==1 );
3143 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3144 db->autoCommit = 1;
3145 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3146 /* If this instruction implements a COMMIT and other VMs are writing
3147 ** return an error indicating that the other VMs must complete first.
3149 sqlite3VdbeError(p, "cannot commit transaction - "
3150 "SQL statements in progress");
3151 rc = SQLITE_BUSY;
3152 goto abort_due_to_error;
3153 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3154 goto vdbe_return;
3155 }else{
3156 db->autoCommit = (u8)desiredAutoCommit;
3158 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3159 p->pc = (int)(pOp - aOp);
3160 db->autoCommit = (u8)(1-desiredAutoCommit);
3161 p->rc = rc = SQLITE_BUSY;
3162 goto vdbe_return;
3164 assert( db->nStatement==0 );
3165 sqlite3CloseSavepoints(db);
3166 if( p->rc==SQLITE_OK ){
3167 rc = SQLITE_DONE;
3168 }else{
3169 rc = SQLITE_ERROR;
3171 goto vdbe_return;
3172 }else{
3173 sqlite3VdbeError(p,
3174 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3175 (iRollback)?"cannot rollback - no transaction is active":
3176 "cannot commit - no transaction is active"));
3178 rc = SQLITE_ERROR;
3179 goto abort_due_to_error;
3181 break;
3184 /* Opcode: Transaction P1 P2 P3 P4 P5
3186 ** Begin a transaction on database P1 if a transaction is not already
3187 ** active.
3188 ** If P2 is non-zero, then a write-transaction is started, or if a
3189 ** read-transaction is already active, it is upgraded to a write-transaction.
3190 ** If P2 is zero, then a read-transaction is started.
3192 ** P1 is the index of the database file on which the transaction is
3193 ** started. Index 0 is the main database file and index 1 is the
3194 ** file used for temporary tables. Indices of 2 or more are used for
3195 ** attached databases.
3197 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3198 ** true (this flag is set if the Vdbe may modify more than one row and may
3199 ** throw an ABORT exception), a statement transaction may also be opened.
3200 ** More specifically, a statement transaction is opened iff the database
3201 ** connection is currently not in autocommit mode, or if there are other
3202 ** active statements. A statement transaction allows the changes made by this
3203 ** VDBE to be rolled back after an error without having to roll back the
3204 ** entire transaction. If no error is encountered, the statement transaction
3205 ** will automatically commit when the VDBE halts.
3207 ** If P5!=0 then this opcode also checks the schema cookie against P3
3208 ** and the schema generation counter against P4.
3209 ** The cookie changes its value whenever the database schema changes.
3210 ** This operation is used to detect when that the cookie has changed
3211 ** and that the current process needs to reread the schema. If the schema
3212 ** cookie in P3 differs from the schema cookie in the database header or
3213 ** if the schema generation counter in P4 differs from the current
3214 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3215 ** halts. The sqlite3_step() wrapper function might then reprepare the
3216 ** statement and rerun it from the beginning.
3218 case OP_Transaction: {
3219 Btree *pBt;
3220 int iMeta = 0;
3222 assert( p->bIsReader );
3223 assert( p->readOnly==0 || pOp->p2==0 );
3224 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3225 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3226 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3227 rc = SQLITE_READONLY;
3228 goto abort_due_to_error;
3230 pBt = db->aDb[pOp->p1].pBt;
3232 if( pBt ){
3233 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
3234 testcase( rc==SQLITE_BUSY_SNAPSHOT );
3235 testcase( rc==SQLITE_BUSY_RECOVERY );
3236 if( rc!=SQLITE_OK ){
3237 if( (rc&0xff)==SQLITE_BUSY ){
3238 p->pc = (int)(pOp - aOp);
3239 p->rc = rc;
3240 goto vdbe_return;
3242 goto abort_due_to_error;
3245 if( pOp->p2 && p->usesStmtJournal
3246 && (db->autoCommit==0 || db->nVdbeRead>1)
3248 assert( sqlite3BtreeIsInTrans(pBt) );
3249 if( p->iStatement==0 ){
3250 assert( db->nStatement>=0 && db->nSavepoint>=0 );
3251 db->nStatement++;
3252 p->iStatement = db->nSavepoint + db->nStatement;
3255 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3256 if( rc==SQLITE_OK ){
3257 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3260 /* Store the current value of the database handles deferred constraint
3261 ** counter. If the statement transaction needs to be rolled back,
3262 ** the value of this counter needs to be restored too. */
3263 p->nStmtDefCons = db->nDeferredCons;
3264 p->nStmtDefImmCons = db->nDeferredImmCons;
3267 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3268 if( pOp->p5
3269 && (iMeta!=pOp->p3
3270 || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
3273 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3274 ** version is checked to ensure that the schema has not changed since the
3275 ** SQL statement was prepared.
3277 sqlite3DbFree(db, p->zErrMsg);
3278 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3279 /* If the schema-cookie from the database file matches the cookie
3280 ** stored with the in-memory representation of the schema, do
3281 ** not reload the schema from the database file.
3283 ** If virtual-tables are in use, this is not just an optimization.
3284 ** Often, v-tables store their data in other SQLite tables, which
3285 ** are queried from within xNext() and other v-table methods using
3286 ** prepared queries. If such a query is out-of-date, we do not want to
3287 ** discard the database schema, as the user code implementing the
3288 ** v-table would have to be ready for the sqlite3_vtab structure itself
3289 ** to be invalidated whenever sqlite3_step() is called from within
3290 ** a v-table method.
3292 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3293 sqlite3ResetOneSchema(db, pOp->p1);
3295 p->expired = 1;
3296 rc = SQLITE_SCHEMA;
3298 if( rc ) goto abort_due_to_error;
3299 break;
3302 /* Opcode: ReadCookie P1 P2 P3 * *
3304 ** Read cookie number P3 from database P1 and write it into register P2.
3305 ** P3==1 is the schema version. P3==2 is the database format.
3306 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3307 ** the main database file and P1==1 is the database file used to store
3308 ** temporary tables.
3310 ** There must be a read-lock on the database (either a transaction
3311 ** must be started or there must be an open cursor) before
3312 ** executing this instruction.
3314 case OP_ReadCookie: { /* out2 */
3315 int iMeta;
3316 int iDb;
3317 int iCookie;
3319 assert( p->bIsReader );
3320 iDb = pOp->p1;
3321 iCookie = pOp->p3;
3322 assert( pOp->p3<SQLITE_N_BTREE_META );
3323 assert( iDb>=0 && iDb<db->nDb );
3324 assert( db->aDb[iDb].pBt!=0 );
3325 assert( DbMaskTest(p->btreeMask, iDb) );
3327 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3328 pOut = out2Prerelease(p, pOp);
3329 pOut->u.i = iMeta;
3330 break;
3333 /* Opcode: SetCookie P1 P2 P3 * *
3335 ** Write the integer value P3 into cookie number P2 of database P1.
3336 ** P2==1 is the schema version. P2==2 is the database format.
3337 ** P2==3 is the recommended pager cache
3338 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3339 ** database file used to store temporary tables.
3341 ** A transaction must be started before executing this opcode.
3343 case OP_SetCookie: {
3344 Db *pDb;
3346 sqlite3VdbeIncrWriteCounter(p, 0);
3347 assert( pOp->p2<SQLITE_N_BTREE_META );
3348 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3349 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3350 assert( p->readOnly==0 );
3351 pDb = &db->aDb[pOp->p1];
3352 assert( pDb->pBt!=0 );
3353 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3354 /* See note about index shifting on OP_ReadCookie */
3355 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3356 if( pOp->p2==BTREE_SCHEMA_VERSION ){
3357 /* When the schema cookie changes, record the new cookie internally */
3358 pDb->pSchema->schema_cookie = pOp->p3;
3359 db->mDbFlags |= DBFLAG_SchemaChange;
3360 }else if( pOp->p2==BTREE_FILE_FORMAT ){
3361 /* Record changes in the file format */
3362 pDb->pSchema->file_format = pOp->p3;
3364 if( pOp->p1==1 ){
3365 /* Invalidate all prepared statements whenever the TEMP database
3366 ** schema is changed. Ticket #1644 */
3367 sqlite3ExpirePreparedStatements(db);
3368 p->expired = 0;
3370 if( rc ) goto abort_due_to_error;
3371 break;
3374 /* Opcode: OpenRead P1 P2 P3 P4 P5
3375 ** Synopsis: root=P2 iDb=P3
3377 ** Open a read-only cursor for the database table whose root page is
3378 ** P2 in a database file. The database file is determined by P3.
3379 ** P3==0 means the main database, P3==1 means the database used for
3380 ** temporary tables, and P3>1 means used the corresponding attached
3381 ** database. Give the new cursor an identifier of P1. The P1
3382 ** values need not be contiguous but all P1 values should be small integers.
3383 ** It is an error for P1 to be negative.
3385 ** Allowed P5 bits:
3386 ** <ul>
3387 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3388 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3389 ** of OP_SeekLE/OP_IdxGT)
3390 ** </ul>
3392 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3393 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3394 ** object, then table being opened must be an [index b-tree] where the
3395 ** KeyInfo object defines the content and collating
3396 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3397 ** value, then the table being opened must be a [table b-tree] with a
3398 ** number of columns no less than the value of P4.
3400 ** See also: OpenWrite, ReopenIdx
3402 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3403 ** Synopsis: root=P2 iDb=P3
3405 ** The ReopenIdx opcode works like OP_OpenRead except that it first
3406 ** checks to see if the cursor on P1 is already open on the same
3407 ** b-tree and if it is this opcode becomes a no-op. In other words,
3408 ** if the cursor is already open, do not reopen it.
3410 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
3411 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
3412 ** be the same as every other ReopenIdx or OpenRead for the same cursor
3413 ** number.
3415 ** Allowed P5 bits:
3416 ** <ul>
3417 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3418 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3419 ** of OP_SeekLE/OP_IdxGT)
3420 ** </ul>
3422 ** See also: OP_OpenRead, OP_OpenWrite
3424 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3425 ** Synopsis: root=P2 iDb=P3
3427 ** Open a read/write cursor named P1 on the table or index whose root
3428 ** page is P2 (or whose root page is held in register P2 if the
3429 ** OPFLAG_P2ISREG bit is set in P5 - see below).
3431 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3432 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3433 ** object, then table being opened must be an [index b-tree] where the
3434 ** KeyInfo object defines the content and collating
3435 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3436 ** value, then the table being opened must be a [table b-tree] with a
3437 ** number of columns no less than the value of P4.
3439 ** Allowed P5 bits:
3440 ** <ul>
3441 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3442 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3443 ** of OP_SeekLE/OP_IdxGT)
3444 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
3445 ** and subsequently delete entries in an index btree. This is a
3446 ** hint to the storage engine that the storage engine is allowed to
3447 ** ignore. The hint is not used by the official SQLite b*tree storage
3448 ** engine, but is used by COMDB2.
3449 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
3450 ** as the root page, not the value of P2 itself.
3451 ** </ul>
3453 ** This instruction works like OpenRead except that it opens the cursor
3454 ** in read/write mode.
3456 ** See also: OP_OpenRead, OP_ReopenIdx
3458 case OP_ReopenIdx: {
3459 int nField;
3460 KeyInfo *pKeyInfo;
3461 int p2;
3462 int iDb;
3463 int wrFlag;
3464 Btree *pX;
3465 VdbeCursor *pCur;
3466 Db *pDb;
3468 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3469 assert( pOp->p4type==P4_KEYINFO );
3470 pCur = p->apCsr[pOp->p1];
3471 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3472 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
3473 goto open_cursor_set_hints;
3475 /* If the cursor is not currently open or is open on a different
3476 ** index, then fall through into OP_OpenRead to force a reopen */
3477 case OP_OpenRead:
3478 case OP_OpenWrite:
3480 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3481 assert( p->bIsReader );
3482 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3483 || p->readOnly==0 );
3485 if( p->expired ){
3486 rc = SQLITE_ABORT_ROLLBACK;
3487 goto abort_due_to_error;
3490 nField = 0;
3491 pKeyInfo = 0;
3492 p2 = pOp->p2;
3493 iDb = pOp->p3;
3494 assert( iDb>=0 && iDb<db->nDb );
3495 assert( DbMaskTest(p->btreeMask, iDb) );
3496 pDb = &db->aDb[iDb];
3497 pX = pDb->pBt;
3498 assert( pX!=0 );
3499 if( pOp->opcode==OP_OpenWrite ){
3500 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
3501 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
3502 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3503 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3504 p->minWriteFileFormat = pDb->pSchema->file_format;
3506 }else{
3507 wrFlag = 0;
3509 if( pOp->p5 & OPFLAG_P2ISREG ){
3510 assert( p2>0 );
3511 assert( p2<=(p->nMem+1 - p->nCursor) );
3512 assert( pOp->opcode==OP_OpenWrite );
3513 pIn2 = &aMem[p2];
3514 assert( memIsValid(pIn2) );
3515 assert( (pIn2->flags & MEM_Int)!=0 );
3516 sqlite3VdbeMemIntegerify(pIn2);
3517 p2 = (int)pIn2->u.i;
3518 /* The p2 value always comes from a prior OP_CreateBtree opcode and
3519 ** that opcode will always set the p2 value to 2 or more or else fail.
3520 ** If there were a failure, the prepared statement would have halted
3521 ** before reaching this instruction. */
3522 assert( p2>=2 );
3524 if( pOp->p4type==P4_KEYINFO ){
3525 pKeyInfo = pOp->p4.pKeyInfo;
3526 assert( pKeyInfo->enc==ENC(db) );
3527 assert( pKeyInfo->db==db );
3528 nField = pKeyInfo->nAllField;
3529 }else if( pOp->p4type==P4_INT32 ){
3530 nField = pOp->p4.i;
3532 assert( pOp->p1>=0 );
3533 assert( nField>=0 );
3534 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3535 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
3536 if( pCur==0 ) goto no_mem;
3537 pCur->nullRow = 1;
3538 pCur->isOrdered = 1;
3539 pCur->pgnoRoot = p2;
3540 #ifdef SQLITE_DEBUG
3541 pCur->wrFlag = wrFlag;
3542 #endif
3543 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
3544 pCur->pKeyInfo = pKeyInfo;
3545 /* Set the VdbeCursor.isTable variable. Previous versions of
3546 ** SQLite used to check if the root-page flags were sane at this point
3547 ** and report database corruption if they were not, but this check has
3548 ** since moved into the btree layer. */
3549 pCur->isTable = pOp->p4type!=P4_KEYINFO;
3551 open_cursor_set_hints:
3552 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3553 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
3554 testcase( pOp->p5 & OPFLAG_BULKCSR );
3555 #ifdef SQLITE_ENABLE_CURSOR_HINTS
3556 testcase( pOp->p2 & OPFLAG_SEEKEQ );
3557 #endif
3558 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
3559 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
3560 if( rc ) goto abort_due_to_error;
3561 break;
3564 /* Opcode: OpenDup P1 P2 * * *
3566 ** Open a new cursor P1 that points to the same ephemeral table as
3567 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
3568 ** opcode. Only ephemeral cursors may be duplicated.
3570 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
3572 case OP_OpenDup: {
3573 VdbeCursor *pOrig; /* The original cursor to be duplicated */
3574 VdbeCursor *pCx; /* The new cursor */
3576 pOrig = p->apCsr[pOp->p2];
3577 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
3579 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
3580 if( pCx==0 ) goto no_mem;
3581 pCx->nullRow = 1;
3582 pCx->isEphemeral = 1;
3583 pCx->pKeyInfo = pOrig->pKeyInfo;
3584 pCx->isTable = pOrig->isTable;
3585 rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
3586 pCx->pKeyInfo, pCx->uc.pCursor);
3587 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
3588 ** opened for a database. Since there is already an open cursor when this
3589 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
3590 assert( rc==SQLITE_OK );
3591 break;
3595 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3596 ** Synopsis: nColumn=P2
3598 ** Open a new cursor P1 to a transient table.
3599 ** The cursor is always opened read/write even if
3600 ** the main database is read-only. The ephemeral
3601 ** table is deleted automatically when the cursor is closed.
3603 ** P2 is the number of columns in the ephemeral table.
3604 ** The cursor points to a BTree table if P4==0 and to a BTree index
3605 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3606 ** that defines the format of keys in the index.
3608 ** The P5 parameter can be a mask of the BTREE_* flags defined
3609 ** in btree.h. These flags control aspects of the operation of
3610 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3611 ** added automatically.
3613 /* Opcode: OpenAutoindex P1 P2 * P4 *
3614 ** Synopsis: nColumn=P2
3616 ** This opcode works the same as OP_OpenEphemeral. It has a
3617 ** different name to distinguish its use. Tables created using
3618 ** by this opcode will be used for automatically created transient
3619 ** indices in joins.
3621 case OP_OpenAutoindex:
3622 case OP_OpenEphemeral: {
3623 VdbeCursor *pCx;
3624 KeyInfo *pKeyInfo;
3626 static const int vfsFlags =
3627 SQLITE_OPEN_READWRITE |
3628 SQLITE_OPEN_CREATE |
3629 SQLITE_OPEN_EXCLUSIVE |
3630 SQLITE_OPEN_DELETEONCLOSE |
3631 SQLITE_OPEN_TRANSIENT_DB;
3632 assert( pOp->p1>=0 );
3633 assert( pOp->p2>=0 );
3634 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
3635 if( pCx==0 ) goto no_mem;
3636 pCx->nullRow = 1;
3637 pCx->isEphemeral = 1;
3638 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
3639 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
3640 if( rc==SQLITE_OK ){
3641 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
3643 if( rc==SQLITE_OK ){
3644 /* If a transient index is required, create it by calling
3645 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3646 ** opening it. If a transient table is required, just use the
3647 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3649 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3650 int pgno;
3651 assert( pOp->p4type==P4_KEYINFO );
3652 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
3653 if( rc==SQLITE_OK ){
3654 assert( pgno==MASTER_ROOT+1 );
3655 assert( pKeyInfo->db==db );
3656 assert( pKeyInfo->enc==ENC(db) );
3657 rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
3658 pKeyInfo, pCx->uc.pCursor);
3660 pCx->isTable = 0;
3661 }else{
3662 rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
3663 0, pCx->uc.pCursor);
3664 pCx->isTable = 1;
3667 if( rc ) goto abort_due_to_error;
3668 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3669 break;
3672 /* Opcode: SorterOpen P1 P2 P3 P4 *
3674 ** This opcode works like OP_OpenEphemeral except that it opens
3675 ** a transient index that is specifically designed to sort large
3676 ** tables using an external merge-sort algorithm.
3678 ** If argument P3 is non-zero, then it indicates that the sorter may
3679 ** assume that a stable sort considering the first P3 fields of each
3680 ** key is sufficient to produce the required results.
3682 case OP_SorterOpen: {
3683 VdbeCursor *pCx;
3685 assert( pOp->p1>=0 );
3686 assert( pOp->p2>=0 );
3687 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
3688 if( pCx==0 ) goto no_mem;
3689 pCx->pKeyInfo = pOp->p4.pKeyInfo;
3690 assert( pCx->pKeyInfo->db==db );
3691 assert( pCx->pKeyInfo->enc==ENC(db) );
3692 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
3693 if( rc ) goto abort_due_to_error;
3694 break;
3697 /* Opcode: SequenceTest P1 P2 * * *
3698 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3700 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3701 ** to P2. Regardless of whether or not the jump is taken, increment the
3702 ** the sequence value.
3704 case OP_SequenceTest: {
3705 VdbeCursor *pC;
3706 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3707 pC = p->apCsr[pOp->p1];
3708 assert( isSorter(pC) );
3709 if( (pC->seqCount++)==0 ){
3710 goto jump_to_p2;
3712 break;
3715 /* Opcode: OpenPseudo P1 P2 P3 * *
3716 ** Synopsis: P3 columns in r[P2]
3718 ** Open a new cursor that points to a fake table that contains a single
3719 ** row of data. The content of that one row is the content of memory
3720 ** register P2. In other words, cursor P1 becomes an alias for the
3721 ** MEM_Blob content contained in register P2.
3723 ** A pseudo-table created by this opcode is used to hold a single
3724 ** row output from the sorter so that the row can be decomposed into
3725 ** individual columns using the OP_Column opcode. The OP_Column opcode
3726 ** is the only cursor opcode that works with a pseudo-table.
3728 ** P3 is the number of fields in the records that will be stored by
3729 ** the pseudo-table.
3731 case OP_OpenPseudo: {
3732 VdbeCursor *pCx;
3734 assert( pOp->p1>=0 );
3735 assert( pOp->p3>=0 );
3736 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
3737 if( pCx==0 ) goto no_mem;
3738 pCx->nullRow = 1;
3739 pCx->seekResult = pOp->p2;
3740 pCx->isTable = 1;
3741 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
3742 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
3743 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
3744 ** which is a performance optimization */
3745 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
3746 assert( pOp->p5==0 );
3747 break;
3750 /* Opcode: Close P1 * * * *
3752 ** Close a cursor previously opened as P1. If P1 is not
3753 ** currently open, this instruction is a no-op.
3755 case OP_Close: {
3756 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3757 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
3758 p->apCsr[pOp->p1] = 0;
3759 break;
3762 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3763 /* Opcode: ColumnsUsed P1 * * P4 *
3765 ** This opcode (which only exists if SQLite was compiled with
3766 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
3767 ** table or index for cursor P1 are used. P4 is a 64-bit integer
3768 ** (P4_INT64) in which the first 63 bits are one for each of the
3769 ** first 63 columns of the table or index that are actually used
3770 ** by the cursor. The high-order bit is set if any column after
3771 ** the 64th is used.
3773 case OP_ColumnsUsed: {
3774 VdbeCursor *pC;
3775 pC = p->apCsr[pOp->p1];
3776 assert( pC->eCurType==CURTYPE_BTREE );
3777 pC->maskUsed = *(u64*)pOp->p4.pI64;
3778 break;
3780 #endif
3782 /* Opcode: SeekGE P1 P2 P3 P4 *
3783 ** Synopsis: key=r[P3@P4]
3785 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3786 ** use the value in register P3 as the key. If cursor P1 refers
3787 ** to an SQL index, then P3 is the first in an array of P4 registers
3788 ** that are used as an unpacked index key.
3790 ** Reposition cursor P1 so that it points to the smallest entry that
3791 ** is greater than or equal to the key value. If there are no records
3792 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3794 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3795 ** opcode will always land on a record that equally equals the key, or
3796 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3797 ** opcode must be followed by an IdxLE opcode with the same arguments.
3798 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
3799 ** IdxLE opcode will be used on subsequent loop iterations.
3801 ** This opcode leaves the cursor configured to move in forward order,
3802 ** from the beginning toward the end. In other words, the cursor is
3803 ** configured to use Next, not Prev.
3805 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3807 /* Opcode: SeekGT P1 P2 P3 P4 *
3808 ** Synopsis: key=r[P3@P4]
3810 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3811 ** use the value in register P3 as a key. If cursor P1 refers
3812 ** to an SQL index, then P3 is the first in an array of P4 registers
3813 ** that are used as an unpacked index key.
3815 ** Reposition cursor P1 so that it points to the smallest entry that
3816 ** is greater than the key value. If there are no records greater than
3817 ** the key and P2 is not zero, then jump to P2.
3819 ** This opcode leaves the cursor configured to move in forward order,
3820 ** from the beginning toward the end. In other words, the cursor is
3821 ** configured to use Next, not Prev.
3823 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3825 /* Opcode: SeekLT P1 P2 P3 P4 *
3826 ** Synopsis: key=r[P3@P4]
3828 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3829 ** use the value in register P3 as a key. If cursor P1 refers
3830 ** to an SQL index, then P3 is the first in an array of P4 registers
3831 ** that are used as an unpacked index key.
3833 ** Reposition cursor P1 so that it points to the largest entry that
3834 ** is less than the key value. If there are no records less than
3835 ** the key and P2 is not zero, then jump to P2.
3837 ** This opcode leaves the cursor configured to move in reverse order,
3838 ** from the end toward the beginning. In other words, the cursor is
3839 ** configured to use Prev, not Next.
3841 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3843 /* Opcode: SeekLE P1 P2 P3 P4 *
3844 ** Synopsis: key=r[P3@P4]
3846 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3847 ** use the value in register P3 as a key. If cursor P1 refers
3848 ** to an SQL index, then P3 is the first in an array of P4 registers
3849 ** that are used as an unpacked index key.
3851 ** Reposition cursor P1 so that it points to the largest entry that
3852 ** is less than or equal to the key value. If there are no records
3853 ** less than or equal to the key and P2 is not zero, then jump to P2.
3855 ** This opcode leaves the cursor configured to move in reverse order,
3856 ** from the end toward the beginning. In other words, the cursor is
3857 ** configured to use Prev, not Next.
3859 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3860 ** opcode will always land on a record that equally equals the key, or
3861 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3862 ** opcode must be followed by an IdxGE opcode with the same arguments.
3863 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
3864 ** IdxGE opcode will be used on subsequent loop iterations.
3866 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3868 case OP_SeekLT: /* jump, in3 */
3869 case OP_SeekLE: /* jump, in3 */
3870 case OP_SeekGE: /* jump, in3 */
3871 case OP_SeekGT: { /* jump, in3 */
3872 int res; /* Comparison result */
3873 int oc; /* Opcode */
3874 VdbeCursor *pC; /* The cursor to seek */
3875 UnpackedRecord r; /* The key to seek for */
3876 int nField; /* Number of columns or fields in the key */
3877 i64 iKey; /* The rowid we are to seek to */
3878 int eqOnly; /* Only interested in == results */
3880 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3881 assert( pOp->p2!=0 );
3882 pC = p->apCsr[pOp->p1];
3883 assert( pC!=0 );
3884 assert( pC->eCurType==CURTYPE_BTREE );
3885 assert( OP_SeekLE == OP_SeekLT+1 );
3886 assert( OP_SeekGE == OP_SeekLT+2 );
3887 assert( OP_SeekGT == OP_SeekLT+3 );
3888 assert( pC->isOrdered );
3889 assert( pC->uc.pCursor!=0 );
3890 oc = pOp->opcode;
3891 eqOnly = 0;
3892 pC->nullRow = 0;
3893 #ifdef SQLITE_DEBUG
3894 pC->seekOp = pOp->opcode;
3895 #endif
3897 if( pC->isTable ){
3898 /* The BTREE_SEEK_EQ flag is only set on index cursors */
3899 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
3900 || CORRUPT_DB );
3902 /* The input value in P3 might be of any type: integer, real, string,
3903 ** blob, or NULL. But it needs to be an integer before we can do
3904 ** the seek, so convert it. */
3905 pIn3 = &aMem[pOp->p3];
3906 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
3907 applyNumericAffinity(pIn3, 0);
3909 iKey = sqlite3VdbeIntValue(pIn3);
3911 /* If the P3 value could not be converted into an integer without
3912 ** loss of information, then special processing is required... */
3913 if( (pIn3->flags & MEM_Int)==0 ){
3914 if( (pIn3->flags & MEM_Real)==0 ){
3915 /* If the P3 value cannot be converted into any kind of a number,
3916 ** then the seek is not possible, so jump to P2 */
3917 VdbeBranchTaken(1,2); goto jump_to_p2;
3918 break;
3921 /* If the approximation iKey is larger than the actual real search
3922 ** term, substitute >= for > and < for <=. e.g. if the search term
3923 ** is 4.9 and the integer approximation 5:
3925 ** (x > 4.9) -> (x >= 5)
3926 ** (x <= 4.9) -> (x < 5)
3928 if( pIn3->u.r<(double)iKey ){
3929 assert( OP_SeekGE==(OP_SeekGT-1) );
3930 assert( OP_SeekLT==(OP_SeekLE-1) );
3931 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
3932 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
3935 /* If the approximation iKey is smaller than the actual real search
3936 ** term, substitute <= for < and > for >=. */
3937 else if( pIn3->u.r>(double)iKey ){
3938 assert( OP_SeekLE==(OP_SeekLT+1) );
3939 assert( OP_SeekGT==(OP_SeekGE+1) );
3940 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
3941 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
3944 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
3945 pC->movetoTarget = iKey; /* Used by OP_Delete */
3946 if( rc!=SQLITE_OK ){
3947 goto abort_due_to_error;
3949 }else{
3950 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
3951 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
3952 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
3954 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
3955 eqOnly = 1;
3956 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
3957 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
3958 assert( pOp[1].p1==pOp[0].p1 );
3959 assert( pOp[1].p2==pOp[0].p2 );
3960 assert( pOp[1].p3==pOp[0].p3 );
3961 assert( pOp[1].p4.i==pOp[0].p4.i );
3964 nField = pOp->p4.i;
3965 assert( pOp->p4type==P4_INT32 );
3966 assert( nField>0 );
3967 r.pKeyInfo = pC->pKeyInfo;
3968 r.nField = (u16)nField;
3970 /* The next line of code computes as follows, only faster:
3971 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3972 ** r.default_rc = -1;
3973 ** }else{
3974 ** r.default_rc = +1;
3975 ** }
3977 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
3978 assert( oc!=OP_SeekGT || r.default_rc==-1 );
3979 assert( oc!=OP_SeekLE || r.default_rc==-1 );
3980 assert( oc!=OP_SeekGE || r.default_rc==+1 );
3981 assert( oc!=OP_SeekLT || r.default_rc==+1 );
3983 r.aMem = &aMem[pOp->p3];
3984 #ifdef SQLITE_DEBUG
3985 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3986 #endif
3987 r.eqSeen = 0;
3988 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
3989 if( rc!=SQLITE_OK ){
3990 goto abort_due_to_error;
3992 if( eqOnly && r.eqSeen==0 ){
3993 assert( res!=0 );
3994 goto seek_not_found;
3997 pC->deferredMoveto = 0;
3998 pC->cacheStatus = CACHE_STALE;
3999 #ifdef SQLITE_TEST
4000 sqlite3_search_count++;
4001 #endif
4002 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
4003 if( res<0 || (res==0 && oc==OP_SeekGT) ){
4004 res = 0;
4005 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4006 if( rc!=SQLITE_OK ){
4007 if( rc==SQLITE_DONE ){
4008 rc = SQLITE_OK;
4009 res = 1;
4010 }else{
4011 goto abort_due_to_error;
4014 }else{
4015 res = 0;
4017 }else{
4018 assert( oc==OP_SeekLT || oc==OP_SeekLE );
4019 if( res>0 || (res==0 && oc==OP_SeekLT) ){
4020 res = 0;
4021 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4022 if( rc!=SQLITE_OK ){
4023 if( rc==SQLITE_DONE ){
4024 rc = SQLITE_OK;
4025 res = 1;
4026 }else{
4027 goto abort_due_to_error;
4030 }else{
4031 /* res might be negative because the table is empty. Check to
4032 ** see if this is the case.
4034 res = sqlite3BtreeEof(pC->uc.pCursor);
4037 seek_not_found:
4038 assert( pOp->p2>0 );
4039 VdbeBranchTaken(res!=0,2);
4040 if( res ){
4041 goto jump_to_p2;
4042 }else if( eqOnly ){
4043 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4044 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4046 break;
4049 /* Opcode: SeekHit P1 P2 * * *
4050 ** Synopsis: seekHit=P2
4052 ** Set the seekHit flag on cursor P1 to the value in P2.
4053 ** The seekHit flag is used by the IfNoHope opcode.
4055 ** P1 must be a valid b-tree cursor. P2 must be a boolean value,
4056 ** either 0 or 1.
4058 case OP_SeekHit: {
4059 VdbeCursor *pC;
4060 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4061 pC = p->apCsr[pOp->p1];
4062 assert( pC!=0 );
4063 assert( pOp->p2==0 || pOp->p2==1 );
4064 pC->seekHit = pOp->p2 & 1;
4065 break;
4068 /* Opcode: Found P1 P2 P3 P4 *
4069 ** Synopsis: key=r[P3@P4]
4071 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4072 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4073 ** record.
4075 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4076 ** is a prefix of any entry in P1 then a jump is made to P2 and
4077 ** P1 is left pointing at the matching entry.
4079 ** This operation leaves the cursor in a state where it can be
4080 ** advanced in the forward direction. The Next instruction will work,
4081 ** but not the Prev instruction.
4083 ** See also: NotFound, NoConflict, NotExists. SeekGe
4085 /* Opcode: NotFound P1 P2 P3 P4 *
4086 ** Synopsis: key=r[P3@P4]
4088 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4089 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4090 ** record.
4092 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4093 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
4094 ** does contain an entry whose prefix matches the P3/P4 record then control
4095 ** falls through to the next instruction and P1 is left pointing at the
4096 ** matching entry.
4098 ** This operation leaves the cursor in a state where it cannot be
4099 ** advanced in either direction. In other words, the Next and Prev
4100 ** opcodes do not work after this operation.
4102 ** See also: Found, NotExists, NoConflict, IfNoHope
4104 /* Opcode: IfNoHope P1 P2 P3 P4 *
4105 ** Synopsis: key=r[P3@P4]
4107 ** Register P3 is the first of P4 registers that form an unpacked
4108 ** record.
4110 ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then
4111 ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then
4112 ** check to see if there is any entry in P1 that matches the
4113 ** prefix identified by P3 and P4. If no entry matches the prefix,
4114 ** jump to P2. Otherwise fall through.
4116 ** This opcode behaves like OP_NotFound if the seekHit
4117 ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
4119 ** This opcode is used in IN clause processing for a multi-column key.
4120 ** If an IN clause is attached to an element of the key other than the
4121 ** left-most element, and if there are no matches on the most recent
4122 ** seek over the whole key, then it might be that one of the key element
4123 ** to the left is prohibiting a match, and hence there is "no hope" of
4124 ** any match regardless of how many IN clause elements are checked.
4125 ** In such a case, we abandon the IN clause search early, using this
4126 ** opcode. The opcode name comes from the fact that the
4127 ** jump is taken if there is "no hope" of achieving a match.
4129 ** See also: NotFound, SeekHit
4131 /* Opcode: NoConflict P1 P2 P3 P4 *
4132 ** Synopsis: key=r[P3@P4]
4134 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4135 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4136 ** record.
4138 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4139 ** contains any NULL value, jump immediately to P2. If all terms of the
4140 ** record are not-NULL then a check is done to determine if any row in the
4141 ** P1 index btree has a matching key prefix. If there are no matches, jump
4142 ** immediately to P2. If there is a match, fall through and leave the P1
4143 ** cursor pointing to the matching row.
4145 ** This opcode is similar to OP_NotFound with the exceptions that the
4146 ** branch is always taken if any part of the search key input is NULL.
4148 ** This operation leaves the cursor in a state where it cannot be
4149 ** advanced in either direction. In other words, the Next and Prev
4150 ** opcodes do not work after this operation.
4152 ** See also: NotFound, Found, NotExists
4154 case OP_IfNoHope: { /* jump, in3 */
4155 VdbeCursor *pC;
4156 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4157 pC = p->apCsr[pOp->p1];
4158 assert( pC!=0 );
4159 if( pC->seekHit ) break;
4160 /* Fall through into OP_NotFound */
4162 case OP_NoConflict: /* jump, in3 */
4163 case OP_NotFound: /* jump, in3 */
4164 case OP_Found: { /* jump, in3 */
4165 int alreadyExists;
4166 int takeJump;
4167 int ii;
4168 VdbeCursor *pC;
4169 int res;
4170 UnpackedRecord *pFree;
4171 UnpackedRecord *pIdxKey;
4172 UnpackedRecord r;
4174 #ifdef SQLITE_TEST
4175 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4176 #endif
4178 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4179 assert( pOp->p4type==P4_INT32 );
4180 pC = p->apCsr[pOp->p1];
4181 assert( pC!=0 );
4182 #ifdef SQLITE_DEBUG
4183 pC->seekOp = pOp->opcode;
4184 #endif
4185 pIn3 = &aMem[pOp->p3];
4186 assert( pC->eCurType==CURTYPE_BTREE );
4187 assert( pC->uc.pCursor!=0 );
4188 assert( pC->isTable==0 );
4189 if( pOp->p4.i>0 ){
4190 r.pKeyInfo = pC->pKeyInfo;
4191 r.nField = (u16)pOp->p4.i;
4192 r.aMem = pIn3;
4193 #ifdef SQLITE_DEBUG
4194 for(ii=0; ii<r.nField; ii++){
4195 assert( memIsValid(&r.aMem[ii]) );
4196 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4197 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4199 #endif
4200 pIdxKey = &r;
4201 pFree = 0;
4202 }else{
4203 assert( pIn3->flags & MEM_Blob );
4204 rc = ExpandBlob(pIn3);
4205 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4206 if( rc ) goto no_mem;
4207 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4208 if( pIdxKey==0 ) goto no_mem;
4209 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4211 pIdxKey->default_rc = 0;
4212 takeJump = 0;
4213 if( pOp->opcode==OP_NoConflict ){
4214 /* For the OP_NoConflict opcode, take the jump if any of the
4215 ** input fields are NULL, since any key with a NULL will not
4216 ** conflict */
4217 for(ii=0; ii<pIdxKey->nField; ii++){
4218 if( pIdxKey->aMem[ii].flags & MEM_Null ){
4219 takeJump = 1;
4220 break;
4224 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
4225 if( pFree ) sqlite3DbFreeNN(db, pFree);
4226 if( rc!=SQLITE_OK ){
4227 goto abort_due_to_error;
4229 pC->seekResult = res;
4230 alreadyExists = (res==0);
4231 pC->nullRow = 1-alreadyExists;
4232 pC->deferredMoveto = 0;
4233 pC->cacheStatus = CACHE_STALE;
4234 if( pOp->opcode==OP_Found ){
4235 VdbeBranchTaken(alreadyExists!=0,2);
4236 if( alreadyExists ) goto jump_to_p2;
4237 }else{
4238 VdbeBranchTaken(takeJump||alreadyExists==0,2);
4239 if( takeJump || !alreadyExists ) goto jump_to_p2;
4241 break;
4244 /* Opcode: SeekRowid P1 P2 P3 * *
4245 ** Synopsis: intkey=r[P3]
4247 ** P1 is the index of a cursor open on an SQL table btree (with integer
4248 ** keys). If register P3 does not contain an integer or if P1 does not
4249 ** contain a record with rowid P3 then jump immediately to P2.
4250 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4251 ** a record with rowid P3 then
4252 ** leave the cursor pointing at that record and fall through to the next
4253 ** instruction.
4255 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4256 ** the P3 register must be guaranteed to contain an integer value. With this
4257 ** opcode, register P3 might not contain an integer.
4259 ** The OP_NotFound opcode performs the same operation on index btrees
4260 ** (with arbitrary multi-value keys).
4262 ** This opcode leaves the cursor in a state where it cannot be advanced
4263 ** in either direction. In other words, the Next and Prev opcodes will
4264 ** not work following this opcode.
4266 ** See also: Found, NotFound, NoConflict, SeekRowid
4268 /* Opcode: NotExists P1 P2 P3 * *
4269 ** Synopsis: intkey=r[P3]
4271 ** P1 is the index of a cursor open on an SQL table btree (with integer
4272 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4273 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4274 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4275 ** leave the cursor pointing at that record and fall through to the next
4276 ** instruction.
4278 ** The OP_SeekRowid opcode performs the same operation but also allows the
4279 ** P3 register to contain a non-integer value, in which case the jump is
4280 ** always taken. This opcode requires that P3 always contain an integer.
4282 ** The OP_NotFound opcode performs the same operation on index btrees
4283 ** (with arbitrary multi-value keys).
4285 ** This opcode leaves the cursor in a state where it cannot be advanced
4286 ** in either direction. In other words, the Next and Prev opcodes will
4287 ** not work following this opcode.
4289 ** See also: Found, NotFound, NoConflict, SeekRowid
4291 case OP_SeekRowid: { /* jump, in3 */
4292 VdbeCursor *pC;
4293 BtCursor *pCrsr;
4294 int res;
4295 u64 iKey;
4297 pIn3 = &aMem[pOp->p3];
4298 if( (pIn3->flags & MEM_Int)==0 ){
4299 applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
4300 if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
4302 /* Fall through into OP_NotExists */
4303 case OP_NotExists: /* jump, in3 */
4304 pIn3 = &aMem[pOp->p3];
4305 assert( pIn3->flags & MEM_Int );
4306 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4307 pC = p->apCsr[pOp->p1];
4308 assert( pC!=0 );
4309 #ifdef SQLITE_DEBUG
4310 pC->seekOp = OP_SeekRowid;
4311 #endif
4312 assert( pC->isTable );
4313 assert( pC->eCurType==CURTYPE_BTREE );
4314 pCrsr = pC->uc.pCursor;
4315 assert( pCrsr!=0 );
4316 res = 0;
4317 iKey = pIn3->u.i;
4318 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
4319 assert( rc==SQLITE_OK || res==0 );
4320 pC->movetoTarget = iKey; /* Used by OP_Delete */
4321 pC->nullRow = 0;
4322 pC->cacheStatus = CACHE_STALE;
4323 pC->deferredMoveto = 0;
4324 VdbeBranchTaken(res!=0,2);
4325 pC->seekResult = res;
4326 if( res!=0 ){
4327 assert( rc==SQLITE_OK );
4328 if( pOp->p2==0 ){
4329 rc = SQLITE_CORRUPT_BKPT;
4330 }else{
4331 goto jump_to_p2;
4334 if( rc ) goto abort_due_to_error;
4335 break;
4338 /* Opcode: Sequence P1 P2 * * *
4339 ** Synopsis: r[P2]=cursor[P1].ctr++
4341 ** Find the next available sequence number for cursor P1.
4342 ** Write the sequence number into register P2.
4343 ** The sequence number on the cursor is incremented after this
4344 ** instruction.
4346 case OP_Sequence: { /* out2 */
4347 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4348 assert( p->apCsr[pOp->p1]!=0 );
4349 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
4350 pOut = out2Prerelease(p, pOp);
4351 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
4352 break;
4356 /* Opcode: NewRowid P1 P2 P3 * *
4357 ** Synopsis: r[P2]=rowid
4359 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4360 ** The record number is not previously used as a key in the database
4361 ** table that cursor P1 points to. The new record number is written
4362 ** written to register P2.
4364 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4365 ** the largest previously generated record number. No new record numbers are
4366 ** allowed to be less than this value. When this value reaches its maximum,
4367 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4368 ** generated record number. This P3 mechanism is used to help implement the
4369 ** AUTOINCREMENT feature.
4371 case OP_NewRowid: { /* out2 */
4372 i64 v; /* The new rowid */
4373 VdbeCursor *pC; /* Cursor of table to get the new rowid */
4374 int res; /* Result of an sqlite3BtreeLast() */
4375 int cnt; /* Counter to limit the number of searches */
4376 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
4377 VdbeFrame *pFrame; /* Root frame of VDBE */
4379 v = 0;
4380 res = 0;
4381 pOut = out2Prerelease(p, pOp);
4382 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4383 pC = p->apCsr[pOp->p1];
4384 assert( pC!=0 );
4385 assert( pC->isTable );
4386 assert( pC->eCurType==CURTYPE_BTREE );
4387 assert( pC->uc.pCursor!=0 );
4389 /* The next rowid or record number (different terms for the same
4390 ** thing) is obtained in a two-step algorithm.
4392 ** First we attempt to find the largest existing rowid and add one
4393 ** to that. But if the largest existing rowid is already the maximum
4394 ** positive integer, we have to fall through to the second
4395 ** probabilistic algorithm
4397 ** The second algorithm is to select a rowid at random and see if
4398 ** it already exists in the table. If it does not exist, we have
4399 ** succeeded. If the random rowid does exist, we select a new one
4400 ** and try again, up to 100 times.
4402 assert( pC->isTable );
4404 #ifdef SQLITE_32BIT_ROWID
4405 # define MAX_ROWID 0x7fffffff
4406 #else
4407 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4408 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4409 ** to provide the constant while making all compilers happy.
4411 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4412 #endif
4414 if( !pC->useRandomRowid ){
4415 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4416 if( rc!=SQLITE_OK ){
4417 goto abort_due_to_error;
4419 if( res ){
4420 v = 1; /* IMP: R-61914-48074 */
4421 }else{
4422 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
4423 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4424 if( v>=MAX_ROWID ){
4425 pC->useRandomRowid = 1;
4426 }else{
4427 v++; /* IMP: R-29538-34987 */
4432 #ifndef SQLITE_OMIT_AUTOINCREMENT
4433 if( pOp->p3 ){
4434 /* Assert that P3 is a valid memory cell. */
4435 assert( pOp->p3>0 );
4436 if( p->pFrame ){
4437 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4438 /* Assert that P3 is a valid memory cell. */
4439 assert( pOp->p3<=pFrame->nMem );
4440 pMem = &pFrame->aMem[pOp->p3];
4441 }else{
4442 /* Assert that P3 is a valid memory cell. */
4443 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
4444 pMem = &aMem[pOp->p3];
4445 memAboutToChange(p, pMem);
4447 assert( memIsValid(pMem) );
4449 REGISTER_TRACE(pOp->p3, pMem);
4450 sqlite3VdbeMemIntegerify(pMem);
4451 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
4452 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4453 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
4454 goto abort_due_to_error;
4456 if( v<pMem->u.i+1 ){
4457 v = pMem->u.i + 1;
4459 pMem->u.i = v;
4461 #endif
4462 if( pC->useRandomRowid ){
4463 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4464 ** largest possible integer (9223372036854775807) then the database
4465 ** engine starts picking positive candidate ROWIDs at random until
4466 ** it finds one that is not previously used. */
4467 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
4468 ** an AUTOINCREMENT table. */
4469 cnt = 0;
4471 sqlite3_randomness(sizeof(v), &v);
4472 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
4473 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
4474 0, &res))==SQLITE_OK)
4475 && (res==0)
4476 && (++cnt<100));
4477 if( rc ) goto abort_due_to_error;
4478 if( res==0 ){
4479 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
4480 goto abort_due_to_error;
4482 assert( v>0 ); /* EV: R-40812-03570 */
4484 pC->deferredMoveto = 0;
4485 pC->cacheStatus = CACHE_STALE;
4487 pOut->u.i = v;
4488 break;
4491 /* Opcode: Insert P1 P2 P3 P4 P5
4492 ** Synopsis: intkey=r[P3] data=r[P2]
4494 ** Write an entry into the table of cursor P1. A new entry is
4495 ** created if it doesn't already exist or the data for an existing
4496 ** entry is overwritten. The data is the value MEM_Blob stored in register
4497 ** number P2. The key is stored in register P3. The key must
4498 ** be a MEM_Int.
4500 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4501 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
4502 ** then rowid is stored for subsequent return by the
4503 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4505 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
4506 ** run faster by avoiding an unnecessary seek on cursor P1. However,
4507 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
4508 ** seeks on the cursor or if the most recent seek used a key equal to P3.
4510 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4511 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
4512 ** is part of an INSERT operation. The difference is only important to
4513 ** the update hook.
4515 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
4516 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
4517 ** following a successful insert.
4519 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4520 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4521 ** and register P2 becomes ephemeral. If the cursor is changed, the
4522 ** value of register P2 will then change. Make sure this does not
4523 ** cause any problems.)
4525 ** This instruction only works on tables. The equivalent instruction
4526 ** for indices is OP_IdxInsert.
4528 /* Opcode: InsertInt P1 P2 P3 P4 P5
4529 ** Synopsis: intkey=P3 data=r[P2]
4531 ** This works exactly like OP_Insert except that the key is the
4532 ** integer value P3, not the value of the integer stored in register P3.
4534 case OP_Insert:
4535 case OP_InsertInt: {
4536 Mem *pData; /* MEM cell holding data for the record to be inserted */
4537 Mem *pKey; /* MEM cell holding key for the record */
4538 VdbeCursor *pC; /* Cursor to table into which insert is written */
4539 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
4540 const char *zDb; /* database name - used by the update hook */
4541 Table *pTab; /* Table structure - used by update and pre-update hooks */
4542 BtreePayload x; /* Payload to be inserted */
4544 pData = &aMem[pOp->p2];
4545 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4546 assert( memIsValid(pData) );
4547 pC = p->apCsr[pOp->p1];
4548 assert( pC!=0 );
4549 assert( pC->eCurType==CURTYPE_BTREE );
4550 assert( pC->uc.pCursor!=0 );
4551 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
4552 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
4553 REGISTER_TRACE(pOp->p2, pData);
4554 sqlite3VdbeIncrWriteCounter(p, pC);
4556 if( pOp->opcode==OP_Insert ){
4557 pKey = &aMem[pOp->p3];
4558 assert( pKey->flags & MEM_Int );
4559 assert( memIsValid(pKey) );
4560 REGISTER_TRACE(pOp->p3, pKey);
4561 x.nKey = pKey->u.i;
4562 }else{
4563 assert( pOp->opcode==OP_InsertInt );
4564 x.nKey = pOp->p3;
4567 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4568 assert( pC->iDb>=0 );
4569 zDb = db->aDb[pC->iDb].zDbSName;
4570 pTab = pOp->p4.pTab;
4571 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
4572 }else{
4573 pTab = 0;
4574 zDb = 0; /* Not needed. Silence a compiler warning. */
4577 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4578 /* Invoke the pre-update hook, if any */
4579 if( pTab ){
4580 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
4581 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
4583 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
4584 /* Prevent post-update hook from running in cases when it should not */
4585 pTab = 0;
4588 if( pOp->p5 & OPFLAG_ISNOOP ) break;
4589 #endif
4591 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4592 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
4593 assert( pData->flags & (MEM_Blob|MEM_Str) );
4594 x.pData = pData->z;
4595 x.nData = pData->n;
4596 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
4597 if( pData->flags & MEM_Zero ){
4598 x.nZero = pData->u.nZero;
4599 }else{
4600 x.nZero = 0;
4602 x.pKey = 0;
4603 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
4604 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
4606 pC->deferredMoveto = 0;
4607 pC->cacheStatus = CACHE_STALE;
4609 /* Invoke the update-hook if required. */
4610 if( rc ) goto abort_due_to_error;
4611 if( pTab ){
4612 assert( db->xUpdateCallback!=0 );
4613 assert( pTab->aCol!=0 );
4614 db->xUpdateCallback(db->pUpdateArg,
4615 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
4616 zDb, pTab->zName, x.nKey);
4618 break;
4621 /* Opcode: Delete P1 P2 P3 P4 P5
4623 ** Delete the record at which the P1 cursor is currently pointing.
4625 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
4626 ** the cursor will be left pointing at either the next or the previous
4627 ** record in the table. If it is left pointing at the next record, then
4628 ** the next Next instruction will be a no-op. As a result, in this case
4629 ** it is ok to delete a record from within a Next loop. If
4630 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
4631 ** left in an undefined state.
4633 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
4634 ** delete one of several associated with deleting a table row and all its
4635 ** associated index entries. Exactly one of those deletes is the "primary"
4636 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
4637 ** marked with the AUXDELETE flag.
4639 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
4640 ** change count is incremented (otherwise not).
4642 ** P1 must not be pseudo-table. It has to be a real table with
4643 ** multiple rows.
4645 ** If P4 is not NULL then it points to a Table object. In this case either
4646 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
4647 ** have been positioned using OP_NotFound prior to invoking this opcode in
4648 ** this case. Specifically, if one is configured, the pre-update hook is
4649 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
4650 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
4652 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
4653 ** of the memory cell that contains the value that the rowid of the row will
4654 ** be set to by the update.
4656 case OP_Delete: {
4657 VdbeCursor *pC;
4658 const char *zDb;
4659 Table *pTab;
4660 int opflags;
4662 opflags = pOp->p2;
4663 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4664 pC = p->apCsr[pOp->p1];
4665 assert( pC!=0 );
4666 assert( pC->eCurType==CURTYPE_BTREE );
4667 assert( pC->uc.pCursor!=0 );
4668 assert( pC->deferredMoveto==0 );
4669 sqlite3VdbeIncrWriteCounter(p, pC);
4671 #ifdef SQLITE_DEBUG
4672 if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
4673 /* If p5 is zero, the seek operation that positioned the cursor prior to
4674 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
4675 ** the row that is being deleted */
4676 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4677 assert( pC->movetoTarget==iKey );
4679 #endif
4681 /* If the update-hook or pre-update-hook will be invoked, set zDb to
4682 ** the name of the db to pass as to it. Also set local pTab to a copy
4683 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
4684 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
4685 ** VdbeCursor.movetoTarget to the current rowid. */
4686 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4687 assert( pC->iDb>=0 );
4688 assert( pOp->p4.pTab!=0 );
4689 zDb = db->aDb[pC->iDb].zDbSName;
4690 pTab = pOp->p4.pTab;
4691 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
4692 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4694 }else{
4695 zDb = 0; /* Not needed. Silence a compiler warning. */
4696 pTab = 0; /* Not needed. Silence a compiler warning. */
4699 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4700 /* Invoke the pre-update-hook if required. */
4701 if( db->xPreUpdateCallback && pOp->p4.pTab ){
4702 assert( !(opflags & OPFLAG_ISUPDATE)
4703 || HasRowid(pTab)==0
4704 || (aMem[pOp->p3].flags & MEM_Int)
4706 sqlite3VdbePreUpdateHook(p, pC,
4707 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
4708 zDb, pTab, pC->movetoTarget,
4709 pOp->p3
4712 if( opflags & OPFLAG_ISNOOP ) break;
4713 #endif
4715 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
4716 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
4717 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
4718 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
4720 #ifdef SQLITE_DEBUG
4721 if( p->pFrame==0 ){
4722 if( pC->isEphemeral==0
4723 && (pOp->p5 & OPFLAG_AUXDELETE)==0
4724 && (pC->wrFlag & OPFLAG_FORDELETE)==0
4726 nExtraDelete++;
4728 if( pOp->p2 & OPFLAG_NCHANGE ){
4729 nExtraDelete--;
4732 #endif
4734 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
4735 pC->cacheStatus = CACHE_STALE;
4736 pC->seekResult = 0;
4737 if( rc ) goto abort_due_to_error;
4739 /* Invoke the update-hook if required. */
4740 if( opflags & OPFLAG_NCHANGE ){
4741 p->nChange++;
4742 if( db->xUpdateCallback && HasRowid(pTab) ){
4743 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
4744 pC->movetoTarget);
4745 assert( pC->iDb>=0 );
4749 break;
4751 /* Opcode: ResetCount * * * * *
4753 ** The value of the change counter is copied to the database handle
4754 ** change counter (returned by subsequent calls to sqlite3_changes()).
4755 ** Then the VMs internal change counter resets to 0.
4756 ** This is used by trigger programs.
4758 case OP_ResetCount: {
4759 sqlite3VdbeSetChanges(db, p->nChange);
4760 p->nChange = 0;
4761 break;
4764 /* Opcode: SorterCompare P1 P2 P3 P4
4765 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4767 ** P1 is a sorter cursor. This instruction compares a prefix of the
4768 ** record blob in register P3 against a prefix of the entry that
4769 ** the sorter cursor currently points to. Only the first P4 fields
4770 ** of r[P3] and the sorter record are compared.
4772 ** If either P3 or the sorter contains a NULL in one of their significant
4773 ** fields (not counting the P4 fields at the end which are ignored) then
4774 ** the comparison is assumed to be equal.
4776 ** Fall through to next instruction if the two records compare equal to
4777 ** each other. Jump to P2 if they are different.
4779 case OP_SorterCompare: {
4780 VdbeCursor *pC;
4781 int res;
4782 int nKeyCol;
4784 pC = p->apCsr[pOp->p1];
4785 assert( isSorter(pC) );
4786 assert( pOp->p4type==P4_INT32 );
4787 pIn3 = &aMem[pOp->p3];
4788 nKeyCol = pOp->p4.i;
4789 res = 0;
4790 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
4791 VdbeBranchTaken(res!=0,2);
4792 if( rc ) goto abort_due_to_error;
4793 if( res ) goto jump_to_p2;
4794 break;
4797 /* Opcode: SorterData P1 P2 P3 * *
4798 ** Synopsis: r[P2]=data
4800 ** Write into register P2 the current sorter data for sorter cursor P1.
4801 ** Then clear the column header cache on cursor P3.
4803 ** This opcode is normally use to move a record out of the sorter and into
4804 ** a register that is the source for a pseudo-table cursor created using
4805 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4806 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4807 ** us from having to issue a separate NullRow instruction to clear that cache.
4809 case OP_SorterData: {
4810 VdbeCursor *pC;
4812 pOut = &aMem[pOp->p2];
4813 pC = p->apCsr[pOp->p1];
4814 assert( isSorter(pC) );
4815 rc = sqlite3VdbeSorterRowkey(pC, pOut);
4816 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
4817 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4818 if( rc ) goto abort_due_to_error;
4819 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
4820 break;
4823 /* Opcode: RowData P1 P2 P3 * *
4824 ** Synopsis: r[P2]=data
4826 ** Write into register P2 the complete row content for the row at
4827 ** which cursor P1 is currently pointing.
4828 ** There is no interpretation of the data.
4829 ** It is just copied onto the P2 register exactly as
4830 ** it is found in the database file.
4832 ** If cursor P1 is an index, then the content is the key of the row.
4833 ** If cursor P2 is a table, then the content extracted is the data.
4835 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4836 ** of a real table, not a pseudo-table.
4838 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
4839 ** into the database page. That means that the content of the output
4840 ** register will be invalidated as soon as the cursor moves - including
4841 ** moves caused by other cursors that "save" the current cursors
4842 ** position in order that they can write to the same table. If P3==0
4843 ** then a copy of the data is made into memory. P3!=0 is faster, but
4844 ** P3==0 is safer.
4846 ** If P3!=0 then the content of the P2 register is unsuitable for use
4847 ** in OP_Result and any OP_Result will invalidate the P2 register content.
4848 ** The P2 register content is invalidated by opcodes like OP_Function or
4849 ** by any use of another cursor pointing to the same table.
4851 case OP_RowData: {
4852 VdbeCursor *pC;
4853 BtCursor *pCrsr;
4854 u32 n;
4856 pOut = out2Prerelease(p, pOp);
4858 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4859 pC = p->apCsr[pOp->p1];
4860 assert( pC!=0 );
4861 assert( pC->eCurType==CURTYPE_BTREE );
4862 assert( isSorter(pC)==0 );
4863 assert( pC->nullRow==0 );
4864 assert( pC->uc.pCursor!=0 );
4865 pCrsr = pC->uc.pCursor;
4867 /* The OP_RowData opcodes always follow OP_NotExists or
4868 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
4869 ** that might invalidate the cursor.
4870 ** If this where not the case, on of the following assert()s
4871 ** would fail. Should this ever change (because of changes in the code
4872 ** generator) then the fix would be to insert a call to
4873 ** sqlite3VdbeCursorMoveto().
4875 assert( pC->deferredMoveto==0 );
4876 assert( sqlite3BtreeCursorIsValid(pCrsr) );
4877 #if 0 /* Not required due to the previous to assert() statements */
4878 rc = sqlite3VdbeCursorMoveto(pC);
4879 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4880 #endif
4882 n = sqlite3BtreePayloadSize(pCrsr);
4883 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
4884 goto too_big;
4886 testcase( n==0 );
4887 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
4888 if( rc ) goto abort_due_to_error;
4889 if( !pOp->p3 ) Deephemeralize(pOut);
4890 UPDATE_MAX_BLOBSIZE(pOut);
4891 REGISTER_TRACE(pOp->p2, pOut);
4892 break;
4895 /* Opcode: Rowid P1 P2 * * *
4896 ** Synopsis: r[P2]=rowid
4898 ** Store in register P2 an integer which is the key of the table entry that
4899 ** P1 is currently point to.
4901 ** P1 can be either an ordinary table or a virtual table. There used to
4902 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4903 ** one opcode now works for both table types.
4905 case OP_Rowid: { /* out2 */
4906 VdbeCursor *pC;
4907 i64 v;
4908 sqlite3_vtab *pVtab;
4909 const sqlite3_module *pModule;
4911 pOut = out2Prerelease(p, pOp);
4912 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4913 pC = p->apCsr[pOp->p1];
4914 assert( pC!=0 );
4915 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
4916 if( pC->nullRow ){
4917 pOut->flags = MEM_Null;
4918 break;
4919 }else if( pC->deferredMoveto ){
4920 v = pC->movetoTarget;
4921 #ifndef SQLITE_OMIT_VIRTUALTABLE
4922 }else if( pC->eCurType==CURTYPE_VTAB ){
4923 assert( pC->uc.pVCur!=0 );
4924 pVtab = pC->uc.pVCur->pVtab;
4925 pModule = pVtab->pModule;
4926 assert( pModule->xRowid );
4927 rc = pModule->xRowid(pC->uc.pVCur, &v);
4928 sqlite3VtabImportErrmsg(p, pVtab);
4929 if( rc ) goto abort_due_to_error;
4930 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4931 }else{
4932 assert( pC->eCurType==CURTYPE_BTREE );
4933 assert( pC->uc.pCursor!=0 );
4934 rc = sqlite3VdbeCursorRestore(pC);
4935 if( rc ) goto abort_due_to_error;
4936 if( pC->nullRow ){
4937 pOut->flags = MEM_Null;
4938 break;
4940 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4942 pOut->u.i = v;
4943 break;
4946 /* Opcode: NullRow P1 * * * *
4948 ** Move the cursor P1 to a null row. Any OP_Column operations
4949 ** that occur while the cursor is on the null row will always
4950 ** write a NULL.
4952 case OP_NullRow: {
4953 VdbeCursor *pC;
4955 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4956 pC = p->apCsr[pOp->p1];
4957 assert( pC!=0 );
4958 pC->nullRow = 1;
4959 pC->cacheStatus = CACHE_STALE;
4960 if( pC->eCurType==CURTYPE_BTREE ){
4961 assert( pC->uc.pCursor!=0 );
4962 sqlite3BtreeClearCursor(pC->uc.pCursor);
4964 #ifdef SQLITE_DEBUG
4965 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
4966 #endif
4967 break;
4970 /* Opcode: SeekEnd P1 * * * *
4972 ** Position cursor P1 at the end of the btree for the purpose of
4973 ** appending a new entry onto the btree.
4975 ** It is assumed that the cursor is used only for appending and so
4976 ** if the cursor is valid, then the cursor must already be pointing
4977 ** at the end of the btree and so no changes are made to
4978 ** the cursor.
4980 /* Opcode: Last P1 P2 * * *
4982 ** The next use of the Rowid or Column or Prev instruction for P1
4983 ** will refer to the last entry in the database table or index.
4984 ** If the table or index is empty and P2>0, then jump immediately to P2.
4985 ** If P2 is 0 or if the table or index is not empty, fall through
4986 ** to the following instruction.
4988 ** This opcode leaves the cursor configured to move in reverse order,
4989 ** from the end toward the beginning. In other words, the cursor is
4990 ** configured to use Prev, not Next.
4992 case OP_SeekEnd:
4993 case OP_Last: { /* jump */
4994 VdbeCursor *pC;
4995 BtCursor *pCrsr;
4996 int res;
4998 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4999 pC = p->apCsr[pOp->p1];
5000 assert( pC!=0 );
5001 assert( pC->eCurType==CURTYPE_BTREE );
5002 pCrsr = pC->uc.pCursor;
5003 res = 0;
5004 assert( pCrsr!=0 );
5005 #ifdef SQLITE_DEBUG
5006 pC->seekOp = pOp->opcode;
5007 #endif
5008 if( pOp->opcode==OP_SeekEnd ){
5009 assert( pOp->p2==0 );
5010 pC->seekResult = -1;
5011 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
5012 break;
5015 rc = sqlite3BtreeLast(pCrsr, &res);
5016 pC->nullRow = (u8)res;
5017 pC->deferredMoveto = 0;
5018 pC->cacheStatus = CACHE_STALE;
5019 if( rc ) goto abort_due_to_error;
5020 if( pOp->p2>0 ){
5021 VdbeBranchTaken(res!=0,2);
5022 if( res ) goto jump_to_p2;
5024 break;
5027 /* Opcode: IfSmaller P1 P2 P3 * *
5029 ** Estimate the number of rows in the table P1. Jump to P2 if that
5030 ** estimate is less than approximately 2**(0.1*P3).
5032 case OP_IfSmaller: { /* jump */
5033 VdbeCursor *pC;
5034 BtCursor *pCrsr;
5035 int res;
5036 i64 sz;
5038 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5039 pC = p->apCsr[pOp->p1];
5040 assert( pC!=0 );
5041 pCrsr = pC->uc.pCursor;
5042 assert( pCrsr );
5043 rc = sqlite3BtreeFirst(pCrsr, &res);
5044 if( rc ) goto abort_due_to_error;
5045 if( res==0 ){
5046 sz = sqlite3BtreeRowCountEst(pCrsr);
5047 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
5049 VdbeBranchTaken(res!=0,2);
5050 if( res ) goto jump_to_p2;
5051 break;
5055 /* Opcode: SorterSort P1 P2 * * *
5057 ** After all records have been inserted into the Sorter object
5058 ** identified by P1, invoke this opcode to actually do the sorting.
5059 ** Jump to P2 if there are no records to be sorted.
5061 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
5062 ** for Sorter objects.
5064 /* Opcode: Sort P1 P2 * * *
5066 ** This opcode does exactly the same thing as OP_Rewind except that
5067 ** it increments an undocumented global variable used for testing.
5069 ** Sorting is accomplished by writing records into a sorting index,
5070 ** then rewinding that index and playing it back from beginning to
5071 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
5072 ** rewinding so that the global variable will be incremented and
5073 ** regression tests can determine whether or not the optimizer is
5074 ** correctly optimizing out sorts.
5076 case OP_SorterSort: /* jump */
5077 case OP_Sort: { /* jump */
5078 #ifdef SQLITE_TEST
5079 sqlite3_sort_count++;
5080 sqlite3_search_count--;
5081 #endif
5082 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
5083 /* Fall through into OP_Rewind */
5085 /* Opcode: Rewind P1 P2 * * P5
5087 ** The next use of the Rowid or Column or Next instruction for P1
5088 ** will refer to the first entry in the database table or index.
5089 ** If the table or index is empty, jump immediately to P2.
5090 ** If the table or index is not empty, fall through to the following
5091 ** instruction.
5093 ** If P5 is non-zero and the table is not empty, then the "skip-next"
5094 ** flag is set on the cursor so that the next OP_Next instruction
5095 ** executed on it is a no-op.
5097 ** This opcode leaves the cursor configured to move in forward order,
5098 ** from the beginning toward the end. In other words, the cursor is
5099 ** configured to use Next, not Prev.
5101 case OP_Rewind: { /* jump */
5102 VdbeCursor *pC;
5103 BtCursor *pCrsr;
5104 int res;
5106 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5107 pC = p->apCsr[pOp->p1];
5108 assert( pC!=0 );
5109 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5110 res = 1;
5111 #ifdef SQLITE_DEBUG
5112 pC->seekOp = OP_Rewind;
5113 #endif
5114 if( isSorter(pC) ){
5115 rc = sqlite3VdbeSorterRewind(pC, &res);
5116 }else{
5117 assert( pC->eCurType==CURTYPE_BTREE );
5118 pCrsr = pC->uc.pCursor;
5119 assert( pCrsr );
5120 rc = sqlite3BtreeFirst(pCrsr, &res);
5121 #ifndef SQLITE_OMIT_WINDOWFUNC
5122 if( pOp->p5 ) sqlite3BtreeSkipNext(pCrsr);
5123 #endif
5124 pC->deferredMoveto = 0;
5125 pC->cacheStatus = CACHE_STALE;
5127 if( rc ) goto abort_due_to_error;
5128 pC->nullRow = (u8)res;
5129 assert( pOp->p2>0 && pOp->p2<p->nOp );
5130 VdbeBranchTaken(res!=0,2);
5131 if( res ) goto jump_to_p2;
5132 break;
5135 /* Opcode: Next P1 P2 P3 P4 P5
5137 ** Advance cursor P1 so that it points to the next key/data pair in its
5138 ** table or index. If there are no more key/value pairs then fall through
5139 ** to the following instruction. But if the cursor advance was successful,
5140 ** jump immediately to P2.
5142 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5143 ** OP_Rewind opcode used to position the cursor. Next is not allowed
5144 ** to follow SeekLT, SeekLE, or OP_Last.
5146 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
5147 ** been opened prior to this opcode or the program will segfault.
5149 ** The P3 value is a hint to the btree implementation. If P3==1, that
5150 ** means P1 is an SQL index and that this instruction could have been
5151 ** omitted if that index had been unique. P3 is usually 0. P3 is
5152 ** always either 0 or 1.
5154 ** P4 is always of type P4_ADVANCE. The function pointer points to
5155 ** sqlite3BtreeNext().
5157 ** If P5 is positive and the jump is taken, then event counter
5158 ** number P5-1 in the prepared statement is incremented.
5160 ** See also: Prev
5162 /* Opcode: Prev P1 P2 P3 P4 P5
5164 ** Back up cursor P1 so that it points to the previous key/data pair in its
5165 ** table or index. If there is no previous key/value pairs then fall through
5166 ** to the following instruction. But if the cursor backup was successful,
5167 ** jump immediately to P2.
5170 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5171 ** OP_Last opcode used to position the cursor. Prev is not allowed
5172 ** to follow SeekGT, SeekGE, or OP_Rewind.
5174 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
5175 ** not open then the behavior is undefined.
5177 ** The P3 value is a hint to the btree implementation. If P3==1, that
5178 ** means P1 is an SQL index and that this instruction could have been
5179 ** omitted if that index had been unique. P3 is usually 0. P3 is
5180 ** always either 0 or 1.
5182 ** P4 is always of type P4_ADVANCE. The function pointer points to
5183 ** sqlite3BtreePrevious().
5185 ** If P5 is positive and the jump is taken, then event counter
5186 ** number P5-1 in the prepared statement is incremented.
5188 /* Opcode: SorterNext P1 P2 * * P5
5190 ** This opcode works just like OP_Next except that P1 must be a
5191 ** sorter object for which the OP_SorterSort opcode has been
5192 ** invoked. This opcode advances the cursor to the next sorted
5193 ** record, or jumps to P2 if there are no more sorted records.
5195 case OP_SorterNext: { /* jump */
5196 VdbeCursor *pC;
5198 pC = p->apCsr[pOp->p1];
5199 assert( isSorter(pC) );
5200 rc = sqlite3VdbeSorterNext(db, pC);
5201 goto next_tail;
5202 case OP_Prev: /* jump */
5203 case OP_Next: /* jump */
5204 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5205 assert( pOp->p5<ArraySize(p->aCounter) );
5206 pC = p->apCsr[pOp->p1];
5207 assert( pC!=0 );
5208 assert( pC->deferredMoveto==0 );
5209 assert( pC->eCurType==CURTYPE_BTREE );
5210 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5211 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5213 /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
5214 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5215 assert( pOp->opcode!=OP_Next
5216 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5217 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
5218 || pC->seekOp==OP_NullRow);
5219 assert( pOp->opcode!=OP_Prev
5220 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5221 || pC->seekOp==OP_Last
5222 || pC->seekOp==OP_NullRow);
5224 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5225 next_tail:
5226 pC->cacheStatus = CACHE_STALE;
5227 VdbeBranchTaken(rc==SQLITE_OK,2);
5228 if( rc==SQLITE_OK ){
5229 pC->nullRow = 0;
5230 p->aCounter[pOp->p5]++;
5231 #ifdef SQLITE_TEST
5232 sqlite3_search_count++;
5233 #endif
5234 goto jump_to_p2_and_check_for_interrupt;
5236 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5237 rc = SQLITE_OK;
5238 pC->nullRow = 1;
5239 goto check_for_interrupt;
5242 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5243 ** Synopsis: key=r[P2]
5245 ** Register P2 holds an SQL index key made using the
5246 ** MakeRecord instructions. This opcode writes that key
5247 ** into the index P1. Data for the entry is nil.
5249 ** If P4 is not zero, then it is the number of values in the unpacked
5250 ** key of reg(P2). In that case, P3 is the index of the first register
5251 ** for the unpacked key. The availability of the unpacked key can sometimes
5252 ** be an optimization.
5254 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5255 ** that this insert is likely to be an append.
5257 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5258 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
5259 ** then the change counter is unchanged.
5261 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5262 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5263 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5264 ** seeks on the cursor or if the most recent seek used a key equivalent
5265 ** to P2.
5267 ** This instruction only works for indices. The equivalent instruction
5268 ** for tables is OP_Insert.
5270 /* Opcode: SorterInsert P1 P2 * * *
5271 ** Synopsis: key=r[P2]
5273 ** Register P2 holds an SQL index key made using the
5274 ** MakeRecord instructions. This opcode writes that key
5275 ** into the sorter P1. Data for the entry is nil.
5277 case OP_SorterInsert: /* in2 */
5278 case OP_IdxInsert: { /* in2 */
5279 VdbeCursor *pC;
5280 BtreePayload x;
5282 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5283 pC = p->apCsr[pOp->p1];
5284 sqlite3VdbeIncrWriteCounter(p, pC);
5285 assert( pC!=0 );
5286 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
5287 pIn2 = &aMem[pOp->p2];
5288 assert( pIn2->flags & MEM_Blob );
5289 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5290 assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
5291 assert( pC->isTable==0 );
5292 rc = ExpandBlob(pIn2);
5293 if( rc ) goto abort_due_to_error;
5294 if( pOp->opcode==OP_SorterInsert ){
5295 rc = sqlite3VdbeSorterWrite(pC, pIn2);
5296 }else{
5297 x.nKey = pIn2->n;
5298 x.pKey = pIn2->z;
5299 x.aMem = aMem + pOp->p3;
5300 x.nMem = (u16)pOp->p4.i;
5301 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5302 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
5303 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
5305 assert( pC->deferredMoveto==0 );
5306 pC->cacheStatus = CACHE_STALE;
5308 if( rc) goto abort_due_to_error;
5309 break;
5312 /* Opcode: IdxDelete P1 P2 P3 * *
5313 ** Synopsis: key=r[P2@P3]
5315 ** The content of P3 registers starting at register P2 form
5316 ** an unpacked index key. This opcode removes that entry from the
5317 ** index opened by cursor P1.
5319 case OP_IdxDelete: {
5320 VdbeCursor *pC;
5321 BtCursor *pCrsr;
5322 int res;
5323 UnpackedRecord r;
5325 assert( pOp->p3>0 );
5326 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
5327 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5328 pC = p->apCsr[pOp->p1];
5329 assert( pC!=0 );
5330 assert( pC->eCurType==CURTYPE_BTREE );
5331 sqlite3VdbeIncrWriteCounter(p, pC);
5332 pCrsr = pC->uc.pCursor;
5333 assert( pCrsr!=0 );
5334 assert( pOp->p5==0 );
5335 r.pKeyInfo = pC->pKeyInfo;
5336 r.nField = (u16)pOp->p3;
5337 r.default_rc = 0;
5338 r.aMem = &aMem[pOp->p2];
5339 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
5340 if( rc ) goto abort_due_to_error;
5341 if( res==0 ){
5342 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
5343 if( rc ) goto abort_due_to_error;
5345 assert( pC->deferredMoveto==0 );
5346 pC->cacheStatus = CACHE_STALE;
5347 pC->seekResult = 0;
5348 break;
5351 /* Opcode: DeferredSeek P1 * P3 P4 *
5352 ** Synopsis: Move P3 to P1.rowid if needed
5354 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5355 ** table. This opcode does a deferred seek of the P3 table cursor
5356 ** to the row that corresponds to the current row of P1.
5358 ** This is a deferred seek. Nothing actually happens until
5359 ** the cursor is used to read a record. That way, if no reads
5360 ** occur, no unnecessary I/O happens.
5362 ** P4 may be an array of integers (type P4_INTARRAY) containing
5363 ** one entry for each column in the P3 table. If array entry a(i)
5364 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5365 ** equivalent to performing the deferred seek and then reading column i
5366 ** from P1. This information is stored in P3 and used to redirect
5367 ** reads against P3 over to P1, thus possibly avoiding the need to
5368 ** seek and read cursor P3.
5370 /* Opcode: IdxRowid P1 P2 * * *
5371 ** Synopsis: r[P2]=rowid
5373 ** Write into register P2 an integer which is the last entry in the record at
5374 ** the end of the index key pointed to by cursor P1. This integer should be
5375 ** the rowid of the table entry to which this index entry points.
5377 ** See also: Rowid, MakeRecord.
5379 case OP_DeferredSeek:
5380 case OP_IdxRowid: { /* out2 */
5381 VdbeCursor *pC; /* The P1 index cursor */
5382 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
5383 i64 rowid; /* Rowid that P1 current points to */
5385 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5386 pC = p->apCsr[pOp->p1];
5387 assert( pC!=0 );
5388 assert( pC->eCurType==CURTYPE_BTREE );
5389 assert( pC->uc.pCursor!=0 );
5390 assert( pC->isTable==0 );
5391 assert( pC->deferredMoveto==0 );
5392 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
5394 /* The IdxRowid and Seek opcodes are combined because of the commonality
5395 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5396 rc = sqlite3VdbeCursorRestore(pC);
5398 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5399 ** out from under the cursor. That will never happens for an IdxRowid
5400 ** or Seek opcode */
5401 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
5403 if( !pC->nullRow ){
5404 rowid = 0; /* Not needed. Only used to silence a warning. */
5405 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
5406 if( rc!=SQLITE_OK ){
5407 goto abort_due_to_error;
5409 if( pOp->opcode==OP_DeferredSeek ){
5410 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
5411 pTabCur = p->apCsr[pOp->p3];
5412 assert( pTabCur!=0 );
5413 assert( pTabCur->eCurType==CURTYPE_BTREE );
5414 assert( pTabCur->uc.pCursor!=0 );
5415 assert( pTabCur->isTable );
5416 pTabCur->nullRow = 0;
5417 pTabCur->movetoTarget = rowid;
5418 pTabCur->deferredMoveto = 1;
5419 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
5420 pTabCur->aAltMap = pOp->p4.ai;
5421 pTabCur->pAltCursor = pC;
5422 }else{
5423 pOut = out2Prerelease(p, pOp);
5424 pOut->u.i = rowid;
5426 }else{
5427 assert( pOp->opcode==OP_IdxRowid );
5428 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
5430 break;
5433 /* Opcode: IdxGE P1 P2 P3 P4 P5
5434 ** Synopsis: key=r[P3@P4]
5436 ** The P4 register values beginning with P3 form an unpacked index
5437 ** key that omits the PRIMARY KEY. Compare this key value against the index
5438 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5439 ** fields at the end.
5441 ** If the P1 index entry is greater than or equal to the key value
5442 ** then jump to P2. Otherwise fall through to the next instruction.
5444 /* Opcode: IdxGT P1 P2 P3 P4 P5
5445 ** Synopsis: key=r[P3@P4]
5447 ** The P4 register values beginning with P3 form an unpacked index
5448 ** key that omits the PRIMARY KEY. Compare this key value against the index
5449 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5450 ** fields at the end.
5452 ** If the P1 index entry is greater than the key value
5453 ** then jump to P2. Otherwise fall through to the next instruction.
5455 /* Opcode: IdxLT P1 P2 P3 P4 P5
5456 ** Synopsis: key=r[P3@P4]
5458 ** The P4 register values beginning with P3 form an unpacked index
5459 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5460 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5461 ** ROWID on the P1 index.
5463 ** If the P1 index entry is less than the key value then jump to P2.
5464 ** Otherwise fall through to the next instruction.
5466 /* Opcode: IdxLE P1 P2 P3 P4 P5
5467 ** Synopsis: key=r[P3@P4]
5469 ** The P4 register values beginning with P3 form an unpacked index
5470 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5471 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5472 ** ROWID on the P1 index.
5474 ** If the P1 index entry is less than or equal to the key value then jump
5475 ** to P2. Otherwise fall through to the next instruction.
5477 case OP_IdxLE: /* jump */
5478 case OP_IdxGT: /* jump */
5479 case OP_IdxLT: /* jump */
5480 case OP_IdxGE: { /* jump */
5481 VdbeCursor *pC;
5482 int res;
5483 UnpackedRecord r;
5485 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5486 pC = p->apCsr[pOp->p1];
5487 assert( pC!=0 );
5488 assert( pC->isOrdered );
5489 assert( pC->eCurType==CURTYPE_BTREE );
5490 assert( pC->uc.pCursor!=0);
5491 assert( pC->deferredMoveto==0 );
5492 assert( pOp->p5==0 || pOp->p5==1 );
5493 assert( pOp->p4type==P4_INT32 );
5494 r.pKeyInfo = pC->pKeyInfo;
5495 r.nField = (u16)pOp->p4.i;
5496 if( pOp->opcode<OP_IdxLT ){
5497 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
5498 r.default_rc = -1;
5499 }else{
5500 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
5501 r.default_rc = 0;
5503 r.aMem = &aMem[pOp->p3];
5504 #ifdef SQLITE_DEBUG
5505 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
5506 #endif
5507 res = 0; /* Not needed. Only used to silence a warning. */
5508 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5509 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
5510 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
5511 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
5512 res = -res;
5513 }else{
5514 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
5515 res++;
5517 VdbeBranchTaken(res>0,2);
5518 if( rc ) goto abort_due_to_error;
5519 if( res>0 ) goto jump_to_p2;
5520 break;
5523 /* Opcode: Destroy P1 P2 P3 * *
5525 ** Delete an entire database table or index whose root page in the database
5526 ** file is given by P1.
5528 ** The table being destroyed is in the main database file if P3==0. If
5529 ** P3==1 then the table to be clear is in the auxiliary database file
5530 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5532 ** If AUTOVACUUM is enabled then it is possible that another root page
5533 ** might be moved into the newly deleted root page in order to keep all
5534 ** root pages contiguous at the beginning of the database. The former
5535 ** value of the root page that moved - its value before the move occurred -
5536 ** is stored in register P2. If no page movement was required (because the
5537 ** table being dropped was already the last one in the database) then a
5538 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
5539 ** is stored in register P2.
5541 ** This opcode throws an error if there are any active reader VMs when
5542 ** it is invoked. This is done to avoid the difficulty associated with
5543 ** updating existing cursors when a root page is moved in an AUTOVACUUM
5544 ** database. This error is thrown even if the database is not an AUTOVACUUM
5545 ** db in order to avoid introducing an incompatibility between autovacuum
5546 ** and non-autovacuum modes.
5548 ** See also: Clear
5550 case OP_Destroy: { /* out2 */
5551 int iMoved;
5552 int iDb;
5554 sqlite3VdbeIncrWriteCounter(p, 0);
5555 assert( p->readOnly==0 );
5556 assert( pOp->p1>1 );
5557 pOut = out2Prerelease(p, pOp);
5558 pOut->flags = MEM_Null;
5559 if( db->nVdbeRead > db->nVDestroy+1 ){
5560 rc = SQLITE_LOCKED;
5561 p->errorAction = OE_Abort;
5562 goto abort_due_to_error;
5563 }else{
5564 iDb = pOp->p3;
5565 assert( DbMaskTest(p->btreeMask, iDb) );
5566 iMoved = 0; /* Not needed. Only to silence a warning. */
5567 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
5568 pOut->flags = MEM_Int;
5569 pOut->u.i = iMoved;
5570 if( rc ) goto abort_due_to_error;
5571 #ifndef SQLITE_OMIT_AUTOVACUUM
5572 if( iMoved!=0 ){
5573 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
5574 /* All OP_Destroy operations occur on the same btree */
5575 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
5576 resetSchemaOnFault = iDb+1;
5578 #endif
5580 break;
5583 /* Opcode: Clear P1 P2 P3
5585 ** Delete all contents of the database table or index whose root page
5586 ** in the database file is given by P1. But, unlike Destroy, do not
5587 ** remove the table or index from the database file.
5589 ** The table being clear is in the main database file if P2==0. If
5590 ** P2==1 then the table to be clear is in the auxiliary database file
5591 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5593 ** If the P3 value is non-zero, then the table referred to must be an
5594 ** intkey table (an SQL table, not an index). In this case the row change
5595 ** count is incremented by the number of rows in the table being cleared.
5596 ** If P3 is greater than zero, then the value stored in register P3 is
5597 ** also incremented by the number of rows in the table being cleared.
5599 ** See also: Destroy
5601 case OP_Clear: {
5602 int nChange;
5604 sqlite3VdbeIncrWriteCounter(p, 0);
5605 nChange = 0;
5606 assert( p->readOnly==0 );
5607 assert( DbMaskTest(p->btreeMask, pOp->p2) );
5608 rc = sqlite3BtreeClearTable(
5609 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
5611 if( pOp->p3 ){
5612 p->nChange += nChange;
5613 if( pOp->p3>0 ){
5614 assert( memIsValid(&aMem[pOp->p3]) );
5615 memAboutToChange(p, &aMem[pOp->p3]);
5616 aMem[pOp->p3].u.i += nChange;
5619 if( rc ) goto abort_due_to_error;
5620 break;
5623 /* Opcode: ResetSorter P1 * * * *
5625 ** Delete all contents from the ephemeral table or sorter
5626 ** that is open on cursor P1.
5628 ** This opcode only works for cursors used for sorting and
5629 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5631 case OP_ResetSorter: {
5632 VdbeCursor *pC;
5634 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5635 pC = p->apCsr[pOp->p1];
5636 assert( pC!=0 );
5637 if( isSorter(pC) ){
5638 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
5639 }else{
5640 assert( pC->eCurType==CURTYPE_BTREE );
5641 assert( pC->isEphemeral );
5642 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
5643 if( rc ) goto abort_due_to_error;
5645 break;
5648 /* Opcode: CreateBtree P1 P2 P3 * *
5649 ** Synopsis: r[P2]=root iDb=P1 flags=P3
5651 ** Allocate a new b-tree in the main database file if P1==0 or in the
5652 ** TEMP database file if P1==1 or in an attached database if
5653 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
5654 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
5655 ** The root page number of the new b-tree is stored in register P2.
5657 case OP_CreateBtree: { /* out2 */
5658 int pgno;
5659 Db *pDb;
5661 sqlite3VdbeIncrWriteCounter(p, 0);
5662 pOut = out2Prerelease(p, pOp);
5663 pgno = 0;
5664 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
5665 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5666 assert( DbMaskTest(p->btreeMask, pOp->p1) );
5667 assert( p->readOnly==0 );
5668 pDb = &db->aDb[pOp->p1];
5669 assert( pDb->pBt!=0 );
5670 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
5671 if( rc ) goto abort_due_to_error;
5672 pOut->u.i = pgno;
5673 break;
5676 /* Opcode: SqlExec * * * P4 *
5678 ** Run the SQL statement or statements specified in the P4 string.
5680 case OP_SqlExec: {
5681 sqlite3VdbeIncrWriteCounter(p, 0);
5682 db->nSqlExec++;
5683 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
5684 db->nSqlExec--;
5685 if( rc ) goto abort_due_to_error;
5686 break;
5689 /* Opcode: ParseSchema P1 * * P4 *
5691 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5692 ** that match the WHERE clause P4.
5694 ** This opcode invokes the parser to create a new virtual machine,
5695 ** then runs the new virtual machine. It is thus a re-entrant opcode.
5697 case OP_ParseSchema: {
5698 int iDb;
5699 const char *zMaster;
5700 char *zSql;
5701 InitData initData;
5703 /* Any prepared statement that invokes this opcode will hold mutexes
5704 ** on every btree. This is a prerequisite for invoking
5705 ** sqlite3InitCallback().
5707 #ifdef SQLITE_DEBUG
5708 for(iDb=0; iDb<db->nDb; iDb++){
5709 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
5711 #endif
5713 iDb = pOp->p1;
5714 assert( iDb>=0 && iDb<db->nDb );
5715 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
5716 /* Used to be a conditional */ {
5717 zMaster = MASTER_NAME;
5718 initData.db = db;
5719 initData.iDb = pOp->p1;
5720 initData.pzErrMsg = &p->zErrMsg;
5721 zSql = sqlite3MPrintf(db,
5722 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5723 db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
5724 if( zSql==0 ){
5725 rc = SQLITE_NOMEM_BKPT;
5726 }else{
5727 assert( db->init.busy==0 );
5728 db->init.busy = 1;
5729 initData.rc = SQLITE_OK;
5730 assert( !db->mallocFailed );
5731 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
5732 if( rc==SQLITE_OK ) rc = initData.rc;
5733 sqlite3DbFreeNN(db, zSql);
5734 db->init.busy = 0;
5737 if( rc ){
5738 sqlite3ResetAllSchemasOfConnection(db);
5739 if( rc==SQLITE_NOMEM ){
5740 goto no_mem;
5742 goto abort_due_to_error;
5744 break;
5747 #if !defined(SQLITE_OMIT_ANALYZE)
5748 /* Opcode: LoadAnalysis P1 * * * *
5750 ** Read the sqlite_stat1 table for database P1 and load the content
5751 ** of that table into the internal index hash table. This will cause
5752 ** the analysis to be used when preparing all subsequent queries.
5754 case OP_LoadAnalysis: {
5755 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5756 rc = sqlite3AnalysisLoad(db, pOp->p1);
5757 if( rc ) goto abort_due_to_error;
5758 break;
5760 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5762 /* Opcode: DropTable P1 * * P4 *
5764 ** Remove the internal (in-memory) data structures that describe
5765 ** the table named P4 in database P1. This is called after a table
5766 ** is dropped from disk (using the Destroy opcode) in order to keep
5767 ** the internal representation of the
5768 ** schema consistent with what is on disk.
5770 case OP_DropTable: {
5771 sqlite3VdbeIncrWriteCounter(p, 0);
5772 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
5773 break;
5776 /* Opcode: DropIndex P1 * * P4 *
5778 ** Remove the internal (in-memory) data structures that describe
5779 ** the index named P4 in database P1. This is called after an index
5780 ** is dropped from disk (using the Destroy opcode)
5781 ** in order to keep the internal representation of the
5782 ** schema consistent with what is on disk.
5784 case OP_DropIndex: {
5785 sqlite3VdbeIncrWriteCounter(p, 0);
5786 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
5787 break;
5790 /* Opcode: DropTrigger P1 * * P4 *
5792 ** Remove the internal (in-memory) data structures that describe
5793 ** the trigger named P4 in database P1. This is called after a trigger
5794 ** is dropped from disk (using the Destroy opcode) in order to keep
5795 ** the internal representation of the
5796 ** schema consistent with what is on disk.
5798 case OP_DropTrigger: {
5799 sqlite3VdbeIncrWriteCounter(p, 0);
5800 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
5801 break;
5805 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5806 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
5808 ** Do an analysis of the currently open database. Store in
5809 ** register P1 the text of an error message describing any problems.
5810 ** If no problems are found, store a NULL in register P1.
5812 ** The register P3 contains one less than the maximum number of allowed errors.
5813 ** At most reg(P3) errors will be reported.
5814 ** In other words, the analysis stops as soon as reg(P1) errors are
5815 ** seen. Reg(P1) is updated with the number of errors remaining.
5817 ** The root page numbers of all tables in the database are integers
5818 ** stored in P4_INTARRAY argument.
5820 ** If P5 is not zero, the check is done on the auxiliary database
5821 ** file, not the main database file.
5823 ** This opcode is used to implement the integrity_check pragma.
5825 case OP_IntegrityCk: {
5826 int nRoot; /* Number of tables to check. (Number of root pages.) */
5827 int *aRoot; /* Array of rootpage numbers for tables to be checked */
5828 int nErr; /* Number of errors reported */
5829 char *z; /* Text of the error report */
5830 Mem *pnErr; /* Register keeping track of errors remaining */
5832 assert( p->bIsReader );
5833 nRoot = pOp->p2;
5834 aRoot = pOp->p4.ai;
5835 assert( nRoot>0 );
5836 assert( aRoot[0]==nRoot );
5837 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
5838 pnErr = &aMem[pOp->p3];
5839 assert( (pnErr->flags & MEM_Int)!=0 );
5840 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
5841 pIn1 = &aMem[pOp->p1];
5842 assert( pOp->p5<db->nDb );
5843 assert( DbMaskTest(p->btreeMask, pOp->p5) );
5844 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
5845 (int)pnErr->u.i+1, &nErr);
5846 sqlite3VdbeMemSetNull(pIn1);
5847 if( nErr==0 ){
5848 assert( z==0 );
5849 }else if( z==0 ){
5850 goto no_mem;
5851 }else{
5852 pnErr->u.i -= nErr-1;
5853 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
5855 UPDATE_MAX_BLOBSIZE(pIn1);
5856 sqlite3VdbeChangeEncoding(pIn1, encoding);
5857 break;
5859 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5861 /* Opcode: RowSetAdd P1 P2 * * *
5862 ** Synopsis: rowset(P1)=r[P2]
5864 ** Insert the integer value held by register P2 into a RowSet object
5865 ** held in register P1.
5867 ** An assertion fails if P2 is not an integer.
5869 case OP_RowSetAdd: { /* in1, in2 */
5870 pIn1 = &aMem[pOp->p1];
5871 pIn2 = &aMem[pOp->p2];
5872 assert( (pIn2->flags & MEM_Int)!=0 );
5873 if( (pIn1->flags & MEM_RowSet)==0 ){
5874 sqlite3VdbeMemSetRowSet(pIn1);
5875 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5877 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
5878 break;
5881 /* Opcode: RowSetRead P1 P2 P3 * *
5882 ** Synopsis: r[P3]=rowset(P1)
5884 ** Extract the smallest value from the RowSet object in P1
5885 ** and put that value into register P3.
5886 ** Or, if RowSet object P1 is initially empty, leave P3
5887 ** unchanged and jump to instruction P2.
5889 case OP_RowSetRead: { /* jump, in1, out3 */
5890 i64 val;
5892 pIn1 = &aMem[pOp->p1];
5893 if( (pIn1->flags & MEM_RowSet)==0
5894 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
5896 /* The boolean index is empty */
5897 sqlite3VdbeMemSetNull(pIn1);
5898 VdbeBranchTaken(1,2);
5899 goto jump_to_p2_and_check_for_interrupt;
5900 }else{
5901 /* A value was pulled from the index */
5902 VdbeBranchTaken(0,2);
5903 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
5905 goto check_for_interrupt;
5908 /* Opcode: RowSetTest P1 P2 P3 P4
5909 ** Synopsis: if r[P3] in rowset(P1) goto P2
5911 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5912 ** contains a RowSet object and that RowSet object contains
5913 ** the value held in P3, jump to register P2. Otherwise, insert the
5914 ** integer in P3 into the RowSet and continue on to the
5915 ** next opcode.
5917 ** The RowSet object is optimized for the case where sets of integers
5918 ** are inserted in distinct phases, which each set contains no duplicates.
5919 ** Each set is identified by a unique P4 value. The first set
5920 ** must have P4==0, the final set must have P4==-1, and for all other sets
5921 ** must have P4>0.
5923 ** This allows optimizations: (a) when P4==0 there is no need to test
5924 ** the RowSet object for P3, as it is guaranteed not to contain it,
5925 ** (b) when P4==-1 there is no need to insert the value, as it will
5926 ** never be tested for, and (c) when a value that is part of set X is
5927 ** inserted, there is no need to search to see if the same value was
5928 ** previously inserted as part of set X (only if it was previously
5929 ** inserted as part of some other set).
5931 case OP_RowSetTest: { /* jump, in1, in3 */
5932 int iSet;
5933 int exists;
5935 pIn1 = &aMem[pOp->p1];
5936 pIn3 = &aMem[pOp->p3];
5937 iSet = pOp->p4.i;
5938 assert( pIn3->flags&MEM_Int );
5940 /* If there is anything other than a rowset object in memory cell P1,
5941 ** delete it now and initialize P1 with an empty rowset
5943 if( (pIn1->flags & MEM_RowSet)==0 ){
5944 sqlite3VdbeMemSetRowSet(pIn1);
5945 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5948 assert( pOp->p4type==P4_INT32 );
5949 assert( iSet==-1 || iSet>=0 );
5950 if( iSet ){
5951 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
5952 VdbeBranchTaken(exists!=0,2);
5953 if( exists ) goto jump_to_p2;
5955 if( iSet>=0 ){
5956 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
5958 break;
5962 #ifndef SQLITE_OMIT_TRIGGER
5964 /* Opcode: Program P1 P2 P3 P4 P5
5966 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5968 ** P1 contains the address of the memory cell that contains the first memory
5969 ** cell in an array of values used as arguments to the sub-program. P2
5970 ** contains the address to jump to if the sub-program throws an IGNORE
5971 ** exception using the RAISE() function. Register P3 contains the address
5972 ** of a memory cell in this (the parent) VM that is used to allocate the
5973 ** memory required by the sub-vdbe at runtime.
5975 ** P4 is a pointer to the VM containing the trigger program.
5977 ** If P5 is non-zero, then recursive program invocation is enabled.
5979 case OP_Program: { /* jump */
5980 int nMem; /* Number of memory registers for sub-program */
5981 int nByte; /* Bytes of runtime space required for sub-program */
5982 Mem *pRt; /* Register to allocate runtime space */
5983 Mem *pMem; /* Used to iterate through memory cells */
5984 Mem *pEnd; /* Last memory cell in new array */
5985 VdbeFrame *pFrame; /* New vdbe frame to execute in */
5986 SubProgram *pProgram; /* Sub-program to execute */
5987 void *t; /* Token identifying trigger */
5989 pProgram = pOp->p4.pProgram;
5990 pRt = &aMem[pOp->p3];
5991 assert( pProgram->nOp>0 );
5993 /* If the p5 flag is clear, then recursive invocation of triggers is
5994 ** disabled for backwards compatibility (p5 is set if this sub-program
5995 ** is really a trigger, not a foreign key action, and the flag set
5996 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
5998 ** It is recursive invocation of triggers, at the SQL level, that is
5999 ** disabled. In some cases a single trigger may generate more than one
6000 ** SubProgram (if the trigger may be executed with more than one different
6001 ** ON CONFLICT algorithm). SubProgram structures associated with a
6002 ** single trigger all have the same value for the SubProgram.token
6003 ** variable. */
6004 if( pOp->p5 ){
6005 t = pProgram->token;
6006 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
6007 if( pFrame ) break;
6010 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
6011 rc = SQLITE_ERROR;
6012 sqlite3VdbeError(p, "too many levels of trigger recursion");
6013 goto abort_due_to_error;
6016 /* Register pRt is used to store the memory required to save the state
6017 ** of the current program, and the memory required at runtime to execute
6018 ** the trigger program. If this trigger has been fired before, then pRt
6019 ** is already allocated. Otherwise, it must be initialized. */
6020 if( (pRt->flags&MEM_Frame)==0 ){
6021 /* SubProgram.nMem is set to the number of memory cells used by the
6022 ** program stored in SubProgram.aOp. As well as these, one memory
6023 ** cell is required for each cursor used by the program. Set local
6024 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
6026 nMem = pProgram->nMem + pProgram->nCsr;
6027 assert( nMem>0 );
6028 if( pProgram->nCsr==0 ) nMem++;
6029 nByte = ROUND8(sizeof(VdbeFrame))
6030 + nMem * sizeof(Mem)
6031 + pProgram->nCsr * sizeof(VdbeCursor*)
6032 + (pProgram->nOp + 7)/8;
6033 pFrame = sqlite3DbMallocZero(db, nByte);
6034 if( !pFrame ){
6035 goto no_mem;
6037 sqlite3VdbeMemRelease(pRt);
6038 pRt->flags = MEM_Frame;
6039 pRt->u.pFrame = pFrame;
6041 pFrame->v = p;
6042 pFrame->nChildMem = nMem;
6043 pFrame->nChildCsr = pProgram->nCsr;
6044 pFrame->pc = (int)(pOp - aOp);
6045 pFrame->aMem = p->aMem;
6046 pFrame->nMem = p->nMem;
6047 pFrame->apCsr = p->apCsr;
6048 pFrame->nCursor = p->nCursor;
6049 pFrame->aOp = p->aOp;
6050 pFrame->nOp = p->nOp;
6051 pFrame->token = pProgram->token;
6052 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6053 pFrame->anExec = p->anExec;
6054 #endif
6056 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
6057 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
6058 pMem->flags = MEM_Undefined;
6059 pMem->db = db;
6061 }else{
6062 pFrame = pRt->u.pFrame;
6063 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
6064 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
6065 assert( pProgram->nCsr==pFrame->nChildCsr );
6066 assert( (int)(pOp - aOp)==pFrame->pc );
6069 p->nFrame++;
6070 pFrame->pParent = p->pFrame;
6071 pFrame->lastRowid = db->lastRowid;
6072 pFrame->nChange = p->nChange;
6073 pFrame->nDbChange = p->db->nChange;
6074 assert( pFrame->pAuxData==0 );
6075 pFrame->pAuxData = p->pAuxData;
6076 p->pAuxData = 0;
6077 p->nChange = 0;
6078 p->pFrame = pFrame;
6079 p->aMem = aMem = VdbeFrameMem(pFrame);
6080 p->nMem = pFrame->nChildMem;
6081 p->nCursor = (u16)pFrame->nChildCsr;
6082 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
6083 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
6084 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
6085 p->aOp = aOp = pProgram->aOp;
6086 p->nOp = pProgram->nOp;
6087 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6088 p->anExec = 0;
6089 #endif
6090 pOp = &aOp[-1];
6092 break;
6095 /* Opcode: Param P1 P2 * * *
6097 ** This opcode is only ever present in sub-programs called via the
6098 ** OP_Program instruction. Copy a value currently stored in a memory
6099 ** cell of the calling (parent) frame to cell P2 in the current frames
6100 ** address space. This is used by trigger programs to access the new.*
6101 ** and old.* values.
6103 ** The address of the cell in the parent frame is determined by adding
6104 ** the value of the P1 argument to the value of the P1 argument to the
6105 ** calling OP_Program instruction.
6107 case OP_Param: { /* out2 */
6108 VdbeFrame *pFrame;
6109 Mem *pIn;
6110 pOut = out2Prerelease(p, pOp);
6111 pFrame = p->pFrame;
6112 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
6113 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
6114 break;
6117 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6119 #ifndef SQLITE_OMIT_FOREIGN_KEY
6120 /* Opcode: FkCounter P1 P2 * * *
6121 ** Synopsis: fkctr[P1]+=P2
6123 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6124 ** If P1 is non-zero, the database constraint counter is incremented
6125 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6126 ** statement counter is incremented (immediate foreign key constraints).
6128 case OP_FkCounter: {
6129 if( db->flags & SQLITE_DeferFKs ){
6130 db->nDeferredImmCons += pOp->p2;
6131 }else if( pOp->p1 ){
6132 db->nDeferredCons += pOp->p2;
6133 }else{
6134 p->nFkConstraint += pOp->p2;
6136 break;
6139 /* Opcode: FkIfZero P1 P2 * * *
6140 ** Synopsis: if fkctr[P1]==0 goto P2
6142 ** This opcode tests if a foreign key constraint-counter is currently zero.
6143 ** If so, jump to instruction P2. Otherwise, fall through to the next
6144 ** instruction.
6146 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6147 ** is zero (the one that counts deferred constraint violations). If P1 is
6148 ** zero, the jump is taken if the statement constraint-counter is zero
6149 ** (immediate foreign key constraint violations).
6151 case OP_FkIfZero: { /* jump */
6152 if( pOp->p1 ){
6153 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6154 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6155 }else{
6156 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6157 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6159 break;
6161 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6163 #ifndef SQLITE_OMIT_AUTOINCREMENT
6164 /* Opcode: MemMax P1 P2 * * *
6165 ** Synopsis: r[P1]=max(r[P1],r[P2])
6167 ** P1 is a register in the root frame of this VM (the root frame is
6168 ** different from the current frame if this instruction is being executed
6169 ** within a sub-program). Set the value of register P1 to the maximum of
6170 ** its current value and the value in register P2.
6172 ** This instruction throws an error if the memory cell is not initially
6173 ** an integer.
6175 case OP_MemMax: { /* in2 */
6176 VdbeFrame *pFrame;
6177 if( p->pFrame ){
6178 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
6179 pIn1 = &pFrame->aMem[pOp->p1];
6180 }else{
6181 pIn1 = &aMem[pOp->p1];
6183 assert( memIsValid(pIn1) );
6184 sqlite3VdbeMemIntegerify(pIn1);
6185 pIn2 = &aMem[pOp->p2];
6186 sqlite3VdbeMemIntegerify(pIn2);
6187 if( pIn1->u.i<pIn2->u.i){
6188 pIn1->u.i = pIn2->u.i;
6190 break;
6192 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6194 /* Opcode: IfPos P1 P2 P3 * *
6195 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6197 ** Register P1 must contain an integer.
6198 ** If the value of register P1 is 1 or greater, subtract P3 from the
6199 ** value in P1 and jump to P2.
6201 ** If the initial value of register P1 is less than 1, then the
6202 ** value is unchanged and control passes through to the next instruction.
6204 case OP_IfPos: { /* jump, in1 */
6205 pIn1 = &aMem[pOp->p1];
6206 assert( pIn1->flags&MEM_Int );
6207 VdbeBranchTaken( pIn1->u.i>0, 2);
6208 if( pIn1->u.i>0 ){
6209 pIn1->u.i -= pOp->p3;
6210 goto jump_to_p2;
6212 break;
6215 /* Opcode: OffsetLimit P1 P2 P3 * *
6216 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6218 ** This opcode performs a commonly used computation associated with
6219 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
6220 ** holds the offset counter. The opcode computes the combined value
6221 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
6222 ** value computed is the total number of rows that will need to be
6223 ** visited in order to complete the query.
6225 ** If r[P3] is zero or negative, that means there is no OFFSET
6226 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6228 ** if r[P1] is zero or negative, that means there is no LIMIT
6229 ** and r[P2] is set to -1.
6231 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6233 case OP_OffsetLimit: { /* in1, out2, in3 */
6234 i64 x;
6235 pIn1 = &aMem[pOp->p1];
6236 pIn3 = &aMem[pOp->p3];
6237 pOut = out2Prerelease(p, pOp);
6238 assert( pIn1->flags & MEM_Int );
6239 assert( pIn3->flags & MEM_Int );
6240 x = pIn1->u.i;
6241 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
6242 /* If the LIMIT is less than or equal to zero, loop forever. This
6243 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
6244 ** also loop forever. This is undocumented. In fact, one could argue
6245 ** that the loop should terminate. But assuming 1 billion iterations
6246 ** per second (far exceeding the capabilities of any current hardware)
6247 ** it would take nearly 300 years to actually reach the limit. So
6248 ** looping forever is a reasonable approximation. */
6249 pOut->u.i = -1;
6250 }else{
6251 pOut->u.i = x;
6253 break;
6256 /* Opcode: IfNotZero P1 P2 * * *
6257 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6259 ** Register P1 must contain an integer. If the content of register P1 is
6260 ** initially greater than zero, then decrement the value in register P1.
6261 ** If it is non-zero (negative or positive) and then also jump to P2.
6262 ** If register P1 is initially zero, leave it unchanged and fall through.
6264 case OP_IfNotZero: { /* jump, in1 */
6265 pIn1 = &aMem[pOp->p1];
6266 assert( pIn1->flags&MEM_Int );
6267 VdbeBranchTaken(pIn1->u.i<0, 2);
6268 if( pIn1->u.i ){
6269 if( pIn1->u.i>0 ) pIn1->u.i--;
6270 goto jump_to_p2;
6272 break;
6275 /* Opcode: DecrJumpZero P1 P2 * * *
6276 ** Synopsis: if (--r[P1])==0 goto P2
6278 ** Register P1 must hold an integer. Decrement the value in P1
6279 ** and jump to P2 if the new value is exactly zero.
6281 case OP_DecrJumpZero: { /* jump, in1 */
6282 pIn1 = &aMem[pOp->p1];
6283 assert( pIn1->flags&MEM_Int );
6284 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
6285 VdbeBranchTaken(pIn1->u.i==0, 2);
6286 if( pIn1->u.i==0 ) goto jump_to_p2;
6287 break;
6291 /* Opcode: AggStep0 P1 P2 P3 P4 P5
6292 ** Synopsis: accum=r[P3] step(r[P2@P5])
6294 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
6295 ** aggregate. The function has P5 arguments. P4 is a pointer to the
6296 ** FuncDef structure that specifies the function. Register P3 is the
6297 ** accumulator.
6299 ** The P5 arguments are taken from register P2 and its
6300 ** successors.
6302 /* Opcode: AggStep P1 P2 P3 P4 P5
6303 ** Synopsis: accum=r[P3] step(r[P2@P5])
6305 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
6306 ** aggregate. The function has P5 arguments. P4 is a pointer to the
6307 ** FuncDef structure that specifies the function. Register P3 is the
6308 ** accumulator.
6310 ** The P5 arguments are taken from register P2 and its
6311 ** successors.
6313 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6314 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6315 ** the opcode is changed. In this way, the initialization of the
6316 ** sqlite3_context only happens once, instead of on each call to the
6317 ** step function.
6319 case OP_AggStep0: {
6320 int n;
6321 sqlite3_context *pCtx;
6323 assert( pOp->p4type==P4_FUNCDEF );
6324 n = pOp->p5;
6325 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6326 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
6327 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
6328 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
6329 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
6330 if( pCtx==0 ) goto no_mem;
6331 pCtx->pMem = 0;
6332 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
6333 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
6334 pCtx->pFunc = pOp->p4.pFunc;
6335 pCtx->iOp = (int)(pOp - aOp);
6336 pCtx->pVdbe = p;
6337 pCtx->skipFlag = 0;
6338 pCtx->isError = 0;
6339 pCtx->argc = n;
6340 pOp->p4type = P4_FUNCCTX;
6341 pOp->p4.pCtx = pCtx;
6342 pOp->opcode = OP_AggStep;
6343 /* Fall through into OP_AggStep */
6345 case OP_AggStep: {
6346 int i;
6347 sqlite3_context *pCtx;
6348 Mem *pMem;
6350 assert( pOp->p4type==P4_FUNCCTX );
6351 pCtx = pOp->p4.pCtx;
6352 pMem = &aMem[pOp->p3];
6354 /* If this function is inside of a trigger, the register array in aMem[]
6355 ** might change from one evaluation to the next. The next block of code
6356 ** checks to see if the register array has changed, and if so it
6357 ** reinitializes the relavant parts of the sqlite3_context object */
6358 if( pCtx->pMem != pMem ){
6359 pCtx->pMem = pMem;
6360 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
6363 #ifdef SQLITE_DEBUG
6364 for(i=0; i<pCtx->argc; i++){
6365 assert( memIsValid(pCtx->argv[i]) );
6366 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
6368 #endif
6370 pMem->n++;
6371 assert( pCtx->pOut->flags==MEM_Null );
6372 assert( pCtx->isError==0 );
6373 assert( pCtx->skipFlag==0 );
6374 #ifndef SQLITE_OMIT_WINDOWFUNC
6375 if( pOp->p1 ){
6376 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
6377 }else
6378 #endif
6379 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
6381 if( pCtx->isError ){
6382 if( pCtx->isError>0 ){
6383 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
6384 rc = pCtx->isError;
6386 if( pCtx->skipFlag ){
6387 assert( pOp[-1].opcode==OP_CollSeq );
6388 i = pOp[-1].p1;
6389 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
6390 pCtx->skipFlag = 0;
6392 sqlite3VdbeMemRelease(pCtx->pOut);
6393 pCtx->pOut->flags = MEM_Null;
6394 pCtx->isError = 0;
6395 if( rc ) goto abort_due_to_error;
6397 assert( pCtx->pOut->flags==MEM_Null );
6398 assert( pCtx->skipFlag==0 );
6399 break;
6402 /* Opcode: AggFinal P1 P2 P3 P4 *
6403 ** Synopsis: accum=r[P1] N=P2
6405 ** P1 is the memory location that is the accumulator for an aggregate
6406 ** or window function. If P3 is zero, then execute the finalizer function
6407 ** for an aggregate and store the result in P1. Or, if P3 is non-zero,
6408 ** invoke the xValue() function and store the result in register P3.
6410 ** P2 is the number of arguments that the step function takes and
6411 ** P4 is a pointer to the FuncDef for this function. The P2
6412 ** argument is not used by this opcode. It is only there to disambiguate
6413 ** functions that can take varying numbers of arguments. The
6414 ** P4 argument is only needed for the degenerate case where
6415 ** the step function was not previously called.
6417 case OP_AggFinal: {
6418 Mem *pMem;
6419 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
6420 pMem = &aMem[pOp->p1];
6421 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
6422 #ifndef SQLITE_OMIT_WINDOWFUNC
6423 if( pOp->p3 ){
6424 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
6425 pMem = &aMem[pOp->p3];
6426 }else
6427 #endif
6428 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
6430 if( rc ){
6431 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
6432 goto abort_due_to_error;
6434 sqlite3VdbeChangeEncoding(pMem, encoding);
6435 UPDATE_MAX_BLOBSIZE(pMem);
6436 if( sqlite3VdbeMemTooBig(pMem) ){
6437 goto too_big;
6439 break;
6442 #ifndef SQLITE_OMIT_WAL
6443 /* Opcode: Checkpoint P1 P2 P3 * *
6445 ** Checkpoint database P1. This is a no-op if P1 is not currently in
6446 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
6447 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
6448 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
6449 ** WAL after the checkpoint into mem[P3+1] and the number of pages
6450 ** in the WAL that have been checkpointed after the checkpoint
6451 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
6452 ** mem[P3+2] are initialized to -1.
6454 case OP_Checkpoint: {
6455 int i; /* Loop counter */
6456 int aRes[3]; /* Results */
6457 Mem *pMem; /* Write results here */
6459 assert( p->readOnly==0 );
6460 aRes[0] = 0;
6461 aRes[1] = aRes[2] = -1;
6462 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
6463 || pOp->p2==SQLITE_CHECKPOINT_FULL
6464 || pOp->p2==SQLITE_CHECKPOINT_RESTART
6465 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
6467 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
6468 if( rc ){
6469 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
6470 rc = SQLITE_OK;
6471 aRes[0] = 1;
6473 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
6474 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
6476 break;
6478 #endif
6480 #ifndef SQLITE_OMIT_PRAGMA
6481 /* Opcode: JournalMode P1 P2 P3 * *
6483 ** Change the journal mode of database P1 to P3. P3 must be one of the
6484 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
6485 ** modes (delete, truncate, persist, off and memory), this is a simple
6486 ** operation. No IO is required.
6488 ** If changing into or out of WAL mode the procedure is more complicated.
6490 ** Write a string containing the final journal-mode to register P2.
6492 case OP_JournalMode: { /* out2 */
6493 Btree *pBt; /* Btree to change journal mode of */
6494 Pager *pPager; /* Pager associated with pBt */
6495 int eNew; /* New journal mode */
6496 int eOld; /* The old journal mode */
6497 #ifndef SQLITE_OMIT_WAL
6498 const char *zFilename; /* Name of database file for pPager */
6499 #endif
6501 pOut = out2Prerelease(p, pOp);
6502 eNew = pOp->p3;
6503 assert( eNew==PAGER_JOURNALMODE_DELETE
6504 || eNew==PAGER_JOURNALMODE_TRUNCATE
6505 || eNew==PAGER_JOURNALMODE_PERSIST
6506 || eNew==PAGER_JOURNALMODE_OFF
6507 || eNew==PAGER_JOURNALMODE_MEMORY
6508 || eNew==PAGER_JOURNALMODE_WAL
6509 || eNew==PAGER_JOURNALMODE_QUERY
6511 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6512 assert( p->readOnly==0 );
6514 pBt = db->aDb[pOp->p1].pBt;
6515 pPager = sqlite3BtreePager(pBt);
6516 eOld = sqlite3PagerGetJournalMode(pPager);
6517 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
6518 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
6520 #ifndef SQLITE_OMIT_WAL
6521 zFilename = sqlite3PagerFilename(pPager, 1);
6523 /* Do not allow a transition to journal_mode=WAL for a database
6524 ** in temporary storage or if the VFS does not support shared memory
6526 if( eNew==PAGER_JOURNALMODE_WAL
6527 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
6528 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
6530 eNew = eOld;
6533 if( (eNew!=eOld)
6534 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
6536 if( !db->autoCommit || db->nVdbeRead>1 ){
6537 rc = SQLITE_ERROR;
6538 sqlite3VdbeError(p,
6539 "cannot change %s wal mode from within a transaction",
6540 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
6542 goto abort_due_to_error;
6543 }else{
6545 if( eOld==PAGER_JOURNALMODE_WAL ){
6546 /* If leaving WAL mode, close the log file. If successful, the call
6547 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
6548 ** file. An EXCLUSIVE lock may still be held on the database file
6549 ** after a successful return.
6551 rc = sqlite3PagerCloseWal(pPager, db);
6552 if( rc==SQLITE_OK ){
6553 sqlite3PagerSetJournalMode(pPager, eNew);
6555 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
6556 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
6557 ** as an intermediate */
6558 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
6561 /* Open a transaction on the database file. Regardless of the journal
6562 ** mode, this transaction always uses a rollback journal.
6564 assert( sqlite3BtreeIsInTrans(pBt)==0 );
6565 if( rc==SQLITE_OK ){
6566 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
6570 #endif /* ifndef SQLITE_OMIT_WAL */
6572 if( rc ) eNew = eOld;
6573 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
6575 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
6576 pOut->z = (char *)sqlite3JournalModename(eNew);
6577 pOut->n = sqlite3Strlen30(pOut->z);
6578 pOut->enc = SQLITE_UTF8;
6579 sqlite3VdbeChangeEncoding(pOut, encoding);
6580 if( rc ) goto abort_due_to_error;
6581 break;
6583 #endif /* SQLITE_OMIT_PRAGMA */
6585 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
6586 /* Opcode: Vacuum P1 * * * *
6588 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
6589 ** for an attached database. The "temp" database may not be vacuumed.
6591 case OP_Vacuum: {
6592 assert( p->readOnly==0 );
6593 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
6594 if( rc ) goto abort_due_to_error;
6595 break;
6597 #endif
6599 #if !defined(SQLITE_OMIT_AUTOVACUUM)
6600 /* Opcode: IncrVacuum P1 P2 * * *
6602 ** Perform a single step of the incremental vacuum procedure on
6603 ** the P1 database. If the vacuum has finished, jump to instruction
6604 ** P2. Otherwise, fall through to the next instruction.
6606 case OP_IncrVacuum: { /* jump */
6607 Btree *pBt;
6609 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6610 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6611 assert( p->readOnly==0 );
6612 pBt = db->aDb[pOp->p1].pBt;
6613 rc = sqlite3BtreeIncrVacuum(pBt);
6614 VdbeBranchTaken(rc==SQLITE_DONE,2);
6615 if( rc ){
6616 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6617 rc = SQLITE_OK;
6618 goto jump_to_p2;
6620 break;
6622 #endif
6624 /* Opcode: Expire P1 * * * *
6626 ** Cause precompiled statements to expire. When an expired statement
6627 ** is executed using sqlite3_step() it will either automatically
6628 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
6629 ** or it will fail with SQLITE_SCHEMA.
6631 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
6632 ** then only the currently executing statement is expired.
6634 case OP_Expire: {
6635 if( !pOp->p1 ){
6636 sqlite3ExpirePreparedStatements(db);
6637 }else{
6638 p->expired = 1;
6640 break;
6643 #ifndef SQLITE_OMIT_SHARED_CACHE
6644 /* Opcode: TableLock P1 P2 P3 P4 *
6645 ** Synopsis: iDb=P1 root=P2 write=P3
6647 ** Obtain a lock on a particular table. This instruction is only used when
6648 ** the shared-cache feature is enabled.
6650 ** P1 is the index of the database in sqlite3.aDb[] of the database
6651 ** on which the lock is acquired. A readlock is obtained if P3==0 or
6652 ** a write lock if P3==1.
6654 ** P2 contains the root-page of the table to lock.
6656 ** P4 contains a pointer to the name of the table being locked. This is only
6657 ** used to generate an error message if the lock cannot be obtained.
6659 case OP_TableLock: {
6660 u8 isWriteLock = (u8)pOp->p3;
6661 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
6662 int p1 = pOp->p1;
6663 assert( p1>=0 && p1<db->nDb );
6664 assert( DbMaskTest(p->btreeMask, p1) );
6665 assert( isWriteLock==0 || isWriteLock==1 );
6666 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
6667 if( rc ){
6668 if( (rc&0xFF)==SQLITE_LOCKED ){
6669 const char *z = pOp->p4.z;
6670 sqlite3VdbeError(p, "database table is locked: %s", z);
6672 goto abort_due_to_error;
6675 break;
6677 #endif /* SQLITE_OMIT_SHARED_CACHE */
6679 #ifndef SQLITE_OMIT_VIRTUALTABLE
6680 /* Opcode: VBegin * * * P4 *
6682 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
6683 ** xBegin method for that table.
6685 ** Also, whether or not P4 is set, check that this is not being called from
6686 ** within a callback to a virtual table xSync() method. If it is, the error
6687 ** code will be set to SQLITE_LOCKED.
6689 case OP_VBegin: {
6690 VTable *pVTab;
6691 pVTab = pOp->p4.pVtab;
6692 rc = sqlite3VtabBegin(db, pVTab);
6693 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
6694 if( rc ) goto abort_due_to_error;
6695 break;
6697 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6699 #ifndef SQLITE_OMIT_VIRTUALTABLE
6700 /* Opcode: VCreate P1 P2 * * *
6702 ** P2 is a register that holds the name of a virtual table in database
6703 ** P1. Call the xCreate method for that table.
6705 case OP_VCreate: {
6706 Mem sMem; /* For storing the record being decoded */
6707 const char *zTab; /* Name of the virtual table */
6709 memset(&sMem, 0, sizeof(sMem));
6710 sMem.db = db;
6711 /* Because P2 is always a static string, it is impossible for the
6712 ** sqlite3VdbeMemCopy() to fail */
6713 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
6714 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
6715 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
6716 assert( rc==SQLITE_OK );
6717 zTab = (const char*)sqlite3_value_text(&sMem);
6718 assert( zTab || db->mallocFailed );
6719 if( zTab ){
6720 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
6722 sqlite3VdbeMemRelease(&sMem);
6723 if( rc ) goto abort_due_to_error;
6724 break;
6726 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6728 #ifndef SQLITE_OMIT_VIRTUALTABLE
6729 /* Opcode: VDestroy P1 * * P4 *
6731 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
6732 ** of that table.
6734 case OP_VDestroy: {
6735 db->nVDestroy++;
6736 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
6737 db->nVDestroy--;
6738 if( rc ) goto abort_due_to_error;
6739 break;
6741 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6743 #ifndef SQLITE_OMIT_VIRTUALTABLE
6744 /* Opcode: VOpen P1 * * P4 *
6746 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6747 ** P1 is a cursor number. This opcode opens a cursor to the virtual
6748 ** table and stores that cursor in P1.
6750 case OP_VOpen: {
6751 VdbeCursor *pCur;
6752 sqlite3_vtab_cursor *pVCur;
6753 sqlite3_vtab *pVtab;
6754 const sqlite3_module *pModule;
6756 assert( p->bIsReader );
6757 pCur = 0;
6758 pVCur = 0;
6759 pVtab = pOp->p4.pVtab->pVtab;
6760 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6761 rc = SQLITE_LOCKED;
6762 goto abort_due_to_error;
6764 pModule = pVtab->pModule;
6765 rc = pModule->xOpen(pVtab, &pVCur);
6766 sqlite3VtabImportErrmsg(p, pVtab);
6767 if( rc ) goto abort_due_to_error;
6769 /* Initialize sqlite3_vtab_cursor base class */
6770 pVCur->pVtab = pVtab;
6772 /* Initialize vdbe cursor object */
6773 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
6774 if( pCur ){
6775 pCur->uc.pVCur = pVCur;
6776 pVtab->nRef++;
6777 }else{
6778 assert( db->mallocFailed );
6779 pModule->xClose(pVCur);
6780 goto no_mem;
6782 break;
6784 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6786 #ifndef SQLITE_OMIT_VIRTUALTABLE
6787 /* Opcode: VFilter P1 P2 P3 P4 *
6788 ** Synopsis: iplan=r[P3] zplan='P4'
6790 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
6791 ** the filtered result set is empty.
6793 ** P4 is either NULL or a string that was generated by the xBestIndex
6794 ** method of the module. The interpretation of the P4 string is left
6795 ** to the module implementation.
6797 ** This opcode invokes the xFilter method on the virtual table specified
6798 ** by P1. The integer query plan parameter to xFilter is stored in register
6799 ** P3. Register P3+1 stores the argc parameter to be passed to the
6800 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6801 ** additional parameters which are passed to
6802 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6804 ** A jump is made to P2 if the result set after filtering would be empty.
6806 case OP_VFilter: { /* jump */
6807 int nArg;
6808 int iQuery;
6809 const sqlite3_module *pModule;
6810 Mem *pQuery;
6811 Mem *pArgc;
6812 sqlite3_vtab_cursor *pVCur;
6813 sqlite3_vtab *pVtab;
6814 VdbeCursor *pCur;
6815 int res;
6816 int i;
6817 Mem **apArg;
6819 pQuery = &aMem[pOp->p3];
6820 pArgc = &pQuery[1];
6821 pCur = p->apCsr[pOp->p1];
6822 assert( memIsValid(pQuery) );
6823 REGISTER_TRACE(pOp->p3, pQuery);
6824 assert( pCur->eCurType==CURTYPE_VTAB );
6825 pVCur = pCur->uc.pVCur;
6826 pVtab = pVCur->pVtab;
6827 pModule = pVtab->pModule;
6829 /* Grab the index number and argc parameters */
6830 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
6831 nArg = (int)pArgc->u.i;
6832 iQuery = (int)pQuery->u.i;
6834 /* Invoke the xFilter method */
6835 res = 0;
6836 apArg = p->apArg;
6837 for(i = 0; i<nArg; i++){
6838 apArg[i] = &pArgc[i+1];
6840 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
6841 sqlite3VtabImportErrmsg(p, pVtab);
6842 if( rc ) goto abort_due_to_error;
6843 res = pModule->xEof(pVCur);
6844 pCur->nullRow = 0;
6845 VdbeBranchTaken(res!=0,2);
6846 if( res ) goto jump_to_p2;
6847 break;
6849 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6851 #ifndef SQLITE_OMIT_VIRTUALTABLE
6852 /* Opcode: VColumn P1 P2 P3 * P5
6853 ** Synopsis: r[P3]=vcolumn(P2)
6855 ** Store in register P3 the value of the P2-th column of
6856 ** the current row of the virtual-table of cursor P1.
6858 ** If the VColumn opcode is being used to fetch the value of
6859 ** an unchanging column during an UPDATE operation, then the P5
6860 ** value is 1. Otherwise, P5 is 0. The P5 value is returned
6861 ** by sqlite3_vtab_nochange() routine and can be used
6862 ** by virtual table implementations to return special "no-change"
6863 ** marks which can be more efficient, depending on the virtual table.
6865 case OP_VColumn: {
6866 sqlite3_vtab *pVtab;
6867 const sqlite3_module *pModule;
6868 Mem *pDest;
6869 sqlite3_context sContext;
6871 VdbeCursor *pCur = p->apCsr[pOp->p1];
6872 assert( pCur->eCurType==CURTYPE_VTAB );
6873 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6874 pDest = &aMem[pOp->p3];
6875 memAboutToChange(p, pDest);
6876 if( pCur->nullRow ){
6877 sqlite3VdbeMemSetNull(pDest);
6878 break;
6880 pVtab = pCur->uc.pVCur->pVtab;
6881 pModule = pVtab->pModule;
6882 assert( pModule->xColumn );
6883 memset(&sContext, 0, sizeof(sContext));
6884 sContext.pOut = pDest;
6885 if( pOp->p5 ){
6886 sqlite3VdbeMemSetNull(pDest);
6887 pDest->flags = MEM_Null|MEM_Zero;
6888 pDest->u.nZero = 0;
6889 }else{
6890 MemSetTypeFlag(pDest, MEM_Null);
6892 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
6893 sqlite3VtabImportErrmsg(p, pVtab);
6894 if( sContext.isError>0 ){
6895 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
6896 rc = sContext.isError;
6898 sqlite3VdbeChangeEncoding(pDest, encoding);
6899 REGISTER_TRACE(pOp->p3, pDest);
6900 UPDATE_MAX_BLOBSIZE(pDest);
6902 if( sqlite3VdbeMemTooBig(pDest) ){
6903 goto too_big;
6905 if( rc ) goto abort_due_to_error;
6906 break;
6908 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6910 #ifndef SQLITE_OMIT_VIRTUALTABLE
6911 /* Opcode: VNext P1 P2 * * *
6913 ** Advance virtual table P1 to the next row in its result set and
6914 ** jump to instruction P2. Or, if the virtual table has reached
6915 ** the end of its result set, then fall through to the next instruction.
6917 case OP_VNext: { /* jump */
6918 sqlite3_vtab *pVtab;
6919 const sqlite3_module *pModule;
6920 int res;
6921 VdbeCursor *pCur;
6923 res = 0;
6924 pCur = p->apCsr[pOp->p1];
6925 assert( pCur->eCurType==CURTYPE_VTAB );
6926 if( pCur->nullRow ){
6927 break;
6929 pVtab = pCur->uc.pVCur->pVtab;
6930 pModule = pVtab->pModule;
6931 assert( pModule->xNext );
6933 /* Invoke the xNext() method of the module. There is no way for the
6934 ** underlying implementation to return an error if one occurs during
6935 ** xNext(). Instead, if an error occurs, true is returned (indicating that
6936 ** data is available) and the error code returned when xColumn or
6937 ** some other method is next invoked on the save virtual table cursor.
6939 rc = pModule->xNext(pCur->uc.pVCur);
6940 sqlite3VtabImportErrmsg(p, pVtab);
6941 if( rc ) goto abort_due_to_error;
6942 res = pModule->xEof(pCur->uc.pVCur);
6943 VdbeBranchTaken(!res,2);
6944 if( !res ){
6945 /* If there is data, jump to P2 */
6946 goto jump_to_p2_and_check_for_interrupt;
6948 goto check_for_interrupt;
6950 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6952 #ifndef SQLITE_OMIT_VIRTUALTABLE
6953 /* Opcode: VRename P1 * * P4 *
6955 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6956 ** This opcode invokes the corresponding xRename method. The value
6957 ** in register P1 is passed as the zName argument to the xRename method.
6959 case OP_VRename: {
6960 sqlite3_vtab *pVtab;
6961 Mem *pName;
6963 pVtab = pOp->p4.pVtab->pVtab;
6964 pName = &aMem[pOp->p1];
6965 assert( pVtab->pModule->xRename );
6966 assert( memIsValid(pName) );
6967 assert( p->readOnly==0 );
6968 REGISTER_TRACE(pOp->p1, pName);
6969 assert( pName->flags & MEM_Str );
6970 testcase( pName->enc==SQLITE_UTF8 );
6971 testcase( pName->enc==SQLITE_UTF16BE );
6972 testcase( pName->enc==SQLITE_UTF16LE );
6973 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
6974 if( rc ) goto abort_due_to_error;
6975 rc = pVtab->pModule->xRename(pVtab, pName->z);
6976 sqlite3VtabImportErrmsg(p, pVtab);
6977 p->expired = 0;
6978 if( rc ) goto abort_due_to_error;
6979 break;
6981 #endif
6983 #ifndef SQLITE_OMIT_VIRTUALTABLE
6984 /* Opcode: VUpdate P1 P2 P3 P4 P5
6985 ** Synopsis: data=r[P3@P2]
6987 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6988 ** This opcode invokes the corresponding xUpdate method. P2 values
6989 ** are contiguous memory cells starting at P3 to pass to the xUpdate
6990 ** invocation. The value in register (P3+P2-1) corresponds to the
6991 ** p2th element of the argv array passed to xUpdate.
6993 ** The xUpdate method will do a DELETE or an INSERT or both.
6994 ** The argv[0] element (which corresponds to memory cell P3)
6995 ** is the rowid of a row to delete. If argv[0] is NULL then no
6996 ** deletion occurs. The argv[1] element is the rowid of the new
6997 ** row. This can be NULL to have the virtual table select the new
6998 ** rowid for itself. The subsequent elements in the array are
6999 ** the values of columns in the new row.
7001 ** If P2==1 then no insert is performed. argv[0] is the rowid of
7002 ** a row to delete.
7004 ** P1 is a boolean flag. If it is set to true and the xUpdate call
7005 ** is successful, then the value returned by sqlite3_last_insert_rowid()
7006 ** is set to the value of the rowid for the row just inserted.
7008 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
7009 ** apply in the case of a constraint failure on an insert or update.
7011 case OP_VUpdate: {
7012 sqlite3_vtab *pVtab;
7013 const sqlite3_module *pModule;
7014 int nArg;
7015 int i;
7016 sqlite_int64 rowid;
7017 Mem **apArg;
7018 Mem *pX;
7020 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
7021 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
7023 assert( p->readOnly==0 );
7024 if( db->mallocFailed ) goto no_mem;
7025 sqlite3VdbeIncrWriteCounter(p, 0);
7026 pVtab = pOp->p4.pVtab->pVtab;
7027 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7028 rc = SQLITE_LOCKED;
7029 goto abort_due_to_error;
7031 pModule = pVtab->pModule;
7032 nArg = pOp->p2;
7033 assert( pOp->p4type==P4_VTAB );
7034 if( ALWAYS(pModule->xUpdate) ){
7035 u8 vtabOnConflict = db->vtabOnConflict;
7036 apArg = p->apArg;
7037 pX = &aMem[pOp->p3];
7038 for(i=0; i<nArg; i++){
7039 assert( memIsValid(pX) );
7040 memAboutToChange(p, pX);
7041 apArg[i] = pX;
7042 pX++;
7044 db->vtabOnConflict = pOp->p5;
7045 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
7046 db->vtabOnConflict = vtabOnConflict;
7047 sqlite3VtabImportErrmsg(p, pVtab);
7048 if( rc==SQLITE_OK && pOp->p1 ){
7049 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
7050 db->lastRowid = rowid;
7052 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
7053 if( pOp->p5==OE_Ignore ){
7054 rc = SQLITE_OK;
7055 }else{
7056 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
7058 }else{
7059 p->nChange++;
7061 if( rc ) goto abort_due_to_error;
7063 break;
7065 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7067 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7068 /* Opcode: Pagecount P1 P2 * * *
7070 ** Write the current number of pages in database P1 to memory cell P2.
7072 case OP_Pagecount: { /* out2 */
7073 pOut = out2Prerelease(p, pOp);
7074 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
7075 break;
7077 #endif
7080 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7081 /* Opcode: MaxPgcnt P1 P2 P3 * *
7083 ** Try to set the maximum page count for database P1 to the value in P3.
7084 ** Do not let the maximum page count fall below the current page count and
7085 ** do not change the maximum page count value if P3==0.
7087 ** Store the maximum page count after the change in register P2.
7089 case OP_MaxPgcnt: { /* out2 */
7090 unsigned int newMax;
7091 Btree *pBt;
7093 pOut = out2Prerelease(p, pOp);
7094 pBt = db->aDb[pOp->p1].pBt;
7095 newMax = 0;
7096 if( pOp->p3 ){
7097 newMax = sqlite3BtreeLastPage(pBt);
7098 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
7100 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
7101 break;
7103 #endif
7105 /* Opcode: Function0 P1 P2 P3 P4 P5
7106 ** Synopsis: r[P3]=func(r[P2@P5])
7108 ** Invoke a user function (P4 is a pointer to a FuncDef object that
7109 ** defines the function) with P5 arguments taken from register P2 and
7110 ** successors. The result of the function is stored in register P3.
7111 ** Register P3 must not be one of the function inputs.
7113 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7114 ** function was determined to be constant at compile time. If the first
7115 ** argument was constant then bit 0 of P1 is set. This is used to determine
7116 ** whether meta data associated with a user function argument using the
7117 ** sqlite3_set_auxdata() API may be safely retained until the next
7118 ** invocation of this opcode.
7120 ** See also: Function, AggStep, AggFinal
7122 /* Opcode: Function P1 P2 P3 P4 P5
7123 ** Synopsis: r[P3]=func(r[P2@P5])
7125 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7126 ** contains a pointer to the function to be run) with P5 arguments taken
7127 ** from register P2 and successors. The result of the function is stored
7128 ** in register P3. Register P3 must not be one of the function inputs.
7130 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7131 ** function was determined to be constant at compile time. If the first
7132 ** argument was constant then bit 0 of P1 is set. This is used to determine
7133 ** whether meta data associated with a user function argument using the
7134 ** sqlite3_set_auxdata() API may be safely retained until the next
7135 ** invocation of this opcode.
7137 ** SQL functions are initially coded as OP_Function0 with P4 pointing
7138 ** to a FuncDef object. But on first evaluation, the P4 operand is
7139 ** automatically converted into an sqlite3_context object and the operation
7140 ** changed to this OP_Function opcode. In this way, the initialization of
7141 ** the sqlite3_context object occurs only once, rather than once for each
7142 ** evaluation of the function.
7144 ** See also: Function0, AggStep, AggFinal
7146 case OP_PureFunc0:
7147 case OP_Function0: {
7148 int n;
7149 sqlite3_context *pCtx;
7151 assert( pOp->p4type==P4_FUNCDEF );
7152 n = pOp->p5;
7153 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7154 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7155 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7156 pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
7157 if( pCtx==0 ) goto no_mem;
7158 pCtx->pOut = 0;
7159 pCtx->pFunc = pOp->p4.pFunc;
7160 pCtx->iOp = (int)(pOp - aOp);
7161 pCtx->pVdbe = p;
7162 pCtx->isError = 0;
7163 pCtx->argc = n;
7164 pOp->p4type = P4_FUNCCTX;
7165 pOp->p4.pCtx = pCtx;
7166 assert( OP_PureFunc == OP_PureFunc0+2 );
7167 assert( OP_Function == OP_Function0+2 );
7168 pOp->opcode += 2;
7169 /* Fall through into OP_Function */
7171 case OP_PureFunc:
7172 case OP_Function: {
7173 int i;
7174 sqlite3_context *pCtx;
7176 assert( pOp->p4type==P4_FUNCCTX );
7177 pCtx = pOp->p4.pCtx;
7179 /* If this function is inside of a trigger, the register array in aMem[]
7180 ** might change from one evaluation to the next. The next block of code
7181 ** checks to see if the register array has changed, and if so it
7182 ** reinitializes the relavant parts of the sqlite3_context object */
7183 pOut = &aMem[pOp->p3];
7184 if( pCtx->pOut != pOut ){
7185 pCtx->pOut = pOut;
7186 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7189 memAboutToChange(p, pOut);
7190 #ifdef SQLITE_DEBUG
7191 for(i=0; i<pCtx->argc; i++){
7192 assert( memIsValid(pCtx->argv[i]) );
7193 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7195 #endif
7196 MemSetTypeFlag(pOut, MEM_Null);
7197 assert( pCtx->isError==0 );
7198 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
7200 /* If the function returned an error, throw an exception */
7201 if( pCtx->isError ){
7202 if( pCtx->isError>0 ){
7203 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
7204 rc = pCtx->isError;
7206 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
7207 pCtx->isError = 0;
7208 if( rc ) goto abort_due_to_error;
7211 /* Copy the result of the function into register P3 */
7212 if( pOut->flags & (MEM_Str|MEM_Blob) ){
7213 sqlite3VdbeChangeEncoding(pOut, encoding);
7214 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
7217 REGISTER_TRACE(pOp->p3, pOut);
7218 UPDATE_MAX_BLOBSIZE(pOut);
7219 break;
7222 /* Opcode: Trace P1 P2 * P4 *
7224 ** Write P4 on the statement trace output if statement tracing is
7225 ** enabled.
7227 ** Operand P1 must be 0x7fffffff and P2 must positive.
7229 /* Opcode: Init P1 P2 P3 P4 *
7230 ** Synopsis: Start at P2
7232 ** Programs contain a single instance of this opcode as the very first
7233 ** opcode.
7235 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7236 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7237 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7239 ** If P2 is not zero, jump to instruction P2.
7241 ** Increment the value of P1 so that OP_Once opcodes will jump the
7242 ** first time they are evaluated for this run.
7244 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7245 ** error is encountered.
7247 case OP_Trace:
7248 case OP_Init: { /* jump */
7249 int i;
7250 #ifndef SQLITE_OMIT_TRACE
7251 char *zTrace;
7252 #endif
7254 /* If the P4 argument is not NULL, then it must be an SQL comment string.
7255 ** The "--" string is broken up to prevent false-positives with srcck1.c.
7257 ** This assert() provides evidence for:
7258 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7259 ** would have been returned by the legacy sqlite3_trace() interface by
7260 ** using the X argument when X begins with "--" and invoking
7261 ** sqlite3_expanded_sql(P) otherwise.
7263 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
7265 /* OP_Init is always instruction 0 */
7266 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
7268 #ifndef SQLITE_OMIT_TRACE
7269 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
7270 && !p->doingRerun
7271 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7273 #ifndef SQLITE_OMIT_DEPRECATED
7274 if( db->mTrace & SQLITE_TRACE_LEGACY ){
7275 void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
7276 char *z = sqlite3VdbeExpandSql(p, zTrace);
7277 x(db->pTraceArg, z);
7278 sqlite3_free(z);
7279 }else
7280 #endif
7281 if( db->nVdbeExec>1 ){
7282 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
7283 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
7284 sqlite3DbFree(db, z);
7285 }else{
7286 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
7289 #ifdef SQLITE_USE_FCNTL_TRACE
7290 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
7291 if( zTrace ){
7292 int j;
7293 for(j=0; j<db->nDb; j++){
7294 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
7295 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
7298 #endif /* SQLITE_USE_FCNTL_TRACE */
7299 #ifdef SQLITE_DEBUG
7300 if( (db->flags & SQLITE_SqlTrace)!=0
7301 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7303 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
7305 #endif /* SQLITE_DEBUG */
7306 #endif /* SQLITE_OMIT_TRACE */
7307 assert( pOp->p2>0 );
7308 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
7309 if( pOp->opcode==OP_Trace ) break;
7310 for(i=1; i<p->nOp; i++){
7311 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
7313 pOp->p1 = 0;
7315 pOp->p1++;
7316 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
7317 goto jump_to_p2;
7320 #ifdef SQLITE_ENABLE_CURSOR_HINTS
7321 /* Opcode: CursorHint P1 * * P4 *
7323 ** Provide a hint to cursor P1 that it only needs to return rows that
7324 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
7325 ** to values currently held in registers. TK_COLUMN terms in the P4
7326 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
7328 case OP_CursorHint: {
7329 VdbeCursor *pC;
7331 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7332 assert( pOp->p4type==P4_EXPR );
7333 pC = p->apCsr[pOp->p1];
7334 if( pC ){
7335 assert( pC->eCurType==CURTYPE_BTREE );
7336 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
7337 pOp->p4.pExpr, aMem);
7339 break;
7341 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
7343 #ifdef SQLITE_DEBUG
7344 /* Opcode: Abortable * * * * *
7346 ** Verify that an Abort can happen. Assert if an Abort at this point
7347 ** might cause database corruption. This opcode only appears in debugging
7348 ** builds.
7350 ** An Abort is safe if either there have been no writes, or if there is
7351 ** an active statement journal.
7353 case OP_Abortable: {
7354 sqlite3VdbeAssertAbortable(p);
7355 break;
7357 #endif
7359 #ifdef SQLITE_DEBUG_COLUMNCACHE
7360 /* Opcode: SetTabCol P1 P2 P3 * *
7362 ** Set a flag in register REG[P3] indicating that it holds the value
7363 ** of column P2 from the table on cursor P1. This flag is checked
7364 ** by a subsequent VerifyTabCol opcode.
7366 ** This opcode only appears SQLITE_DEBUG builds. It is used to verify
7367 ** that the expression table column cache is working correctly.
7369 case OP_SetTabCol: {
7370 aMem[pOp->p3].iTabColHash = TableColumnHash(pOp->p1,pOp->p2);
7371 break;
7373 /* Opcode: VerifyTabCol P1 P2 P3 * *
7375 ** Verify that register REG[P3] contains the value of column P2 from
7376 ** cursor P1. Assert() if this is not the case.
7378 ** This opcode only appears SQLITE_DEBUG builds. It is used to verify
7379 ** that the expression table column cache is working correctly.
7381 case OP_VerifyTabCol: {
7382 assert( aMem[pOp->p3].iTabColHash == TableColumnHash(pOp->p1,pOp->p2) );
7383 break;
7385 #endif
7387 /* Opcode: Noop * * * * *
7389 ** Do nothing. This instruction is often useful as a jump
7390 ** destination.
7393 ** The magic Explain opcode are only inserted when explain==2 (which
7394 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
7395 ** This opcode records information from the optimizer. It is the
7396 ** the same as a no-op. This opcodesnever appears in a real VM program.
7398 default: { /* This is really OP_Noop, OP_Explain */
7399 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
7401 break;
7404 /*****************************************************************************
7405 ** The cases of the switch statement above this line should all be indented
7406 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
7407 ** readability. From this point on down, the normal indentation rules are
7408 ** restored.
7409 *****************************************************************************/
7412 #ifdef VDBE_PROFILE
7414 u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
7415 if( endTime>start ) pOrigOp->cycles += endTime - start;
7416 pOrigOp->cnt++;
7418 #endif
7420 /* The following code adds nothing to the actual functionality
7421 ** of the program. It is only here for testing and debugging.
7422 ** On the other hand, it does burn CPU cycles every time through
7423 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
7425 #ifndef NDEBUG
7426 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
7428 #ifdef SQLITE_DEBUG
7429 if( db->flags & SQLITE_VdbeTrace ){
7430 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
7431 if( rc!=0 ) printf("rc=%d\n",rc);
7432 if( opProperty & (OPFLG_OUT2) ){
7433 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
7435 if( opProperty & OPFLG_OUT3 ){
7436 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
7439 #endif /* SQLITE_DEBUG */
7440 #endif /* NDEBUG */
7441 } /* The end of the for(;;) loop the loops through opcodes */
7443 /* If we reach this point, it means that execution is finished with
7444 ** an error of some kind.
7446 abort_due_to_error:
7447 if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
7448 assert( rc );
7449 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
7450 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7452 p->rc = rc;
7453 sqlite3SystemError(db, rc);
7454 testcase( sqlite3GlobalConfig.xLog!=0 );
7455 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
7456 (int)(pOp - aOp), p->zSql, p->zErrMsg);
7457 sqlite3VdbeHalt(p);
7458 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
7459 rc = SQLITE_ERROR;
7460 if( resetSchemaOnFault>0 ){
7461 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
7464 /* This is the only way out of this procedure. We have to
7465 ** release the mutexes on btrees that were acquired at the
7466 ** top. */
7467 vdbe_return:
7468 testcase( nVmStep>0 );
7469 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
7470 sqlite3VdbeLeave(p);
7471 assert( rc!=SQLITE_OK || nExtraDelete==0
7472 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
7474 return rc;
7476 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
7477 ** is encountered.
7479 too_big:
7480 sqlite3VdbeError(p, "string or blob too big");
7481 rc = SQLITE_TOOBIG;
7482 goto abort_due_to_error;
7484 /* Jump to here if a malloc() fails.
7486 no_mem:
7487 sqlite3OomFault(db);
7488 sqlite3VdbeError(p, "out of memory");
7489 rc = SQLITE_NOMEM_BKPT;
7490 goto abort_due_to_error;
7492 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
7493 ** flag.
7495 abort_due_to_interrupt:
7496 assert( db->u1.isInterrupted );
7497 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
7498 p->rc = rc;
7499 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7500 goto abort_due_to_error;