Simplifications to the implementation of the sum() SQL function.
[sqlite.git] / src / vdbe.c
blobf2e68d4c1ee2ddbccd1e7e6205683cbd2deffb6b
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 #ifdef SQLITE_DEBUG
1159 pOut->uTemp = 0;
1160 #endif
1161 while( cnt>0 ){
1162 pOut++;
1163 memAboutToChange(p, pOut);
1164 sqlite3VdbeMemSetNull(pOut);
1165 pOut->flags = nullFlag;
1166 pOut->n = 0;
1167 cnt--;
1169 break;
1172 /* Opcode: SoftNull P1 * * * *
1173 ** Synopsis: r[P1]=NULL
1175 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1176 ** instruction, but do not free any string or blob memory associated with
1177 ** the register, so that if the value was a string or blob that was
1178 ** previously copied using OP_SCopy, the copies will continue to be valid.
1180 case OP_SoftNull: {
1181 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1182 pOut = &aMem[pOp->p1];
1183 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1184 break;
1187 /* Opcode: Blob P1 P2 * P4 *
1188 ** Synopsis: r[P2]=P4 (len=P1)
1190 ** P4 points to a blob of data P1 bytes long. Store this
1191 ** blob in register P2.
1193 case OP_Blob: { /* out2 */
1194 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1195 pOut = out2Prerelease(p, pOp);
1196 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1197 pOut->enc = encoding;
1198 UPDATE_MAX_BLOBSIZE(pOut);
1199 break;
1202 /* Opcode: Variable P1 P2 * P4 *
1203 ** Synopsis: r[P2]=parameter(P1,P4)
1205 ** Transfer the values of bound parameter P1 into register P2
1207 ** If the parameter is named, then its name appears in P4.
1208 ** The P4 value is used by sqlite3_bind_parameter_name().
1210 case OP_Variable: { /* out2 */
1211 Mem *pVar; /* Value being transferred */
1213 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1214 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1215 pVar = &p->aVar[pOp->p1 - 1];
1216 if( sqlite3VdbeMemTooBig(pVar) ){
1217 goto too_big;
1219 pOut = &aMem[pOp->p2];
1220 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
1221 UPDATE_MAX_BLOBSIZE(pOut);
1222 break;
1225 /* Opcode: Move P1 P2 P3 * *
1226 ** Synopsis: r[P2@P3]=r[P1@P3]
1228 ** Move the P3 values in register P1..P1+P3-1 over into
1229 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1230 ** left holding a NULL. It is an error for register ranges
1231 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1232 ** for P3 to be less than 1.
1234 case OP_Move: {
1235 int n; /* Number of registers left to copy */
1236 int p1; /* Register to copy from */
1237 int p2; /* Register to copy to */
1239 n = pOp->p3;
1240 p1 = pOp->p1;
1241 p2 = pOp->p2;
1242 assert( n>0 && p1>0 && p2>0 );
1243 assert( p1+n<=p2 || p2+n<=p1 );
1245 pIn1 = &aMem[p1];
1246 pOut = &aMem[p2];
1248 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1249 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1250 assert( memIsValid(pIn1) );
1251 memAboutToChange(p, pOut);
1252 sqlite3VdbeMemMove(pOut, pIn1);
1253 #ifdef SQLITE_DEBUG
1254 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
1255 pOut->pScopyFrom += pOp->p2 - p1;
1257 #endif
1258 Deephemeralize(pOut);
1259 REGISTER_TRACE(p2++, pOut);
1260 pIn1++;
1261 pOut++;
1262 }while( --n );
1263 break;
1266 /* Opcode: Copy P1 P2 P3 * *
1267 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1269 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1271 ** This instruction makes a deep copy of the value. A duplicate
1272 ** is made of any string or blob constant. See also OP_SCopy.
1274 case OP_Copy: {
1275 int n;
1277 n = pOp->p3;
1278 pIn1 = &aMem[pOp->p1];
1279 pOut = &aMem[pOp->p2];
1280 assert( pOut!=pIn1 );
1281 while( 1 ){
1282 memAboutToChange(p, pOut);
1283 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1284 Deephemeralize(pOut);
1285 #ifdef SQLITE_DEBUG
1286 pOut->pScopyFrom = 0;
1287 pOut->iTabColHash = 0;
1288 #endif
1289 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1290 if( (n--)==0 ) break;
1291 pOut++;
1292 pIn1++;
1294 break;
1297 /* Opcode: SCopy P1 P2 * * *
1298 ** Synopsis: r[P2]=r[P1]
1300 ** Make a shallow copy of register P1 into register P2.
1302 ** This instruction makes a shallow copy of the value. If the value
1303 ** is a string or blob, then the copy is only a pointer to the
1304 ** original and hence if the original changes so will the copy.
1305 ** Worse, if the original is deallocated, the copy becomes invalid.
1306 ** Thus the program must guarantee that the original will not change
1307 ** during the lifetime of the copy. Use OP_Copy to make a complete
1308 ** copy.
1310 case OP_SCopy: { /* out2 */
1311 pIn1 = &aMem[pOp->p1];
1312 pOut = &aMem[pOp->p2];
1313 assert( pOut!=pIn1 );
1314 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1315 #ifdef SQLITE_DEBUG
1316 pOut->pScopyFrom = pIn1;
1317 pOut->mScopyFlags = pIn1->flags;
1318 #endif
1319 break;
1322 /* Opcode: IntCopy P1 P2 * * *
1323 ** Synopsis: r[P2]=r[P1]
1325 ** Transfer the integer value held in register P1 into register P2.
1327 ** This is an optimized version of SCopy that works only for integer
1328 ** values.
1330 case OP_IntCopy: { /* out2 */
1331 pIn1 = &aMem[pOp->p1];
1332 assert( (pIn1->flags & MEM_Int)!=0 );
1333 pOut = &aMem[pOp->p2];
1334 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1335 break;
1338 /* Opcode: ResultRow P1 P2 * * *
1339 ** Synopsis: output=r[P1@P2]
1341 ** The registers P1 through P1+P2-1 contain a single row of
1342 ** results. This opcode causes the sqlite3_step() call to terminate
1343 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1344 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1345 ** the result row.
1347 case OP_ResultRow: {
1348 Mem *pMem;
1349 int i;
1350 assert( p->nResColumn==pOp->p2 );
1351 assert( pOp->p1>0 );
1352 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1354 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1355 /* Run the progress counter just before returning.
1357 if( db->xProgress!=0
1358 && nVmStep>=nProgressLimit
1359 && db->xProgress(db->pProgressArg)!=0
1361 rc = SQLITE_INTERRUPT;
1362 goto abort_due_to_error;
1364 #endif
1366 /* If this statement has violated immediate foreign key constraints, do
1367 ** not return the number of rows modified. And do not RELEASE the statement
1368 ** transaction. It needs to be rolled back. */
1369 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
1370 assert( db->flags&SQLITE_CountRows );
1371 assert( p->usesStmtJournal );
1372 goto abort_due_to_error;
1375 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1376 ** DML statements invoke this opcode to return the number of rows
1377 ** modified to the user. This is the only way that a VM that
1378 ** opens a statement transaction may invoke this opcode.
1380 ** In case this is such a statement, close any statement transaction
1381 ** opened by this VM before returning control to the user. This is to
1382 ** ensure that statement-transactions are always nested, not overlapping.
1383 ** If the open statement-transaction is not closed here, then the user
1384 ** may step another VM that opens its own statement transaction. This
1385 ** may lead to overlapping statement transactions.
1387 ** The statement transaction is never a top-level transaction. Hence
1388 ** the RELEASE call below can never fail.
1390 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
1391 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
1392 assert( rc==SQLITE_OK );
1394 /* Invalidate all ephemeral cursor row caches */
1395 p->cacheCtr = (p->cacheCtr + 2)|1;
1397 /* Make sure the results of the current row are \000 terminated
1398 ** and have an assigned type. The results are de-ephemeralized as
1399 ** a side effect.
1401 pMem = p->pResultSet = &aMem[pOp->p1];
1402 for(i=0; i<pOp->p2; i++){
1403 assert( memIsValid(&pMem[i]) );
1404 Deephemeralize(&pMem[i]);
1405 assert( (pMem[i].flags & MEM_Ephem)==0
1406 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1407 sqlite3VdbeMemNulTerminate(&pMem[i]);
1408 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1410 if( db->mallocFailed ) goto no_mem;
1412 if( db->mTrace & SQLITE_TRACE_ROW ){
1413 db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1416 /* Return SQLITE_ROW
1418 p->pc = (int)(pOp - aOp) + 1;
1419 rc = SQLITE_ROW;
1420 goto vdbe_return;
1423 /* Opcode: Concat P1 P2 P3 * *
1424 ** Synopsis: r[P3]=r[P2]+r[P1]
1426 ** Add the text in register P1 onto the end of the text in
1427 ** register P2 and store the result in register P3.
1428 ** If either the P1 or P2 text are NULL then store NULL in P3.
1430 ** P3 = P2 || P1
1432 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1433 ** if P3 is the same register as P2, the implementation is able
1434 ** to avoid a memcpy().
1436 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1437 i64 nByte;
1439 pIn1 = &aMem[pOp->p1];
1440 pIn2 = &aMem[pOp->p2];
1441 pOut = &aMem[pOp->p3];
1442 assert( pIn1!=pOut );
1443 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1444 sqlite3VdbeMemSetNull(pOut);
1445 break;
1447 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
1448 Stringify(pIn1, encoding);
1449 Stringify(pIn2, encoding);
1450 nByte = pIn1->n + pIn2->n;
1451 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1452 goto too_big;
1454 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1455 goto no_mem;
1457 MemSetTypeFlag(pOut, MEM_Str);
1458 if( pOut!=pIn2 ){
1459 memcpy(pOut->z, pIn2->z, pIn2->n);
1461 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1462 pOut->z[nByte]=0;
1463 pOut->z[nByte+1] = 0;
1464 pOut->flags |= MEM_Term;
1465 pOut->n = (int)nByte;
1466 pOut->enc = encoding;
1467 UPDATE_MAX_BLOBSIZE(pOut);
1468 break;
1471 /* Opcode: Add P1 P2 P3 * *
1472 ** Synopsis: r[P3]=r[P1]+r[P2]
1474 ** Add the value in register P1 to the value in register P2
1475 ** and store the result in register P3.
1476 ** If either input is NULL, the result is NULL.
1478 /* Opcode: Multiply P1 P2 P3 * *
1479 ** Synopsis: r[P3]=r[P1]*r[P2]
1482 ** Multiply the value in register P1 by the value in register P2
1483 ** and store the result in register P3.
1484 ** If either input is NULL, the result is NULL.
1486 /* Opcode: Subtract P1 P2 P3 * *
1487 ** Synopsis: r[P3]=r[P2]-r[P1]
1489 ** Subtract the value in register P1 from the value in register P2
1490 ** and store the result in register P3.
1491 ** If either input is NULL, the result is NULL.
1493 /* Opcode: Divide P1 P2 P3 * *
1494 ** Synopsis: r[P3]=r[P2]/r[P1]
1496 ** Divide the value in register P1 by the value in register P2
1497 ** and store the result in register P3 (P3=P2/P1). If the value in
1498 ** register P1 is zero, then the result is NULL. If either input is
1499 ** NULL, the result is NULL.
1501 /* Opcode: Remainder P1 P2 P3 * *
1502 ** Synopsis: r[P3]=r[P2]%r[P1]
1504 ** Compute the remainder after integer register P2 is divided by
1505 ** register P1 and store the result in register P3.
1506 ** If the value in register P1 is zero the result is NULL.
1507 ** If either operand is NULL, the result is NULL.
1509 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1510 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1511 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1512 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1513 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1514 char bIntint; /* Started out as two integer operands */
1515 u16 flags; /* Combined MEM_* flags from both inputs */
1516 u16 type1; /* Numeric type of left operand */
1517 u16 type2; /* Numeric type of right operand */
1518 i64 iA; /* Integer value of left operand */
1519 i64 iB; /* Integer value of right operand */
1520 double rA; /* Real value of left operand */
1521 double rB; /* Real value of right operand */
1523 pIn1 = &aMem[pOp->p1];
1524 type1 = numericType(pIn1);
1525 pIn2 = &aMem[pOp->p2];
1526 type2 = numericType(pIn2);
1527 pOut = &aMem[pOp->p3];
1528 flags = pIn1->flags | pIn2->flags;
1529 if( (type1 & type2 & MEM_Int)!=0 ){
1530 iA = pIn1->u.i;
1531 iB = pIn2->u.i;
1532 bIntint = 1;
1533 switch( pOp->opcode ){
1534 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1535 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1536 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1537 case OP_Divide: {
1538 if( iA==0 ) goto arithmetic_result_is_null;
1539 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1540 iB /= iA;
1541 break;
1543 default: {
1544 if( iA==0 ) goto arithmetic_result_is_null;
1545 if( iA==-1 ) iA = 1;
1546 iB %= iA;
1547 break;
1550 pOut->u.i = iB;
1551 MemSetTypeFlag(pOut, MEM_Int);
1552 }else if( (flags & MEM_Null)!=0 ){
1553 goto arithmetic_result_is_null;
1554 }else{
1555 bIntint = 0;
1556 fp_math:
1557 rA = sqlite3VdbeRealValue(pIn1);
1558 rB = sqlite3VdbeRealValue(pIn2);
1559 switch( pOp->opcode ){
1560 case OP_Add: rB += rA; break;
1561 case OP_Subtract: rB -= rA; break;
1562 case OP_Multiply: rB *= rA; break;
1563 case OP_Divide: {
1564 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1565 if( rA==(double)0 ) goto arithmetic_result_is_null;
1566 rB /= rA;
1567 break;
1569 default: {
1570 iA = (i64)rA;
1571 iB = (i64)rB;
1572 if( iA==0 ) goto arithmetic_result_is_null;
1573 if( iA==-1 ) iA = 1;
1574 rB = (double)(iB % iA);
1575 break;
1578 #ifdef SQLITE_OMIT_FLOATING_POINT
1579 pOut->u.i = rB;
1580 MemSetTypeFlag(pOut, MEM_Int);
1581 #else
1582 if( sqlite3IsNaN(rB) ){
1583 goto arithmetic_result_is_null;
1585 pOut->u.r = rB;
1586 MemSetTypeFlag(pOut, MEM_Real);
1587 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
1588 sqlite3VdbeIntegerAffinity(pOut);
1590 #endif
1592 break;
1594 arithmetic_result_is_null:
1595 sqlite3VdbeMemSetNull(pOut);
1596 break;
1599 /* Opcode: CollSeq P1 * * P4
1601 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1602 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1603 ** be returned. This is used by the built-in min(), max() and nullif()
1604 ** functions.
1606 ** If P1 is not zero, then it is a register that a subsequent min() or
1607 ** max() aggregate will set to 1 if the current row is not the minimum or
1608 ** maximum. The P1 register is initialized to 0 by this instruction.
1610 ** The interface used by the implementation of the aforementioned functions
1611 ** to retrieve the collation sequence set by this opcode is not available
1612 ** publicly. Only built-in functions have access to this feature.
1614 case OP_CollSeq: {
1615 assert( pOp->p4type==P4_COLLSEQ );
1616 if( pOp->p1 ){
1617 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1619 break;
1622 /* Opcode: BitAnd P1 P2 P3 * *
1623 ** Synopsis: r[P3]=r[P1]&r[P2]
1625 ** Take the bit-wise AND of the values in register P1 and P2 and
1626 ** store the result in register P3.
1627 ** If either input is NULL, the result is NULL.
1629 /* Opcode: BitOr P1 P2 P3 * *
1630 ** Synopsis: r[P3]=r[P1]|r[P2]
1632 ** Take the bit-wise OR of the values in register P1 and P2 and
1633 ** store the result in register P3.
1634 ** If either input is NULL, the result is NULL.
1636 /* Opcode: ShiftLeft P1 P2 P3 * *
1637 ** Synopsis: r[P3]=r[P2]<<r[P1]
1639 ** Shift the integer value in register P2 to the left by the
1640 ** number of bits specified by the integer in register P1.
1641 ** Store the result in register P3.
1642 ** If either input is NULL, the result is NULL.
1644 /* Opcode: ShiftRight P1 P2 P3 * *
1645 ** Synopsis: r[P3]=r[P2]>>r[P1]
1647 ** Shift the integer value in register P2 to the right by the
1648 ** number of bits specified by the integer in register P1.
1649 ** Store the result in register P3.
1650 ** If either input is NULL, the result is NULL.
1652 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1653 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1654 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1655 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1656 i64 iA;
1657 u64 uA;
1658 i64 iB;
1659 u8 op;
1661 pIn1 = &aMem[pOp->p1];
1662 pIn2 = &aMem[pOp->p2];
1663 pOut = &aMem[pOp->p3];
1664 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1665 sqlite3VdbeMemSetNull(pOut);
1666 break;
1668 iA = sqlite3VdbeIntValue(pIn2);
1669 iB = sqlite3VdbeIntValue(pIn1);
1670 op = pOp->opcode;
1671 if( op==OP_BitAnd ){
1672 iA &= iB;
1673 }else if( op==OP_BitOr ){
1674 iA |= iB;
1675 }else if( iB!=0 ){
1676 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1678 /* If shifting by a negative amount, shift in the other direction */
1679 if( iB<0 ){
1680 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1681 op = 2*OP_ShiftLeft + 1 - op;
1682 iB = iB>(-64) ? -iB : 64;
1685 if( iB>=64 ){
1686 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1687 }else{
1688 memcpy(&uA, &iA, sizeof(uA));
1689 if( op==OP_ShiftLeft ){
1690 uA <<= iB;
1691 }else{
1692 uA >>= iB;
1693 /* Sign-extend on a right shift of a negative number */
1694 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1696 memcpy(&iA, &uA, sizeof(iA));
1699 pOut->u.i = iA;
1700 MemSetTypeFlag(pOut, MEM_Int);
1701 break;
1704 /* Opcode: AddImm P1 P2 * * *
1705 ** Synopsis: r[P1]=r[P1]+P2
1707 ** Add the constant P2 to the value in register P1.
1708 ** The result is always an integer.
1710 ** To force any register to be an integer, just add 0.
1712 case OP_AddImm: { /* in1 */
1713 pIn1 = &aMem[pOp->p1];
1714 memAboutToChange(p, pIn1);
1715 sqlite3VdbeMemIntegerify(pIn1);
1716 pIn1->u.i += pOp->p2;
1717 break;
1720 /* Opcode: MustBeInt P1 P2 * * *
1722 ** Force the value in register P1 to be an integer. If the value
1723 ** in P1 is not an integer and cannot be converted into an integer
1724 ** without data loss, then jump immediately to P2, or if P2==0
1725 ** raise an SQLITE_MISMATCH exception.
1727 case OP_MustBeInt: { /* jump, in1 */
1728 pIn1 = &aMem[pOp->p1];
1729 if( (pIn1->flags & MEM_Int)==0 ){
1730 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1731 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
1732 if( (pIn1->flags & MEM_Int)==0 ){
1733 if( pOp->p2==0 ){
1734 rc = SQLITE_MISMATCH;
1735 goto abort_due_to_error;
1736 }else{
1737 goto jump_to_p2;
1741 MemSetTypeFlag(pIn1, MEM_Int);
1742 break;
1745 #ifndef SQLITE_OMIT_FLOATING_POINT
1746 /* Opcode: RealAffinity P1 * * * *
1748 ** If register P1 holds an integer convert it to a real value.
1750 ** This opcode is used when extracting information from a column that
1751 ** has REAL affinity. Such column values may still be stored as
1752 ** integers, for space efficiency, but after extraction we want them
1753 ** to have only a real value.
1755 case OP_RealAffinity: { /* in1 */
1756 pIn1 = &aMem[pOp->p1];
1757 if( pIn1->flags & MEM_Int ){
1758 sqlite3VdbeMemRealify(pIn1);
1760 break;
1762 #endif
1764 #ifndef SQLITE_OMIT_CAST
1765 /* Opcode: Cast P1 P2 * * *
1766 ** Synopsis: affinity(r[P1])
1768 ** Force the value in register P1 to be the type defined by P2.
1770 ** <ul>
1771 ** <li> P2=='A' &rarr; BLOB
1772 ** <li> P2=='B' &rarr; TEXT
1773 ** <li> P2=='C' &rarr; NUMERIC
1774 ** <li> P2=='D' &rarr; INTEGER
1775 ** <li> P2=='E' &rarr; REAL
1776 ** </ul>
1778 ** A NULL value is not changed by this routine. It remains NULL.
1780 case OP_Cast: { /* in1 */
1781 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
1782 testcase( pOp->p2==SQLITE_AFF_TEXT );
1783 testcase( pOp->p2==SQLITE_AFF_BLOB );
1784 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
1785 testcase( pOp->p2==SQLITE_AFF_INTEGER );
1786 testcase( pOp->p2==SQLITE_AFF_REAL );
1787 pIn1 = &aMem[pOp->p1];
1788 memAboutToChange(p, pIn1);
1789 rc = ExpandBlob(pIn1);
1790 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
1791 UPDATE_MAX_BLOBSIZE(pIn1);
1792 if( rc ) goto abort_due_to_error;
1793 break;
1795 #endif /* SQLITE_OMIT_CAST */
1797 /* Opcode: Eq P1 P2 P3 P4 P5
1798 ** Synopsis: IF r[P3]==r[P1]
1800 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
1801 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
1802 ** store the result of comparison in register P2.
1804 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1805 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1806 ** to coerce both inputs according to this affinity before the
1807 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1808 ** affinity is used. Note that the affinity conversions are stored
1809 ** back into the input registers P1 and P3. So this opcode can cause
1810 ** persistent changes to registers P1 and P3.
1812 ** Once any conversions have taken place, and neither value is NULL,
1813 ** the values are compared. If both values are blobs then memcmp() is
1814 ** used to determine the results of the comparison. If both values
1815 ** are text, then the appropriate collating function specified in
1816 ** P4 is used to do the comparison. If P4 is not specified then
1817 ** memcmp() is used to compare text string. If both values are
1818 ** numeric, then a numeric comparison is used. If the two values
1819 ** are of different types, then numbers are considered less than
1820 ** strings and strings are considered less than blobs.
1822 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1823 ** true or false and is never NULL. If both operands are NULL then the result
1824 ** of comparison is true. If either operand is NULL then the result is false.
1825 ** If neither operand is NULL the result is the same as it would be if
1826 ** the SQLITE_NULLEQ flag were omitted from P5.
1828 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1829 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
1830 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
1832 /* Opcode: Ne P1 P2 P3 P4 P5
1833 ** Synopsis: IF r[P3]!=r[P1]
1835 ** This works just like the Eq opcode except that the jump is taken if
1836 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
1837 ** additional information.
1839 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1840 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
1841 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
1843 /* Opcode: Lt P1 P2 P3 P4 P5
1844 ** Synopsis: IF r[P3]<r[P1]
1846 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1847 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
1848 ** the result of comparison (0 or 1 or NULL) into register P2.
1850 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1851 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
1852 ** bit is clear then fall through if either operand is NULL.
1854 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1855 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1856 ** to coerce both inputs according to this affinity before the
1857 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1858 ** affinity is used. Note that the affinity conversions are stored
1859 ** back into the input registers P1 and P3. So this opcode can cause
1860 ** persistent changes to registers P1 and P3.
1862 ** Once any conversions have taken place, and neither value is NULL,
1863 ** the values are compared. If both values are blobs then memcmp() is
1864 ** used to determine the results of the comparison. If both values
1865 ** are text, then the appropriate collating function specified in
1866 ** P4 is used to do the comparison. If P4 is not specified then
1867 ** memcmp() is used to compare text string. If both values are
1868 ** numeric, then a numeric comparison is used. If the two values
1869 ** are of different types, then numbers are considered less than
1870 ** strings and strings are considered less than blobs.
1872 /* Opcode: Le P1 P2 P3 P4 P5
1873 ** Synopsis: IF r[P3]<=r[P1]
1875 ** This works just like the Lt opcode except that the jump is taken if
1876 ** the content of register P3 is less than or equal to the content of
1877 ** register P1. See the Lt opcode for additional information.
1879 /* Opcode: Gt P1 P2 P3 P4 P5
1880 ** Synopsis: IF r[P3]>r[P1]
1882 ** This works just like the Lt opcode except that the jump is taken if
1883 ** the content of register P3 is greater than the content of
1884 ** register P1. See the Lt opcode for additional information.
1886 /* Opcode: Ge P1 P2 P3 P4 P5
1887 ** Synopsis: IF r[P3]>=r[P1]
1889 ** This works just like the Lt opcode except that the jump is taken if
1890 ** the content of register P3 is greater than or equal to the content of
1891 ** register P1. See the Lt opcode for additional information.
1893 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
1894 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
1895 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
1896 case OP_Le: /* same as TK_LE, jump, in1, in3 */
1897 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
1898 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
1899 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
1900 char affinity; /* Affinity to use for comparison */
1901 u16 flags1; /* Copy of initial value of pIn1->flags */
1902 u16 flags3; /* Copy of initial value of pIn3->flags */
1904 pIn1 = &aMem[pOp->p1];
1905 pIn3 = &aMem[pOp->p3];
1906 flags1 = pIn1->flags;
1907 flags3 = pIn3->flags;
1908 if( (flags1 | flags3)&MEM_Null ){
1909 /* One or both operands are NULL */
1910 if( pOp->p5 & SQLITE_NULLEQ ){
1911 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1912 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1913 ** or not both operands are null.
1915 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
1916 assert( (flags1 & MEM_Cleared)==0 );
1917 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
1918 if( (flags1&flags3&MEM_Null)!=0
1919 && (flags3&MEM_Cleared)==0
1921 res = 0; /* Operands are equal */
1922 }else{
1923 res = 1; /* Operands are not equal */
1925 }else{
1926 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1927 ** then the result is always NULL.
1928 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1930 if( pOp->p5 & SQLITE_STOREP2 ){
1931 pOut = &aMem[pOp->p2];
1932 iCompare = 1; /* Operands are not equal */
1933 memAboutToChange(p, pOut);
1934 MemSetTypeFlag(pOut, MEM_Null);
1935 REGISTER_TRACE(pOp->p2, pOut);
1936 }else{
1937 VdbeBranchTaken(2,3);
1938 if( pOp->p5 & SQLITE_JUMPIFNULL ){
1939 goto jump_to_p2;
1942 break;
1944 }else{
1945 /* Neither operand is NULL. Do a comparison. */
1946 affinity = pOp->p5 & SQLITE_AFF_MASK;
1947 if( affinity>=SQLITE_AFF_NUMERIC ){
1948 if( (flags1 | flags3)&MEM_Str ){
1949 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1950 applyNumericAffinity(pIn1,0);
1951 testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
1952 flags3 = pIn3->flags;
1954 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1955 applyNumericAffinity(pIn3,0);
1958 /* Handle the common case of integer comparison here, as an
1959 ** optimization, to avoid a call to sqlite3MemCompare() */
1960 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
1961 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
1962 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
1963 res = 0;
1964 goto compare_op;
1966 }else if( affinity==SQLITE_AFF_TEXT ){
1967 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
1968 testcase( pIn1->flags & MEM_Int );
1969 testcase( pIn1->flags & MEM_Real );
1970 sqlite3VdbeMemStringify(pIn1, encoding, 1);
1971 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
1972 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
1973 assert( pIn1!=pIn3 );
1975 if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
1976 testcase( pIn3->flags & MEM_Int );
1977 testcase( pIn3->flags & MEM_Real );
1978 sqlite3VdbeMemStringify(pIn3, encoding, 1);
1979 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
1980 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
1983 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1984 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1986 compare_op:
1987 /* At this point, res is negative, zero, or positive if reg[P1] is
1988 ** less than, equal to, or greater than reg[P3], respectively. Compute
1989 ** the answer to this operator in res2, depending on what the comparison
1990 ** operator actually is. The next block of code depends on the fact
1991 ** that the 6 comparison operators are consecutive integers in this
1992 ** order: NE, EQ, GT, LE, LT, GE */
1993 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
1994 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
1995 if( res<0 ){ /* ne, eq, gt, le, lt, ge */
1996 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
1997 res2 = aLTb[pOp->opcode - OP_Ne];
1998 }else if( res==0 ){
1999 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
2000 res2 = aEQb[pOp->opcode - OP_Ne];
2001 }else{
2002 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
2003 res2 = aGTb[pOp->opcode - OP_Ne];
2006 /* Undo any changes made by applyAffinity() to the input registers. */
2007 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
2008 pIn1->flags = flags1;
2009 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
2010 pIn3->flags = flags3;
2012 if( pOp->p5 & SQLITE_STOREP2 ){
2013 pOut = &aMem[pOp->p2];
2014 iCompare = res;
2015 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
2016 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
2017 ** and prevents OP_Ne from overwriting NULL with 0. This flag
2018 ** is only used in contexts where either:
2019 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
2020 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
2021 ** Therefore it is not necessary to check the content of r[P2] for
2022 ** NULL. */
2023 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
2024 assert( res2==0 || res2==1 );
2025 testcase( res2==0 && pOp->opcode==OP_Eq );
2026 testcase( res2==1 && pOp->opcode==OP_Eq );
2027 testcase( res2==0 && pOp->opcode==OP_Ne );
2028 testcase( res2==1 && pOp->opcode==OP_Ne );
2029 if( (pOp->opcode==OP_Eq)==res2 ) break;
2031 memAboutToChange(p, pOut);
2032 MemSetTypeFlag(pOut, MEM_Int);
2033 pOut->u.i = res2;
2034 REGISTER_TRACE(pOp->p2, pOut);
2035 }else{
2036 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2037 if( res2 ){
2038 goto jump_to_p2;
2041 break;
2044 /* Opcode: ElseNotEq * P2 * * *
2046 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
2047 ** If result of an OP_Eq comparison on the same two operands
2048 ** would have be NULL or false (0), then then jump to P2.
2049 ** If the result of an OP_Eq comparison on the two previous operands
2050 ** would have been true (1), then fall through.
2052 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
2053 assert( pOp>aOp );
2054 assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
2055 assert( pOp[-1].p5 & SQLITE_STOREP2 );
2056 VdbeBranchTaken(iCompare!=0, 2);
2057 if( iCompare!=0 ) goto jump_to_p2;
2058 break;
2062 /* Opcode: Permutation * * * P4 *
2064 ** Set the permutation used by the OP_Compare operator in the next
2065 ** instruction. The permutation is stored in the P4 operand.
2067 ** The permutation is only valid until the next OP_Compare that has
2068 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2069 ** occur immediately prior to the OP_Compare.
2071 ** The first integer in the P4 integer array is the length of the array
2072 ** and does not become part of the permutation.
2074 case OP_Permutation: {
2075 assert( pOp->p4type==P4_INTARRAY );
2076 assert( pOp->p4.ai );
2077 assert( pOp[1].opcode==OP_Compare );
2078 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2079 break;
2082 /* Opcode: Compare P1 P2 P3 P4 P5
2083 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2085 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2086 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2087 ** the comparison for use by the next OP_Jump instruct.
2089 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2090 ** determined by the most recent OP_Permutation operator. If the
2091 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2092 ** order.
2094 ** P4 is a KeyInfo structure that defines collating sequences and sort
2095 ** orders for the comparison. The permutation applies to registers
2096 ** only. The KeyInfo elements are used sequentially.
2098 ** The comparison is a sort comparison, so NULLs compare equal,
2099 ** NULLs are less than numbers, numbers are less than strings,
2100 ** and strings are less than blobs.
2102 case OP_Compare: {
2103 int n;
2104 int i;
2105 int p1;
2106 int p2;
2107 const KeyInfo *pKeyInfo;
2108 int idx;
2109 CollSeq *pColl; /* Collating sequence to use on this term */
2110 int bRev; /* True for DESCENDING sort order */
2111 int *aPermute; /* The permutation */
2113 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2114 aPermute = 0;
2115 }else{
2116 assert( pOp>aOp );
2117 assert( pOp[-1].opcode==OP_Permutation );
2118 assert( pOp[-1].p4type==P4_INTARRAY );
2119 aPermute = pOp[-1].p4.ai + 1;
2120 assert( aPermute!=0 );
2122 n = pOp->p3;
2123 pKeyInfo = pOp->p4.pKeyInfo;
2124 assert( n>0 );
2125 assert( pKeyInfo!=0 );
2126 p1 = pOp->p1;
2127 p2 = pOp->p2;
2128 #ifdef SQLITE_DEBUG
2129 if( aPermute ){
2130 int k, mx = 0;
2131 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
2132 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2133 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2134 }else{
2135 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2136 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2138 #endif /* SQLITE_DEBUG */
2139 for(i=0; i<n; i++){
2140 idx = aPermute ? aPermute[i] : i;
2141 assert( memIsValid(&aMem[p1+idx]) );
2142 assert( memIsValid(&aMem[p2+idx]) );
2143 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2144 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2145 assert( i<pKeyInfo->nKeyField );
2146 pColl = pKeyInfo->aColl[i];
2147 bRev = pKeyInfo->aSortOrder[i];
2148 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2149 if( iCompare ){
2150 if( bRev ) iCompare = -iCompare;
2151 break;
2154 break;
2157 /* Opcode: Jump P1 P2 P3 * *
2159 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2160 ** in the most recent OP_Compare instruction the P1 vector was less than
2161 ** equal to, or greater than the P2 vector, respectively.
2163 case OP_Jump: { /* jump */
2164 if( iCompare<0 ){
2165 VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
2166 }else if( iCompare==0 ){
2167 VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
2168 }else{
2169 VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
2171 break;
2174 /* Opcode: And P1 P2 P3 * *
2175 ** Synopsis: r[P3]=(r[P1] && r[P2])
2177 ** Take the logical AND of the values in registers P1 and P2 and
2178 ** write the result into register P3.
2180 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2181 ** the other input is NULL. A NULL and true or two NULLs give
2182 ** a NULL output.
2184 /* Opcode: Or P1 P2 P3 * *
2185 ** Synopsis: r[P3]=(r[P1] || r[P2])
2187 ** Take the logical OR of the values in register P1 and P2 and
2188 ** store the answer in register P3.
2190 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2191 ** even if the other input is NULL. A NULL and false or two NULLs
2192 ** give a NULL output.
2194 case OP_And: /* same as TK_AND, in1, in2, out3 */
2195 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2196 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2197 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2199 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2200 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2201 if( pOp->opcode==OP_And ){
2202 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2203 v1 = and_logic[v1*3+v2];
2204 }else{
2205 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2206 v1 = or_logic[v1*3+v2];
2208 pOut = &aMem[pOp->p3];
2209 if( v1==2 ){
2210 MemSetTypeFlag(pOut, MEM_Null);
2211 }else{
2212 pOut->u.i = v1;
2213 MemSetTypeFlag(pOut, MEM_Int);
2215 break;
2218 /* Opcode: IsTrue P1 P2 P3 P4 *
2219 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2221 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2222 ** IS NOT FALSE operators.
2224 ** Interpret the value in register P1 as a boolean value. Store that
2225 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2226 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2227 ** is 1.
2229 ** The logic is summarized like this:
2231 ** <ul>
2232 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2233 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2234 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2235 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2236 ** </ul>
2238 case OP_IsTrue: { /* in1, out2 */
2239 assert( pOp->p4type==P4_INT32 );
2240 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2241 assert( pOp->p3==0 || pOp->p3==1 );
2242 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2243 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2244 break;
2247 /* Opcode: Not P1 P2 * * *
2248 ** Synopsis: r[P2]= !r[P1]
2250 ** Interpret the value in register P1 as a boolean value. Store the
2251 ** boolean complement in register P2. If the value in register P1 is
2252 ** NULL, then a NULL is stored in P2.
2254 case OP_Not: { /* same as TK_NOT, in1, out2 */
2255 pIn1 = &aMem[pOp->p1];
2256 pOut = &aMem[pOp->p2];
2257 if( (pIn1->flags & MEM_Null)==0 ){
2258 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2259 }else{
2260 sqlite3VdbeMemSetNull(pOut);
2262 break;
2265 /* Opcode: BitNot P1 P2 * * *
2266 ** Synopsis: r[P2]= ~r[P1]
2268 ** Interpret the content of register P1 as an integer. Store the
2269 ** ones-complement of the P1 value into register P2. If P1 holds
2270 ** a NULL then store a NULL in P2.
2272 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2273 pIn1 = &aMem[pOp->p1];
2274 pOut = &aMem[pOp->p2];
2275 sqlite3VdbeMemSetNull(pOut);
2276 if( (pIn1->flags & MEM_Null)==0 ){
2277 pOut->flags = MEM_Int;
2278 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2280 break;
2283 /* Opcode: Once P1 P2 * * *
2285 ** Fall through to the next instruction the first time this opcode is
2286 ** encountered on each invocation of the byte-code program. Jump to P2
2287 ** on the second and all subsequent encounters during the same invocation.
2289 ** Top-level programs determine first invocation by comparing the P1
2290 ** operand against the P1 operand on the OP_Init opcode at the beginning
2291 ** of the program. If the P1 values differ, then fall through and make
2292 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2293 ** the same then take the jump.
2295 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2296 ** whether or not the jump should be taken. The bitmask is necessary
2297 ** because the self-altering code trick does not work for recursive
2298 ** triggers.
2300 case OP_Once: { /* jump */
2301 u32 iAddr; /* Address of this instruction */
2302 assert( p->aOp[0].opcode==OP_Init );
2303 if( p->pFrame ){
2304 iAddr = (int)(pOp - p->aOp);
2305 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2306 VdbeBranchTaken(1, 2);
2307 goto jump_to_p2;
2309 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2310 }else{
2311 if( p->aOp[0].p1==pOp->p1 ){
2312 VdbeBranchTaken(1, 2);
2313 goto jump_to_p2;
2316 VdbeBranchTaken(0, 2);
2317 pOp->p1 = p->aOp[0].p1;
2318 break;
2321 /* Opcode: If P1 P2 P3 * *
2323 ** Jump to P2 if the value in register P1 is true. The value
2324 ** is considered true if it is numeric and non-zero. If the value
2325 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2327 case OP_If: { /* jump, in1 */
2328 int c;
2329 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2330 VdbeBranchTaken(c!=0, 2);
2331 if( c ) goto jump_to_p2;
2332 break;
2335 /* Opcode: IfNot P1 P2 P3 * *
2337 ** Jump to P2 if the value in register P1 is False. The value
2338 ** is considered false if it has a numeric value of zero. If the value
2339 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2341 case OP_IfNot: { /* jump, in1 */
2342 int c;
2343 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2344 VdbeBranchTaken(c!=0, 2);
2345 if( c ) goto jump_to_p2;
2346 break;
2349 /* Opcode: IsNull P1 P2 * * *
2350 ** Synopsis: if r[P1]==NULL goto P2
2352 ** Jump to P2 if the value in register P1 is NULL.
2354 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2355 pIn1 = &aMem[pOp->p1];
2356 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2357 if( (pIn1->flags & MEM_Null)!=0 ){
2358 goto jump_to_p2;
2360 break;
2363 /* Opcode: NotNull P1 P2 * * *
2364 ** Synopsis: if r[P1]!=NULL goto P2
2366 ** Jump to P2 if the value in register P1 is not NULL.
2368 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2369 pIn1 = &aMem[pOp->p1];
2370 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2371 if( (pIn1->flags & MEM_Null)==0 ){
2372 goto jump_to_p2;
2374 break;
2377 /* Opcode: IfNullRow P1 P2 P3 * *
2378 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2380 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2381 ** If it is, then set register P3 to NULL and jump immediately to P2.
2382 ** If P1 is not on a NULL row, then fall through without making any
2383 ** changes.
2385 case OP_IfNullRow: { /* jump */
2386 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2387 assert( p->apCsr[pOp->p1]!=0 );
2388 if( p->apCsr[pOp->p1]->nullRow ){
2389 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2390 goto jump_to_p2;
2392 break;
2395 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2396 /* Opcode: Offset P1 P2 P3 * *
2397 ** Synopsis: r[P3] = sqlite_offset(P1)
2399 ** Store in register r[P3] the byte offset into the database file that is the
2400 ** start of the payload for the record at which that cursor P1 is currently
2401 ** pointing.
2403 ** P2 is the column number for the argument to the sqlite_offset() function.
2404 ** This opcode does not use P2 itself, but the P2 value is used by the
2405 ** code generator. The P1, P2, and P3 operands to this opcode are the
2406 ** same as for OP_Column.
2408 ** This opcode is only available if SQLite is compiled with the
2409 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2411 case OP_Offset: { /* out3 */
2412 VdbeCursor *pC; /* The VDBE cursor */
2413 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2414 pC = p->apCsr[pOp->p1];
2415 pOut = &p->aMem[pOp->p3];
2416 if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
2417 sqlite3VdbeMemSetNull(pOut);
2418 }else{
2419 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2421 break;
2423 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2425 /* Opcode: Column P1 P2 P3 P4 P5
2426 ** Synopsis: r[P3]=PX
2428 ** Interpret the data that cursor P1 points to as a structure built using
2429 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2430 ** information about the format of the data.) Extract the P2-th column
2431 ** from this record. If there are less that (P2+1)
2432 ** values in the record, extract a NULL.
2434 ** The value extracted is stored in register P3.
2436 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2437 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2438 ** the result.
2440 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2441 ** then the cache of the cursor is reset prior to extracting the column.
2442 ** The first OP_Column against a pseudo-table after the value of the content
2443 ** register has changed should have this bit set.
2445 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2446 ** the result is guaranteed to only be used as the argument of a length()
2447 ** or typeof() function, respectively. The loading of large blobs can be
2448 ** skipped for length() and all content loading can be skipped for typeof().
2450 case OP_Column: {
2451 int p2; /* column number to retrieve */
2452 VdbeCursor *pC; /* The VDBE cursor */
2453 BtCursor *pCrsr; /* The BTree cursor */
2454 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2455 int len; /* The length of the serialized data for the column */
2456 int i; /* Loop counter */
2457 Mem *pDest; /* Where to write the extracted value */
2458 Mem sMem; /* For storing the record being decoded */
2459 const u8 *zData; /* Part of the record being decoded */
2460 const u8 *zHdr; /* Next unparsed byte of the header */
2461 const u8 *zEndHdr; /* Pointer to first byte after the header */
2462 u64 offset64; /* 64-bit offset */
2463 u32 t; /* A type code from the record header */
2464 Mem *pReg; /* PseudoTable input register */
2466 pC = p->apCsr[pOp->p1];
2467 p2 = pOp->p2;
2469 /* If the cursor cache is stale (meaning it is not currently point at
2470 ** the correct row) then bring it up-to-date by doing the necessary
2471 ** B-Tree seek. */
2472 rc = sqlite3VdbeCursorMoveto(&pC, &p2);
2473 if( rc ) goto abort_due_to_error;
2475 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2476 pDest = &aMem[pOp->p3];
2477 memAboutToChange(p, pDest);
2478 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2479 assert( pC!=0 );
2480 assert( p2<pC->nField );
2481 aOffset = pC->aOffset;
2482 assert( pC->eCurType!=CURTYPE_VTAB );
2483 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2484 assert( pC->eCurType!=CURTYPE_SORTER );
2486 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2487 if( pC->nullRow ){
2488 if( pC->eCurType==CURTYPE_PSEUDO ){
2489 /* For the special case of as pseudo-cursor, the seekResult field
2490 ** identifies the register that holds the record */
2491 assert( pC->seekResult>0 );
2492 pReg = &aMem[pC->seekResult];
2493 assert( pReg->flags & MEM_Blob );
2494 assert( memIsValid(pReg) );
2495 pC->payloadSize = pC->szRow = pReg->n;
2496 pC->aRow = (u8*)pReg->z;
2497 }else{
2498 sqlite3VdbeMemSetNull(pDest);
2499 goto op_column_out;
2501 }else{
2502 pCrsr = pC->uc.pCursor;
2503 assert( pC->eCurType==CURTYPE_BTREE );
2504 assert( pCrsr );
2505 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2506 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2507 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2508 assert( pC->szRow<=pC->payloadSize );
2509 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2510 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2511 goto too_big;
2514 pC->cacheStatus = p->cacheCtr;
2515 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
2516 pC->nHdrParsed = 0;
2519 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2520 /* pC->aRow does not have to hold the entire row, but it does at least
2521 ** need to cover the header of the record. If pC->aRow does not contain
2522 ** the complete header, then set it to zero, forcing the header to be
2523 ** dynamically allocated. */
2524 pC->aRow = 0;
2525 pC->szRow = 0;
2527 /* Make sure a corrupt database has not given us an oversize header.
2528 ** Do this now to avoid an oversize memory allocation.
2530 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2531 ** types use so much data space that there can only be 4096 and 32 of
2532 ** them, respectively. So the maximum header length results from a
2533 ** 3-byte type for each of the maximum of 32768 columns plus three
2534 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2536 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2537 goto op_column_corrupt;
2539 }else{
2540 /* This is an optimization. By skipping over the first few tests
2541 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2542 ** measurable performance gain.
2544 ** This branch is taken even if aOffset[0]==0. Such a record is never
2545 ** generated by SQLite, and could be considered corruption, but we
2546 ** accept it for historical reasons. When aOffset[0]==0, the code this
2547 ** branch jumps to reads past the end of the record, but never more
2548 ** than a few bytes. Even if the record occurs at the end of the page
2549 ** content area, the "page header" comes after the page content and so
2550 ** this overread is harmless. Similar overreads can occur for a corrupt
2551 ** database file.
2553 zData = pC->aRow;
2554 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2555 testcase( aOffset[0]==0 );
2556 goto op_column_read_header;
2560 /* Make sure at least the first p2+1 entries of the header have been
2561 ** parsed and valid information is in aOffset[] and pC->aType[].
2563 if( pC->nHdrParsed<=p2 ){
2564 /* If there is more header available for parsing in the record, try
2565 ** to extract additional fields up through the p2+1-th field
2567 if( pC->iHdrOffset<aOffset[0] ){
2568 /* Make sure zData points to enough of the record to cover the header. */
2569 if( pC->aRow==0 ){
2570 memset(&sMem, 0, sizeof(sMem));
2571 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
2572 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2573 zData = (u8*)sMem.z;
2574 }else{
2575 zData = pC->aRow;
2578 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2579 op_column_read_header:
2580 i = pC->nHdrParsed;
2581 offset64 = aOffset[i];
2582 zHdr = zData + pC->iHdrOffset;
2583 zEndHdr = zData + aOffset[0];
2584 testcase( zHdr>=zEndHdr );
2586 if( (t = zHdr[0])<0x80 ){
2587 zHdr++;
2588 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2589 }else{
2590 zHdr += sqlite3GetVarint32(zHdr, &t);
2591 offset64 += sqlite3VdbeSerialTypeLen(t);
2593 pC->aType[i++] = t;
2594 aOffset[i] = (u32)(offset64 & 0xffffffff);
2595 }while( i<=p2 && zHdr<zEndHdr );
2597 /* The record is corrupt if any of the following are true:
2598 ** (1) the bytes of the header extend past the declared header size
2599 ** (2) the entire header was used but not all data was used
2600 ** (3) the end of the data extends beyond the end of the record.
2602 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2603 || (offset64 > pC->payloadSize)
2605 if( aOffset[0]==0 ){
2606 i = 0;
2607 zHdr = zEndHdr;
2608 }else{
2609 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2610 goto op_column_corrupt;
2614 pC->nHdrParsed = i;
2615 pC->iHdrOffset = (u32)(zHdr - zData);
2616 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2617 }else{
2618 t = 0;
2621 /* If after trying to extract new entries from the header, nHdrParsed is
2622 ** still not up to p2, that means that the record has fewer than p2
2623 ** columns. So the result will be either the default value or a NULL.
2625 if( pC->nHdrParsed<=p2 ){
2626 if( pOp->p4type==P4_MEM ){
2627 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2628 }else{
2629 sqlite3VdbeMemSetNull(pDest);
2631 goto op_column_out;
2633 }else{
2634 t = pC->aType[p2];
2637 /* Extract the content for the p2+1-th column. Control can only
2638 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2639 ** all valid.
2641 assert( p2<pC->nHdrParsed );
2642 assert( rc==SQLITE_OK );
2643 assert( sqlite3VdbeCheckMemInvariants(pDest) );
2644 if( VdbeMemDynamic(pDest) ){
2645 sqlite3VdbeMemSetNull(pDest);
2647 assert( t==pC->aType[p2] );
2648 if( pC->szRow>=aOffset[p2+1] ){
2649 /* This is the common case where the desired content fits on the original
2650 ** page - where the content is not on an overflow page */
2651 zData = pC->aRow + aOffset[p2];
2652 if( t<12 ){
2653 sqlite3VdbeSerialGet(zData, t, pDest);
2654 }else{
2655 /* If the column value is a string, we need a persistent value, not
2656 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2657 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2659 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
2660 pDest->n = len = (t-12)/2;
2661 pDest->enc = encoding;
2662 if( pDest->szMalloc < len+2 ){
2663 pDest->flags = MEM_Null;
2664 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
2665 }else{
2666 pDest->z = pDest->zMalloc;
2668 memcpy(pDest->z, zData, len);
2669 pDest->z[len] = 0;
2670 pDest->z[len+1] = 0;
2671 pDest->flags = aFlag[t&1];
2673 }else{
2674 pDest->enc = encoding;
2675 /* This branch happens only when content is on overflow pages */
2676 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2677 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2678 || (len = sqlite3VdbeSerialTypeLen(t))==0
2680 /* Content is irrelevant for
2681 ** 1. the typeof() function,
2682 ** 2. the length(X) function if X is a blob, and
2683 ** 3. if the content length is zero.
2684 ** So we might as well use bogus content rather than reading
2685 ** content from disk.
2687 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2688 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2689 ** read up to 16. So 16 bytes of bogus content is supplied.
2691 static u8 aZero[16]; /* This is the bogus content */
2692 sqlite3VdbeSerialGet(aZero, t, pDest);
2693 }else{
2694 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
2695 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2696 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2697 pDest->flags &= ~MEM_Ephem;
2701 op_column_out:
2702 UPDATE_MAX_BLOBSIZE(pDest);
2703 REGISTER_TRACE(pOp->p3, pDest);
2704 break;
2706 op_column_corrupt:
2707 if( aOp[0].p3>0 ){
2708 pOp = &aOp[aOp[0].p3-1];
2709 break;
2710 }else{
2711 rc = SQLITE_CORRUPT_BKPT;
2712 goto abort_due_to_error;
2716 /* Opcode: Affinity P1 P2 * P4 *
2717 ** Synopsis: affinity(r[P1@P2])
2719 ** Apply affinities to a range of P2 registers starting with P1.
2721 ** P4 is a string that is P2 characters long. The N-th character of the
2722 ** string indicates the column affinity that should be used for the N-th
2723 ** memory cell in the range.
2725 case OP_Affinity: {
2726 const char *zAffinity; /* The affinity to be applied */
2728 zAffinity = pOp->p4.z;
2729 assert( zAffinity!=0 );
2730 assert( pOp->p2>0 );
2731 assert( zAffinity[pOp->p2]==0 );
2732 pIn1 = &aMem[pOp->p1];
2734 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
2735 assert( memIsValid(pIn1) );
2736 applyAffinity(pIn1, *(zAffinity++), encoding);
2737 pIn1++;
2738 }while( zAffinity[0] );
2739 break;
2742 /* Opcode: MakeRecord P1 P2 P3 P4 *
2743 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2745 ** Convert P2 registers beginning with P1 into the [record format]
2746 ** use as a data record in a database table or as a key
2747 ** in an index. The OP_Column opcode can decode the record later.
2749 ** P4 may be a string that is P2 characters long. The N-th character of the
2750 ** string indicates the column affinity that should be used for the N-th
2751 ** field of the index key.
2753 ** The mapping from character to affinity is given by the SQLITE_AFF_
2754 ** macros defined in sqliteInt.h.
2756 ** If P4 is NULL then all index fields have the affinity BLOB.
2758 case OP_MakeRecord: {
2759 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2760 Mem *pRec; /* The new record */
2761 u64 nData; /* Number of bytes of data space */
2762 int nHdr; /* Number of bytes of header space */
2763 i64 nByte; /* Data space required for this record */
2764 i64 nZero; /* Number of zero bytes at the end of the record */
2765 int nVarint; /* Number of bytes in a varint */
2766 u32 serial_type; /* Type field */
2767 Mem *pData0; /* First field to be combined into the record */
2768 Mem *pLast; /* Last field of the record */
2769 int nField; /* Number of fields in the record */
2770 char *zAffinity; /* The affinity string for the record */
2771 int file_format; /* File format to use for encoding */
2772 int i; /* Space used in zNewRecord[] header */
2773 int j; /* Space used in zNewRecord[] content */
2774 u32 len; /* Length of a field */
2776 /* Assuming the record contains N fields, the record format looks
2777 ** like this:
2779 ** ------------------------------------------------------------------------
2780 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2781 ** ------------------------------------------------------------------------
2783 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2784 ** and so forth.
2786 ** Each type field is a varint representing the serial type of the
2787 ** corresponding data element (see sqlite3VdbeSerialType()). The
2788 ** hdr-size field is also a varint which is the offset from the beginning
2789 ** of the record to data0.
2791 nData = 0; /* Number of bytes of data space */
2792 nHdr = 0; /* Number of bytes of header space */
2793 nZero = 0; /* Number of zero bytes at the end of the record */
2794 nField = pOp->p1;
2795 zAffinity = pOp->p4.z;
2796 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
2797 pData0 = &aMem[nField];
2798 nField = pOp->p2;
2799 pLast = &pData0[nField-1];
2800 file_format = p->minWriteFileFormat;
2802 /* Identify the output register */
2803 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2804 pOut = &aMem[pOp->p3];
2805 memAboutToChange(p, pOut);
2807 /* Apply the requested affinity to all inputs
2809 assert( pData0<=pLast );
2810 if( zAffinity ){
2811 pRec = pData0;
2813 applyAffinity(pRec++, *(zAffinity++), encoding);
2814 assert( zAffinity[0]==0 || pRec<=pLast );
2815 }while( zAffinity[0] );
2818 #ifdef SQLITE_ENABLE_NULL_TRIM
2819 /* NULLs can be safely trimmed from the end of the record, as long as
2820 ** as the schema format is 2 or more and none of the omitted columns
2821 ** have a non-NULL default value. Also, the record must be left with
2822 ** at least one field. If P5>0 then it will be one more than the
2823 ** index of the right-most column with a non-NULL default value */
2824 if( pOp->p5 ){
2825 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
2826 pLast--;
2827 nField--;
2830 #endif
2832 /* Loop through the elements that will make up the record to figure
2833 ** out how much space is required for the new record.
2835 pRec = pLast;
2837 assert( memIsValid(pRec) );
2838 serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
2839 if( pRec->flags & MEM_Zero ){
2840 if( serial_type==0 ){
2841 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
2842 ** table methods that never invoke sqlite3_result_xxxxx() while
2843 ** computing an unchanging column value in an UPDATE statement.
2844 ** Give such values a special internal-use-only serial-type of 10
2845 ** so that they can be passed through to xUpdate and have
2846 ** a true sqlite3_value_nochange(). */
2847 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
2848 serial_type = 10;
2849 }else if( nData ){
2850 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
2851 }else{
2852 nZero += pRec->u.nZero;
2853 len -= pRec->u.nZero;
2856 nData += len;
2857 testcase( serial_type==127 );
2858 testcase( serial_type==128 );
2859 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
2860 pRec->uTemp = serial_type;
2861 if( pRec==pData0 ) break;
2862 pRec--;
2863 }while(1);
2865 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
2866 ** which determines the total number of bytes in the header. The varint
2867 ** value is the size of the header in bytes including the size varint
2868 ** itself. */
2869 testcase( nHdr==126 );
2870 testcase( nHdr==127 );
2871 if( nHdr<=126 ){
2872 /* The common case */
2873 nHdr += 1;
2874 }else{
2875 /* Rare case of a really large header */
2876 nVarint = sqlite3VarintLen(nHdr);
2877 nHdr += nVarint;
2878 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
2880 nByte = nHdr+nData;
2881 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2882 goto too_big;
2885 /* Make sure the output register has a buffer large enough to store
2886 ** the new record. The output register (pOp->p3) is not allowed to
2887 ** be one of the input registers (because the following call to
2888 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2890 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
2891 goto no_mem;
2893 zNewRecord = (u8 *)pOut->z;
2895 /* Write the record */
2896 i = putVarint32(zNewRecord, nHdr);
2897 j = nHdr;
2898 assert( pData0<=pLast );
2899 pRec = pData0;
2901 serial_type = pRec->uTemp;
2902 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
2903 ** additional varints, one per column. */
2904 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
2905 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
2906 ** immediately follow the header. */
2907 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
2908 }while( (++pRec)<=pLast );
2909 assert( i==nHdr );
2910 assert( j==nByte );
2912 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2913 pOut->n = (int)nByte;
2914 pOut->flags = MEM_Blob;
2915 if( nZero ){
2916 pOut->u.nZero = nZero;
2917 pOut->flags |= MEM_Zero;
2919 REGISTER_TRACE(pOp->p3, pOut);
2920 UPDATE_MAX_BLOBSIZE(pOut);
2921 break;
2924 /* Opcode: Count P1 P2 * * *
2925 ** Synopsis: r[P2]=count()
2927 ** Store the number of entries (an integer value) in the table or index
2928 ** opened by cursor P1 in register P2
2930 #ifndef SQLITE_OMIT_BTREECOUNT
2931 case OP_Count: { /* out2 */
2932 i64 nEntry;
2933 BtCursor *pCrsr;
2935 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
2936 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
2937 assert( pCrsr );
2938 nEntry = 0; /* Not needed. Only used to silence a warning. */
2939 rc = sqlite3BtreeCount(pCrsr, &nEntry);
2940 if( rc ) goto abort_due_to_error;
2941 pOut = out2Prerelease(p, pOp);
2942 pOut->u.i = nEntry;
2943 break;
2945 #endif
2947 /* Opcode: Savepoint P1 * * P4 *
2949 ** Open, release or rollback the savepoint named by parameter P4, depending
2950 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2951 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2953 case OP_Savepoint: {
2954 int p1; /* Value of P1 operand */
2955 char *zName; /* Name of savepoint */
2956 int nName;
2957 Savepoint *pNew;
2958 Savepoint *pSavepoint;
2959 Savepoint *pTmp;
2960 int iSavepoint;
2961 int ii;
2963 p1 = pOp->p1;
2964 zName = pOp->p4.z;
2966 /* Assert that the p1 parameter is valid. Also that if there is no open
2967 ** transaction, then there cannot be any savepoints.
2969 assert( db->pSavepoint==0 || db->autoCommit==0 );
2970 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
2971 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
2972 assert( checkSavepointCount(db) );
2973 assert( p->bIsReader );
2975 if( p1==SAVEPOINT_BEGIN ){
2976 if( db->nVdbeWrite>0 ){
2977 /* A new savepoint cannot be created if there are active write
2978 ** statements (i.e. open read/write incremental blob handles).
2980 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
2981 rc = SQLITE_BUSY;
2982 }else{
2983 nName = sqlite3Strlen30(zName);
2985 #ifndef SQLITE_OMIT_VIRTUALTABLE
2986 /* This call is Ok even if this savepoint is actually a transaction
2987 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2988 ** If this is a transaction savepoint being opened, it is guaranteed
2989 ** that the db->aVTrans[] array is empty. */
2990 assert( db->autoCommit==0 || db->nVTrans==0 );
2991 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
2992 db->nStatement+db->nSavepoint);
2993 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2994 #endif
2996 /* Create a new savepoint structure. */
2997 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
2998 if( pNew ){
2999 pNew->zName = (char *)&pNew[1];
3000 memcpy(pNew->zName, zName, nName+1);
3002 /* If there is no open transaction, then mark this as a special
3003 ** "transaction savepoint". */
3004 if( db->autoCommit ){
3005 db->autoCommit = 0;
3006 db->isTransactionSavepoint = 1;
3007 }else{
3008 db->nSavepoint++;
3011 /* Link the new savepoint into the database handle's list. */
3012 pNew->pNext = db->pSavepoint;
3013 db->pSavepoint = pNew;
3014 pNew->nDeferredCons = db->nDeferredCons;
3015 pNew->nDeferredImmCons = db->nDeferredImmCons;
3018 }else{
3019 iSavepoint = 0;
3021 /* Find the named savepoint. If there is no such savepoint, then an
3022 ** an error is returned to the user. */
3023 for(
3024 pSavepoint = db->pSavepoint;
3025 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3026 pSavepoint = pSavepoint->pNext
3028 iSavepoint++;
3030 if( !pSavepoint ){
3031 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3032 rc = SQLITE_ERROR;
3033 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3034 /* It is not possible to release (commit) a savepoint if there are
3035 ** active write statements.
3037 sqlite3VdbeError(p, "cannot release savepoint - "
3038 "SQL statements in progress");
3039 rc = SQLITE_BUSY;
3040 }else{
3042 /* Determine whether or not this is a transaction savepoint. If so,
3043 ** and this is a RELEASE command, then the current transaction
3044 ** is committed.
3046 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3047 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3048 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3049 goto vdbe_return;
3051 db->autoCommit = 1;
3052 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3053 p->pc = (int)(pOp - aOp);
3054 db->autoCommit = 0;
3055 p->rc = rc = SQLITE_BUSY;
3056 goto vdbe_return;
3058 db->isTransactionSavepoint = 0;
3059 rc = p->rc;
3060 }else{
3061 int isSchemaChange;
3062 iSavepoint = db->nSavepoint - iSavepoint - 1;
3063 if( p1==SAVEPOINT_ROLLBACK ){
3064 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3065 for(ii=0; ii<db->nDb; ii++){
3066 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3067 SQLITE_ABORT_ROLLBACK,
3068 isSchemaChange==0);
3069 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3071 }else{
3072 isSchemaChange = 0;
3074 for(ii=0; ii<db->nDb; ii++){
3075 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3076 if( rc!=SQLITE_OK ){
3077 goto abort_due_to_error;
3080 if( isSchemaChange ){
3081 sqlite3ExpirePreparedStatements(db);
3082 sqlite3ResetAllSchemasOfConnection(db);
3083 db->mDbFlags |= DBFLAG_SchemaChange;
3087 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3088 ** savepoints nested inside of the savepoint being operated on. */
3089 while( db->pSavepoint!=pSavepoint ){
3090 pTmp = db->pSavepoint;
3091 db->pSavepoint = pTmp->pNext;
3092 sqlite3DbFree(db, pTmp);
3093 db->nSavepoint--;
3096 /* If it is a RELEASE, then destroy the savepoint being operated on
3097 ** too. If it is a ROLLBACK TO, then set the number of deferred
3098 ** constraint violations present in the database to the value stored
3099 ** when the savepoint was created. */
3100 if( p1==SAVEPOINT_RELEASE ){
3101 assert( pSavepoint==db->pSavepoint );
3102 db->pSavepoint = pSavepoint->pNext;
3103 sqlite3DbFree(db, pSavepoint);
3104 if( !isTransaction ){
3105 db->nSavepoint--;
3107 }else{
3108 db->nDeferredCons = pSavepoint->nDeferredCons;
3109 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3112 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3113 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3114 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3118 if( rc ) goto abort_due_to_error;
3120 break;
3123 /* Opcode: AutoCommit P1 P2 * * *
3125 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3126 ** back any currently active btree transactions. If there are any active
3127 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3128 ** there are active writing VMs or active VMs that use shared cache.
3130 ** This instruction causes the VM to halt.
3132 case OP_AutoCommit: {
3133 int desiredAutoCommit;
3134 int iRollback;
3136 desiredAutoCommit = pOp->p1;
3137 iRollback = pOp->p2;
3138 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3139 assert( desiredAutoCommit==1 || iRollback==0 );
3140 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3141 assert( p->bIsReader );
3143 if( desiredAutoCommit!=db->autoCommit ){
3144 if( iRollback ){
3145 assert( desiredAutoCommit==1 );
3146 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3147 db->autoCommit = 1;
3148 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3149 /* If this instruction implements a COMMIT and other VMs are writing
3150 ** return an error indicating that the other VMs must complete first.
3152 sqlite3VdbeError(p, "cannot commit transaction - "
3153 "SQL statements in progress");
3154 rc = SQLITE_BUSY;
3155 goto abort_due_to_error;
3156 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3157 goto vdbe_return;
3158 }else{
3159 db->autoCommit = (u8)desiredAutoCommit;
3161 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3162 p->pc = (int)(pOp - aOp);
3163 db->autoCommit = (u8)(1-desiredAutoCommit);
3164 p->rc = rc = SQLITE_BUSY;
3165 goto vdbe_return;
3167 assert( db->nStatement==0 );
3168 sqlite3CloseSavepoints(db);
3169 if( p->rc==SQLITE_OK ){
3170 rc = SQLITE_DONE;
3171 }else{
3172 rc = SQLITE_ERROR;
3174 goto vdbe_return;
3175 }else{
3176 sqlite3VdbeError(p,
3177 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3178 (iRollback)?"cannot rollback - no transaction is active":
3179 "cannot commit - no transaction is active"));
3181 rc = SQLITE_ERROR;
3182 goto abort_due_to_error;
3184 break;
3187 /* Opcode: Transaction P1 P2 P3 P4 P5
3189 ** Begin a transaction on database P1 if a transaction is not already
3190 ** active.
3191 ** If P2 is non-zero, then a write-transaction is started, or if a
3192 ** read-transaction is already active, it is upgraded to a write-transaction.
3193 ** If P2 is zero, then a read-transaction is started.
3195 ** P1 is the index of the database file on which the transaction is
3196 ** started. Index 0 is the main database file and index 1 is the
3197 ** file used for temporary tables. Indices of 2 or more are used for
3198 ** attached databases.
3200 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3201 ** true (this flag is set if the Vdbe may modify more than one row and may
3202 ** throw an ABORT exception), a statement transaction may also be opened.
3203 ** More specifically, a statement transaction is opened iff the database
3204 ** connection is currently not in autocommit mode, or if there are other
3205 ** active statements. A statement transaction allows the changes made by this
3206 ** VDBE to be rolled back after an error without having to roll back the
3207 ** entire transaction. If no error is encountered, the statement transaction
3208 ** will automatically commit when the VDBE halts.
3210 ** If P5!=0 then this opcode also checks the schema cookie against P3
3211 ** and the schema generation counter against P4.
3212 ** The cookie changes its value whenever the database schema changes.
3213 ** This operation is used to detect when that the cookie has changed
3214 ** and that the current process needs to reread the schema. If the schema
3215 ** cookie in P3 differs from the schema cookie in the database header or
3216 ** if the schema generation counter in P4 differs from the current
3217 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3218 ** halts. The sqlite3_step() wrapper function might then reprepare the
3219 ** statement and rerun it from the beginning.
3221 case OP_Transaction: {
3222 Btree *pBt;
3223 int iMeta = 0;
3225 assert( p->bIsReader );
3226 assert( p->readOnly==0 || pOp->p2==0 );
3227 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3228 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3229 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3230 rc = SQLITE_READONLY;
3231 goto abort_due_to_error;
3233 pBt = db->aDb[pOp->p1].pBt;
3235 if( pBt ){
3236 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
3237 testcase( rc==SQLITE_BUSY_SNAPSHOT );
3238 testcase( rc==SQLITE_BUSY_RECOVERY );
3239 if( rc!=SQLITE_OK ){
3240 if( (rc&0xff)==SQLITE_BUSY ){
3241 p->pc = (int)(pOp - aOp);
3242 p->rc = rc;
3243 goto vdbe_return;
3245 goto abort_due_to_error;
3248 if( pOp->p2 && p->usesStmtJournal
3249 && (db->autoCommit==0 || db->nVdbeRead>1)
3251 assert( sqlite3BtreeIsInTrans(pBt) );
3252 if( p->iStatement==0 ){
3253 assert( db->nStatement>=0 && db->nSavepoint>=0 );
3254 db->nStatement++;
3255 p->iStatement = db->nSavepoint + db->nStatement;
3258 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3259 if( rc==SQLITE_OK ){
3260 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3263 /* Store the current value of the database handles deferred constraint
3264 ** counter. If the statement transaction needs to be rolled back,
3265 ** the value of this counter needs to be restored too. */
3266 p->nStmtDefCons = db->nDeferredCons;
3267 p->nStmtDefImmCons = db->nDeferredImmCons;
3270 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3271 if( pOp->p5
3272 && (iMeta!=pOp->p3
3273 || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
3276 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3277 ** version is checked to ensure that the schema has not changed since the
3278 ** SQL statement was prepared.
3280 sqlite3DbFree(db, p->zErrMsg);
3281 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3282 /* If the schema-cookie from the database file matches the cookie
3283 ** stored with the in-memory representation of the schema, do
3284 ** not reload the schema from the database file.
3286 ** If virtual-tables are in use, this is not just an optimization.
3287 ** Often, v-tables store their data in other SQLite tables, which
3288 ** are queried from within xNext() and other v-table methods using
3289 ** prepared queries. If such a query is out-of-date, we do not want to
3290 ** discard the database schema, as the user code implementing the
3291 ** v-table would have to be ready for the sqlite3_vtab structure itself
3292 ** to be invalidated whenever sqlite3_step() is called from within
3293 ** a v-table method.
3295 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3296 sqlite3ResetOneSchema(db, pOp->p1);
3298 p->expired = 1;
3299 rc = SQLITE_SCHEMA;
3301 if( rc ) goto abort_due_to_error;
3302 break;
3305 /* Opcode: ReadCookie P1 P2 P3 * *
3307 ** Read cookie number P3 from database P1 and write it into register P2.
3308 ** P3==1 is the schema version. P3==2 is the database format.
3309 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3310 ** the main database file and P1==1 is the database file used to store
3311 ** temporary tables.
3313 ** There must be a read-lock on the database (either a transaction
3314 ** must be started or there must be an open cursor) before
3315 ** executing this instruction.
3317 case OP_ReadCookie: { /* out2 */
3318 int iMeta;
3319 int iDb;
3320 int iCookie;
3322 assert( p->bIsReader );
3323 iDb = pOp->p1;
3324 iCookie = pOp->p3;
3325 assert( pOp->p3<SQLITE_N_BTREE_META );
3326 assert( iDb>=0 && iDb<db->nDb );
3327 assert( db->aDb[iDb].pBt!=0 );
3328 assert( DbMaskTest(p->btreeMask, iDb) );
3330 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3331 pOut = out2Prerelease(p, pOp);
3332 pOut->u.i = iMeta;
3333 break;
3336 /* Opcode: SetCookie P1 P2 P3 * *
3338 ** Write the integer value P3 into cookie number P2 of database P1.
3339 ** P2==1 is the schema version. P2==2 is the database format.
3340 ** P2==3 is the recommended pager cache
3341 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3342 ** database file used to store temporary tables.
3344 ** A transaction must be started before executing this opcode.
3346 case OP_SetCookie: {
3347 Db *pDb;
3349 sqlite3VdbeIncrWriteCounter(p, 0);
3350 assert( pOp->p2<SQLITE_N_BTREE_META );
3351 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3352 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3353 assert( p->readOnly==0 );
3354 pDb = &db->aDb[pOp->p1];
3355 assert( pDb->pBt!=0 );
3356 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3357 /* See note about index shifting on OP_ReadCookie */
3358 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3359 if( pOp->p2==BTREE_SCHEMA_VERSION ){
3360 /* When the schema cookie changes, record the new cookie internally */
3361 pDb->pSchema->schema_cookie = pOp->p3;
3362 db->mDbFlags |= DBFLAG_SchemaChange;
3363 }else if( pOp->p2==BTREE_FILE_FORMAT ){
3364 /* Record changes in the file format */
3365 pDb->pSchema->file_format = pOp->p3;
3367 if( pOp->p1==1 ){
3368 /* Invalidate all prepared statements whenever the TEMP database
3369 ** schema is changed. Ticket #1644 */
3370 sqlite3ExpirePreparedStatements(db);
3371 p->expired = 0;
3373 if( rc ) goto abort_due_to_error;
3374 break;
3377 /* Opcode: OpenRead P1 P2 P3 P4 P5
3378 ** Synopsis: root=P2 iDb=P3
3380 ** Open a read-only cursor for the database table whose root page is
3381 ** P2 in a database file. The database file is determined by P3.
3382 ** P3==0 means the main database, P3==1 means the database used for
3383 ** temporary tables, and P3>1 means used the corresponding attached
3384 ** database. Give the new cursor an identifier of P1. The P1
3385 ** values need not be contiguous but all P1 values should be small integers.
3386 ** It is an error for P1 to be negative.
3388 ** Allowed P5 bits:
3389 ** <ul>
3390 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3391 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3392 ** of OP_SeekLE/OP_IdxGT)
3393 ** </ul>
3395 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3396 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3397 ** object, then table being opened must be an [index b-tree] where the
3398 ** KeyInfo object defines the content and collating
3399 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3400 ** value, then the table being opened must be a [table b-tree] with a
3401 ** number of columns no less than the value of P4.
3403 ** See also: OpenWrite, ReopenIdx
3405 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3406 ** Synopsis: root=P2 iDb=P3
3408 ** The ReopenIdx opcode works like OP_OpenRead except that it first
3409 ** checks to see if the cursor on P1 is already open on the same
3410 ** b-tree and if it is this opcode becomes a no-op. In other words,
3411 ** if the cursor is already open, do not reopen it.
3413 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
3414 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
3415 ** be the same as every other ReopenIdx or OpenRead for the same cursor
3416 ** number.
3418 ** Allowed P5 bits:
3419 ** <ul>
3420 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3421 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3422 ** of OP_SeekLE/OP_IdxGT)
3423 ** </ul>
3425 ** See also: OP_OpenRead, OP_OpenWrite
3427 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3428 ** Synopsis: root=P2 iDb=P3
3430 ** Open a read/write cursor named P1 on the table or index whose root
3431 ** page is P2 (or whose root page is held in register P2 if the
3432 ** OPFLAG_P2ISREG bit is set in P5 - see below).
3434 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3435 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3436 ** object, then table being opened must be an [index b-tree] where the
3437 ** KeyInfo object defines the content and collating
3438 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3439 ** value, then the table being opened must be a [table b-tree] with a
3440 ** number of columns no less than the value of P4.
3442 ** Allowed P5 bits:
3443 ** <ul>
3444 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3445 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3446 ** of OP_SeekLE/OP_IdxGT)
3447 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
3448 ** and subsequently delete entries in an index btree. This is a
3449 ** hint to the storage engine that the storage engine is allowed to
3450 ** ignore. The hint is not used by the official SQLite b*tree storage
3451 ** engine, but is used by COMDB2.
3452 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
3453 ** as the root page, not the value of P2 itself.
3454 ** </ul>
3456 ** This instruction works like OpenRead except that it opens the cursor
3457 ** in read/write mode.
3459 ** See also: OP_OpenRead, OP_ReopenIdx
3461 case OP_ReopenIdx: {
3462 int nField;
3463 KeyInfo *pKeyInfo;
3464 int p2;
3465 int iDb;
3466 int wrFlag;
3467 Btree *pX;
3468 VdbeCursor *pCur;
3469 Db *pDb;
3471 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3472 assert( pOp->p4type==P4_KEYINFO );
3473 pCur = p->apCsr[pOp->p1];
3474 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3475 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
3476 goto open_cursor_set_hints;
3478 /* If the cursor is not currently open or is open on a different
3479 ** index, then fall through into OP_OpenRead to force a reopen */
3480 case OP_OpenRead:
3481 case OP_OpenWrite:
3483 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3484 assert( p->bIsReader );
3485 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3486 || p->readOnly==0 );
3488 if( p->expired ){
3489 rc = SQLITE_ABORT_ROLLBACK;
3490 goto abort_due_to_error;
3493 nField = 0;
3494 pKeyInfo = 0;
3495 p2 = pOp->p2;
3496 iDb = pOp->p3;
3497 assert( iDb>=0 && iDb<db->nDb );
3498 assert( DbMaskTest(p->btreeMask, iDb) );
3499 pDb = &db->aDb[iDb];
3500 pX = pDb->pBt;
3501 assert( pX!=0 );
3502 if( pOp->opcode==OP_OpenWrite ){
3503 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
3504 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
3505 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3506 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3507 p->minWriteFileFormat = pDb->pSchema->file_format;
3509 }else{
3510 wrFlag = 0;
3512 if( pOp->p5 & OPFLAG_P2ISREG ){
3513 assert( p2>0 );
3514 assert( p2<=(p->nMem+1 - p->nCursor) );
3515 assert( pOp->opcode==OP_OpenWrite );
3516 pIn2 = &aMem[p2];
3517 assert( memIsValid(pIn2) );
3518 assert( (pIn2->flags & MEM_Int)!=0 );
3519 sqlite3VdbeMemIntegerify(pIn2);
3520 p2 = (int)pIn2->u.i;
3521 /* The p2 value always comes from a prior OP_CreateBtree opcode and
3522 ** that opcode will always set the p2 value to 2 or more or else fail.
3523 ** If there were a failure, the prepared statement would have halted
3524 ** before reaching this instruction. */
3525 assert( p2>=2 );
3527 if( pOp->p4type==P4_KEYINFO ){
3528 pKeyInfo = pOp->p4.pKeyInfo;
3529 assert( pKeyInfo->enc==ENC(db) );
3530 assert( pKeyInfo->db==db );
3531 nField = pKeyInfo->nAllField;
3532 }else if( pOp->p4type==P4_INT32 ){
3533 nField = pOp->p4.i;
3535 assert( pOp->p1>=0 );
3536 assert( nField>=0 );
3537 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3538 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
3539 if( pCur==0 ) goto no_mem;
3540 pCur->nullRow = 1;
3541 pCur->isOrdered = 1;
3542 pCur->pgnoRoot = p2;
3543 #ifdef SQLITE_DEBUG
3544 pCur->wrFlag = wrFlag;
3545 #endif
3546 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
3547 pCur->pKeyInfo = pKeyInfo;
3548 /* Set the VdbeCursor.isTable variable. Previous versions of
3549 ** SQLite used to check if the root-page flags were sane at this point
3550 ** and report database corruption if they were not, but this check has
3551 ** since moved into the btree layer. */
3552 pCur->isTable = pOp->p4type!=P4_KEYINFO;
3554 open_cursor_set_hints:
3555 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3556 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
3557 testcase( pOp->p5 & OPFLAG_BULKCSR );
3558 #ifdef SQLITE_ENABLE_CURSOR_HINTS
3559 testcase( pOp->p2 & OPFLAG_SEEKEQ );
3560 #endif
3561 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
3562 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
3563 if( rc ) goto abort_due_to_error;
3564 break;
3567 /* Opcode: OpenDup P1 P2 * * *
3569 ** Open a new cursor P1 that points to the same ephemeral table as
3570 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
3571 ** opcode. Only ephemeral cursors may be duplicated.
3573 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
3575 case OP_OpenDup: {
3576 VdbeCursor *pOrig; /* The original cursor to be duplicated */
3577 VdbeCursor *pCx; /* The new cursor */
3579 pOrig = p->apCsr[pOp->p2];
3580 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
3582 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
3583 if( pCx==0 ) goto no_mem;
3584 pCx->nullRow = 1;
3585 pCx->isEphemeral = 1;
3586 pCx->pKeyInfo = pOrig->pKeyInfo;
3587 pCx->isTable = pOrig->isTable;
3588 rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
3589 pCx->pKeyInfo, pCx->uc.pCursor);
3590 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
3591 ** opened for a database. Since there is already an open cursor when this
3592 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
3593 assert( rc==SQLITE_OK );
3594 break;
3598 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3599 ** Synopsis: nColumn=P2
3601 ** Open a new cursor P1 to a transient table.
3602 ** The cursor is always opened read/write even if
3603 ** the main database is read-only. The ephemeral
3604 ** table is deleted automatically when the cursor is closed.
3606 ** P2 is the number of columns in the ephemeral table.
3607 ** The cursor points to a BTree table if P4==0 and to a BTree index
3608 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3609 ** that defines the format of keys in the index.
3611 ** The P5 parameter can be a mask of the BTREE_* flags defined
3612 ** in btree.h. These flags control aspects of the operation of
3613 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3614 ** added automatically.
3616 /* Opcode: OpenAutoindex P1 P2 * P4 *
3617 ** Synopsis: nColumn=P2
3619 ** This opcode works the same as OP_OpenEphemeral. It has a
3620 ** different name to distinguish its use. Tables created using
3621 ** by this opcode will be used for automatically created transient
3622 ** indices in joins.
3624 case OP_OpenAutoindex:
3625 case OP_OpenEphemeral: {
3626 VdbeCursor *pCx;
3627 KeyInfo *pKeyInfo;
3629 static const int vfsFlags =
3630 SQLITE_OPEN_READWRITE |
3631 SQLITE_OPEN_CREATE |
3632 SQLITE_OPEN_EXCLUSIVE |
3633 SQLITE_OPEN_DELETEONCLOSE |
3634 SQLITE_OPEN_TRANSIENT_DB;
3635 assert( pOp->p1>=0 );
3636 assert( pOp->p2>=0 );
3637 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
3638 if( pCx==0 ) goto no_mem;
3639 pCx->nullRow = 1;
3640 pCx->isEphemeral = 1;
3641 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
3642 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
3643 if( rc==SQLITE_OK ){
3644 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
3646 if( rc==SQLITE_OK ){
3647 /* If a transient index is required, create it by calling
3648 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3649 ** opening it. If a transient table is required, just use the
3650 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3652 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3653 int pgno;
3654 assert( pOp->p4type==P4_KEYINFO );
3655 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
3656 if( rc==SQLITE_OK ){
3657 assert( pgno==MASTER_ROOT+1 );
3658 assert( pKeyInfo->db==db );
3659 assert( pKeyInfo->enc==ENC(db) );
3660 rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
3661 pKeyInfo, pCx->uc.pCursor);
3663 pCx->isTable = 0;
3664 }else{
3665 rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
3666 0, pCx->uc.pCursor);
3667 pCx->isTable = 1;
3670 if( rc ) goto abort_due_to_error;
3671 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3672 break;
3675 /* Opcode: SorterOpen P1 P2 P3 P4 *
3677 ** This opcode works like OP_OpenEphemeral except that it opens
3678 ** a transient index that is specifically designed to sort large
3679 ** tables using an external merge-sort algorithm.
3681 ** If argument P3 is non-zero, then it indicates that the sorter may
3682 ** assume that a stable sort considering the first P3 fields of each
3683 ** key is sufficient to produce the required results.
3685 case OP_SorterOpen: {
3686 VdbeCursor *pCx;
3688 assert( pOp->p1>=0 );
3689 assert( pOp->p2>=0 );
3690 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
3691 if( pCx==0 ) goto no_mem;
3692 pCx->pKeyInfo = pOp->p4.pKeyInfo;
3693 assert( pCx->pKeyInfo->db==db );
3694 assert( pCx->pKeyInfo->enc==ENC(db) );
3695 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
3696 if( rc ) goto abort_due_to_error;
3697 break;
3700 /* Opcode: SequenceTest P1 P2 * * *
3701 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3703 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3704 ** to P2. Regardless of whether or not the jump is taken, increment the
3705 ** the sequence value.
3707 case OP_SequenceTest: {
3708 VdbeCursor *pC;
3709 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3710 pC = p->apCsr[pOp->p1];
3711 assert( isSorter(pC) );
3712 if( (pC->seqCount++)==0 ){
3713 goto jump_to_p2;
3715 break;
3718 /* Opcode: OpenPseudo P1 P2 P3 * *
3719 ** Synopsis: P3 columns in r[P2]
3721 ** Open a new cursor that points to a fake table that contains a single
3722 ** row of data. The content of that one row is the content of memory
3723 ** register P2. In other words, cursor P1 becomes an alias for the
3724 ** MEM_Blob content contained in register P2.
3726 ** A pseudo-table created by this opcode is used to hold a single
3727 ** row output from the sorter so that the row can be decomposed into
3728 ** individual columns using the OP_Column opcode. The OP_Column opcode
3729 ** is the only cursor opcode that works with a pseudo-table.
3731 ** P3 is the number of fields in the records that will be stored by
3732 ** the pseudo-table.
3734 case OP_OpenPseudo: {
3735 VdbeCursor *pCx;
3737 assert( pOp->p1>=0 );
3738 assert( pOp->p3>=0 );
3739 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
3740 if( pCx==0 ) goto no_mem;
3741 pCx->nullRow = 1;
3742 pCx->seekResult = pOp->p2;
3743 pCx->isTable = 1;
3744 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
3745 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
3746 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
3747 ** which is a performance optimization */
3748 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
3749 assert( pOp->p5==0 );
3750 break;
3753 /* Opcode: Close P1 * * * *
3755 ** Close a cursor previously opened as P1. If P1 is not
3756 ** currently open, this instruction is a no-op.
3758 case OP_Close: {
3759 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3760 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
3761 p->apCsr[pOp->p1] = 0;
3762 break;
3765 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3766 /* Opcode: ColumnsUsed P1 * * P4 *
3768 ** This opcode (which only exists if SQLite was compiled with
3769 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
3770 ** table or index for cursor P1 are used. P4 is a 64-bit integer
3771 ** (P4_INT64) in which the first 63 bits are one for each of the
3772 ** first 63 columns of the table or index that are actually used
3773 ** by the cursor. The high-order bit is set if any column after
3774 ** the 64th is used.
3776 case OP_ColumnsUsed: {
3777 VdbeCursor *pC;
3778 pC = p->apCsr[pOp->p1];
3779 assert( pC->eCurType==CURTYPE_BTREE );
3780 pC->maskUsed = *(u64*)pOp->p4.pI64;
3781 break;
3783 #endif
3785 /* Opcode: SeekGE P1 P2 P3 P4 *
3786 ** Synopsis: key=r[P3@P4]
3788 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3789 ** use the value in register P3 as the key. If cursor P1 refers
3790 ** to an SQL index, then P3 is the first in an array of P4 registers
3791 ** that are used as an unpacked index key.
3793 ** Reposition cursor P1 so that it points to the smallest entry that
3794 ** is greater than or equal to the key value. If there are no records
3795 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3797 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3798 ** opcode will always land on a record that equally equals the key, or
3799 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3800 ** opcode must be followed by an IdxLE opcode with the same arguments.
3801 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
3802 ** IdxLE opcode will be used on subsequent loop iterations.
3804 ** This opcode leaves the cursor configured to move in forward order,
3805 ** from the beginning toward the end. In other words, the cursor is
3806 ** configured to use Next, not Prev.
3808 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3810 /* Opcode: SeekGT P1 P2 P3 P4 *
3811 ** Synopsis: key=r[P3@P4]
3813 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3814 ** use the value in register P3 as a key. If cursor P1 refers
3815 ** to an SQL index, then P3 is the first in an array of P4 registers
3816 ** that are used as an unpacked index key.
3818 ** Reposition cursor P1 so that it points to the smallest entry that
3819 ** is greater than the key value. If there are no records greater than
3820 ** the key and P2 is not zero, then jump to P2.
3822 ** This opcode leaves the cursor configured to move in forward order,
3823 ** from the beginning toward the end. In other words, the cursor is
3824 ** configured to use Next, not Prev.
3826 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3828 /* Opcode: SeekLT P1 P2 P3 P4 *
3829 ** Synopsis: key=r[P3@P4]
3831 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3832 ** use the value in register P3 as a key. If cursor P1 refers
3833 ** to an SQL index, then P3 is the first in an array of P4 registers
3834 ** that are used as an unpacked index key.
3836 ** Reposition cursor P1 so that it points to the largest entry that
3837 ** is less than the key value. If there are no records less than
3838 ** the key and P2 is not zero, then jump to P2.
3840 ** This opcode leaves the cursor configured to move in reverse order,
3841 ** from the end toward the beginning. In other words, the cursor is
3842 ** configured to use Prev, not Next.
3844 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3846 /* Opcode: SeekLE P1 P2 P3 P4 *
3847 ** Synopsis: key=r[P3@P4]
3849 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3850 ** use the value in register P3 as a key. If cursor P1 refers
3851 ** to an SQL index, then P3 is the first in an array of P4 registers
3852 ** that are used as an unpacked index key.
3854 ** Reposition cursor P1 so that it points to the largest entry that
3855 ** is less than or equal to the key value. If there are no records
3856 ** less than or equal to the key and P2 is not zero, then jump to P2.
3858 ** This opcode leaves the cursor configured to move in reverse order,
3859 ** from the end toward the beginning. In other words, the cursor is
3860 ** configured to use Prev, not Next.
3862 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3863 ** opcode will always land on a record that equally equals the key, or
3864 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3865 ** opcode must be followed by an IdxGE opcode with the same arguments.
3866 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
3867 ** IdxGE opcode will be used on subsequent loop iterations.
3869 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3871 case OP_SeekLT: /* jump, in3 */
3872 case OP_SeekLE: /* jump, in3 */
3873 case OP_SeekGE: /* jump, in3 */
3874 case OP_SeekGT: { /* jump, in3 */
3875 int res; /* Comparison result */
3876 int oc; /* Opcode */
3877 VdbeCursor *pC; /* The cursor to seek */
3878 UnpackedRecord r; /* The key to seek for */
3879 int nField; /* Number of columns or fields in the key */
3880 i64 iKey; /* The rowid we are to seek to */
3881 int eqOnly; /* Only interested in == results */
3883 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3884 assert( pOp->p2!=0 );
3885 pC = p->apCsr[pOp->p1];
3886 assert( pC!=0 );
3887 assert( pC->eCurType==CURTYPE_BTREE );
3888 assert( OP_SeekLE == OP_SeekLT+1 );
3889 assert( OP_SeekGE == OP_SeekLT+2 );
3890 assert( OP_SeekGT == OP_SeekLT+3 );
3891 assert( pC->isOrdered );
3892 assert( pC->uc.pCursor!=0 );
3893 oc = pOp->opcode;
3894 eqOnly = 0;
3895 pC->nullRow = 0;
3896 #ifdef SQLITE_DEBUG
3897 pC->seekOp = pOp->opcode;
3898 #endif
3900 if( pC->isTable ){
3901 /* The BTREE_SEEK_EQ flag is only set on index cursors */
3902 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
3903 || CORRUPT_DB );
3905 /* The input value in P3 might be of any type: integer, real, string,
3906 ** blob, or NULL. But it needs to be an integer before we can do
3907 ** the seek, so convert it. */
3908 pIn3 = &aMem[pOp->p3];
3909 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
3910 applyNumericAffinity(pIn3, 0);
3912 iKey = sqlite3VdbeIntValue(pIn3);
3914 /* If the P3 value could not be converted into an integer without
3915 ** loss of information, then special processing is required... */
3916 if( (pIn3->flags & MEM_Int)==0 ){
3917 if( (pIn3->flags & MEM_Real)==0 ){
3918 /* If the P3 value cannot be converted into any kind of a number,
3919 ** then the seek is not possible, so jump to P2 */
3920 VdbeBranchTaken(1,2); goto jump_to_p2;
3921 break;
3924 /* If the approximation iKey is larger than the actual real search
3925 ** term, substitute >= for > and < for <=. e.g. if the search term
3926 ** is 4.9 and the integer approximation 5:
3928 ** (x > 4.9) -> (x >= 5)
3929 ** (x <= 4.9) -> (x < 5)
3931 if( pIn3->u.r<(double)iKey ){
3932 assert( OP_SeekGE==(OP_SeekGT-1) );
3933 assert( OP_SeekLT==(OP_SeekLE-1) );
3934 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
3935 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
3938 /* If the approximation iKey is smaller than the actual real search
3939 ** term, substitute <= for < and > for >=. */
3940 else if( pIn3->u.r>(double)iKey ){
3941 assert( OP_SeekLE==(OP_SeekLT+1) );
3942 assert( OP_SeekGT==(OP_SeekGE+1) );
3943 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
3944 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
3947 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
3948 pC->movetoTarget = iKey; /* Used by OP_Delete */
3949 if( rc!=SQLITE_OK ){
3950 goto abort_due_to_error;
3952 }else{
3953 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
3954 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
3955 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
3957 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
3958 eqOnly = 1;
3959 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
3960 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
3961 assert( pOp[1].p1==pOp[0].p1 );
3962 assert( pOp[1].p2==pOp[0].p2 );
3963 assert( pOp[1].p3==pOp[0].p3 );
3964 assert( pOp[1].p4.i==pOp[0].p4.i );
3967 nField = pOp->p4.i;
3968 assert( pOp->p4type==P4_INT32 );
3969 assert( nField>0 );
3970 r.pKeyInfo = pC->pKeyInfo;
3971 r.nField = (u16)nField;
3973 /* The next line of code computes as follows, only faster:
3974 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3975 ** r.default_rc = -1;
3976 ** }else{
3977 ** r.default_rc = +1;
3978 ** }
3980 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
3981 assert( oc!=OP_SeekGT || r.default_rc==-1 );
3982 assert( oc!=OP_SeekLE || r.default_rc==-1 );
3983 assert( oc!=OP_SeekGE || r.default_rc==+1 );
3984 assert( oc!=OP_SeekLT || r.default_rc==+1 );
3986 r.aMem = &aMem[pOp->p3];
3987 #ifdef SQLITE_DEBUG
3988 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3989 #endif
3990 r.eqSeen = 0;
3991 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
3992 if( rc!=SQLITE_OK ){
3993 goto abort_due_to_error;
3995 if( eqOnly && r.eqSeen==0 ){
3996 assert( res!=0 );
3997 goto seek_not_found;
4000 pC->deferredMoveto = 0;
4001 pC->cacheStatus = CACHE_STALE;
4002 #ifdef SQLITE_TEST
4003 sqlite3_search_count++;
4004 #endif
4005 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
4006 if( res<0 || (res==0 && oc==OP_SeekGT) ){
4007 res = 0;
4008 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4009 if( rc!=SQLITE_OK ){
4010 if( rc==SQLITE_DONE ){
4011 rc = SQLITE_OK;
4012 res = 1;
4013 }else{
4014 goto abort_due_to_error;
4017 }else{
4018 res = 0;
4020 }else{
4021 assert( oc==OP_SeekLT || oc==OP_SeekLE );
4022 if( res>0 || (res==0 && oc==OP_SeekLT) ){
4023 res = 0;
4024 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4025 if( rc!=SQLITE_OK ){
4026 if( rc==SQLITE_DONE ){
4027 rc = SQLITE_OK;
4028 res = 1;
4029 }else{
4030 goto abort_due_to_error;
4033 }else{
4034 /* res might be negative because the table is empty. Check to
4035 ** see if this is the case.
4037 res = sqlite3BtreeEof(pC->uc.pCursor);
4040 seek_not_found:
4041 assert( pOp->p2>0 );
4042 VdbeBranchTaken(res!=0,2);
4043 if( res ){
4044 goto jump_to_p2;
4045 }else if( eqOnly ){
4046 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4047 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4049 break;
4052 /* Opcode: SeekHit P1 P2 * * *
4053 ** Synopsis: seekHit=P2
4055 ** Set the seekHit flag on cursor P1 to the value in P2.
4056 ** The seekHit flag is used by the IfNoHope opcode.
4058 ** P1 must be a valid b-tree cursor. P2 must be a boolean value,
4059 ** either 0 or 1.
4061 case OP_SeekHit: {
4062 VdbeCursor *pC;
4063 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4064 pC = p->apCsr[pOp->p1];
4065 assert( pC!=0 );
4066 assert( pOp->p2==0 || pOp->p2==1 );
4067 pC->seekHit = pOp->p2 & 1;
4068 break;
4071 /* Opcode: Found P1 P2 P3 P4 *
4072 ** Synopsis: key=r[P3@P4]
4074 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4075 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4076 ** record.
4078 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4079 ** is a prefix of any entry in P1 then a jump is made to P2 and
4080 ** P1 is left pointing at the matching entry.
4082 ** This operation leaves the cursor in a state where it can be
4083 ** advanced in the forward direction. The Next instruction will work,
4084 ** but not the Prev instruction.
4086 ** See also: NotFound, NoConflict, NotExists. SeekGe
4088 /* Opcode: NotFound P1 P2 P3 P4 *
4089 ** Synopsis: key=r[P3@P4]
4091 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4092 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4093 ** record.
4095 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4096 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
4097 ** does contain an entry whose prefix matches the P3/P4 record then control
4098 ** falls through to the next instruction and P1 is left pointing at the
4099 ** matching entry.
4101 ** This operation leaves the cursor in a state where it cannot be
4102 ** advanced in either direction. In other words, the Next and Prev
4103 ** opcodes do not work after this operation.
4105 ** See also: Found, NotExists, NoConflict, IfNoHope
4107 /* Opcode: IfNoHope P1 P2 P3 P4 *
4108 ** Synopsis: key=r[P3@P4]
4110 ** Register P3 is the first of P4 registers that form an unpacked
4111 ** record.
4113 ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then
4114 ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then
4115 ** check to see if there is any entry in P1 that matches the
4116 ** prefix identified by P3 and P4. If no entry matches the prefix,
4117 ** jump to P2. Otherwise fall through.
4119 ** This opcode behaves like OP_NotFound if the seekHit
4120 ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
4122 ** This opcode is used in IN clause processing for a multi-column key.
4123 ** If an IN clause is attached to an element of the key other than the
4124 ** left-most element, and if there are no matches on the most recent
4125 ** seek over the whole key, then it might be that one of the key element
4126 ** to the left is prohibiting a match, and hence there is "no hope" of
4127 ** any match regardless of how many IN clause elements are checked.
4128 ** In such a case, we abandon the IN clause search early, using this
4129 ** opcode. The opcode name comes from the fact that the
4130 ** jump is taken if there is "no hope" of achieving a match.
4132 ** See also: NotFound, SeekHit
4134 /* Opcode: NoConflict P1 P2 P3 P4 *
4135 ** Synopsis: key=r[P3@P4]
4137 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4138 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4139 ** record.
4141 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4142 ** contains any NULL value, jump immediately to P2. If all terms of the
4143 ** record are not-NULL then a check is done to determine if any row in the
4144 ** P1 index btree has a matching key prefix. If there are no matches, jump
4145 ** immediately to P2. If there is a match, fall through and leave the P1
4146 ** cursor pointing to the matching row.
4148 ** This opcode is similar to OP_NotFound with the exceptions that the
4149 ** branch is always taken if any part of the search key input is NULL.
4151 ** This operation leaves the cursor in a state where it cannot be
4152 ** advanced in either direction. In other words, the Next and Prev
4153 ** opcodes do not work after this operation.
4155 ** See also: NotFound, Found, NotExists
4157 case OP_IfNoHope: { /* jump, in3 */
4158 VdbeCursor *pC;
4159 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4160 pC = p->apCsr[pOp->p1];
4161 assert( pC!=0 );
4162 if( pC->seekHit ) break;
4163 /* Fall through into OP_NotFound */
4165 case OP_NoConflict: /* jump, in3 */
4166 case OP_NotFound: /* jump, in3 */
4167 case OP_Found: { /* jump, in3 */
4168 int alreadyExists;
4169 int takeJump;
4170 int ii;
4171 VdbeCursor *pC;
4172 int res;
4173 UnpackedRecord *pFree;
4174 UnpackedRecord *pIdxKey;
4175 UnpackedRecord r;
4177 #ifdef SQLITE_TEST
4178 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4179 #endif
4181 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4182 assert( pOp->p4type==P4_INT32 );
4183 pC = p->apCsr[pOp->p1];
4184 assert( pC!=0 );
4185 #ifdef SQLITE_DEBUG
4186 pC->seekOp = pOp->opcode;
4187 #endif
4188 pIn3 = &aMem[pOp->p3];
4189 assert( pC->eCurType==CURTYPE_BTREE );
4190 assert( pC->uc.pCursor!=0 );
4191 assert( pC->isTable==0 );
4192 if( pOp->p4.i>0 ){
4193 r.pKeyInfo = pC->pKeyInfo;
4194 r.nField = (u16)pOp->p4.i;
4195 r.aMem = pIn3;
4196 #ifdef SQLITE_DEBUG
4197 for(ii=0; ii<r.nField; ii++){
4198 assert( memIsValid(&r.aMem[ii]) );
4199 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4200 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4202 #endif
4203 pIdxKey = &r;
4204 pFree = 0;
4205 }else{
4206 assert( pIn3->flags & MEM_Blob );
4207 rc = ExpandBlob(pIn3);
4208 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4209 if( rc ) goto no_mem;
4210 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4211 if( pIdxKey==0 ) goto no_mem;
4212 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4214 pIdxKey->default_rc = 0;
4215 takeJump = 0;
4216 if( pOp->opcode==OP_NoConflict ){
4217 /* For the OP_NoConflict opcode, take the jump if any of the
4218 ** input fields are NULL, since any key with a NULL will not
4219 ** conflict */
4220 for(ii=0; ii<pIdxKey->nField; ii++){
4221 if( pIdxKey->aMem[ii].flags & MEM_Null ){
4222 takeJump = 1;
4223 break;
4227 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
4228 if( pFree ) sqlite3DbFreeNN(db, pFree);
4229 if( rc!=SQLITE_OK ){
4230 goto abort_due_to_error;
4232 pC->seekResult = res;
4233 alreadyExists = (res==0);
4234 pC->nullRow = 1-alreadyExists;
4235 pC->deferredMoveto = 0;
4236 pC->cacheStatus = CACHE_STALE;
4237 if( pOp->opcode==OP_Found ){
4238 VdbeBranchTaken(alreadyExists!=0,2);
4239 if( alreadyExists ) goto jump_to_p2;
4240 }else{
4241 VdbeBranchTaken(takeJump||alreadyExists==0,2);
4242 if( takeJump || !alreadyExists ) goto jump_to_p2;
4244 break;
4247 /* Opcode: SeekRowid P1 P2 P3 * *
4248 ** Synopsis: intkey=r[P3]
4250 ** P1 is the index of a cursor open on an SQL table btree (with integer
4251 ** keys). If register P3 does not contain an integer or if P1 does not
4252 ** contain a record with rowid P3 then jump immediately to P2.
4253 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4254 ** a record with rowid P3 then
4255 ** leave the cursor pointing at that record and fall through to the next
4256 ** instruction.
4258 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4259 ** the P3 register must be guaranteed to contain an integer value. With this
4260 ** opcode, register P3 might not contain an integer.
4262 ** The OP_NotFound opcode performs the same operation on index btrees
4263 ** (with arbitrary multi-value keys).
4265 ** This opcode leaves the cursor in a state where it cannot be advanced
4266 ** in either direction. In other words, the Next and Prev opcodes will
4267 ** not work following this opcode.
4269 ** See also: Found, NotFound, NoConflict, SeekRowid
4271 /* Opcode: NotExists P1 P2 P3 * *
4272 ** Synopsis: intkey=r[P3]
4274 ** P1 is the index of a cursor open on an SQL table btree (with integer
4275 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4276 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4277 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4278 ** leave the cursor pointing at that record and fall through to the next
4279 ** instruction.
4281 ** The OP_SeekRowid opcode performs the same operation but also allows the
4282 ** P3 register to contain a non-integer value, in which case the jump is
4283 ** always taken. This opcode requires that P3 always contain an integer.
4285 ** The OP_NotFound opcode performs the same operation on index btrees
4286 ** (with arbitrary multi-value keys).
4288 ** This opcode leaves the cursor in a state where it cannot be advanced
4289 ** in either direction. In other words, the Next and Prev opcodes will
4290 ** not work following this opcode.
4292 ** See also: Found, NotFound, NoConflict, SeekRowid
4294 case OP_SeekRowid: { /* jump, in3 */
4295 VdbeCursor *pC;
4296 BtCursor *pCrsr;
4297 int res;
4298 u64 iKey;
4300 pIn3 = &aMem[pOp->p3];
4301 if( (pIn3->flags & MEM_Int)==0 ){
4302 applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
4303 if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
4305 /* Fall through into OP_NotExists */
4306 case OP_NotExists: /* jump, in3 */
4307 pIn3 = &aMem[pOp->p3];
4308 assert( pIn3->flags & MEM_Int );
4309 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4310 pC = p->apCsr[pOp->p1];
4311 assert( pC!=0 );
4312 #ifdef SQLITE_DEBUG
4313 pC->seekOp = OP_SeekRowid;
4314 #endif
4315 assert( pC->isTable );
4316 assert( pC->eCurType==CURTYPE_BTREE );
4317 pCrsr = pC->uc.pCursor;
4318 assert( pCrsr!=0 );
4319 res = 0;
4320 iKey = pIn3->u.i;
4321 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
4322 assert( rc==SQLITE_OK || res==0 );
4323 pC->movetoTarget = iKey; /* Used by OP_Delete */
4324 pC->nullRow = 0;
4325 pC->cacheStatus = CACHE_STALE;
4326 pC->deferredMoveto = 0;
4327 VdbeBranchTaken(res!=0,2);
4328 pC->seekResult = res;
4329 if( res!=0 ){
4330 assert( rc==SQLITE_OK );
4331 if( pOp->p2==0 ){
4332 rc = SQLITE_CORRUPT_BKPT;
4333 }else{
4334 goto jump_to_p2;
4337 if( rc ) goto abort_due_to_error;
4338 break;
4341 /* Opcode: Sequence P1 P2 * * *
4342 ** Synopsis: r[P2]=cursor[P1].ctr++
4344 ** Find the next available sequence number for cursor P1.
4345 ** Write the sequence number into register P2.
4346 ** The sequence number on the cursor is incremented after this
4347 ** instruction.
4349 case OP_Sequence: { /* out2 */
4350 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4351 assert( p->apCsr[pOp->p1]!=0 );
4352 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
4353 pOut = out2Prerelease(p, pOp);
4354 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
4355 break;
4359 /* Opcode: NewRowid P1 P2 P3 * *
4360 ** Synopsis: r[P2]=rowid
4362 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4363 ** The record number is not previously used as a key in the database
4364 ** table that cursor P1 points to. The new record number is written
4365 ** written to register P2.
4367 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4368 ** the largest previously generated record number. No new record numbers are
4369 ** allowed to be less than this value. When this value reaches its maximum,
4370 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4371 ** generated record number. This P3 mechanism is used to help implement the
4372 ** AUTOINCREMENT feature.
4374 case OP_NewRowid: { /* out2 */
4375 i64 v; /* The new rowid */
4376 VdbeCursor *pC; /* Cursor of table to get the new rowid */
4377 int res; /* Result of an sqlite3BtreeLast() */
4378 int cnt; /* Counter to limit the number of searches */
4379 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
4380 VdbeFrame *pFrame; /* Root frame of VDBE */
4382 v = 0;
4383 res = 0;
4384 pOut = out2Prerelease(p, pOp);
4385 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4386 pC = p->apCsr[pOp->p1];
4387 assert( pC!=0 );
4388 assert( pC->isTable );
4389 assert( pC->eCurType==CURTYPE_BTREE );
4390 assert( pC->uc.pCursor!=0 );
4392 /* The next rowid or record number (different terms for the same
4393 ** thing) is obtained in a two-step algorithm.
4395 ** First we attempt to find the largest existing rowid and add one
4396 ** to that. But if the largest existing rowid is already the maximum
4397 ** positive integer, we have to fall through to the second
4398 ** probabilistic algorithm
4400 ** The second algorithm is to select a rowid at random and see if
4401 ** it already exists in the table. If it does not exist, we have
4402 ** succeeded. If the random rowid does exist, we select a new one
4403 ** and try again, up to 100 times.
4405 assert( pC->isTable );
4407 #ifdef SQLITE_32BIT_ROWID
4408 # define MAX_ROWID 0x7fffffff
4409 #else
4410 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4411 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4412 ** to provide the constant while making all compilers happy.
4414 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4415 #endif
4417 if( !pC->useRandomRowid ){
4418 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4419 if( rc!=SQLITE_OK ){
4420 goto abort_due_to_error;
4422 if( res ){
4423 v = 1; /* IMP: R-61914-48074 */
4424 }else{
4425 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
4426 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4427 if( v>=MAX_ROWID ){
4428 pC->useRandomRowid = 1;
4429 }else{
4430 v++; /* IMP: R-29538-34987 */
4435 #ifndef SQLITE_OMIT_AUTOINCREMENT
4436 if( pOp->p3 ){
4437 /* Assert that P3 is a valid memory cell. */
4438 assert( pOp->p3>0 );
4439 if( p->pFrame ){
4440 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4441 /* Assert that P3 is a valid memory cell. */
4442 assert( pOp->p3<=pFrame->nMem );
4443 pMem = &pFrame->aMem[pOp->p3];
4444 }else{
4445 /* Assert that P3 is a valid memory cell. */
4446 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
4447 pMem = &aMem[pOp->p3];
4448 memAboutToChange(p, pMem);
4450 assert( memIsValid(pMem) );
4452 REGISTER_TRACE(pOp->p3, pMem);
4453 sqlite3VdbeMemIntegerify(pMem);
4454 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
4455 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4456 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
4457 goto abort_due_to_error;
4459 if( v<pMem->u.i+1 ){
4460 v = pMem->u.i + 1;
4462 pMem->u.i = v;
4464 #endif
4465 if( pC->useRandomRowid ){
4466 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4467 ** largest possible integer (9223372036854775807) then the database
4468 ** engine starts picking positive candidate ROWIDs at random until
4469 ** it finds one that is not previously used. */
4470 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
4471 ** an AUTOINCREMENT table. */
4472 cnt = 0;
4474 sqlite3_randomness(sizeof(v), &v);
4475 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
4476 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
4477 0, &res))==SQLITE_OK)
4478 && (res==0)
4479 && (++cnt<100));
4480 if( rc ) goto abort_due_to_error;
4481 if( res==0 ){
4482 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
4483 goto abort_due_to_error;
4485 assert( v>0 ); /* EV: R-40812-03570 */
4487 pC->deferredMoveto = 0;
4488 pC->cacheStatus = CACHE_STALE;
4490 pOut->u.i = v;
4491 break;
4494 /* Opcode: Insert P1 P2 P3 P4 P5
4495 ** Synopsis: intkey=r[P3] data=r[P2]
4497 ** Write an entry into the table of cursor P1. A new entry is
4498 ** created if it doesn't already exist or the data for an existing
4499 ** entry is overwritten. The data is the value MEM_Blob stored in register
4500 ** number P2. The key is stored in register P3. The key must
4501 ** be a MEM_Int.
4503 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4504 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
4505 ** then rowid is stored for subsequent return by the
4506 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4508 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
4509 ** run faster by avoiding an unnecessary seek on cursor P1. However,
4510 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
4511 ** seeks on the cursor or if the most recent seek used a key equal to P3.
4513 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4514 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
4515 ** is part of an INSERT operation. The difference is only important to
4516 ** the update hook.
4518 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
4519 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
4520 ** following a successful insert.
4522 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4523 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4524 ** and register P2 becomes ephemeral. If the cursor is changed, the
4525 ** value of register P2 will then change. Make sure this does not
4526 ** cause any problems.)
4528 ** This instruction only works on tables. The equivalent instruction
4529 ** for indices is OP_IdxInsert.
4531 /* Opcode: InsertInt P1 P2 P3 P4 P5
4532 ** Synopsis: intkey=P3 data=r[P2]
4534 ** This works exactly like OP_Insert except that the key is the
4535 ** integer value P3, not the value of the integer stored in register P3.
4537 case OP_Insert:
4538 case OP_InsertInt: {
4539 Mem *pData; /* MEM cell holding data for the record to be inserted */
4540 Mem *pKey; /* MEM cell holding key for the record */
4541 VdbeCursor *pC; /* Cursor to table into which insert is written */
4542 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
4543 const char *zDb; /* database name - used by the update hook */
4544 Table *pTab; /* Table structure - used by update and pre-update hooks */
4545 BtreePayload x; /* Payload to be inserted */
4547 pData = &aMem[pOp->p2];
4548 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4549 assert( memIsValid(pData) );
4550 pC = p->apCsr[pOp->p1];
4551 assert( pC!=0 );
4552 assert( pC->eCurType==CURTYPE_BTREE );
4553 assert( pC->uc.pCursor!=0 );
4554 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
4555 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
4556 REGISTER_TRACE(pOp->p2, pData);
4557 sqlite3VdbeIncrWriteCounter(p, pC);
4559 if( pOp->opcode==OP_Insert ){
4560 pKey = &aMem[pOp->p3];
4561 assert( pKey->flags & MEM_Int );
4562 assert( memIsValid(pKey) );
4563 REGISTER_TRACE(pOp->p3, pKey);
4564 x.nKey = pKey->u.i;
4565 }else{
4566 assert( pOp->opcode==OP_InsertInt );
4567 x.nKey = pOp->p3;
4570 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4571 assert( pC->iDb>=0 );
4572 zDb = db->aDb[pC->iDb].zDbSName;
4573 pTab = pOp->p4.pTab;
4574 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
4575 }else{
4576 pTab = 0;
4577 zDb = 0; /* Not needed. Silence a compiler warning. */
4580 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4581 /* Invoke the pre-update hook, if any */
4582 if( pTab ){
4583 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
4584 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
4586 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
4587 /* Prevent post-update hook from running in cases when it should not */
4588 pTab = 0;
4591 if( pOp->p5 & OPFLAG_ISNOOP ) break;
4592 #endif
4594 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4595 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
4596 assert( pData->flags & (MEM_Blob|MEM_Str) );
4597 x.pData = pData->z;
4598 x.nData = pData->n;
4599 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
4600 if( pData->flags & MEM_Zero ){
4601 x.nZero = pData->u.nZero;
4602 }else{
4603 x.nZero = 0;
4605 x.pKey = 0;
4606 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
4607 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
4609 pC->deferredMoveto = 0;
4610 pC->cacheStatus = CACHE_STALE;
4612 /* Invoke the update-hook if required. */
4613 if( rc ) goto abort_due_to_error;
4614 if( pTab ){
4615 assert( db->xUpdateCallback!=0 );
4616 assert( pTab->aCol!=0 );
4617 db->xUpdateCallback(db->pUpdateArg,
4618 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
4619 zDb, pTab->zName, x.nKey);
4621 break;
4624 /* Opcode: Delete P1 P2 P3 P4 P5
4626 ** Delete the record at which the P1 cursor is currently pointing.
4628 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
4629 ** the cursor will be left pointing at either the next or the previous
4630 ** record in the table. If it is left pointing at the next record, then
4631 ** the next Next instruction will be a no-op. As a result, in this case
4632 ** it is ok to delete a record from within a Next loop. If
4633 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
4634 ** left in an undefined state.
4636 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
4637 ** delete one of several associated with deleting a table row and all its
4638 ** associated index entries. Exactly one of those deletes is the "primary"
4639 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
4640 ** marked with the AUXDELETE flag.
4642 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
4643 ** change count is incremented (otherwise not).
4645 ** P1 must not be pseudo-table. It has to be a real table with
4646 ** multiple rows.
4648 ** If P4 is not NULL then it points to a Table object. In this case either
4649 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
4650 ** have been positioned using OP_NotFound prior to invoking this opcode in
4651 ** this case. Specifically, if one is configured, the pre-update hook is
4652 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
4653 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
4655 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
4656 ** of the memory cell that contains the value that the rowid of the row will
4657 ** be set to by the update.
4659 case OP_Delete: {
4660 VdbeCursor *pC;
4661 const char *zDb;
4662 Table *pTab;
4663 int opflags;
4665 opflags = pOp->p2;
4666 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4667 pC = p->apCsr[pOp->p1];
4668 assert( pC!=0 );
4669 assert( pC->eCurType==CURTYPE_BTREE );
4670 assert( pC->uc.pCursor!=0 );
4671 assert( pC->deferredMoveto==0 );
4672 sqlite3VdbeIncrWriteCounter(p, pC);
4674 #ifdef SQLITE_DEBUG
4675 if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
4676 /* If p5 is zero, the seek operation that positioned the cursor prior to
4677 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
4678 ** the row that is being deleted */
4679 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4680 assert( pC->movetoTarget==iKey );
4682 #endif
4684 /* If the update-hook or pre-update-hook will be invoked, set zDb to
4685 ** the name of the db to pass as to it. Also set local pTab to a copy
4686 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
4687 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
4688 ** VdbeCursor.movetoTarget to the current rowid. */
4689 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4690 assert( pC->iDb>=0 );
4691 assert( pOp->p4.pTab!=0 );
4692 zDb = db->aDb[pC->iDb].zDbSName;
4693 pTab = pOp->p4.pTab;
4694 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
4695 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4697 }else{
4698 zDb = 0; /* Not needed. Silence a compiler warning. */
4699 pTab = 0; /* Not needed. Silence a compiler warning. */
4702 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4703 /* Invoke the pre-update-hook if required. */
4704 if( db->xPreUpdateCallback && pOp->p4.pTab ){
4705 assert( !(opflags & OPFLAG_ISUPDATE)
4706 || HasRowid(pTab)==0
4707 || (aMem[pOp->p3].flags & MEM_Int)
4709 sqlite3VdbePreUpdateHook(p, pC,
4710 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
4711 zDb, pTab, pC->movetoTarget,
4712 pOp->p3
4715 if( opflags & OPFLAG_ISNOOP ) break;
4716 #endif
4718 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
4719 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
4720 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
4721 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
4723 #ifdef SQLITE_DEBUG
4724 if( p->pFrame==0 ){
4725 if( pC->isEphemeral==0
4726 && (pOp->p5 & OPFLAG_AUXDELETE)==0
4727 && (pC->wrFlag & OPFLAG_FORDELETE)==0
4729 nExtraDelete++;
4731 if( pOp->p2 & OPFLAG_NCHANGE ){
4732 nExtraDelete--;
4735 #endif
4737 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
4738 pC->cacheStatus = CACHE_STALE;
4739 pC->seekResult = 0;
4740 if( rc ) goto abort_due_to_error;
4742 /* Invoke the update-hook if required. */
4743 if( opflags & OPFLAG_NCHANGE ){
4744 p->nChange++;
4745 if( db->xUpdateCallback && HasRowid(pTab) ){
4746 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
4747 pC->movetoTarget);
4748 assert( pC->iDb>=0 );
4752 break;
4754 /* Opcode: ResetCount * * * * *
4756 ** The value of the change counter is copied to the database handle
4757 ** change counter (returned by subsequent calls to sqlite3_changes()).
4758 ** Then the VMs internal change counter resets to 0.
4759 ** This is used by trigger programs.
4761 case OP_ResetCount: {
4762 sqlite3VdbeSetChanges(db, p->nChange);
4763 p->nChange = 0;
4764 break;
4767 /* Opcode: SorterCompare P1 P2 P3 P4
4768 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4770 ** P1 is a sorter cursor. This instruction compares a prefix of the
4771 ** record blob in register P3 against a prefix of the entry that
4772 ** the sorter cursor currently points to. Only the first P4 fields
4773 ** of r[P3] and the sorter record are compared.
4775 ** If either P3 or the sorter contains a NULL in one of their significant
4776 ** fields (not counting the P4 fields at the end which are ignored) then
4777 ** the comparison is assumed to be equal.
4779 ** Fall through to next instruction if the two records compare equal to
4780 ** each other. Jump to P2 if they are different.
4782 case OP_SorterCompare: {
4783 VdbeCursor *pC;
4784 int res;
4785 int nKeyCol;
4787 pC = p->apCsr[pOp->p1];
4788 assert( isSorter(pC) );
4789 assert( pOp->p4type==P4_INT32 );
4790 pIn3 = &aMem[pOp->p3];
4791 nKeyCol = pOp->p4.i;
4792 res = 0;
4793 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
4794 VdbeBranchTaken(res!=0,2);
4795 if( rc ) goto abort_due_to_error;
4796 if( res ) goto jump_to_p2;
4797 break;
4800 /* Opcode: SorterData P1 P2 P3 * *
4801 ** Synopsis: r[P2]=data
4803 ** Write into register P2 the current sorter data for sorter cursor P1.
4804 ** Then clear the column header cache on cursor P3.
4806 ** This opcode is normally use to move a record out of the sorter and into
4807 ** a register that is the source for a pseudo-table cursor created using
4808 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4809 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4810 ** us from having to issue a separate NullRow instruction to clear that cache.
4812 case OP_SorterData: {
4813 VdbeCursor *pC;
4815 pOut = &aMem[pOp->p2];
4816 pC = p->apCsr[pOp->p1];
4817 assert( isSorter(pC) );
4818 rc = sqlite3VdbeSorterRowkey(pC, pOut);
4819 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
4820 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4821 if( rc ) goto abort_due_to_error;
4822 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
4823 break;
4826 /* Opcode: RowData P1 P2 P3 * *
4827 ** Synopsis: r[P2]=data
4829 ** Write into register P2 the complete row content for the row at
4830 ** which cursor P1 is currently pointing.
4831 ** There is no interpretation of the data.
4832 ** It is just copied onto the P2 register exactly as
4833 ** it is found in the database file.
4835 ** If cursor P1 is an index, then the content is the key of the row.
4836 ** If cursor P2 is a table, then the content extracted is the data.
4838 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4839 ** of a real table, not a pseudo-table.
4841 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
4842 ** into the database page. That means that the content of the output
4843 ** register will be invalidated as soon as the cursor moves - including
4844 ** moves caused by other cursors that "save" the current cursors
4845 ** position in order that they can write to the same table. If P3==0
4846 ** then a copy of the data is made into memory. P3!=0 is faster, but
4847 ** P3==0 is safer.
4849 ** If P3!=0 then the content of the P2 register is unsuitable for use
4850 ** in OP_Result and any OP_Result will invalidate the P2 register content.
4851 ** The P2 register content is invalidated by opcodes like OP_Function or
4852 ** by any use of another cursor pointing to the same table.
4854 case OP_RowData: {
4855 VdbeCursor *pC;
4856 BtCursor *pCrsr;
4857 u32 n;
4859 pOut = out2Prerelease(p, pOp);
4861 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4862 pC = p->apCsr[pOp->p1];
4863 assert( pC!=0 );
4864 assert( pC->eCurType==CURTYPE_BTREE );
4865 assert( isSorter(pC)==0 );
4866 assert( pC->nullRow==0 );
4867 assert( pC->uc.pCursor!=0 );
4868 pCrsr = pC->uc.pCursor;
4870 /* The OP_RowData opcodes always follow OP_NotExists or
4871 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
4872 ** that might invalidate the cursor.
4873 ** If this where not the case, on of the following assert()s
4874 ** would fail. Should this ever change (because of changes in the code
4875 ** generator) then the fix would be to insert a call to
4876 ** sqlite3VdbeCursorMoveto().
4878 assert( pC->deferredMoveto==0 );
4879 assert( sqlite3BtreeCursorIsValid(pCrsr) );
4880 #if 0 /* Not required due to the previous to assert() statements */
4881 rc = sqlite3VdbeCursorMoveto(pC);
4882 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4883 #endif
4885 n = sqlite3BtreePayloadSize(pCrsr);
4886 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
4887 goto too_big;
4889 testcase( n==0 );
4890 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
4891 if( rc ) goto abort_due_to_error;
4892 if( !pOp->p3 ) Deephemeralize(pOut);
4893 UPDATE_MAX_BLOBSIZE(pOut);
4894 REGISTER_TRACE(pOp->p2, pOut);
4895 break;
4898 /* Opcode: Rowid P1 P2 * * *
4899 ** Synopsis: r[P2]=rowid
4901 ** Store in register P2 an integer which is the key of the table entry that
4902 ** P1 is currently point to.
4904 ** P1 can be either an ordinary table or a virtual table. There used to
4905 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4906 ** one opcode now works for both table types.
4908 case OP_Rowid: { /* out2 */
4909 VdbeCursor *pC;
4910 i64 v;
4911 sqlite3_vtab *pVtab;
4912 const sqlite3_module *pModule;
4914 pOut = out2Prerelease(p, pOp);
4915 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4916 pC = p->apCsr[pOp->p1];
4917 assert( pC!=0 );
4918 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
4919 if( pC->nullRow ){
4920 pOut->flags = MEM_Null;
4921 break;
4922 }else if( pC->deferredMoveto ){
4923 v = pC->movetoTarget;
4924 #ifndef SQLITE_OMIT_VIRTUALTABLE
4925 }else if( pC->eCurType==CURTYPE_VTAB ){
4926 assert( pC->uc.pVCur!=0 );
4927 pVtab = pC->uc.pVCur->pVtab;
4928 pModule = pVtab->pModule;
4929 assert( pModule->xRowid );
4930 rc = pModule->xRowid(pC->uc.pVCur, &v);
4931 sqlite3VtabImportErrmsg(p, pVtab);
4932 if( rc ) goto abort_due_to_error;
4933 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4934 }else{
4935 assert( pC->eCurType==CURTYPE_BTREE );
4936 assert( pC->uc.pCursor!=0 );
4937 rc = sqlite3VdbeCursorRestore(pC);
4938 if( rc ) goto abort_due_to_error;
4939 if( pC->nullRow ){
4940 pOut->flags = MEM_Null;
4941 break;
4943 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4945 pOut->u.i = v;
4946 break;
4949 /* Opcode: NullRow P1 * * * *
4951 ** Move the cursor P1 to a null row. Any OP_Column operations
4952 ** that occur while the cursor is on the null row will always
4953 ** write a NULL.
4955 case OP_NullRow: {
4956 VdbeCursor *pC;
4958 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4959 pC = p->apCsr[pOp->p1];
4960 assert( pC!=0 );
4961 pC->nullRow = 1;
4962 pC->cacheStatus = CACHE_STALE;
4963 if( pC->eCurType==CURTYPE_BTREE ){
4964 assert( pC->uc.pCursor!=0 );
4965 sqlite3BtreeClearCursor(pC->uc.pCursor);
4967 #ifdef SQLITE_DEBUG
4968 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
4969 #endif
4970 break;
4973 /* Opcode: SeekEnd P1 * * * *
4975 ** Position cursor P1 at the end of the btree for the purpose of
4976 ** appending a new entry onto the btree.
4978 ** It is assumed that the cursor is used only for appending and so
4979 ** if the cursor is valid, then the cursor must already be pointing
4980 ** at the end of the btree and so no changes are made to
4981 ** the cursor.
4983 /* Opcode: Last P1 P2 * * *
4985 ** The next use of the Rowid or Column or Prev instruction for P1
4986 ** will refer to the last entry in the database table or index.
4987 ** If the table or index is empty and P2>0, then jump immediately to P2.
4988 ** If P2 is 0 or if the table or index is not empty, fall through
4989 ** to the following instruction.
4991 ** This opcode leaves the cursor configured to move in reverse order,
4992 ** from the end toward the beginning. In other words, the cursor is
4993 ** configured to use Prev, not Next.
4995 case OP_SeekEnd:
4996 case OP_Last: { /* jump */
4997 VdbeCursor *pC;
4998 BtCursor *pCrsr;
4999 int res;
5001 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5002 pC = p->apCsr[pOp->p1];
5003 assert( pC!=0 );
5004 assert( pC->eCurType==CURTYPE_BTREE );
5005 pCrsr = pC->uc.pCursor;
5006 res = 0;
5007 assert( pCrsr!=0 );
5008 #ifdef SQLITE_DEBUG
5009 pC->seekOp = pOp->opcode;
5010 #endif
5011 if( pOp->opcode==OP_SeekEnd ){
5012 assert( pOp->p2==0 );
5013 pC->seekResult = -1;
5014 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
5015 break;
5018 rc = sqlite3BtreeLast(pCrsr, &res);
5019 pC->nullRow = (u8)res;
5020 pC->deferredMoveto = 0;
5021 pC->cacheStatus = CACHE_STALE;
5022 if( rc ) goto abort_due_to_error;
5023 if( pOp->p2>0 ){
5024 VdbeBranchTaken(res!=0,2);
5025 if( res ) goto jump_to_p2;
5027 break;
5030 /* Opcode: IfSmaller P1 P2 P3 * *
5032 ** Estimate the number of rows in the table P1. Jump to P2 if that
5033 ** estimate is less than approximately 2**(0.1*P3).
5035 case OP_IfSmaller: { /* jump */
5036 VdbeCursor *pC;
5037 BtCursor *pCrsr;
5038 int res;
5039 i64 sz;
5041 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5042 pC = p->apCsr[pOp->p1];
5043 assert( pC!=0 );
5044 pCrsr = pC->uc.pCursor;
5045 assert( pCrsr );
5046 rc = sqlite3BtreeFirst(pCrsr, &res);
5047 if( rc ) goto abort_due_to_error;
5048 if( res==0 ){
5049 sz = sqlite3BtreeRowCountEst(pCrsr);
5050 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
5052 VdbeBranchTaken(res!=0,2);
5053 if( res ) goto jump_to_p2;
5054 break;
5058 /* Opcode: SorterSort P1 P2 * * *
5060 ** After all records have been inserted into the Sorter object
5061 ** identified by P1, invoke this opcode to actually do the sorting.
5062 ** Jump to P2 if there are no records to be sorted.
5064 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
5065 ** for Sorter objects.
5067 /* Opcode: Sort P1 P2 * * *
5069 ** This opcode does exactly the same thing as OP_Rewind except that
5070 ** it increments an undocumented global variable used for testing.
5072 ** Sorting is accomplished by writing records into a sorting index,
5073 ** then rewinding that index and playing it back from beginning to
5074 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
5075 ** rewinding so that the global variable will be incremented and
5076 ** regression tests can determine whether or not the optimizer is
5077 ** correctly optimizing out sorts.
5079 case OP_SorterSort: /* jump */
5080 case OP_Sort: { /* jump */
5081 #ifdef SQLITE_TEST
5082 sqlite3_sort_count++;
5083 sqlite3_search_count--;
5084 #endif
5085 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
5086 /* Fall through into OP_Rewind */
5088 /* Opcode: Rewind P1 P2 * * P5
5090 ** The next use of the Rowid or Column or Next instruction for P1
5091 ** will refer to the first entry in the database table or index.
5092 ** If the table or index is empty, jump immediately to P2.
5093 ** If the table or index is not empty, fall through to the following
5094 ** instruction.
5096 ** If P5 is non-zero and the table is not empty, then the "skip-next"
5097 ** flag is set on the cursor so that the next OP_Next instruction
5098 ** executed on it is a no-op.
5100 ** This opcode leaves the cursor configured to move in forward order,
5101 ** from the beginning toward the end. In other words, the cursor is
5102 ** configured to use Next, not Prev.
5104 case OP_Rewind: { /* jump */
5105 VdbeCursor *pC;
5106 BtCursor *pCrsr;
5107 int res;
5109 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5110 pC = p->apCsr[pOp->p1];
5111 assert( pC!=0 );
5112 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5113 res = 1;
5114 #ifdef SQLITE_DEBUG
5115 pC->seekOp = OP_Rewind;
5116 #endif
5117 if( isSorter(pC) ){
5118 rc = sqlite3VdbeSorterRewind(pC, &res);
5119 }else{
5120 assert( pC->eCurType==CURTYPE_BTREE );
5121 pCrsr = pC->uc.pCursor;
5122 assert( pCrsr );
5123 rc = sqlite3BtreeFirst(pCrsr, &res);
5124 #ifndef SQLITE_OMIT_WINDOWFUNC
5125 if( pOp->p5 ) sqlite3BtreeSkipNext(pCrsr);
5126 #endif
5127 pC->deferredMoveto = 0;
5128 pC->cacheStatus = CACHE_STALE;
5130 if( rc ) goto abort_due_to_error;
5131 pC->nullRow = (u8)res;
5132 assert( pOp->p2>0 && pOp->p2<p->nOp );
5133 VdbeBranchTaken(res!=0,2);
5134 if( res ) goto jump_to_p2;
5135 break;
5138 /* Opcode: Next P1 P2 P3 P4 P5
5140 ** Advance cursor P1 so that it points to the next key/data pair in its
5141 ** table or index. If there are no more key/value pairs then fall through
5142 ** to the following instruction. But if the cursor advance was successful,
5143 ** jump immediately to P2.
5145 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5146 ** OP_Rewind opcode used to position the cursor. Next is not allowed
5147 ** to follow SeekLT, SeekLE, or OP_Last.
5149 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
5150 ** been opened prior to this opcode or the program will segfault.
5152 ** The P3 value is a hint to the btree implementation. If P3==1, that
5153 ** means P1 is an SQL index and that this instruction could have been
5154 ** omitted if that index had been unique. P3 is usually 0. P3 is
5155 ** always either 0 or 1.
5157 ** P4 is always of type P4_ADVANCE. The function pointer points to
5158 ** sqlite3BtreeNext().
5160 ** If P5 is positive and the jump is taken, then event counter
5161 ** number P5-1 in the prepared statement is incremented.
5163 ** See also: Prev
5165 /* Opcode: Prev P1 P2 P3 P4 P5
5167 ** Back up cursor P1 so that it points to the previous key/data pair in its
5168 ** table or index. If there is no previous key/value pairs then fall through
5169 ** to the following instruction. But if the cursor backup was successful,
5170 ** jump immediately to P2.
5173 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5174 ** OP_Last opcode used to position the cursor. Prev is not allowed
5175 ** to follow SeekGT, SeekGE, or OP_Rewind.
5177 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
5178 ** not open then the behavior is undefined.
5180 ** The P3 value is a hint to the btree implementation. If P3==1, that
5181 ** means P1 is an SQL index and that this instruction could have been
5182 ** omitted if that index had been unique. P3 is usually 0. P3 is
5183 ** always either 0 or 1.
5185 ** P4 is always of type P4_ADVANCE. The function pointer points to
5186 ** sqlite3BtreePrevious().
5188 ** If P5 is positive and the jump is taken, then event counter
5189 ** number P5-1 in the prepared statement is incremented.
5191 /* Opcode: SorterNext P1 P2 * * P5
5193 ** This opcode works just like OP_Next except that P1 must be a
5194 ** sorter object for which the OP_SorterSort opcode has been
5195 ** invoked. This opcode advances the cursor to the next sorted
5196 ** record, or jumps to P2 if there are no more sorted records.
5198 case OP_SorterNext: { /* jump */
5199 VdbeCursor *pC;
5201 pC = p->apCsr[pOp->p1];
5202 assert( isSorter(pC) );
5203 rc = sqlite3VdbeSorterNext(db, pC);
5204 goto next_tail;
5205 case OP_Prev: /* jump */
5206 case OP_Next: /* jump */
5207 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5208 assert( pOp->p5<ArraySize(p->aCounter) );
5209 pC = p->apCsr[pOp->p1];
5210 assert( pC!=0 );
5211 assert( pC->deferredMoveto==0 );
5212 assert( pC->eCurType==CURTYPE_BTREE );
5213 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5214 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5216 /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
5217 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5218 assert( pOp->opcode!=OP_Next
5219 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5220 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
5221 || pC->seekOp==OP_NullRow);
5222 assert( pOp->opcode!=OP_Prev
5223 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5224 || pC->seekOp==OP_Last
5225 || pC->seekOp==OP_NullRow);
5227 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5228 next_tail:
5229 pC->cacheStatus = CACHE_STALE;
5230 VdbeBranchTaken(rc==SQLITE_OK,2);
5231 if( rc==SQLITE_OK ){
5232 pC->nullRow = 0;
5233 p->aCounter[pOp->p5]++;
5234 #ifdef SQLITE_TEST
5235 sqlite3_search_count++;
5236 #endif
5237 goto jump_to_p2_and_check_for_interrupt;
5239 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5240 rc = SQLITE_OK;
5241 pC->nullRow = 1;
5242 goto check_for_interrupt;
5245 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5246 ** Synopsis: key=r[P2]
5248 ** Register P2 holds an SQL index key made using the
5249 ** MakeRecord instructions. This opcode writes that key
5250 ** into the index P1. Data for the entry is nil.
5252 ** If P4 is not zero, then it is the number of values in the unpacked
5253 ** key of reg(P2). In that case, P3 is the index of the first register
5254 ** for the unpacked key. The availability of the unpacked key can sometimes
5255 ** be an optimization.
5257 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5258 ** that this insert is likely to be an append.
5260 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5261 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
5262 ** then the change counter is unchanged.
5264 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5265 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5266 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5267 ** seeks on the cursor or if the most recent seek used a key equivalent
5268 ** to P2.
5270 ** This instruction only works for indices. The equivalent instruction
5271 ** for tables is OP_Insert.
5273 /* Opcode: SorterInsert P1 P2 * * *
5274 ** Synopsis: key=r[P2]
5276 ** Register P2 holds an SQL index key made using the
5277 ** MakeRecord instructions. This opcode writes that key
5278 ** into the sorter P1. Data for the entry is nil.
5280 case OP_SorterInsert: /* in2 */
5281 case OP_IdxInsert: { /* in2 */
5282 VdbeCursor *pC;
5283 BtreePayload x;
5285 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5286 pC = p->apCsr[pOp->p1];
5287 sqlite3VdbeIncrWriteCounter(p, pC);
5288 assert( pC!=0 );
5289 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
5290 pIn2 = &aMem[pOp->p2];
5291 assert( pIn2->flags & MEM_Blob );
5292 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5293 assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
5294 assert( pC->isTable==0 );
5295 rc = ExpandBlob(pIn2);
5296 if( rc ) goto abort_due_to_error;
5297 if( pOp->opcode==OP_SorterInsert ){
5298 rc = sqlite3VdbeSorterWrite(pC, pIn2);
5299 }else{
5300 x.nKey = pIn2->n;
5301 x.pKey = pIn2->z;
5302 x.aMem = aMem + pOp->p3;
5303 x.nMem = (u16)pOp->p4.i;
5304 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5305 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
5306 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
5308 assert( pC->deferredMoveto==0 );
5309 pC->cacheStatus = CACHE_STALE;
5311 if( rc) goto abort_due_to_error;
5312 break;
5315 /* Opcode: IdxDelete P1 P2 P3 * *
5316 ** Synopsis: key=r[P2@P3]
5318 ** The content of P3 registers starting at register P2 form
5319 ** an unpacked index key. This opcode removes that entry from the
5320 ** index opened by cursor P1.
5322 case OP_IdxDelete: {
5323 VdbeCursor *pC;
5324 BtCursor *pCrsr;
5325 int res;
5326 UnpackedRecord r;
5328 assert( pOp->p3>0 );
5329 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
5330 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5331 pC = p->apCsr[pOp->p1];
5332 assert( pC!=0 );
5333 assert( pC->eCurType==CURTYPE_BTREE );
5334 sqlite3VdbeIncrWriteCounter(p, pC);
5335 pCrsr = pC->uc.pCursor;
5336 assert( pCrsr!=0 );
5337 assert( pOp->p5==0 );
5338 r.pKeyInfo = pC->pKeyInfo;
5339 r.nField = (u16)pOp->p3;
5340 r.default_rc = 0;
5341 r.aMem = &aMem[pOp->p2];
5342 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
5343 if( rc ) goto abort_due_to_error;
5344 if( res==0 ){
5345 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
5346 if( rc ) goto abort_due_to_error;
5348 assert( pC->deferredMoveto==0 );
5349 pC->cacheStatus = CACHE_STALE;
5350 pC->seekResult = 0;
5351 break;
5354 /* Opcode: DeferredSeek P1 * P3 P4 *
5355 ** Synopsis: Move P3 to P1.rowid if needed
5357 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5358 ** table. This opcode does a deferred seek of the P3 table cursor
5359 ** to the row that corresponds to the current row of P1.
5361 ** This is a deferred seek. Nothing actually happens until
5362 ** the cursor is used to read a record. That way, if no reads
5363 ** occur, no unnecessary I/O happens.
5365 ** P4 may be an array of integers (type P4_INTARRAY) containing
5366 ** one entry for each column in the P3 table. If array entry a(i)
5367 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5368 ** equivalent to performing the deferred seek and then reading column i
5369 ** from P1. This information is stored in P3 and used to redirect
5370 ** reads against P3 over to P1, thus possibly avoiding the need to
5371 ** seek and read cursor P3.
5373 /* Opcode: IdxRowid P1 P2 * * *
5374 ** Synopsis: r[P2]=rowid
5376 ** Write into register P2 an integer which is the last entry in the record at
5377 ** the end of the index key pointed to by cursor P1. This integer should be
5378 ** the rowid of the table entry to which this index entry points.
5380 ** See also: Rowid, MakeRecord.
5382 case OP_DeferredSeek:
5383 case OP_IdxRowid: { /* out2 */
5384 VdbeCursor *pC; /* The P1 index cursor */
5385 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
5386 i64 rowid; /* Rowid that P1 current points to */
5388 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5389 pC = p->apCsr[pOp->p1];
5390 assert( pC!=0 );
5391 assert( pC->eCurType==CURTYPE_BTREE );
5392 assert( pC->uc.pCursor!=0 );
5393 assert( pC->isTable==0 );
5394 assert( pC->deferredMoveto==0 );
5395 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
5397 /* The IdxRowid and Seek opcodes are combined because of the commonality
5398 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5399 rc = sqlite3VdbeCursorRestore(pC);
5401 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5402 ** out from under the cursor. That will never happens for an IdxRowid
5403 ** or Seek opcode */
5404 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
5406 if( !pC->nullRow ){
5407 rowid = 0; /* Not needed. Only used to silence a warning. */
5408 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
5409 if( rc!=SQLITE_OK ){
5410 goto abort_due_to_error;
5412 if( pOp->opcode==OP_DeferredSeek ){
5413 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
5414 pTabCur = p->apCsr[pOp->p3];
5415 assert( pTabCur!=0 );
5416 assert( pTabCur->eCurType==CURTYPE_BTREE );
5417 assert( pTabCur->uc.pCursor!=0 );
5418 assert( pTabCur->isTable );
5419 pTabCur->nullRow = 0;
5420 pTabCur->movetoTarget = rowid;
5421 pTabCur->deferredMoveto = 1;
5422 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
5423 pTabCur->aAltMap = pOp->p4.ai;
5424 pTabCur->pAltCursor = pC;
5425 }else{
5426 pOut = out2Prerelease(p, pOp);
5427 pOut->u.i = rowid;
5429 }else{
5430 assert( pOp->opcode==OP_IdxRowid );
5431 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
5433 break;
5436 /* Opcode: IdxGE P1 P2 P3 P4 P5
5437 ** Synopsis: key=r[P3@P4]
5439 ** The P4 register values beginning with P3 form an unpacked index
5440 ** key that omits the PRIMARY KEY. Compare this key value against the index
5441 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5442 ** fields at the end.
5444 ** If the P1 index entry is greater than or equal to the key value
5445 ** then jump to P2. Otherwise fall through to the next instruction.
5447 /* Opcode: IdxGT P1 P2 P3 P4 P5
5448 ** Synopsis: key=r[P3@P4]
5450 ** The P4 register values beginning with P3 form an unpacked index
5451 ** key that omits the PRIMARY KEY. Compare this key value against the index
5452 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5453 ** fields at the end.
5455 ** If the P1 index entry is greater than the key value
5456 ** then jump to P2. Otherwise fall through to the next instruction.
5458 /* Opcode: IdxLT P1 P2 P3 P4 P5
5459 ** Synopsis: key=r[P3@P4]
5461 ** The P4 register values beginning with P3 form an unpacked index
5462 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5463 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5464 ** ROWID on the P1 index.
5466 ** If the P1 index entry is less than the key value then jump to P2.
5467 ** Otherwise fall through to the next instruction.
5469 /* Opcode: IdxLE P1 P2 P3 P4 P5
5470 ** Synopsis: key=r[P3@P4]
5472 ** The P4 register values beginning with P3 form an unpacked index
5473 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5474 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5475 ** ROWID on the P1 index.
5477 ** If the P1 index entry is less than or equal to the key value then jump
5478 ** to P2. Otherwise fall through to the next instruction.
5480 case OP_IdxLE: /* jump */
5481 case OP_IdxGT: /* jump */
5482 case OP_IdxLT: /* jump */
5483 case OP_IdxGE: { /* jump */
5484 VdbeCursor *pC;
5485 int res;
5486 UnpackedRecord r;
5488 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5489 pC = p->apCsr[pOp->p1];
5490 assert( pC!=0 );
5491 assert( pC->isOrdered );
5492 assert( pC->eCurType==CURTYPE_BTREE );
5493 assert( pC->uc.pCursor!=0);
5494 assert( pC->deferredMoveto==0 );
5495 assert( pOp->p5==0 || pOp->p5==1 );
5496 assert( pOp->p4type==P4_INT32 );
5497 r.pKeyInfo = pC->pKeyInfo;
5498 r.nField = (u16)pOp->p4.i;
5499 if( pOp->opcode<OP_IdxLT ){
5500 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
5501 r.default_rc = -1;
5502 }else{
5503 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
5504 r.default_rc = 0;
5506 r.aMem = &aMem[pOp->p3];
5507 #ifdef SQLITE_DEBUG
5508 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
5509 #endif
5510 res = 0; /* Not needed. Only used to silence a warning. */
5511 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5512 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
5513 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
5514 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
5515 res = -res;
5516 }else{
5517 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
5518 res++;
5520 VdbeBranchTaken(res>0,2);
5521 if( rc ) goto abort_due_to_error;
5522 if( res>0 ) goto jump_to_p2;
5523 break;
5526 /* Opcode: Destroy P1 P2 P3 * *
5528 ** Delete an entire database table or index whose root page in the database
5529 ** file is given by P1.
5531 ** The table being destroyed is in the main database file if P3==0. If
5532 ** P3==1 then the table to be clear is in the auxiliary database file
5533 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5535 ** If AUTOVACUUM is enabled then it is possible that another root page
5536 ** might be moved into the newly deleted root page in order to keep all
5537 ** root pages contiguous at the beginning of the database. The former
5538 ** value of the root page that moved - its value before the move occurred -
5539 ** is stored in register P2. If no page movement was required (because the
5540 ** table being dropped was already the last one in the database) then a
5541 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
5542 ** is stored in register P2.
5544 ** This opcode throws an error if there are any active reader VMs when
5545 ** it is invoked. This is done to avoid the difficulty associated with
5546 ** updating existing cursors when a root page is moved in an AUTOVACUUM
5547 ** database. This error is thrown even if the database is not an AUTOVACUUM
5548 ** db in order to avoid introducing an incompatibility between autovacuum
5549 ** and non-autovacuum modes.
5551 ** See also: Clear
5553 case OP_Destroy: { /* out2 */
5554 int iMoved;
5555 int iDb;
5557 sqlite3VdbeIncrWriteCounter(p, 0);
5558 assert( p->readOnly==0 );
5559 assert( pOp->p1>1 );
5560 pOut = out2Prerelease(p, pOp);
5561 pOut->flags = MEM_Null;
5562 if( db->nVdbeRead > db->nVDestroy+1 ){
5563 rc = SQLITE_LOCKED;
5564 p->errorAction = OE_Abort;
5565 goto abort_due_to_error;
5566 }else{
5567 iDb = pOp->p3;
5568 assert( DbMaskTest(p->btreeMask, iDb) );
5569 iMoved = 0; /* Not needed. Only to silence a warning. */
5570 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
5571 pOut->flags = MEM_Int;
5572 pOut->u.i = iMoved;
5573 if( rc ) goto abort_due_to_error;
5574 #ifndef SQLITE_OMIT_AUTOVACUUM
5575 if( iMoved!=0 ){
5576 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
5577 /* All OP_Destroy operations occur on the same btree */
5578 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
5579 resetSchemaOnFault = iDb+1;
5581 #endif
5583 break;
5586 /* Opcode: Clear P1 P2 P3
5588 ** Delete all contents of the database table or index whose root page
5589 ** in the database file is given by P1. But, unlike Destroy, do not
5590 ** remove the table or index from the database file.
5592 ** The table being clear is in the main database file if P2==0. If
5593 ** P2==1 then the table to be clear is in the auxiliary database file
5594 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5596 ** If the P3 value is non-zero, then the table referred to must be an
5597 ** intkey table (an SQL table, not an index). In this case the row change
5598 ** count is incremented by the number of rows in the table being cleared.
5599 ** If P3 is greater than zero, then the value stored in register P3 is
5600 ** also incremented by the number of rows in the table being cleared.
5602 ** See also: Destroy
5604 case OP_Clear: {
5605 int nChange;
5607 sqlite3VdbeIncrWriteCounter(p, 0);
5608 nChange = 0;
5609 assert( p->readOnly==0 );
5610 assert( DbMaskTest(p->btreeMask, pOp->p2) );
5611 rc = sqlite3BtreeClearTable(
5612 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
5614 if( pOp->p3 ){
5615 p->nChange += nChange;
5616 if( pOp->p3>0 ){
5617 assert( memIsValid(&aMem[pOp->p3]) );
5618 memAboutToChange(p, &aMem[pOp->p3]);
5619 aMem[pOp->p3].u.i += nChange;
5622 if( rc ) goto abort_due_to_error;
5623 break;
5626 /* Opcode: ResetSorter P1 * * * *
5628 ** Delete all contents from the ephemeral table or sorter
5629 ** that is open on cursor P1.
5631 ** This opcode only works for cursors used for sorting and
5632 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5634 case OP_ResetSorter: {
5635 VdbeCursor *pC;
5637 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5638 pC = p->apCsr[pOp->p1];
5639 assert( pC!=0 );
5640 if( isSorter(pC) ){
5641 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
5642 }else{
5643 assert( pC->eCurType==CURTYPE_BTREE );
5644 assert( pC->isEphemeral );
5645 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
5646 if( rc ) goto abort_due_to_error;
5648 break;
5651 /* Opcode: CreateBtree P1 P2 P3 * *
5652 ** Synopsis: r[P2]=root iDb=P1 flags=P3
5654 ** Allocate a new b-tree in the main database file if P1==0 or in the
5655 ** TEMP database file if P1==1 or in an attached database if
5656 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
5657 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
5658 ** The root page number of the new b-tree is stored in register P2.
5660 case OP_CreateBtree: { /* out2 */
5661 int pgno;
5662 Db *pDb;
5664 sqlite3VdbeIncrWriteCounter(p, 0);
5665 pOut = out2Prerelease(p, pOp);
5666 pgno = 0;
5667 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
5668 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5669 assert( DbMaskTest(p->btreeMask, pOp->p1) );
5670 assert( p->readOnly==0 );
5671 pDb = &db->aDb[pOp->p1];
5672 assert( pDb->pBt!=0 );
5673 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
5674 if( rc ) goto abort_due_to_error;
5675 pOut->u.i = pgno;
5676 break;
5679 /* Opcode: SqlExec * * * P4 *
5681 ** Run the SQL statement or statements specified in the P4 string.
5683 case OP_SqlExec: {
5684 sqlite3VdbeIncrWriteCounter(p, 0);
5685 db->nSqlExec++;
5686 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
5687 db->nSqlExec--;
5688 if( rc ) goto abort_due_to_error;
5689 break;
5692 /* Opcode: ParseSchema P1 * * P4 *
5694 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5695 ** that match the WHERE clause P4.
5697 ** This opcode invokes the parser to create a new virtual machine,
5698 ** then runs the new virtual machine. It is thus a re-entrant opcode.
5700 case OP_ParseSchema: {
5701 int iDb;
5702 const char *zMaster;
5703 char *zSql;
5704 InitData initData;
5706 /* Any prepared statement that invokes this opcode will hold mutexes
5707 ** on every btree. This is a prerequisite for invoking
5708 ** sqlite3InitCallback().
5710 #ifdef SQLITE_DEBUG
5711 for(iDb=0; iDb<db->nDb; iDb++){
5712 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
5714 #endif
5716 iDb = pOp->p1;
5717 assert( iDb>=0 && iDb<db->nDb );
5718 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
5719 /* Used to be a conditional */ {
5720 zMaster = MASTER_NAME;
5721 initData.db = db;
5722 initData.iDb = pOp->p1;
5723 initData.pzErrMsg = &p->zErrMsg;
5724 zSql = sqlite3MPrintf(db,
5725 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5726 db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
5727 if( zSql==0 ){
5728 rc = SQLITE_NOMEM_BKPT;
5729 }else{
5730 assert( db->init.busy==0 );
5731 db->init.busy = 1;
5732 initData.rc = SQLITE_OK;
5733 assert( !db->mallocFailed );
5734 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
5735 if( rc==SQLITE_OK ) rc = initData.rc;
5736 sqlite3DbFreeNN(db, zSql);
5737 db->init.busy = 0;
5740 if( rc ){
5741 sqlite3ResetAllSchemasOfConnection(db);
5742 if( rc==SQLITE_NOMEM ){
5743 goto no_mem;
5745 goto abort_due_to_error;
5747 break;
5750 #if !defined(SQLITE_OMIT_ANALYZE)
5751 /* Opcode: LoadAnalysis P1 * * * *
5753 ** Read the sqlite_stat1 table for database P1 and load the content
5754 ** of that table into the internal index hash table. This will cause
5755 ** the analysis to be used when preparing all subsequent queries.
5757 case OP_LoadAnalysis: {
5758 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5759 rc = sqlite3AnalysisLoad(db, pOp->p1);
5760 if( rc ) goto abort_due_to_error;
5761 break;
5763 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5765 /* Opcode: DropTable P1 * * P4 *
5767 ** Remove the internal (in-memory) data structures that describe
5768 ** the table named P4 in database P1. This is called after a table
5769 ** is dropped from disk (using the Destroy opcode) in order to keep
5770 ** the internal representation of the
5771 ** schema consistent with what is on disk.
5773 case OP_DropTable: {
5774 sqlite3VdbeIncrWriteCounter(p, 0);
5775 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
5776 break;
5779 /* Opcode: DropIndex P1 * * P4 *
5781 ** Remove the internal (in-memory) data structures that describe
5782 ** the index named P4 in database P1. This is called after an index
5783 ** is dropped from disk (using the Destroy opcode)
5784 ** in order to keep the internal representation of the
5785 ** schema consistent with what is on disk.
5787 case OP_DropIndex: {
5788 sqlite3VdbeIncrWriteCounter(p, 0);
5789 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
5790 break;
5793 /* Opcode: DropTrigger P1 * * P4 *
5795 ** Remove the internal (in-memory) data structures that describe
5796 ** the trigger named P4 in database P1. This is called after a trigger
5797 ** is dropped from disk (using the Destroy opcode) in order to keep
5798 ** the internal representation of the
5799 ** schema consistent with what is on disk.
5801 case OP_DropTrigger: {
5802 sqlite3VdbeIncrWriteCounter(p, 0);
5803 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
5804 break;
5808 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5809 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
5811 ** Do an analysis of the currently open database. Store in
5812 ** register P1 the text of an error message describing any problems.
5813 ** If no problems are found, store a NULL in register P1.
5815 ** The register P3 contains one less than the maximum number of allowed errors.
5816 ** At most reg(P3) errors will be reported.
5817 ** In other words, the analysis stops as soon as reg(P1) errors are
5818 ** seen. Reg(P1) is updated with the number of errors remaining.
5820 ** The root page numbers of all tables in the database are integers
5821 ** stored in P4_INTARRAY argument.
5823 ** If P5 is not zero, the check is done on the auxiliary database
5824 ** file, not the main database file.
5826 ** This opcode is used to implement the integrity_check pragma.
5828 case OP_IntegrityCk: {
5829 int nRoot; /* Number of tables to check. (Number of root pages.) */
5830 int *aRoot; /* Array of rootpage numbers for tables to be checked */
5831 int nErr; /* Number of errors reported */
5832 char *z; /* Text of the error report */
5833 Mem *pnErr; /* Register keeping track of errors remaining */
5835 assert( p->bIsReader );
5836 nRoot = pOp->p2;
5837 aRoot = pOp->p4.ai;
5838 assert( nRoot>0 );
5839 assert( aRoot[0]==nRoot );
5840 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
5841 pnErr = &aMem[pOp->p3];
5842 assert( (pnErr->flags & MEM_Int)!=0 );
5843 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
5844 pIn1 = &aMem[pOp->p1];
5845 assert( pOp->p5<db->nDb );
5846 assert( DbMaskTest(p->btreeMask, pOp->p5) );
5847 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
5848 (int)pnErr->u.i+1, &nErr);
5849 sqlite3VdbeMemSetNull(pIn1);
5850 if( nErr==0 ){
5851 assert( z==0 );
5852 }else if( z==0 ){
5853 goto no_mem;
5854 }else{
5855 pnErr->u.i -= nErr-1;
5856 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
5858 UPDATE_MAX_BLOBSIZE(pIn1);
5859 sqlite3VdbeChangeEncoding(pIn1, encoding);
5860 break;
5862 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5864 /* Opcode: RowSetAdd P1 P2 * * *
5865 ** Synopsis: rowset(P1)=r[P2]
5867 ** Insert the integer value held by register P2 into a RowSet object
5868 ** held in register P1.
5870 ** An assertion fails if P2 is not an integer.
5872 case OP_RowSetAdd: { /* in1, in2 */
5873 pIn1 = &aMem[pOp->p1];
5874 pIn2 = &aMem[pOp->p2];
5875 assert( (pIn2->flags & MEM_Int)!=0 );
5876 if( (pIn1->flags & MEM_RowSet)==0 ){
5877 sqlite3VdbeMemSetRowSet(pIn1);
5878 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5880 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
5881 break;
5884 /* Opcode: RowSetRead P1 P2 P3 * *
5885 ** Synopsis: r[P3]=rowset(P1)
5887 ** Extract the smallest value from the RowSet object in P1
5888 ** and put that value into register P3.
5889 ** Or, if RowSet object P1 is initially empty, leave P3
5890 ** unchanged and jump to instruction P2.
5892 case OP_RowSetRead: { /* jump, in1, out3 */
5893 i64 val;
5895 pIn1 = &aMem[pOp->p1];
5896 if( (pIn1->flags & MEM_RowSet)==0
5897 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
5899 /* The boolean index is empty */
5900 sqlite3VdbeMemSetNull(pIn1);
5901 VdbeBranchTaken(1,2);
5902 goto jump_to_p2_and_check_for_interrupt;
5903 }else{
5904 /* A value was pulled from the index */
5905 VdbeBranchTaken(0,2);
5906 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
5908 goto check_for_interrupt;
5911 /* Opcode: RowSetTest P1 P2 P3 P4
5912 ** Synopsis: if r[P3] in rowset(P1) goto P2
5914 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5915 ** contains a RowSet object and that RowSet object contains
5916 ** the value held in P3, jump to register P2. Otherwise, insert the
5917 ** integer in P3 into the RowSet and continue on to the
5918 ** next opcode.
5920 ** The RowSet object is optimized for the case where sets of integers
5921 ** are inserted in distinct phases, which each set contains no duplicates.
5922 ** Each set is identified by a unique P4 value. The first set
5923 ** must have P4==0, the final set must have P4==-1, and for all other sets
5924 ** must have P4>0.
5926 ** This allows optimizations: (a) when P4==0 there is no need to test
5927 ** the RowSet object for P3, as it is guaranteed not to contain it,
5928 ** (b) when P4==-1 there is no need to insert the value, as it will
5929 ** never be tested for, and (c) when a value that is part of set X is
5930 ** inserted, there is no need to search to see if the same value was
5931 ** previously inserted as part of set X (only if it was previously
5932 ** inserted as part of some other set).
5934 case OP_RowSetTest: { /* jump, in1, in3 */
5935 int iSet;
5936 int exists;
5938 pIn1 = &aMem[pOp->p1];
5939 pIn3 = &aMem[pOp->p3];
5940 iSet = pOp->p4.i;
5941 assert( pIn3->flags&MEM_Int );
5943 /* If there is anything other than a rowset object in memory cell P1,
5944 ** delete it now and initialize P1 with an empty rowset
5946 if( (pIn1->flags & MEM_RowSet)==0 ){
5947 sqlite3VdbeMemSetRowSet(pIn1);
5948 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5951 assert( pOp->p4type==P4_INT32 );
5952 assert( iSet==-1 || iSet>=0 );
5953 if( iSet ){
5954 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
5955 VdbeBranchTaken(exists!=0,2);
5956 if( exists ) goto jump_to_p2;
5958 if( iSet>=0 ){
5959 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
5961 break;
5965 #ifndef SQLITE_OMIT_TRIGGER
5967 /* Opcode: Program P1 P2 P3 P4 P5
5969 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5971 ** P1 contains the address of the memory cell that contains the first memory
5972 ** cell in an array of values used as arguments to the sub-program. P2
5973 ** contains the address to jump to if the sub-program throws an IGNORE
5974 ** exception using the RAISE() function. Register P3 contains the address
5975 ** of a memory cell in this (the parent) VM that is used to allocate the
5976 ** memory required by the sub-vdbe at runtime.
5978 ** P4 is a pointer to the VM containing the trigger program.
5980 ** If P5 is non-zero, then recursive program invocation is enabled.
5982 case OP_Program: { /* jump */
5983 int nMem; /* Number of memory registers for sub-program */
5984 int nByte; /* Bytes of runtime space required for sub-program */
5985 Mem *pRt; /* Register to allocate runtime space */
5986 Mem *pMem; /* Used to iterate through memory cells */
5987 Mem *pEnd; /* Last memory cell in new array */
5988 VdbeFrame *pFrame; /* New vdbe frame to execute in */
5989 SubProgram *pProgram; /* Sub-program to execute */
5990 void *t; /* Token identifying trigger */
5992 pProgram = pOp->p4.pProgram;
5993 pRt = &aMem[pOp->p3];
5994 assert( pProgram->nOp>0 );
5996 /* If the p5 flag is clear, then recursive invocation of triggers is
5997 ** disabled for backwards compatibility (p5 is set if this sub-program
5998 ** is really a trigger, not a foreign key action, and the flag set
5999 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
6001 ** It is recursive invocation of triggers, at the SQL level, that is
6002 ** disabled. In some cases a single trigger may generate more than one
6003 ** SubProgram (if the trigger may be executed with more than one different
6004 ** ON CONFLICT algorithm). SubProgram structures associated with a
6005 ** single trigger all have the same value for the SubProgram.token
6006 ** variable. */
6007 if( pOp->p5 ){
6008 t = pProgram->token;
6009 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
6010 if( pFrame ) break;
6013 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
6014 rc = SQLITE_ERROR;
6015 sqlite3VdbeError(p, "too many levels of trigger recursion");
6016 goto abort_due_to_error;
6019 /* Register pRt is used to store the memory required to save the state
6020 ** of the current program, and the memory required at runtime to execute
6021 ** the trigger program. If this trigger has been fired before, then pRt
6022 ** is already allocated. Otherwise, it must be initialized. */
6023 if( (pRt->flags&MEM_Frame)==0 ){
6024 /* SubProgram.nMem is set to the number of memory cells used by the
6025 ** program stored in SubProgram.aOp. As well as these, one memory
6026 ** cell is required for each cursor used by the program. Set local
6027 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
6029 nMem = pProgram->nMem + pProgram->nCsr;
6030 assert( nMem>0 );
6031 if( pProgram->nCsr==0 ) nMem++;
6032 nByte = ROUND8(sizeof(VdbeFrame))
6033 + nMem * sizeof(Mem)
6034 + pProgram->nCsr * sizeof(VdbeCursor*)
6035 + (pProgram->nOp + 7)/8;
6036 pFrame = sqlite3DbMallocZero(db, nByte);
6037 if( !pFrame ){
6038 goto no_mem;
6040 sqlite3VdbeMemRelease(pRt);
6041 pRt->flags = MEM_Frame;
6042 pRt->u.pFrame = pFrame;
6044 pFrame->v = p;
6045 pFrame->nChildMem = nMem;
6046 pFrame->nChildCsr = pProgram->nCsr;
6047 pFrame->pc = (int)(pOp - aOp);
6048 pFrame->aMem = p->aMem;
6049 pFrame->nMem = p->nMem;
6050 pFrame->apCsr = p->apCsr;
6051 pFrame->nCursor = p->nCursor;
6052 pFrame->aOp = p->aOp;
6053 pFrame->nOp = p->nOp;
6054 pFrame->token = pProgram->token;
6055 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6056 pFrame->anExec = p->anExec;
6057 #endif
6059 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
6060 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
6061 pMem->flags = MEM_Undefined;
6062 pMem->db = db;
6064 }else{
6065 pFrame = pRt->u.pFrame;
6066 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
6067 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
6068 assert( pProgram->nCsr==pFrame->nChildCsr );
6069 assert( (int)(pOp - aOp)==pFrame->pc );
6072 p->nFrame++;
6073 pFrame->pParent = p->pFrame;
6074 pFrame->lastRowid = db->lastRowid;
6075 pFrame->nChange = p->nChange;
6076 pFrame->nDbChange = p->db->nChange;
6077 assert( pFrame->pAuxData==0 );
6078 pFrame->pAuxData = p->pAuxData;
6079 p->pAuxData = 0;
6080 p->nChange = 0;
6081 p->pFrame = pFrame;
6082 p->aMem = aMem = VdbeFrameMem(pFrame);
6083 p->nMem = pFrame->nChildMem;
6084 p->nCursor = (u16)pFrame->nChildCsr;
6085 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
6086 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
6087 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
6088 p->aOp = aOp = pProgram->aOp;
6089 p->nOp = pProgram->nOp;
6090 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6091 p->anExec = 0;
6092 #endif
6093 pOp = &aOp[-1];
6095 break;
6098 /* Opcode: Param P1 P2 * * *
6100 ** This opcode is only ever present in sub-programs called via the
6101 ** OP_Program instruction. Copy a value currently stored in a memory
6102 ** cell of the calling (parent) frame to cell P2 in the current frames
6103 ** address space. This is used by trigger programs to access the new.*
6104 ** and old.* values.
6106 ** The address of the cell in the parent frame is determined by adding
6107 ** the value of the P1 argument to the value of the P1 argument to the
6108 ** calling OP_Program instruction.
6110 case OP_Param: { /* out2 */
6111 VdbeFrame *pFrame;
6112 Mem *pIn;
6113 pOut = out2Prerelease(p, pOp);
6114 pFrame = p->pFrame;
6115 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
6116 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
6117 break;
6120 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6122 #ifndef SQLITE_OMIT_FOREIGN_KEY
6123 /* Opcode: FkCounter P1 P2 * * *
6124 ** Synopsis: fkctr[P1]+=P2
6126 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6127 ** If P1 is non-zero, the database constraint counter is incremented
6128 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6129 ** statement counter is incremented (immediate foreign key constraints).
6131 case OP_FkCounter: {
6132 if( db->flags & SQLITE_DeferFKs ){
6133 db->nDeferredImmCons += pOp->p2;
6134 }else if( pOp->p1 ){
6135 db->nDeferredCons += pOp->p2;
6136 }else{
6137 p->nFkConstraint += pOp->p2;
6139 break;
6142 /* Opcode: FkIfZero P1 P2 * * *
6143 ** Synopsis: if fkctr[P1]==0 goto P2
6145 ** This opcode tests if a foreign key constraint-counter is currently zero.
6146 ** If so, jump to instruction P2. Otherwise, fall through to the next
6147 ** instruction.
6149 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6150 ** is zero (the one that counts deferred constraint violations). If P1 is
6151 ** zero, the jump is taken if the statement constraint-counter is zero
6152 ** (immediate foreign key constraint violations).
6154 case OP_FkIfZero: { /* jump */
6155 if( pOp->p1 ){
6156 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6157 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6158 }else{
6159 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6160 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6162 break;
6164 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6166 #ifndef SQLITE_OMIT_AUTOINCREMENT
6167 /* Opcode: MemMax P1 P2 * * *
6168 ** Synopsis: r[P1]=max(r[P1],r[P2])
6170 ** P1 is a register in the root frame of this VM (the root frame is
6171 ** different from the current frame if this instruction is being executed
6172 ** within a sub-program). Set the value of register P1 to the maximum of
6173 ** its current value and the value in register P2.
6175 ** This instruction throws an error if the memory cell is not initially
6176 ** an integer.
6178 case OP_MemMax: { /* in2 */
6179 VdbeFrame *pFrame;
6180 if( p->pFrame ){
6181 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
6182 pIn1 = &pFrame->aMem[pOp->p1];
6183 }else{
6184 pIn1 = &aMem[pOp->p1];
6186 assert( memIsValid(pIn1) );
6187 sqlite3VdbeMemIntegerify(pIn1);
6188 pIn2 = &aMem[pOp->p2];
6189 sqlite3VdbeMemIntegerify(pIn2);
6190 if( pIn1->u.i<pIn2->u.i){
6191 pIn1->u.i = pIn2->u.i;
6193 break;
6195 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6197 /* Opcode: IfPos P1 P2 P3 * *
6198 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6200 ** Register P1 must contain an integer.
6201 ** If the value of register P1 is 1 or greater, subtract P3 from the
6202 ** value in P1 and jump to P2.
6204 ** If the initial value of register P1 is less than 1, then the
6205 ** value is unchanged and control passes through to the next instruction.
6207 case OP_IfPos: { /* jump, in1 */
6208 pIn1 = &aMem[pOp->p1];
6209 assert( pIn1->flags&MEM_Int );
6210 VdbeBranchTaken( pIn1->u.i>0, 2);
6211 if( pIn1->u.i>0 ){
6212 pIn1->u.i -= pOp->p3;
6213 goto jump_to_p2;
6215 break;
6218 /* Opcode: OffsetLimit P1 P2 P3 * *
6219 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6221 ** This opcode performs a commonly used computation associated with
6222 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
6223 ** holds the offset counter. The opcode computes the combined value
6224 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
6225 ** value computed is the total number of rows that will need to be
6226 ** visited in order to complete the query.
6228 ** If r[P3] is zero or negative, that means there is no OFFSET
6229 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6231 ** if r[P1] is zero or negative, that means there is no LIMIT
6232 ** and r[P2] is set to -1.
6234 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6236 case OP_OffsetLimit: { /* in1, out2, in3 */
6237 i64 x;
6238 pIn1 = &aMem[pOp->p1];
6239 pIn3 = &aMem[pOp->p3];
6240 pOut = out2Prerelease(p, pOp);
6241 assert( pIn1->flags & MEM_Int );
6242 assert( pIn3->flags & MEM_Int );
6243 x = pIn1->u.i;
6244 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
6245 /* If the LIMIT is less than or equal to zero, loop forever. This
6246 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
6247 ** also loop forever. This is undocumented. In fact, one could argue
6248 ** that the loop should terminate. But assuming 1 billion iterations
6249 ** per second (far exceeding the capabilities of any current hardware)
6250 ** it would take nearly 300 years to actually reach the limit. So
6251 ** looping forever is a reasonable approximation. */
6252 pOut->u.i = -1;
6253 }else{
6254 pOut->u.i = x;
6256 break;
6259 /* Opcode: IfNotZero P1 P2 * * *
6260 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6262 ** Register P1 must contain an integer. If the content of register P1 is
6263 ** initially greater than zero, then decrement the value in register P1.
6264 ** If it is non-zero (negative or positive) and then also jump to P2.
6265 ** If register P1 is initially zero, leave it unchanged and fall through.
6267 case OP_IfNotZero: { /* jump, in1 */
6268 pIn1 = &aMem[pOp->p1];
6269 assert( pIn1->flags&MEM_Int );
6270 VdbeBranchTaken(pIn1->u.i<0, 2);
6271 if( pIn1->u.i ){
6272 if( pIn1->u.i>0 ) pIn1->u.i--;
6273 goto jump_to_p2;
6275 break;
6278 /* Opcode: DecrJumpZero P1 P2 * * *
6279 ** Synopsis: if (--r[P1])==0 goto P2
6281 ** Register P1 must hold an integer. Decrement the value in P1
6282 ** and jump to P2 if the new value is exactly zero.
6284 case OP_DecrJumpZero: { /* jump, in1 */
6285 pIn1 = &aMem[pOp->p1];
6286 assert( pIn1->flags&MEM_Int );
6287 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
6288 VdbeBranchTaken(pIn1->u.i==0, 2);
6289 if( pIn1->u.i==0 ) goto jump_to_p2;
6290 break;
6294 /* Opcode: AggStep * P2 P3 P4 P5
6295 ** Synopsis: accum=r[P3] step(r[P2@P5])
6297 ** Execute the xStep function for an aggregate.
6298 ** The function has P5 arguments. P4 is a pointer to the
6299 ** FuncDef structure that specifies the function. Register P3 is the
6300 ** accumulator.
6302 ** The P5 arguments are taken from register P2 and its
6303 ** successors.
6305 /* Opcode: AggInverse * P2 P3 P4 P5
6306 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
6308 ** Execute the xInverse function for an aggregate.
6309 ** The function has P5 arguments. P4 is a pointer to the
6310 ** FuncDef structure that specifies the function. Register P3 is the
6311 ** accumulator.
6313 ** The P5 arguments are taken from register P2 and its
6314 ** successors.
6316 /* Opcode: AggStep1 P1 P2 P3 P4 P5
6317 ** Synopsis: accum=r[P3] step(r[P2@P5])
6319 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
6320 ** aggregate. The function has P5 arguments. P4 is a pointer to the
6321 ** FuncDef structure that specifies the function. Register P3 is the
6322 ** accumulator.
6324 ** The P5 arguments are taken from register P2 and its
6325 ** successors.
6327 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6328 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6329 ** the opcode is changed. In this way, the initialization of the
6330 ** sqlite3_context only happens once, instead of on each call to the
6331 ** step function.
6333 case OP_AggInverse:
6334 case OP_AggStep: {
6335 int n;
6336 sqlite3_context *pCtx;
6338 assert( pOp->p4type==P4_FUNCDEF );
6339 n = pOp->p5;
6340 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6341 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
6342 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
6343 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
6344 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
6345 if( pCtx==0 ) goto no_mem;
6346 pCtx->pMem = 0;
6347 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
6348 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
6349 pCtx->pFunc = pOp->p4.pFunc;
6350 pCtx->iOp = (int)(pOp - aOp);
6351 pCtx->pVdbe = p;
6352 pCtx->skipFlag = 0;
6353 pCtx->isError = 0;
6354 pCtx->argc = n;
6355 pOp->p4type = P4_FUNCCTX;
6356 pOp->p4.pCtx = pCtx;
6358 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
6359 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
6361 pOp->opcode = OP_AggStep1;
6362 /* Fall through into OP_AggStep */
6364 case OP_AggStep1: {
6365 int i;
6366 sqlite3_context *pCtx;
6367 Mem *pMem;
6369 assert( pOp->p4type==P4_FUNCCTX );
6370 pCtx = pOp->p4.pCtx;
6371 pMem = &aMem[pOp->p3];
6373 #ifdef SQLITE_DEBUG
6374 if( pOp->p1 ){
6375 /* This is an OP_AggInverse call. Verify that xStep has always
6376 ** been called at least once prior to any xInverse call. */
6377 assert( pMem->uTemp==0x1122e0e3 );
6378 }else{
6379 /* This is an OP_AggStep call. Mark it as such. */
6380 pMem->uTemp = 0x1122e0e3;
6382 #endif
6384 /* If this function is inside of a trigger, the register array in aMem[]
6385 ** might change from one evaluation to the next. The next block of code
6386 ** checks to see if the register array has changed, and if so it
6387 ** reinitializes the relavant parts of the sqlite3_context object */
6388 if( pCtx->pMem != pMem ){
6389 pCtx->pMem = pMem;
6390 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
6393 #ifdef SQLITE_DEBUG
6394 for(i=0; i<pCtx->argc; i++){
6395 assert( memIsValid(pCtx->argv[i]) );
6396 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
6398 #endif
6400 pMem->n++;
6401 assert( pCtx->pOut->flags==MEM_Null );
6402 assert( pCtx->isError==0 );
6403 assert( pCtx->skipFlag==0 );
6404 #ifndef SQLITE_OMIT_WINDOWFUNC
6405 if( pOp->p1 ){
6406 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
6407 }else
6408 #endif
6409 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
6411 if( pCtx->isError ){
6412 if( pCtx->isError>0 ){
6413 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
6414 rc = pCtx->isError;
6416 if( pCtx->skipFlag ){
6417 assert( pOp[-1].opcode==OP_CollSeq );
6418 i = pOp[-1].p1;
6419 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
6420 pCtx->skipFlag = 0;
6422 sqlite3VdbeMemRelease(pCtx->pOut);
6423 pCtx->pOut->flags = MEM_Null;
6424 pCtx->isError = 0;
6425 if( rc ) goto abort_due_to_error;
6427 assert( pCtx->pOut->flags==MEM_Null );
6428 assert( pCtx->skipFlag==0 );
6429 break;
6432 /* Opcode: AggFinal P1 P2 * P4 *
6433 ** Synopsis: accum=r[P1] N=P2
6435 ** P1 is the memory location that is the accumulator for an aggregate
6436 ** or window function. Execute the finalizer function
6437 ** for an aggregate and store the result in P1.
6439 ** P2 is the number of arguments that the step function takes and
6440 ** P4 is a pointer to the FuncDef for this function. The P2
6441 ** argument is not used by this opcode. It is only there to disambiguate
6442 ** functions that can take varying numbers of arguments. The
6443 ** P4 argument is only needed for the case where
6444 ** the step function was not previously called.
6446 /* Opcode: AggValue * P2 P3 P4 *
6447 ** Synopsis: r[P3]=value N=P2
6449 ** Invoke the xValue() function and store the result in register P3.
6451 ** P2 is the number of arguments that the step function takes and
6452 ** P4 is a pointer to the FuncDef for this function. The P2
6453 ** argument is not used by this opcode. It is only there to disambiguate
6454 ** functions that can take varying numbers of arguments. The
6455 ** P4 argument is only needed for the case where
6456 ** the step function was not previously called.
6458 case OP_AggValue:
6459 case OP_AggFinal: {
6460 Mem *pMem;
6461 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
6462 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
6463 pMem = &aMem[pOp->p1];
6464 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
6465 #ifndef SQLITE_OMIT_WINDOWFUNC
6466 if( pOp->p3 ){
6467 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
6468 pMem = &aMem[pOp->p3];
6469 }else
6470 #endif
6472 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
6475 if( rc ){
6476 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
6477 goto abort_due_to_error;
6479 sqlite3VdbeChangeEncoding(pMem, encoding);
6480 UPDATE_MAX_BLOBSIZE(pMem);
6481 if( sqlite3VdbeMemTooBig(pMem) ){
6482 goto too_big;
6484 break;
6487 #ifndef SQLITE_OMIT_WAL
6488 /* Opcode: Checkpoint P1 P2 P3 * *
6490 ** Checkpoint database P1. This is a no-op if P1 is not currently in
6491 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
6492 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
6493 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
6494 ** WAL after the checkpoint into mem[P3+1] and the number of pages
6495 ** in the WAL that have been checkpointed after the checkpoint
6496 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
6497 ** mem[P3+2] are initialized to -1.
6499 case OP_Checkpoint: {
6500 int i; /* Loop counter */
6501 int aRes[3]; /* Results */
6502 Mem *pMem; /* Write results here */
6504 assert( p->readOnly==0 );
6505 aRes[0] = 0;
6506 aRes[1] = aRes[2] = -1;
6507 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
6508 || pOp->p2==SQLITE_CHECKPOINT_FULL
6509 || pOp->p2==SQLITE_CHECKPOINT_RESTART
6510 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
6512 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
6513 if( rc ){
6514 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
6515 rc = SQLITE_OK;
6516 aRes[0] = 1;
6518 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
6519 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
6521 break;
6523 #endif
6525 #ifndef SQLITE_OMIT_PRAGMA
6526 /* Opcode: JournalMode P1 P2 P3 * *
6528 ** Change the journal mode of database P1 to P3. P3 must be one of the
6529 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
6530 ** modes (delete, truncate, persist, off and memory), this is a simple
6531 ** operation. No IO is required.
6533 ** If changing into or out of WAL mode the procedure is more complicated.
6535 ** Write a string containing the final journal-mode to register P2.
6537 case OP_JournalMode: { /* out2 */
6538 Btree *pBt; /* Btree to change journal mode of */
6539 Pager *pPager; /* Pager associated with pBt */
6540 int eNew; /* New journal mode */
6541 int eOld; /* The old journal mode */
6542 #ifndef SQLITE_OMIT_WAL
6543 const char *zFilename; /* Name of database file for pPager */
6544 #endif
6546 pOut = out2Prerelease(p, pOp);
6547 eNew = pOp->p3;
6548 assert( eNew==PAGER_JOURNALMODE_DELETE
6549 || eNew==PAGER_JOURNALMODE_TRUNCATE
6550 || eNew==PAGER_JOURNALMODE_PERSIST
6551 || eNew==PAGER_JOURNALMODE_OFF
6552 || eNew==PAGER_JOURNALMODE_MEMORY
6553 || eNew==PAGER_JOURNALMODE_WAL
6554 || eNew==PAGER_JOURNALMODE_QUERY
6556 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6557 assert( p->readOnly==0 );
6559 pBt = db->aDb[pOp->p1].pBt;
6560 pPager = sqlite3BtreePager(pBt);
6561 eOld = sqlite3PagerGetJournalMode(pPager);
6562 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
6563 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
6565 #ifndef SQLITE_OMIT_WAL
6566 zFilename = sqlite3PagerFilename(pPager, 1);
6568 /* Do not allow a transition to journal_mode=WAL for a database
6569 ** in temporary storage or if the VFS does not support shared memory
6571 if( eNew==PAGER_JOURNALMODE_WAL
6572 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
6573 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
6575 eNew = eOld;
6578 if( (eNew!=eOld)
6579 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
6581 if( !db->autoCommit || db->nVdbeRead>1 ){
6582 rc = SQLITE_ERROR;
6583 sqlite3VdbeError(p,
6584 "cannot change %s wal mode from within a transaction",
6585 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
6587 goto abort_due_to_error;
6588 }else{
6590 if( eOld==PAGER_JOURNALMODE_WAL ){
6591 /* If leaving WAL mode, close the log file. If successful, the call
6592 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
6593 ** file. An EXCLUSIVE lock may still be held on the database file
6594 ** after a successful return.
6596 rc = sqlite3PagerCloseWal(pPager, db);
6597 if( rc==SQLITE_OK ){
6598 sqlite3PagerSetJournalMode(pPager, eNew);
6600 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
6601 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
6602 ** as an intermediate */
6603 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
6606 /* Open a transaction on the database file. Regardless of the journal
6607 ** mode, this transaction always uses a rollback journal.
6609 assert( sqlite3BtreeIsInTrans(pBt)==0 );
6610 if( rc==SQLITE_OK ){
6611 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
6615 #endif /* ifndef SQLITE_OMIT_WAL */
6617 if( rc ) eNew = eOld;
6618 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
6620 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
6621 pOut->z = (char *)sqlite3JournalModename(eNew);
6622 pOut->n = sqlite3Strlen30(pOut->z);
6623 pOut->enc = SQLITE_UTF8;
6624 sqlite3VdbeChangeEncoding(pOut, encoding);
6625 if( rc ) goto abort_due_to_error;
6626 break;
6628 #endif /* SQLITE_OMIT_PRAGMA */
6630 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
6631 /* Opcode: Vacuum P1 * * * *
6633 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
6634 ** for an attached database. The "temp" database may not be vacuumed.
6636 case OP_Vacuum: {
6637 assert( p->readOnly==0 );
6638 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
6639 if( rc ) goto abort_due_to_error;
6640 break;
6642 #endif
6644 #if !defined(SQLITE_OMIT_AUTOVACUUM)
6645 /* Opcode: IncrVacuum P1 P2 * * *
6647 ** Perform a single step of the incremental vacuum procedure on
6648 ** the P1 database. If the vacuum has finished, jump to instruction
6649 ** P2. Otherwise, fall through to the next instruction.
6651 case OP_IncrVacuum: { /* jump */
6652 Btree *pBt;
6654 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6655 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6656 assert( p->readOnly==0 );
6657 pBt = db->aDb[pOp->p1].pBt;
6658 rc = sqlite3BtreeIncrVacuum(pBt);
6659 VdbeBranchTaken(rc==SQLITE_DONE,2);
6660 if( rc ){
6661 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6662 rc = SQLITE_OK;
6663 goto jump_to_p2;
6665 break;
6667 #endif
6669 /* Opcode: Expire P1 * * * *
6671 ** Cause precompiled statements to expire. When an expired statement
6672 ** is executed using sqlite3_step() it will either automatically
6673 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
6674 ** or it will fail with SQLITE_SCHEMA.
6676 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
6677 ** then only the currently executing statement is expired.
6679 case OP_Expire: {
6680 if( !pOp->p1 ){
6681 sqlite3ExpirePreparedStatements(db);
6682 }else{
6683 p->expired = 1;
6685 break;
6688 #ifndef SQLITE_OMIT_SHARED_CACHE
6689 /* Opcode: TableLock P1 P2 P3 P4 *
6690 ** Synopsis: iDb=P1 root=P2 write=P3
6692 ** Obtain a lock on a particular table. This instruction is only used when
6693 ** the shared-cache feature is enabled.
6695 ** P1 is the index of the database in sqlite3.aDb[] of the database
6696 ** on which the lock is acquired. A readlock is obtained if P3==0 or
6697 ** a write lock if P3==1.
6699 ** P2 contains the root-page of the table to lock.
6701 ** P4 contains a pointer to the name of the table being locked. This is only
6702 ** used to generate an error message if the lock cannot be obtained.
6704 case OP_TableLock: {
6705 u8 isWriteLock = (u8)pOp->p3;
6706 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
6707 int p1 = pOp->p1;
6708 assert( p1>=0 && p1<db->nDb );
6709 assert( DbMaskTest(p->btreeMask, p1) );
6710 assert( isWriteLock==0 || isWriteLock==1 );
6711 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
6712 if( rc ){
6713 if( (rc&0xFF)==SQLITE_LOCKED ){
6714 const char *z = pOp->p4.z;
6715 sqlite3VdbeError(p, "database table is locked: %s", z);
6717 goto abort_due_to_error;
6720 break;
6722 #endif /* SQLITE_OMIT_SHARED_CACHE */
6724 #ifndef SQLITE_OMIT_VIRTUALTABLE
6725 /* Opcode: VBegin * * * P4 *
6727 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
6728 ** xBegin method for that table.
6730 ** Also, whether or not P4 is set, check that this is not being called from
6731 ** within a callback to a virtual table xSync() method. If it is, the error
6732 ** code will be set to SQLITE_LOCKED.
6734 case OP_VBegin: {
6735 VTable *pVTab;
6736 pVTab = pOp->p4.pVtab;
6737 rc = sqlite3VtabBegin(db, pVTab);
6738 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
6739 if( rc ) goto abort_due_to_error;
6740 break;
6742 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6744 #ifndef SQLITE_OMIT_VIRTUALTABLE
6745 /* Opcode: VCreate P1 P2 * * *
6747 ** P2 is a register that holds the name of a virtual table in database
6748 ** P1. Call the xCreate method for that table.
6750 case OP_VCreate: {
6751 Mem sMem; /* For storing the record being decoded */
6752 const char *zTab; /* Name of the virtual table */
6754 memset(&sMem, 0, sizeof(sMem));
6755 sMem.db = db;
6756 /* Because P2 is always a static string, it is impossible for the
6757 ** sqlite3VdbeMemCopy() to fail */
6758 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
6759 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
6760 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
6761 assert( rc==SQLITE_OK );
6762 zTab = (const char*)sqlite3_value_text(&sMem);
6763 assert( zTab || db->mallocFailed );
6764 if( zTab ){
6765 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
6767 sqlite3VdbeMemRelease(&sMem);
6768 if( rc ) goto abort_due_to_error;
6769 break;
6771 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6773 #ifndef SQLITE_OMIT_VIRTUALTABLE
6774 /* Opcode: VDestroy P1 * * P4 *
6776 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
6777 ** of that table.
6779 case OP_VDestroy: {
6780 db->nVDestroy++;
6781 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
6782 db->nVDestroy--;
6783 if( rc ) goto abort_due_to_error;
6784 break;
6786 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6788 #ifndef SQLITE_OMIT_VIRTUALTABLE
6789 /* Opcode: VOpen P1 * * P4 *
6791 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6792 ** P1 is a cursor number. This opcode opens a cursor to the virtual
6793 ** table and stores that cursor in P1.
6795 case OP_VOpen: {
6796 VdbeCursor *pCur;
6797 sqlite3_vtab_cursor *pVCur;
6798 sqlite3_vtab *pVtab;
6799 const sqlite3_module *pModule;
6801 assert( p->bIsReader );
6802 pCur = 0;
6803 pVCur = 0;
6804 pVtab = pOp->p4.pVtab->pVtab;
6805 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6806 rc = SQLITE_LOCKED;
6807 goto abort_due_to_error;
6809 pModule = pVtab->pModule;
6810 rc = pModule->xOpen(pVtab, &pVCur);
6811 sqlite3VtabImportErrmsg(p, pVtab);
6812 if( rc ) goto abort_due_to_error;
6814 /* Initialize sqlite3_vtab_cursor base class */
6815 pVCur->pVtab = pVtab;
6817 /* Initialize vdbe cursor object */
6818 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
6819 if( pCur ){
6820 pCur->uc.pVCur = pVCur;
6821 pVtab->nRef++;
6822 }else{
6823 assert( db->mallocFailed );
6824 pModule->xClose(pVCur);
6825 goto no_mem;
6827 break;
6829 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6831 #ifndef SQLITE_OMIT_VIRTUALTABLE
6832 /* Opcode: VFilter P1 P2 P3 P4 *
6833 ** Synopsis: iplan=r[P3] zplan='P4'
6835 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
6836 ** the filtered result set is empty.
6838 ** P4 is either NULL or a string that was generated by the xBestIndex
6839 ** method of the module. The interpretation of the P4 string is left
6840 ** to the module implementation.
6842 ** This opcode invokes the xFilter method on the virtual table specified
6843 ** by P1. The integer query plan parameter to xFilter is stored in register
6844 ** P3. Register P3+1 stores the argc parameter to be passed to the
6845 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6846 ** additional parameters which are passed to
6847 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6849 ** A jump is made to P2 if the result set after filtering would be empty.
6851 case OP_VFilter: { /* jump */
6852 int nArg;
6853 int iQuery;
6854 const sqlite3_module *pModule;
6855 Mem *pQuery;
6856 Mem *pArgc;
6857 sqlite3_vtab_cursor *pVCur;
6858 sqlite3_vtab *pVtab;
6859 VdbeCursor *pCur;
6860 int res;
6861 int i;
6862 Mem **apArg;
6864 pQuery = &aMem[pOp->p3];
6865 pArgc = &pQuery[1];
6866 pCur = p->apCsr[pOp->p1];
6867 assert( memIsValid(pQuery) );
6868 REGISTER_TRACE(pOp->p3, pQuery);
6869 assert( pCur->eCurType==CURTYPE_VTAB );
6870 pVCur = pCur->uc.pVCur;
6871 pVtab = pVCur->pVtab;
6872 pModule = pVtab->pModule;
6874 /* Grab the index number and argc parameters */
6875 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
6876 nArg = (int)pArgc->u.i;
6877 iQuery = (int)pQuery->u.i;
6879 /* Invoke the xFilter method */
6880 res = 0;
6881 apArg = p->apArg;
6882 for(i = 0; i<nArg; i++){
6883 apArg[i] = &pArgc[i+1];
6885 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
6886 sqlite3VtabImportErrmsg(p, pVtab);
6887 if( rc ) goto abort_due_to_error;
6888 res = pModule->xEof(pVCur);
6889 pCur->nullRow = 0;
6890 VdbeBranchTaken(res!=0,2);
6891 if( res ) goto jump_to_p2;
6892 break;
6894 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6896 #ifndef SQLITE_OMIT_VIRTUALTABLE
6897 /* Opcode: VColumn P1 P2 P3 * P5
6898 ** Synopsis: r[P3]=vcolumn(P2)
6900 ** Store in register P3 the value of the P2-th column of
6901 ** the current row of the virtual-table of cursor P1.
6903 ** If the VColumn opcode is being used to fetch the value of
6904 ** an unchanging column during an UPDATE operation, then the P5
6905 ** value is 1. Otherwise, P5 is 0. The P5 value is returned
6906 ** by sqlite3_vtab_nochange() routine and can be used
6907 ** by virtual table implementations to return special "no-change"
6908 ** marks which can be more efficient, depending on the virtual table.
6910 case OP_VColumn: {
6911 sqlite3_vtab *pVtab;
6912 const sqlite3_module *pModule;
6913 Mem *pDest;
6914 sqlite3_context sContext;
6916 VdbeCursor *pCur = p->apCsr[pOp->p1];
6917 assert( pCur->eCurType==CURTYPE_VTAB );
6918 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6919 pDest = &aMem[pOp->p3];
6920 memAboutToChange(p, pDest);
6921 if( pCur->nullRow ){
6922 sqlite3VdbeMemSetNull(pDest);
6923 break;
6925 pVtab = pCur->uc.pVCur->pVtab;
6926 pModule = pVtab->pModule;
6927 assert( pModule->xColumn );
6928 memset(&sContext, 0, sizeof(sContext));
6929 sContext.pOut = pDest;
6930 if( pOp->p5 ){
6931 sqlite3VdbeMemSetNull(pDest);
6932 pDest->flags = MEM_Null|MEM_Zero;
6933 pDest->u.nZero = 0;
6934 }else{
6935 MemSetTypeFlag(pDest, MEM_Null);
6937 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
6938 sqlite3VtabImportErrmsg(p, pVtab);
6939 if( sContext.isError>0 ){
6940 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
6941 rc = sContext.isError;
6943 sqlite3VdbeChangeEncoding(pDest, encoding);
6944 REGISTER_TRACE(pOp->p3, pDest);
6945 UPDATE_MAX_BLOBSIZE(pDest);
6947 if( sqlite3VdbeMemTooBig(pDest) ){
6948 goto too_big;
6950 if( rc ) goto abort_due_to_error;
6951 break;
6953 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6955 #ifndef SQLITE_OMIT_VIRTUALTABLE
6956 /* Opcode: VNext P1 P2 * * *
6958 ** Advance virtual table P1 to the next row in its result set and
6959 ** jump to instruction P2. Or, if the virtual table has reached
6960 ** the end of its result set, then fall through to the next instruction.
6962 case OP_VNext: { /* jump */
6963 sqlite3_vtab *pVtab;
6964 const sqlite3_module *pModule;
6965 int res;
6966 VdbeCursor *pCur;
6968 res = 0;
6969 pCur = p->apCsr[pOp->p1];
6970 assert( pCur->eCurType==CURTYPE_VTAB );
6971 if( pCur->nullRow ){
6972 break;
6974 pVtab = pCur->uc.pVCur->pVtab;
6975 pModule = pVtab->pModule;
6976 assert( pModule->xNext );
6978 /* Invoke the xNext() method of the module. There is no way for the
6979 ** underlying implementation to return an error if one occurs during
6980 ** xNext(). Instead, if an error occurs, true is returned (indicating that
6981 ** data is available) and the error code returned when xColumn or
6982 ** some other method is next invoked on the save virtual table cursor.
6984 rc = pModule->xNext(pCur->uc.pVCur);
6985 sqlite3VtabImportErrmsg(p, pVtab);
6986 if( rc ) goto abort_due_to_error;
6987 res = pModule->xEof(pCur->uc.pVCur);
6988 VdbeBranchTaken(!res,2);
6989 if( !res ){
6990 /* If there is data, jump to P2 */
6991 goto jump_to_p2_and_check_for_interrupt;
6993 goto check_for_interrupt;
6995 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6997 #ifndef SQLITE_OMIT_VIRTUALTABLE
6998 /* Opcode: VRename P1 * * P4 *
7000 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7001 ** This opcode invokes the corresponding xRename method. The value
7002 ** in register P1 is passed as the zName argument to the xRename method.
7004 case OP_VRename: {
7005 sqlite3_vtab *pVtab;
7006 Mem *pName;
7008 pVtab = pOp->p4.pVtab->pVtab;
7009 pName = &aMem[pOp->p1];
7010 assert( pVtab->pModule->xRename );
7011 assert( memIsValid(pName) );
7012 assert( p->readOnly==0 );
7013 REGISTER_TRACE(pOp->p1, pName);
7014 assert( pName->flags & MEM_Str );
7015 testcase( pName->enc==SQLITE_UTF8 );
7016 testcase( pName->enc==SQLITE_UTF16BE );
7017 testcase( pName->enc==SQLITE_UTF16LE );
7018 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
7019 if( rc ) goto abort_due_to_error;
7020 rc = pVtab->pModule->xRename(pVtab, pName->z);
7021 sqlite3VtabImportErrmsg(p, pVtab);
7022 p->expired = 0;
7023 if( rc ) goto abort_due_to_error;
7024 break;
7026 #endif
7028 #ifndef SQLITE_OMIT_VIRTUALTABLE
7029 /* Opcode: VUpdate P1 P2 P3 P4 P5
7030 ** Synopsis: data=r[P3@P2]
7032 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7033 ** This opcode invokes the corresponding xUpdate method. P2 values
7034 ** are contiguous memory cells starting at P3 to pass to the xUpdate
7035 ** invocation. The value in register (P3+P2-1) corresponds to the
7036 ** p2th element of the argv array passed to xUpdate.
7038 ** The xUpdate method will do a DELETE or an INSERT or both.
7039 ** The argv[0] element (which corresponds to memory cell P3)
7040 ** is the rowid of a row to delete. If argv[0] is NULL then no
7041 ** deletion occurs. The argv[1] element is the rowid of the new
7042 ** row. This can be NULL to have the virtual table select the new
7043 ** rowid for itself. The subsequent elements in the array are
7044 ** the values of columns in the new row.
7046 ** If P2==1 then no insert is performed. argv[0] is the rowid of
7047 ** a row to delete.
7049 ** P1 is a boolean flag. If it is set to true and the xUpdate call
7050 ** is successful, then the value returned by sqlite3_last_insert_rowid()
7051 ** is set to the value of the rowid for the row just inserted.
7053 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
7054 ** apply in the case of a constraint failure on an insert or update.
7056 case OP_VUpdate: {
7057 sqlite3_vtab *pVtab;
7058 const sqlite3_module *pModule;
7059 int nArg;
7060 int i;
7061 sqlite_int64 rowid;
7062 Mem **apArg;
7063 Mem *pX;
7065 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
7066 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
7068 assert( p->readOnly==0 );
7069 if( db->mallocFailed ) goto no_mem;
7070 sqlite3VdbeIncrWriteCounter(p, 0);
7071 pVtab = pOp->p4.pVtab->pVtab;
7072 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7073 rc = SQLITE_LOCKED;
7074 goto abort_due_to_error;
7076 pModule = pVtab->pModule;
7077 nArg = pOp->p2;
7078 assert( pOp->p4type==P4_VTAB );
7079 if( ALWAYS(pModule->xUpdate) ){
7080 u8 vtabOnConflict = db->vtabOnConflict;
7081 apArg = p->apArg;
7082 pX = &aMem[pOp->p3];
7083 for(i=0; i<nArg; i++){
7084 assert( memIsValid(pX) );
7085 memAboutToChange(p, pX);
7086 apArg[i] = pX;
7087 pX++;
7089 db->vtabOnConflict = pOp->p5;
7090 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
7091 db->vtabOnConflict = vtabOnConflict;
7092 sqlite3VtabImportErrmsg(p, pVtab);
7093 if( rc==SQLITE_OK && pOp->p1 ){
7094 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
7095 db->lastRowid = rowid;
7097 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
7098 if( pOp->p5==OE_Ignore ){
7099 rc = SQLITE_OK;
7100 }else{
7101 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
7103 }else{
7104 p->nChange++;
7106 if( rc ) goto abort_due_to_error;
7108 break;
7110 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7112 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7113 /* Opcode: Pagecount P1 P2 * * *
7115 ** Write the current number of pages in database P1 to memory cell P2.
7117 case OP_Pagecount: { /* out2 */
7118 pOut = out2Prerelease(p, pOp);
7119 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
7120 break;
7122 #endif
7125 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7126 /* Opcode: MaxPgcnt P1 P2 P3 * *
7128 ** Try to set the maximum page count for database P1 to the value in P3.
7129 ** Do not let the maximum page count fall below the current page count and
7130 ** do not change the maximum page count value if P3==0.
7132 ** Store the maximum page count after the change in register P2.
7134 case OP_MaxPgcnt: { /* out2 */
7135 unsigned int newMax;
7136 Btree *pBt;
7138 pOut = out2Prerelease(p, pOp);
7139 pBt = db->aDb[pOp->p1].pBt;
7140 newMax = 0;
7141 if( pOp->p3 ){
7142 newMax = sqlite3BtreeLastPage(pBt);
7143 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
7145 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
7146 break;
7148 #endif
7150 /* Opcode: Function0 P1 P2 P3 P4 P5
7151 ** Synopsis: r[P3]=func(r[P2@P5])
7153 ** Invoke a user function (P4 is a pointer to a FuncDef object that
7154 ** defines the function) with P5 arguments taken from register P2 and
7155 ** successors. The result of the function is stored in register P3.
7156 ** Register P3 must not be one of the function inputs.
7158 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7159 ** function was determined to be constant at compile time. If the first
7160 ** argument was constant then bit 0 of P1 is set. This is used to determine
7161 ** whether meta data associated with a user function argument using the
7162 ** sqlite3_set_auxdata() API may be safely retained until the next
7163 ** invocation of this opcode.
7165 ** See also: Function, AggStep, AggFinal
7167 /* Opcode: Function P1 P2 P3 P4 P5
7168 ** Synopsis: r[P3]=func(r[P2@P5])
7170 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7171 ** contains a pointer to the function to be run) with P5 arguments taken
7172 ** from register P2 and successors. The result of the function is stored
7173 ** in register P3. Register P3 must not be one of the function inputs.
7175 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7176 ** function was determined to be constant at compile time. If the first
7177 ** argument was constant then bit 0 of P1 is set. This is used to determine
7178 ** whether meta data associated with a user function argument using the
7179 ** sqlite3_set_auxdata() API may be safely retained until the next
7180 ** invocation of this opcode.
7182 ** SQL functions are initially coded as OP_Function0 with P4 pointing
7183 ** to a FuncDef object. But on first evaluation, the P4 operand is
7184 ** automatically converted into an sqlite3_context object and the operation
7185 ** changed to this OP_Function opcode. In this way, the initialization of
7186 ** the sqlite3_context object occurs only once, rather than once for each
7187 ** evaluation of the function.
7189 ** See also: Function0, AggStep, AggFinal
7191 case OP_PureFunc0:
7192 case OP_Function0: {
7193 int n;
7194 sqlite3_context *pCtx;
7196 assert( pOp->p4type==P4_FUNCDEF );
7197 n = pOp->p5;
7198 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7199 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7200 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7201 pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
7202 if( pCtx==0 ) goto no_mem;
7203 pCtx->pOut = 0;
7204 pCtx->pFunc = pOp->p4.pFunc;
7205 pCtx->iOp = (int)(pOp - aOp);
7206 pCtx->pVdbe = p;
7207 pCtx->isError = 0;
7208 pCtx->argc = n;
7209 pOp->p4type = P4_FUNCCTX;
7210 pOp->p4.pCtx = pCtx;
7211 assert( OP_PureFunc == OP_PureFunc0+2 );
7212 assert( OP_Function == OP_Function0+2 );
7213 pOp->opcode += 2;
7214 /* Fall through into OP_Function */
7216 case OP_PureFunc:
7217 case OP_Function: {
7218 int i;
7219 sqlite3_context *pCtx;
7221 assert( pOp->p4type==P4_FUNCCTX );
7222 pCtx = pOp->p4.pCtx;
7224 /* If this function is inside of a trigger, the register array in aMem[]
7225 ** might change from one evaluation to the next. The next block of code
7226 ** checks to see if the register array has changed, and if so it
7227 ** reinitializes the relavant parts of the sqlite3_context object */
7228 pOut = &aMem[pOp->p3];
7229 if( pCtx->pOut != pOut ){
7230 pCtx->pOut = pOut;
7231 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7234 memAboutToChange(p, pOut);
7235 #ifdef SQLITE_DEBUG
7236 for(i=0; i<pCtx->argc; i++){
7237 assert( memIsValid(pCtx->argv[i]) );
7238 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7240 #endif
7241 MemSetTypeFlag(pOut, MEM_Null);
7242 assert( pCtx->isError==0 );
7243 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
7245 /* If the function returned an error, throw an exception */
7246 if( pCtx->isError ){
7247 if( pCtx->isError>0 ){
7248 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
7249 rc = pCtx->isError;
7251 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
7252 pCtx->isError = 0;
7253 if( rc ) goto abort_due_to_error;
7256 /* Copy the result of the function into register P3 */
7257 if( pOut->flags & (MEM_Str|MEM_Blob) ){
7258 sqlite3VdbeChangeEncoding(pOut, encoding);
7259 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
7262 REGISTER_TRACE(pOp->p3, pOut);
7263 UPDATE_MAX_BLOBSIZE(pOut);
7264 break;
7267 /* Opcode: Trace P1 P2 * P4 *
7269 ** Write P4 on the statement trace output if statement tracing is
7270 ** enabled.
7272 ** Operand P1 must be 0x7fffffff and P2 must positive.
7274 /* Opcode: Init P1 P2 P3 P4 *
7275 ** Synopsis: Start at P2
7277 ** Programs contain a single instance of this opcode as the very first
7278 ** opcode.
7280 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7281 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7282 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7284 ** If P2 is not zero, jump to instruction P2.
7286 ** Increment the value of P1 so that OP_Once opcodes will jump the
7287 ** first time they are evaluated for this run.
7289 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7290 ** error is encountered.
7292 case OP_Trace:
7293 case OP_Init: { /* jump */
7294 int i;
7295 #ifndef SQLITE_OMIT_TRACE
7296 char *zTrace;
7297 #endif
7299 /* If the P4 argument is not NULL, then it must be an SQL comment string.
7300 ** The "--" string is broken up to prevent false-positives with srcck1.c.
7302 ** This assert() provides evidence for:
7303 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7304 ** would have been returned by the legacy sqlite3_trace() interface by
7305 ** using the X argument when X begins with "--" and invoking
7306 ** sqlite3_expanded_sql(P) otherwise.
7308 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
7310 /* OP_Init is always instruction 0 */
7311 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
7313 #ifndef SQLITE_OMIT_TRACE
7314 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
7315 && !p->doingRerun
7316 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7318 #ifndef SQLITE_OMIT_DEPRECATED
7319 if( db->mTrace & SQLITE_TRACE_LEGACY ){
7320 void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
7321 char *z = sqlite3VdbeExpandSql(p, zTrace);
7322 x(db->pTraceArg, z);
7323 sqlite3_free(z);
7324 }else
7325 #endif
7326 if( db->nVdbeExec>1 ){
7327 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
7328 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
7329 sqlite3DbFree(db, z);
7330 }else{
7331 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
7334 #ifdef SQLITE_USE_FCNTL_TRACE
7335 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
7336 if( zTrace ){
7337 int j;
7338 for(j=0; j<db->nDb; j++){
7339 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
7340 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
7343 #endif /* SQLITE_USE_FCNTL_TRACE */
7344 #ifdef SQLITE_DEBUG
7345 if( (db->flags & SQLITE_SqlTrace)!=0
7346 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7348 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
7350 #endif /* SQLITE_DEBUG */
7351 #endif /* SQLITE_OMIT_TRACE */
7352 assert( pOp->p2>0 );
7353 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
7354 if( pOp->opcode==OP_Trace ) break;
7355 for(i=1; i<p->nOp; i++){
7356 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
7358 pOp->p1 = 0;
7360 pOp->p1++;
7361 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
7362 goto jump_to_p2;
7365 #ifdef SQLITE_ENABLE_CURSOR_HINTS
7366 /* Opcode: CursorHint P1 * * P4 *
7368 ** Provide a hint to cursor P1 that it only needs to return rows that
7369 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
7370 ** to values currently held in registers. TK_COLUMN terms in the P4
7371 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
7373 case OP_CursorHint: {
7374 VdbeCursor *pC;
7376 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7377 assert( pOp->p4type==P4_EXPR );
7378 pC = p->apCsr[pOp->p1];
7379 if( pC ){
7380 assert( pC->eCurType==CURTYPE_BTREE );
7381 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
7382 pOp->p4.pExpr, aMem);
7384 break;
7386 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
7388 #ifdef SQLITE_DEBUG
7389 /* Opcode: Abortable * * * * *
7391 ** Verify that an Abort can happen. Assert if an Abort at this point
7392 ** might cause database corruption. This opcode only appears in debugging
7393 ** builds.
7395 ** An Abort is safe if either there have been no writes, or if there is
7396 ** an active statement journal.
7398 case OP_Abortable: {
7399 sqlite3VdbeAssertAbortable(p);
7400 break;
7402 #endif
7404 #ifdef SQLITE_DEBUG_COLUMNCACHE
7405 /* Opcode: SetTabCol P1 P2 P3 * *
7407 ** Set a flag in register REG[P3] indicating that it holds the value
7408 ** of column P2 from the table on cursor P1. This flag is checked
7409 ** by a subsequent VerifyTabCol opcode.
7411 ** This opcode only appears SQLITE_DEBUG builds. It is used to verify
7412 ** that the expression table column cache is working correctly.
7414 case OP_SetTabCol: {
7415 aMem[pOp->p3].iTabColHash = TableColumnHash(pOp->p1,pOp->p2);
7416 break;
7418 /* Opcode: VerifyTabCol P1 P2 P3 * *
7420 ** Verify that register REG[P3] contains the value of column P2 from
7421 ** cursor P1. Assert() if this is not the case.
7423 ** This opcode only appears SQLITE_DEBUG builds. It is used to verify
7424 ** that the expression table column cache is working correctly.
7426 case OP_VerifyTabCol: {
7427 assert( aMem[pOp->p3].iTabColHash == TableColumnHash(pOp->p1,pOp->p2) );
7428 break;
7430 #endif
7432 /* Opcode: Noop * * * * *
7434 ** Do nothing. This instruction is often useful as a jump
7435 ** destination.
7438 ** The magic Explain opcode are only inserted when explain==2 (which
7439 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
7440 ** This opcode records information from the optimizer. It is the
7441 ** the same as a no-op. This opcodesnever appears in a real VM program.
7443 default: { /* This is really OP_Noop, OP_Explain */
7444 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
7446 break;
7449 /*****************************************************************************
7450 ** The cases of the switch statement above this line should all be indented
7451 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
7452 ** readability. From this point on down, the normal indentation rules are
7453 ** restored.
7454 *****************************************************************************/
7457 #ifdef VDBE_PROFILE
7459 u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
7460 if( endTime>start ) pOrigOp->cycles += endTime - start;
7461 pOrigOp->cnt++;
7463 #endif
7465 /* The following code adds nothing to the actual functionality
7466 ** of the program. It is only here for testing and debugging.
7467 ** On the other hand, it does burn CPU cycles every time through
7468 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
7470 #ifndef NDEBUG
7471 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
7473 #ifdef SQLITE_DEBUG
7474 if( db->flags & SQLITE_VdbeTrace ){
7475 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
7476 if( rc!=0 ) printf("rc=%d\n",rc);
7477 if( opProperty & (OPFLG_OUT2) ){
7478 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
7480 if( opProperty & OPFLG_OUT3 ){
7481 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
7484 #endif /* SQLITE_DEBUG */
7485 #endif /* NDEBUG */
7486 } /* The end of the for(;;) loop the loops through opcodes */
7488 /* If we reach this point, it means that execution is finished with
7489 ** an error of some kind.
7491 abort_due_to_error:
7492 if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
7493 assert( rc );
7494 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
7495 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7497 p->rc = rc;
7498 sqlite3SystemError(db, rc);
7499 testcase( sqlite3GlobalConfig.xLog!=0 );
7500 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
7501 (int)(pOp - aOp), p->zSql, p->zErrMsg);
7502 sqlite3VdbeHalt(p);
7503 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
7504 rc = SQLITE_ERROR;
7505 if( resetSchemaOnFault>0 ){
7506 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
7509 /* This is the only way out of this procedure. We have to
7510 ** release the mutexes on btrees that were acquired at the
7511 ** top. */
7512 vdbe_return:
7513 testcase( nVmStep>0 );
7514 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
7515 sqlite3VdbeLeave(p);
7516 assert( rc!=SQLITE_OK || nExtraDelete==0
7517 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
7519 return rc;
7521 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
7522 ** is encountered.
7524 too_big:
7525 sqlite3VdbeError(p, "string or blob too big");
7526 rc = SQLITE_TOOBIG;
7527 goto abort_due_to_error;
7529 /* Jump to here if a malloc() fails.
7531 no_mem:
7532 sqlite3OomFault(db);
7533 sqlite3VdbeError(p, "out of memory");
7534 rc = SQLITE_NOMEM_BKPT;
7535 goto abort_due_to_error;
7537 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
7538 ** flag.
7540 abort_due_to_interrupt:
7541 assert( db->u1.isInterrupted );
7542 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
7543 p->rc = rc;
7544 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7545 goto abort_due_to_error;