Merge enhancements from trunk, especially the CLI fixes.
[sqlite.git] / src / vdbe.c
blob70537ce114b116e49bce47728936c21deceed109
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** The code in this file implements the function that runs the
13 ** bytecode of a prepared statement.
15 ** Various scripts scan this source file in order to generate HTML
16 ** documentation, headers files, or other derived files. The formatting
17 ** of the code in this file is, therefore, important. See other comments
18 ** in this file for details. If in doubt, do not deviate from existing
19 ** commenting and indentation practices when changing or adding code.
21 #include "sqliteInt.h"
22 #include "vdbeInt.h"
25 ** Invoke this macro on memory cells just prior to changing the
26 ** value of the cell. This macro verifies that shallow copies are
27 ** not misused. A shallow copy of a string or blob just copies a
28 ** pointer to the string or blob, not the content. If the original
29 ** is changed while the copy is still in use, the string or blob might
30 ** be changed out from under the copy. This macro verifies that nothing
31 ** like that ever happens.
33 #ifdef SQLITE_DEBUG
34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
35 #else
36 # define memAboutToChange(P,M)
37 #endif
40 ** The following global variable is incremented every time a cursor
41 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
42 ** procedures use this information to make sure that indices are
43 ** working correctly. This variable has no function other than to
44 ** help verify the correct operation of the library.
46 #ifdef SQLITE_TEST
47 int sqlite3_search_count = 0;
48 #endif
51 ** When this global variable is positive, it gets decremented once before
52 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
53 ** field of the sqlite3 structure is set in order to simulate an interrupt.
55 ** This facility is used for testing purposes only. It does not function
56 ** in an ordinary build.
58 #ifdef SQLITE_TEST
59 int sqlite3_interrupt_count = 0;
60 #endif
63 ** The next global variable is incremented each type the OP_Sort opcode
64 ** is executed. The test procedures use this information to make sure that
65 ** sorting is occurring or not occurring at appropriate times. This variable
66 ** has no function other than to help verify the correct operation of the
67 ** library.
69 #ifdef SQLITE_TEST
70 int sqlite3_sort_count = 0;
71 #endif
74 ** The next global variable records the size of the largest MEM_Blob
75 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
76 ** use this information to make sure that the zero-blob functionality
77 ** is working correctly. This variable has no function other than to
78 ** help verify the correct operation of the library.
80 #ifdef SQLITE_TEST
81 int sqlite3_max_blobsize = 0;
82 static void updateMaxBlobsize(Mem *p){
83 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
84 sqlite3_max_blobsize = p->n;
87 #endif
90 ** This macro evaluates to true if either the update hook or the preupdate
91 ** hook are enabled for database connect DB.
93 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
94 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
95 #else
96 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
97 #endif
100 ** The next global variable is incremented each time the OP_Found opcode
101 ** is executed. This is used to test whether or not the foreign key
102 ** operation implemented using OP_FkIsZero is working. This variable
103 ** has no function other than to help verify the correct operation of the
104 ** library.
106 #ifdef SQLITE_TEST
107 int sqlite3_found_count = 0;
108 #endif
111 ** Test a register to see if it exceeds the current maximum blob size.
112 ** If it does, record the new maximum blob size.
114 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
115 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
116 #else
117 # define UPDATE_MAX_BLOBSIZE(P)
118 #endif
121 ** Invoke the VDBE coverage callback, if that callback is defined. This
122 ** feature is used for test suite validation only and does not appear an
123 ** production builds.
125 ** M is an integer, 2 or 3, that indices how many different ways the
126 ** branch can go. It is usually 2. "I" is the direction the branch
127 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
128 ** second alternative branch is taken.
130 ** iSrcLine is the source code line (from the __LINE__ macro) that
131 ** generated the VDBE instruction. This instrumentation assumes that all
132 ** source code is in a single file (the amalgamation). Special values 1
133 ** and 2 for the iSrcLine parameter mean that this particular branch is
134 ** always taken or never taken, respectively.
136 #if !defined(SQLITE_VDBE_COVERAGE)
137 # define VdbeBranchTaken(I,M)
138 #else
139 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
140 static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
141 if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
142 M = iSrcLine;
143 /* Assert the truth of VdbeCoverageAlwaysTaken() and
144 ** VdbeCoverageNeverTaken() */
145 assert( (M & I)==I );
146 }else{
147 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
148 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
149 iSrcLine,I,M);
152 #endif
155 ** Convert the given register into a string if it isn't one
156 ** already. Return non-zero if a malloc() fails.
158 #define Stringify(P, enc) \
159 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
160 { goto no_mem; }
163 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
164 ** a pointer to a dynamically allocated string where some other entity
165 ** is responsible for deallocating that string. Because the register
166 ** does not control the string, it might be deleted without the register
167 ** knowing it.
169 ** This routine converts an ephemeral string into a dynamically allocated
170 ** string that the register itself controls. In other words, it
171 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
173 #define Deephemeralize(P) \
174 if( ((P)->flags&MEM_Ephem)!=0 \
175 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
177 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
178 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
181 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
182 ** if we run out of memory.
184 static VdbeCursor *allocateCursor(
185 Vdbe *p, /* The virtual machine */
186 int iCur, /* Index of the new VdbeCursor */
187 int nField, /* Number of fields in the table or index */
188 int iDb, /* Database the cursor belongs to, or -1 */
189 u8 eCurType /* Type of the new cursor */
191 /* Find the memory cell that will be used to store the blob of memory
192 ** required for this VdbeCursor structure. It is convenient to use a
193 ** vdbe memory cell to manage the memory allocation required for a
194 ** VdbeCursor structure for the following reasons:
196 ** * Sometimes cursor numbers are used for a couple of different
197 ** purposes in a vdbe program. The different uses might require
198 ** different sized allocations. Memory cells provide growable
199 ** allocations.
201 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
202 ** be freed lazily via the sqlite3_release_memory() API. This
203 ** minimizes the number of malloc calls made by the system.
205 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
206 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
207 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
209 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
211 int nByte;
212 VdbeCursor *pCx = 0;
213 nByte =
214 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
215 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
217 assert( iCur>=0 && iCur<p->nCursor );
218 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
219 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
220 p->apCsr[iCur] = 0;
222 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
223 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
224 memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
225 pCx->eCurType = eCurType;
226 pCx->iDb = iDb;
227 pCx->nField = nField;
228 pCx->aOffset = &pCx->aType[nField];
229 if( eCurType==CURTYPE_BTREE ){
230 pCx->uc.pCursor = (BtCursor*)
231 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
232 sqlite3BtreeCursorZero(pCx->uc.pCursor);
235 return pCx;
239 ** Try to convert a value into a numeric representation if we can
240 ** do so without loss of information. In other words, if the string
241 ** looks like a number, convert it into a number. If it does not
242 ** look like a number, leave it alone.
244 ** If the bTryForInt flag is true, then extra effort is made to give
245 ** an integer representation. Strings that look like floating point
246 ** values but which have no fractional component (example: '48.00')
247 ** will have a MEM_Int representation when bTryForInt is true.
249 ** If bTryForInt is false, then if the input string contains a decimal
250 ** point or exponential notation, the result is only MEM_Real, even
251 ** if there is an exact integer representation of the quantity.
253 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
254 double rValue;
255 i64 iValue;
256 u8 enc = pRec->enc;
257 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
258 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
259 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
260 pRec->u.i = iValue;
261 pRec->flags |= MEM_Int;
262 }else{
263 pRec->u.r = rValue;
264 pRec->flags |= MEM_Real;
265 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
267 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
268 ** string representation after computing a numeric equivalent, because the
269 ** string representation might not be the canonical representation for the
270 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
271 pRec->flags &= ~MEM_Str;
275 ** Processing is determine by the affinity parameter:
277 ** SQLITE_AFF_INTEGER:
278 ** SQLITE_AFF_REAL:
279 ** SQLITE_AFF_NUMERIC:
280 ** Try to convert pRec to an integer representation or a
281 ** floating-point representation if an integer representation
282 ** is not possible. Note that the integer representation is
283 ** always preferred, even if the affinity is REAL, because
284 ** an integer representation is more space efficient on disk.
286 ** SQLITE_AFF_TEXT:
287 ** Convert pRec to a text representation.
289 ** SQLITE_AFF_BLOB:
290 ** No-op. pRec is unchanged.
292 static void applyAffinity(
293 Mem *pRec, /* The value to apply affinity to */
294 char affinity, /* The affinity to be applied */
295 u8 enc /* Use this text encoding */
297 if( affinity>=SQLITE_AFF_NUMERIC ){
298 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
299 || affinity==SQLITE_AFF_NUMERIC );
300 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
301 if( (pRec->flags & MEM_Real)==0 ){
302 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
303 }else{
304 sqlite3VdbeIntegerAffinity(pRec);
307 }else if( affinity==SQLITE_AFF_TEXT ){
308 /* Only attempt the conversion to TEXT if there is an integer or real
309 ** representation (blob and NULL do not get converted) but no string
310 ** representation. It would be harmless to repeat the conversion if
311 ** there is already a string rep, but it is pointless to waste those
312 ** CPU cycles. */
313 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
314 if( (pRec->flags&(MEM_Real|MEM_Int)) ){
315 sqlite3VdbeMemStringify(pRec, enc, 1);
318 pRec->flags &= ~(MEM_Real|MEM_Int);
323 ** Try to convert the type of a function argument or a result column
324 ** into a numeric representation. Use either INTEGER or REAL whichever
325 ** is appropriate. But only do the conversion if it is possible without
326 ** loss of information and return the revised type of the argument.
328 int sqlite3_value_numeric_type(sqlite3_value *pVal){
329 int eType = sqlite3_value_type(pVal);
330 if( eType==SQLITE_TEXT ){
331 Mem *pMem = (Mem*)pVal;
332 applyNumericAffinity(pMem, 0);
333 eType = sqlite3_value_type(pVal);
335 return eType;
339 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
340 ** not the internal Mem* type.
342 void sqlite3ValueApplyAffinity(
343 sqlite3_value *pVal,
344 u8 affinity,
345 u8 enc
347 applyAffinity((Mem *)pVal, affinity, enc);
351 ** pMem currently only holds a string type (or maybe a BLOB that we can
352 ** interpret as a string if we want to). Compute its corresponding
353 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
354 ** accordingly.
356 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
357 assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
358 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
359 if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
360 return 0;
362 if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
363 return MEM_Int;
365 return MEM_Real;
369 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
370 ** none.
372 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
373 ** But it does set pMem->u.r and pMem->u.i appropriately.
375 static u16 numericType(Mem *pMem){
376 if( pMem->flags & (MEM_Int|MEM_Real) ){
377 return pMem->flags & (MEM_Int|MEM_Real);
379 if( pMem->flags & (MEM_Str|MEM_Blob) ){
380 return computeNumericType(pMem);
382 return 0;
385 #ifdef SQLITE_DEBUG
387 ** Write a nice string representation of the contents of cell pMem
388 ** into buffer zBuf, length nBuf.
390 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
391 char *zCsr = zBuf;
392 int f = pMem->flags;
394 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
396 if( f&MEM_Blob ){
397 int i;
398 char c;
399 if( f & MEM_Dyn ){
400 c = 'z';
401 assert( (f & (MEM_Static|MEM_Ephem))==0 );
402 }else if( f & MEM_Static ){
403 c = 't';
404 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
405 }else if( f & MEM_Ephem ){
406 c = 'e';
407 assert( (f & (MEM_Static|MEM_Dyn))==0 );
408 }else{
409 c = 's';
411 *(zCsr++) = c;
412 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
413 zCsr += sqlite3Strlen30(zCsr);
414 for(i=0; i<16 && i<pMem->n; i++){
415 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
416 zCsr += sqlite3Strlen30(zCsr);
418 for(i=0; i<16 && i<pMem->n; i++){
419 char z = pMem->z[i];
420 if( z<32 || z>126 ) *zCsr++ = '.';
421 else *zCsr++ = z;
423 *(zCsr++) = ']';
424 if( f & MEM_Zero ){
425 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
426 zCsr += sqlite3Strlen30(zCsr);
428 *zCsr = '\0';
429 }else if( f & MEM_Str ){
430 int j, k;
431 zBuf[0] = ' ';
432 if( f & MEM_Dyn ){
433 zBuf[1] = 'z';
434 assert( (f & (MEM_Static|MEM_Ephem))==0 );
435 }else if( f & MEM_Static ){
436 zBuf[1] = 't';
437 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
438 }else if( f & MEM_Ephem ){
439 zBuf[1] = 'e';
440 assert( (f & (MEM_Static|MEM_Dyn))==0 );
441 }else{
442 zBuf[1] = 's';
444 k = 2;
445 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
446 k += sqlite3Strlen30(&zBuf[k]);
447 zBuf[k++] = '[';
448 for(j=0; j<15 && j<pMem->n; j++){
449 u8 c = pMem->z[j];
450 if( c>=0x20 && c<0x7f ){
451 zBuf[k++] = c;
452 }else{
453 zBuf[k++] = '.';
456 zBuf[k++] = ']';
457 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
458 k += sqlite3Strlen30(&zBuf[k]);
459 zBuf[k++] = 0;
462 #endif
464 #ifdef SQLITE_DEBUG
466 ** Print the value of a register for tracing purposes:
468 static void memTracePrint(Mem *p){
469 if( p->flags & MEM_Undefined ){
470 printf(" undefined");
471 }else if( p->flags & MEM_Null ){
472 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
473 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
474 printf(" si:%lld", p->u.i);
475 }else if( p->flags & MEM_Int ){
476 printf(" i:%lld", p->u.i);
477 #ifndef SQLITE_OMIT_FLOATING_POINT
478 }else if( p->flags & MEM_Real ){
479 printf(" r:%g", p->u.r);
480 #endif
481 }else if( p->flags & MEM_RowSet ){
482 printf(" (rowset)");
483 }else{
484 char zBuf[200];
485 sqlite3VdbeMemPrettyPrint(p, zBuf);
486 printf(" %s", zBuf);
488 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
490 static void registerTrace(int iReg, Mem *p){
491 printf("REG[%d] = ", iReg);
492 memTracePrint(p);
493 printf("\n");
494 sqlite3VdbeCheckMemInvariants(p);
496 #endif
498 #ifdef SQLITE_DEBUG
499 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
500 #else
501 # define REGISTER_TRACE(R,M)
502 #endif
505 #ifdef VDBE_PROFILE
508 ** hwtime.h contains inline assembler code for implementing
509 ** high-performance timing routines.
511 #include "hwtime.h"
513 #endif
515 #ifndef NDEBUG
517 ** This function is only called from within an assert() expression. It
518 ** checks that the sqlite3.nTransaction variable is correctly set to
519 ** the number of non-transaction savepoints currently in the
520 ** linked list starting at sqlite3.pSavepoint.
522 ** Usage:
524 ** assert( checkSavepointCount(db) );
526 static int checkSavepointCount(sqlite3 *db){
527 int n = 0;
528 Savepoint *p;
529 for(p=db->pSavepoint; p; p=p->pNext) n++;
530 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
531 return 1;
533 #endif
536 ** Return the register of pOp->p2 after first preparing it to be
537 ** overwritten with an integer value.
539 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
540 sqlite3VdbeMemSetNull(pOut);
541 pOut->flags = MEM_Int;
542 return pOut;
544 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
545 Mem *pOut;
546 assert( pOp->p2>0 );
547 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
548 pOut = &p->aMem[pOp->p2];
549 memAboutToChange(p, pOut);
550 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
551 return out2PrereleaseWithClear(pOut);
552 }else{
553 pOut->flags = MEM_Int;
554 return pOut;
560 ** Execute as much of a VDBE program as we can.
561 ** This is the core of sqlite3_step().
563 int sqlite3VdbeExec(
564 Vdbe *p /* The VDBE */
566 Op *aOp = p->aOp; /* Copy of p->aOp */
567 Op *pOp = aOp; /* Current operation */
568 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
569 Op *pOrigOp; /* Value of pOp at the top of the loop */
570 #endif
571 #ifdef SQLITE_DEBUG
572 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
573 #endif
574 int rc = SQLITE_OK; /* Value to return */
575 sqlite3 *db = p->db; /* The database */
576 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
577 u8 encoding = ENC(db); /* The database encoding */
578 int iCompare = 0; /* Result of last comparison */
579 unsigned nVmStep = 0; /* Number of virtual machine steps */
580 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
581 unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
582 #endif
583 Mem *aMem = p->aMem; /* Copy of p->aMem */
584 Mem *pIn1 = 0; /* 1st input operand */
585 Mem *pIn2 = 0; /* 2nd input operand */
586 Mem *pIn3 = 0; /* 3rd input operand */
587 Mem *pOut = 0; /* Output operand */
588 #ifdef VDBE_PROFILE
589 u64 start; /* CPU clock count at start of opcode */
590 #endif
591 /*** INSERT STACK UNION HERE ***/
593 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
594 sqlite3VdbeEnter(p);
595 if( p->rc==SQLITE_NOMEM ){
596 /* This happens if a malloc() inside a call to sqlite3_column_text() or
597 ** sqlite3_column_text16() failed. */
598 goto no_mem;
600 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
601 assert( p->bIsReader || p->readOnly!=0 );
602 p->iCurrentTime = 0;
603 assert( p->explain==0 );
604 p->pResultSet = 0;
605 db->busyHandler.nBusy = 0;
606 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
607 sqlite3VdbeIOTraceSql(p);
608 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
609 if( db->xProgress ){
610 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
611 assert( 0 < db->nProgressOps );
612 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
613 }else{
614 nProgressLimit = 0xffffffff;
616 #endif
617 #ifdef SQLITE_DEBUG
618 sqlite3BeginBenignMalloc();
619 if( p->pc==0
620 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
622 int i;
623 int once = 1;
624 sqlite3VdbePrintSql(p);
625 if( p->db->flags & SQLITE_VdbeListing ){
626 printf("VDBE Program Listing:\n");
627 for(i=0; i<p->nOp; i++){
628 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
631 if( p->db->flags & SQLITE_VdbeEQP ){
632 for(i=0; i<p->nOp; i++){
633 if( aOp[i].opcode==OP_Explain ){
634 if( once ) printf("VDBE Query Plan:\n");
635 printf("%s\n", aOp[i].p4.z);
636 once = 0;
640 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
642 sqlite3EndBenignMalloc();
643 #endif
644 for(pOp=&aOp[p->pc]; 1; pOp++){
645 /* Errors are detected by individual opcodes, with an immediate
646 ** jumps to abort_due_to_error. */
647 assert( rc==SQLITE_OK );
649 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
650 #ifdef VDBE_PROFILE
651 start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
652 #endif
653 nVmStep++;
654 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
655 if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
656 #endif
658 /* Only allow tracing if SQLITE_DEBUG is defined.
660 #ifdef SQLITE_DEBUG
661 if( db->flags & SQLITE_VdbeTrace ){
662 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
664 #endif
667 /* Check to see if we need to simulate an interrupt. This only happens
668 ** if we have a special test build.
670 #ifdef SQLITE_TEST
671 if( sqlite3_interrupt_count>0 ){
672 sqlite3_interrupt_count--;
673 if( sqlite3_interrupt_count==0 ){
674 sqlite3_interrupt(db);
677 #endif
679 /* Sanity checking on other operands */
680 #ifdef SQLITE_DEBUG
682 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
683 if( (opProperty & OPFLG_IN1)!=0 ){
684 assert( pOp->p1>0 );
685 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
686 assert( memIsValid(&aMem[pOp->p1]) );
687 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
688 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
690 if( (opProperty & OPFLG_IN2)!=0 ){
691 assert( pOp->p2>0 );
692 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
693 assert( memIsValid(&aMem[pOp->p2]) );
694 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
695 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
697 if( (opProperty & OPFLG_IN3)!=0 ){
698 assert( pOp->p3>0 );
699 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
700 assert( memIsValid(&aMem[pOp->p3]) );
701 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
702 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
704 if( (opProperty & OPFLG_OUT2)!=0 ){
705 assert( pOp->p2>0 );
706 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
707 memAboutToChange(p, &aMem[pOp->p2]);
709 if( (opProperty & OPFLG_OUT3)!=0 ){
710 assert( pOp->p3>0 );
711 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
712 memAboutToChange(p, &aMem[pOp->p3]);
715 #endif
716 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
717 pOrigOp = pOp;
718 #endif
720 switch( pOp->opcode ){
722 /*****************************************************************************
723 ** What follows is a massive switch statement where each case implements a
724 ** separate instruction in the virtual machine. If we follow the usual
725 ** indentation conventions, each case should be indented by 6 spaces. But
726 ** that is a lot of wasted space on the left margin. So the code within
727 ** the switch statement will break with convention and be flush-left. Another
728 ** big comment (similar to this one) will mark the point in the code where
729 ** we transition back to normal indentation.
731 ** The formatting of each case is important. The makefile for SQLite
732 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
733 ** file looking for lines that begin with "case OP_". The opcodes.h files
734 ** will be filled with #defines that give unique integer values to each
735 ** opcode and the opcodes.c file is filled with an array of strings where
736 ** each string is the symbolic name for the corresponding opcode. If the
737 ** case statement is followed by a comment of the form "/# same as ... #/"
738 ** that comment is used to determine the particular value of the opcode.
740 ** Other keywords in the comment that follows each case are used to
741 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
742 ** Keywords include: in1, in2, in3, out2, out3. See
743 ** the mkopcodeh.awk script for additional information.
745 ** Documentation about VDBE opcodes is generated by scanning this file
746 ** for lines of that contain "Opcode:". That line and all subsequent
747 ** comment lines are used in the generation of the opcode.html documentation
748 ** file.
750 ** SUMMARY:
752 ** Formatting is important to scripts that scan this file.
753 ** Do not deviate from the formatting style currently in use.
755 *****************************************************************************/
757 /* Opcode: Goto * P2 * * *
759 ** An unconditional jump to address P2.
760 ** The next instruction executed will be
761 ** the one at index P2 from the beginning of
762 ** the program.
764 ** The P1 parameter is not actually used by this opcode. However, it
765 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
766 ** that this Goto is the bottom of a loop and that the lines from P2 down
767 ** to the current line should be indented for EXPLAIN output.
769 case OP_Goto: { /* jump */
770 jump_to_p2_and_check_for_interrupt:
771 pOp = &aOp[pOp->p2 - 1];
773 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
774 ** OP_VNext, or OP_SorterNext) all jump here upon
775 ** completion. Check to see if sqlite3_interrupt() has been called
776 ** or if the progress callback needs to be invoked.
778 ** This code uses unstructured "goto" statements and does not look clean.
779 ** But that is not due to sloppy coding habits. The code is written this
780 ** way for performance, to avoid having to run the interrupt and progress
781 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
782 ** faster according to "valgrind --tool=cachegrind" */
783 check_for_interrupt:
784 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
785 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
786 /* Call the progress callback if it is configured and the required number
787 ** of VDBE ops have been executed (either since this invocation of
788 ** sqlite3VdbeExec() or since last time the progress callback was called).
789 ** If the progress callback returns non-zero, exit the virtual machine with
790 ** a return code SQLITE_ABORT.
792 if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
793 assert( db->nProgressOps!=0 );
794 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
795 if( db->xProgress(db->pProgressArg) ){
796 rc = SQLITE_INTERRUPT;
797 goto abort_due_to_error;
800 #endif
802 break;
805 /* Opcode: Gosub P1 P2 * * *
807 ** Write the current address onto register P1
808 ** and then jump to address P2.
810 case OP_Gosub: { /* jump */
811 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
812 pIn1 = &aMem[pOp->p1];
813 assert( VdbeMemDynamic(pIn1)==0 );
814 memAboutToChange(p, pIn1);
815 pIn1->flags = MEM_Int;
816 pIn1->u.i = (int)(pOp-aOp);
817 REGISTER_TRACE(pOp->p1, pIn1);
819 /* Most jump operations do a goto to this spot in order to update
820 ** the pOp pointer. */
821 jump_to_p2:
822 pOp = &aOp[pOp->p2 - 1];
823 break;
826 /* Opcode: Return P1 * * * *
828 ** Jump to the next instruction after the address in register P1. After
829 ** the jump, register P1 becomes undefined.
831 case OP_Return: { /* in1 */
832 pIn1 = &aMem[pOp->p1];
833 assert( pIn1->flags==MEM_Int );
834 pOp = &aOp[pIn1->u.i];
835 pIn1->flags = MEM_Undefined;
836 break;
839 /* Opcode: InitCoroutine P1 P2 P3 * *
841 ** Set up register P1 so that it will Yield to the coroutine
842 ** located at address P3.
844 ** If P2!=0 then the coroutine implementation immediately follows
845 ** this opcode. So jump over the coroutine implementation to
846 ** address P2.
848 ** See also: EndCoroutine
850 case OP_InitCoroutine: { /* jump */
851 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
852 assert( pOp->p2>=0 && pOp->p2<p->nOp );
853 assert( pOp->p3>=0 && pOp->p3<p->nOp );
854 pOut = &aMem[pOp->p1];
855 assert( !VdbeMemDynamic(pOut) );
856 pOut->u.i = pOp->p3 - 1;
857 pOut->flags = MEM_Int;
858 if( pOp->p2 ) goto jump_to_p2;
859 break;
862 /* Opcode: EndCoroutine P1 * * * *
864 ** The instruction at the address in register P1 is a Yield.
865 ** Jump to the P2 parameter of that Yield.
866 ** After the jump, register P1 becomes undefined.
868 ** See also: InitCoroutine
870 case OP_EndCoroutine: { /* in1 */
871 VdbeOp *pCaller;
872 pIn1 = &aMem[pOp->p1];
873 assert( pIn1->flags==MEM_Int );
874 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
875 pCaller = &aOp[pIn1->u.i];
876 assert( pCaller->opcode==OP_Yield );
877 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
878 pOp = &aOp[pCaller->p2 - 1];
879 pIn1->flags = MEM_Undefined;
880 break;
883 /* Opcode: Yield P1 P2 * * *
885 ** Swap the program counter with the value in register P1. This
886 ** has the effect of yielding to a coroutine.
888 ** If the coroutine that is launched by this instruction ends with
889 ** Yield or Return then continue to the next instruction. But if
890 ** the coroutine launched by this instruction ends with
891 ** EndCoroutine, then jump to P2 rather than continuing with the
892 ** next instruction.
894 ** See also: InitCoroutine
896 case OP_Yield: { /* in1, jump */
897 int pcDest;
898 pIn1 = &aMem[pOp->p1];
899 assert( VdbeMemDynamic(pIn1)==0 );
900 pIn1->flags = MEM_Int;
901 pcDest = (int)pIn1->u.i;
902 pIn1->u.i = (int)(pOp - aOp);
903 REGISTER_TRACE(pOp->p1, pIn1);
904 pOp = &aOp[pcDest];
905 break;
908 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
909 ** Synopsis: if r[P3]=null halt
911 ** Check the value in register P3. If it is NULL then Halt using
912 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
913 ** value in register P3 is not NULL, then this routine is a no-op.
914 ** The P5 parameter should be 1.
916 case OP_HaltIfNull: { /* in3 */
917 pIn3 = &aMem[pOp->p3];
918 if( (pIn3->flags & MEM_Null)==0 ) break;
919 /* Fall through into OP_Halt */
922 /* Opcode: Halt P1 P2 * P4 P5
924 ** Exit immediately. All open cursors, etc are closed
925 ** automatically.
927 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
928 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
929 ** For errors, it can be some other value. If P1!=0 then P2 will determine
930 ** whether or not to rollback the current transaction. Do not rollback
931 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
932 ** then back out all changes that have occurred during this execution of the
933 ** VDBE, but do not rollback the transaction.
935 ** If P4 is not null then it is an error message string.
937 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
939 ** 0: (no change)
940 ** 1: NOT NULL contraint failed: P4
941 ** 2: UNIQUE constraint failed: P4
942 ** 3: CHECK constraint failed: P4
943 ** 4: FOREIGN KEY constraint failed: P4
945 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
946 ** omitted.
948 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
949 ** every program. So a jump past the last instruction of the program
950 ** is the same as executing Halt.
952 case OP_Halt: {
953 VdbeFrame *pFrame;
954 int pcx;
956 pcx = (int)(pOp - aOp);
957 if( pOp->p1==SQLITE_OK && p->pFrame ){
958 /* Halt the sub-program. Return control to the parent frame. */
959 pFrame = p->pFrame;
960 p->pFrame = pFrame->pParent;
961 p->nFrame--;
962 sqlite3VdbeSetChanges(db, p->nChange);
963 pcx = sqlite3VdbeFrameRestore(pFrame);
964 if( pOp->p2==OE_Ignore ){
965 /* Instruction pcx is the OP_Program that invoked the sub-program
966 ** currently being halted. If the p2 instruction of this OP_Halt
967 ** instruction is set to OE_Ignore, then the sub-program is throwing
968 ** an IGNORE exception. In this case jump to the address specified
969 ** as the p2 of the calling OP_Program. */
970 pcx = p->aOp[pcx].p2-1;
972 aOp = p->aOp;
973 aMem = p->aMem;
974 pOp = &aOp[pcx];
975 break;
977 p->rc = pOp->p1;
978 p->errorAction = (u8)pOp->p2;
979 p->pc = pcx;
980 assert( pOp->p5<=4 );
981 if( p->rc ){
982 if( pOp->p5 ){
983 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
984 "FOREIGN KEY" };
985 testcase( pOp->p5==1 );
986 testcase( pOp->p5==2 );
987 testcase( pOp->p5==3 );
988 testcase( pOp->p5==4 );
989 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
990 if( pOp->p4.z ){
991 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
993 }else{
994 sqlite3VdbeError(p, "%s", pOp->p4.z);
996 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
998 rc = sqlite3VdbeHalt(p);
999 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1000 if( rc==SQLITE_BUSY ){
1001 p->rc = SQLITE_BUSY;
1002 }else{
1003 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1004 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1005 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1007 goto vdbe_return;
1010 /* Opcode: Integer P1 P2 * * *
1011 ** Synopsis: r[P2]=P1
1013 ** The 32-bit integer value P1 is written into register P2.
1015 case OP_Integer: { /* out2 */
1016 pOut = out2Prerelease(p, pOp);
1017 pOut->u.i = pOp->p1;
1018 break;
1021 /* Opcode: Int64 * P2 * P4 *
1022 ** Synopsis: r[P2]=P4
1024 ** P4 is a pointer to a 64-bit integer value.
1025 ** Write that value into register P2.
1027 case OP_Int64: { /* out2 */
1028 pOut = out2Prerelease(p, pOp);
1029 assert( pOp->p4.pI64!=0 );
1030 pOut->u.i = *pOp->p4.pI64;
1031 break;
1034 #ifndef SQLITE_OMIT_FLOATING_POINT
1035 /* Opcode: Real * P2 * P4 *
1036 ** Synopsis: r[P2]=P4
1038 ** P4 is a pointer to a 64-bit floating point value.
1039 ** Write that value into register P2.
1041 case OP_Real: { /* same as TK_FLOAT, out2 */
1042 pOut = out2Prerelease(p, pOp);
1043 pOut->flags = MEM_Real;
1044 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1045 pOut->u.r = *pOp->p4.pReal;
1046 break;
1048 #endif
1050 /* Opcode: String8 * P2 * P4 *
1051 ** Synopsis: r[P2]='P4'
1053 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1054 ** into a String opcode before it is executed for the first time. During
1055 ** this transformation, the length of string P4 is computed and stored
1056 ** as the P1 parameter.
1058 case OP_String8: { /* same as TK_STRING, out2 */
1059 assert( pOp->p4.z!=0 );
1060 pOut = out2Prerelease(p, pOp);
1061 pOp->opcode = OP_String;
1062 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1064 #ifndef SQLITE_OMIT_UTF16
1065 if( encoding!=SQLITE_UTF8 ){
1066 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1067 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1068 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1069 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1070 assert( VdbeMemDynamic(pOut)==0 );
1071 pOut->szMalloc = 0;
1072 pOut->flags |= MEM_Static;
1073 if( pOp->p4type==P4_DYNAMIC ){
1074 sqlite3DbFree(db, pOp->p4.z);
1076 pOp->p4type = P4_DYNAMIC;
1077 pOp->p4.z = pOut->z;
1078 pOp->p1 = pOut->n;
1080 testcase( rc==SQLITE_TOOBIG );
1081 #endif
1082 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1083 goto too_big;
1085 assert( rc==SQLITE_OK );
1086 /* Fall through to the next case, OP_String */
1089 /* Opcode: String P1 P2 P3 P4 P5
1090 ** Synopsis: r[P2]='P4' (len=P1)
1092 ** The string value P4 of length P1 (bytes) is stored in register P2.
1094 ** If P3 is not zero and the content of register P3 is equal to P5, then
1095 ** the datatype of the register P2 is converted to BLOB. The content is
1096 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1097 ** of a string, as if it had been CAST. In other words:
1099 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1101 case OP_String: { /* out2 */
1102 assert( pOp->p4.z!=0 );
1103 pOut = out2Prerelease(p, pOp);
1104 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1105 pOut->z = pOp->p4.z;
1106 pOut->n = pOp->p1;
1107 pOut->enc = encoding;
1108 UPDATE_MAX_BLOBSIZE(pOut);
1109 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1110 if( pOp->p3>0 ){
1111 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1112 pIn3 = &aMem[pOp->p3];
1113 assert( pIn3->flags & MEM_Int );
1114 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1116 #endif
1117 break;
1120 /* Opcode: Null P1 P2 P3 * *
1121 ** Synopsis: r[P2..P3]=NULL
1123 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1124 ** NULL into register P3 and every register in between P2 and P3. If P3
1125 ** is less than P2 (typically P3 is zero) then only register P2 is
1126 ** set to NULL.
1128 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1129 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1130 ** OP_Ne or OP_Eq.
1132 case OP_Null: { /* out2 */
1133 int cnt;
1134 u16 nullFlag;
1135 pOut = out2Prerelease(p, pOp);
1136 cnt = pOp->p3-pOp->p2;
1137 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1138 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1139 pOut->n = 0;
1140 while( cnt>0 ){
1141 pOut++;
1142 memAboutToChange(p, pOut);
1143 sqlite3VdbeMemSetNull(pOut);
1144 pOut->flags = nullFlag;
1145 pOut->n = 0;
1146 cnt--;
1148 break;
1151 /* Opcode: SoftNull P1 * * * *
1152 ** Synopsis: r[P1]=NULL
1154 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1155 ** instruction, but do not free any string or blob memory associated with
1156 ** the register, so that if the value was a string or blob that was
1157 ** previously copied using OP_SCopy, the copies will continue to be valid.
1159 case OP_SoftNull: {
1160 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1161 pOut = &aMem[pOp->p1];
1162 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1163 break;
1166 /* Opcode: Blob P1 P2 * P4 *
1167 ** Synopsis: r[P2]=P4 (len=P1)
1169 ** P4 points to a blob of data P1 bytes long. Store this
1170 ** blob in register P2.
1172 case OP_Blob: { /* out2 */
1173 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1174 pOut = out2Prerelease(p, pOp);
1175 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1176 pOut->enc = encoding;
1177 UPDATE_MAX_BLOBSIZE(pOut);
1178 break;
1181 /* Opcode: Variable P1 P2 * P4 *
1182 ** Synopsis: r[P2]=parameter(P1,P4)
1184 ** Transfer the values of bound parameter P1 into register P2
1186 ** If the parameter is named, then its name appears in P4.
1187 ** The P4 value is used by sqlite3_bind_parameter_name().
1189 case OP_Variable: { /* out2 */
1190 Mem *pVar; /* Value being transferred */
1192 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1193 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1194 pVar = &p->aVar[pOp->p1 - 1];
1195 if( sqlite3VdbeMemTooBig(pVar) ){
1196 goto too_big;
1198 pOut = &aMem[pOp->p2];
1199 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
1200 UPDATE_MAX_BLOBSIZE(pOut);
1201 break;
1204 /* Opcode: Move P1 P2 P3 * *
1205 ** Synopsis: r[P2@P3]=r[P1@P3]
1207 ** Move the P3 values in register P1..P1+P3-1 over into
1208 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1209 ** left holding a NULL. It is an error for register ranges
1210 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1211 ** for P3 to be less than 1.
1213 case OP_Move: {
1214 int n; /* Number of registers left to copy */
1215 int p1; /* Register to copy from */
1216 int p2; /* Register to copy to */
1218 n = pOp->p3;
1219 p1 = pOp->p1;
1220 p2 = pOp->p2;
1221 assert( n>0 && p1>0 && p2>0 );
1222 assert( p1+n<=p2 || p2+n<=p1 );
1224 pIn1 = &aMem[p1];
1225 pOut = &aMem[p2];
1227 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1228 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1229 assert( memIsValid(pIn1) );
1230 memAboutToChange(p, pOut);
1231 sqlite3VdbeMemMove(pOut, pIn1);
1232 #ifdef SQLITE_DEBUG
1233 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
1234 pOut->pScopyFrom += pOp->p2 - p1;
1236 #endif
1237 Deephemeralize(pOut);
1238 REGISTER_TRACE(p2++, pOut);
1239 pIn1++;
1240 pOut++;
1241 }while( --n );
1242 break;
1245 /* Opcode: Copy P1 P2 P3 * *
1246 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1248 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1250 ** This instruction makes a deep copy of the value. A duplicate
1251 ** is made of any string or blob constant. See also OP_SCopy.
1253 case OP_Copy: {
1254 int n;
1256 n = pOp->p3;
1257 pIn1 = &aMem[pOp->p1];
1258 pOut = &aMem[pOp->p2];
1259 assert( pOut!=pIn1 );
1260 while( 1 ){
1261 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1262 Deephemeralize(pOut);
1263 #ifdef SQLITE_DEBUG
1264 pOut->pScopyFrom = 0;
1265 #endif
1266 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1267 if( (n--)==0 ) break;
1268 pOut++;
1269 pIn1++;
1271 break;
1274 /* Opcode: SCopy P1 P2 * * *
1275 ** Synopsis: r[P2]=r[P1]
1277 ** Make a shallow copy of register P1 into register P2.
1279 ** This instruction makes a shallow copy of the value. If the value
1280 ** is a string or blob, then the copy is only a pointer to the
1281 ** original and hence if the original changes so will the copy.
1282 ** Worse, if the original is deallocated, the copy becomes invalid.
1283 ** Thus the program must guarantee that the original will not change
1284 ** during the lifetime of the copy. Use OP_Copy to make a complete
1285 ** copy.
1287 case OP_SCopy: { /* out2 */
1288 pIn1 = &aMem[pOp->p1];
1289 pOut = &aMem[pOp->p2];
1290 assert( pOut!=pIn1 );
1291 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1292 #ifdef SQLITE_DEBUG
1293 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
1294 #endif
1295 break;
1298 /* Opcode: IntCopy P1 P2 * * *
1299 ** Synopsis: r[P2]=r[P1]
1301 ** Transfer the integer value held in register P1 into register P2.
1303 ** This is an optimized version of SCopy that works only for integer
1304 ** values.
1306 case OP_IntCopy: { /* out2 */
1307 pIn1 = &aMem[pOp->p1];
1308 assert( (pIn1->flags & MEM_Int)!=0 );
1309 pOut = &aMem[pOp->p2];
1310 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1311 break;
1314 /* Opcode: ResultRow P1 P2 * * *
1315 ** Synopsis: output=r[P1@P2]
1317 ** The registers P1 through P1+P2-1 contain a single row of
1318 ** results. This opcode causes the sqlite3_step() call to terminate
1319 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1320 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1321 ** the result row.
1323 case OP_ResultRow: {
1324 Mem *pMem;
1325 int i;
1326 assert( p->nResColumn==pOp->p2 );
1327 assert( pOp->p1>0 );
1328 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1330 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1331 /* Run the progress counter just before returning.
1333 if( db->xProgress!=0
1334 && nVmStep>=nProgressLimit
1335 && db->xProgress(db->pProgressArg)!=0
1337 rc = SQLITE_INTERRUPT;
1338 goto abort_due_to_error;
1340 #endif
1342 /* If this statement has violated immediate foreign key constraints, do
1343 ** not return the number of rows modified. And do not RELEASE the statement
1344 ** transaction. It needs to be rolled back. */
1345 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
1346 assert( db->flags&SQLITE_CountRows );
1347 assert( p->usesStmtJournal );
1348 goto abort_due_to_error;
1351 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1352 ** DML statements invoke this opcode to return the number of rows
1353 ** modified to the user. This is the only way that a VM that
1354 ** opens a statement transaction may invoke this opcode.
1356 ** In case this is such a statement, close any statement transaction
1357 ** opened by this VM before returning control to the user. This is to
1358 ** ensure that statement-transactions are always nested, not overlapping.
1359 ** If the open statement-transaction is not closed here, then the user
1360 ** may step another VM that opens its own statement transaction. This
1361 ** may lead to overlapping statement transactions.
1363 ** The statement transaction is never a top-level transaction. Hence
1364 ** the RELEASE call below can never fail.
1366 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
1367 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
1368 assert( rc==SQLITE_OK );
1370 /* Invalidate all ephemeral cursor row caches */
1371 p->cacheCtr = (p->cacheCtr + 2)|1;
1373 /* Make sure the results of the current row are \000 terminated
1374 ** and have an assigned type. The results are de-ephemeralized as
1375 ** a side effect.
1377 pMem = p->pResultSet = &aMem[pOp->p1];
1378 for(i=0; i<pOp->p2; i++){
1379 assert( memIsValid(&pMem[i]) );
1380 Deephemeralize(&pMem[i]);
1381 assert( (pMem[i].flags & MEM_Ephem)==0
1382 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1383 sqlite3VdbeMemNulTerminate(&pMem[i]);
1384 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1386 if( db->mallocFailed ) goto no_mem;
1388 if( db->mTrace & SQLITE_TRACE_ROW ){
1389 db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1392 /* Return SQLITE_ROW
1394 p->pc = (int)(pOp - aOp) + 1;
1395 rc = SQLITE_ROW;
1396 goto vdbe_return;
1399 /* Opcode: Concat P1 P2 P3 * *
1400 ** Synopsis: r[P3]=r[P2]+r[P1]
1402 ** Add the text in register P1 onto the end of the text in
1403 ** register P2 and store the result in register P3.
1404 ** If either the P1 or P2 text are NULL then store NULL in P3.
1406 ** P3 = P2 || P1
1408 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1409 ** if P3 is the same register as P2, the implementation is able
1410 ** to avoid a memcpy().
1412 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1413 i64 nByte;
1415 pIn1 = &aMem[pOp->p1];
1416 pIn2 = &aMem[pOp->p2];
1417 pOut = &aMem[pOp->p3];
1418 assert( pIn1!=pOut );
1419 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1420 sqlite3VdbeMemSetNull(pOut);
1421 break;
1423 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
1424 Stringify(pIn1, encoding);
1425 Stringify(pIn2, encoding);
1426 nByte = pIn1->n + pIn2->n;
1427 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1428 goto too_big;
1430 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1431 goto no_mem;
1433 MemSetTypeFlag(pOut, MEM_Str);
1434 if( pOut!=pIn2 ){
1435 memcpy(pOut->z, pIn2->z, pIn2->n);
1437 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1438 pOut->z[nByte]=0;
1439 pOut->z[nByte+1] = 0;
1440 pOut->flags |= MEM_Term;
1441 pOut->n = (int)nByte;
1442 pOut->enc = encoding;
1443 UPDATE_MAX_BLOBSIZE(pOut);
1444 break;
1447 /* Opcode: Add P1 P2 P3 * *
1448 ** Synopsis: r[P3]=r[P1]+r[P2]
1450 ** Add the value in register P1 to the value in register P2
1451 ** and store the result in register P3.
1452 ** If either input is NULL, the result is NULL.
1454 /* Opcode: Multiply P1 P2 P3 * *
1455 ** Synopsis: r[P3]=r[P1]*r[P2]
1458 ** Multiply the value in register P1 by the value in register P2
1459 ** and store the result in register P3.
1460 ** If either input is NULL, the result is NULL.
1462 /* Opcode: Subtract P1 P2 P3 * *
1463 ** Synopsis: r[P3]=r[P2]-r[P1]
1465 ** Subtract the value in register P1 from the value in register P2
1466 ** and store the result in register P3.
1467 ** If either input is NULL, the result is NULL.
1469 /* Opcode: Divide P1 P2 P3 * *
1470 ** Synopsis: r[P3]=r[P2]/r[P1]
1472 ** Divide the value in register P1 by the value in register P2
1473 ** and store the result in register P3 (P3=P2/P1). If the value in
1474 ** register P1 is zero, then the result is NULL. If either input is
1475 ** NULL, the result is NULL.
1477 /* Opcode: Remainder P1 P2 P3 * *
1478 ** Synopsis: r[P3]=r[P2]%r[P1]
1480 ** Compute the remainder after integer register P2 is divided by
1481 ** register P1 and store the result in register P3.
1482 ** If the value in register P1 is zero the result is NULL.
1483 ** If either operand is NULL, the result is NULL.
1485 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1486 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1487 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1488 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1489 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1490 char bIntint; /* Started out as two integer operands */
1491 u16 flags; /* Combined MEM_* flags from both inputs */
1492 u16 type1; /* Numeric type of left operand */
1493 u16 type2; /* Numeric type of right operand */
1494 i64 iA; /* Integer value of left operand */
1495 i64 iB; /* Integer value of right operand */
1496 double rA; /* Real value of left operand */
1497 double rB; /* Real value of right operand */
1499 pIn1 = &aMem[pOp->p1];
1500 type1 = numericType(pIn1);
1501 pIn2 = &aMem[pOp->p2];
1502 type2 = numericType(pIn2);
1503 pOut = &aMem[pOp->p3];
1504 flags = pIn1->flags | pIn2->flags;
1505 if( (type1 & type2 & MEM_Int)!=0 ){
1506 iA = pIn1->u.i;
1507 iB = pIn2->u.i;
1508 bIntint = 1;
1509 switch( pOp->opcode ){
1510 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1511 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1512 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1513 case OP_Divide: {
1514 if( iA==0 ) goto arithmetic_result_is_null;
1515 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1516 iB /= iA;
1517 break;
1519 default: {
1520 if( iA==0 ) goto arithmetic_result_is_null;
1521 if( iA==-1 ) iA = 1;
1522 iB %= iA;
1523 break;
1526 pOut->u.i = iB;
1527 MemSetTypeFlag(pOut, MEM_Int);
1528 }else if( (flags & MEM_Null)!=0 ){
1529 goto arithmetic_result_is_null;
1530 }else{
1531 bIntint = 0;
1532 fp_math:
1533 rA = sqlite3VdbeRealValue(pIn1);
1534 rB = sqlite3VdbeRealValue(pIn2);
1535 switch( pOp->opcode ){
1536 case OP_Add: rB += rA; break;
1537 case OP_Subtract: rB -= rA; break;
1538 case OP_Multiply: rB *= rA; break;
1539 case OP_Divide: {
1540 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1541 if( rA==(double)0 ) goto arithmetic_result_is_null;
1542 rB /= rA;
1543 break;
1545 default: {
1546 iA = (i64)rA;
1547 iB = (i64)rB;
1548 if( iA==0 ) goto arithmetic_result_is_null;
1549 if( iA==-1 ) iA = 1;
1550 rB = (double)(iB % iA);
1551 break;
1554 #ifdef SQLITE_OMIT_FLOATING_POINT
1555 pOut->u.i = rB;
1556 MemSetTypeFlag(pOut, MEM_Int);
1557 #else
1558 if( sqlite3IsNaN(rB) ){
1559 goto arithmetic_result_is_null;
1561 pOut->u.r = rB;
1562 MemSetTypeFlag(pOut, MEM_Real);
1563 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
1564 sqlite3VdbeIntegerAffinity(pOut);
1566 #endif
1568 break;
1570 arithmetic_result_is_null:
1571 sqlite3VdbeMemSetNull(pOut);
1572 break;
1575 /* Opcode: CollSeq P1 * * P4
1577 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1578 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1579 ** be returned. This is used by the built-in min(), max() and nullif()
1580 ** functions.
1582 ** If P1 is not zero, then it is a register that a subsequent min() or
1583 ** max() aggregate will set to 1 if the current row is not the minimum or
1584 ** maximum. The P1 register is initialized to 0 by this instruction.
1586 ** The interface used by the implementation of the aforementioned functions
1587 ** to retrieve the collation sequence set by this opcode is not available
1588 ** publicly. Only built-in functions have access to this feature.
1590 case OP_CollSeq: {
1591 assert( pOp->p4type==P4_COLLSEQ );
1592 if( pOp->p1 ){
1593 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1595 break;
1598 /* Opcode: BitAnd P1 P2 P3 * *
1599 ** Synopsis: r[P3]=r[P1]&r[P2]
1601 ** Take the bit-wise AND of the values in register P1 and P2 and
1602 ** store the result in register P3.
1603 ** If either input is NULL, the result is NULL.
1605 /* Opcode: BitOr P1 P2 P3 * *
1606 ** Synopsis: r[P3]=r[P1]|r[P2]
1608 ** Take the bit-wise OR of the values in register P1 and P2 and
1609 ** store the result in register P3.
1610 ** If either input is NULL, the result is NULL.
1612 /* Opcode: ShiftLeft P1 P2 P3 * *
1613 ** Synopsis: r[P3]=r[P2]<<r[P1]
1615 ** Shift the integer value in register P2 to the left by the
1616 ** number of bits specified by the integer in register P1.
1617 ** Store the result in register P3.
1618 ** If either input is NULL, the result is NULL.
1620 /* Opcode: ShiftRight P1 P2 P3 * *
1621 ** Synopsis: r[P3]=r[P2]>>r[P1]
1623 ** Shift the integer value in register P2 to the right by the
1624 ** number of bits specified by the integer in register P1.
1625 ** Store the result in register P3.
1626 ** If either input is NULL, the result is NULL.
1628 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1629 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1630 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1631 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1632 i64 iA;
1633 u64 uA;
1634 i64 iB;
1635 u8 op;
1637 pIn1 = &aMem[pOp->p1];
1638 pIn2 = &aMem[pOp->p2];
1639 pOut = &aMem[pOp->p3];
1640 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1641 sqlite3VdbeMemSetNull(pOut);
1642 break;
1644 iA = sqlite3VdbeIntValue(pIn2);
1645 iB = sqlite3VdbeIntValue(pIn1);
1646 op = pOp->opcode;
1647 if( op==OP_BitAnd ){
1648 iA &= iB;
1649 }else if( op==OP_BitOr ){
1650 iA |= iB;
1651 }else if( iB!=0 ){
1652 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1654 /* If shifting by a negative amount, shift in the other direction */
1655 if( iB<0 ){
1656 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1657 op = 2*OP_ShiftLeft + 1 - op;
1658 iB = iB>(-64) ? -iB : 64;
1661 if( iB>=64 ){
1662 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1663 }else{
1664 memcpy(&uA, &iA, sizeof(uA));
1665 if( op==OP_ShiftLeft ){
1666 uA <<= iB;
1667 }else{
1668 uA >>= iB;
1669 /* Sign-extend on a right shift of a negative number */
1670 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1672 memcpy(&iA, &uA, sizeof(iA));
1675 pOut->u.i = iA;
1676 MemSetTypeFlag(pOut, MEM_Int);
1677 break;
1680 /* Opcode: AddImm P1 P2 * * *
1681 ** Synopsis: r[P1]=r[P1]+P2
1683 ** Add the constant P2 to the value in register P1.
1684 ** The result is always an integer.
1686 ** To force any register to be an integer, just add 0.
1688 case OP_AddImm: { /* in1 */
1689 pIn1 = &aMem[pOp->p1];
1690 memAboutToChange(p, pIn1);
1691 sqlite3VdbeMemIntegerify(pIn1);
1692 pIn1->u.i += pOp->p2;
1693 break;
1696 /* Opcode: MustBeInt P1 P2 * * *
1698 ** Force the value in register P1 to be an integer. If the value
1699 ** in P1 is not an integer and cannot be converted into an integer
1700 ** without data loss, then jump immediately to P2, or if P2==0
1701 ** raise an SQLITE_MISMATCH exception.
1703 case OP_MustBeInt: { /* jump, in1 */
1704 pIn1 = &aMem[pOp->p1];
1705 if( (pIn1->flags & MEM_Int)==0 ){
1706 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1707 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
1708 if( (pIn1->flags & MEM_Int)==0 ){
1709 if( pOp->p2==0 ){
1710 rc = SQLITE_MISMATCH;
1711 goto abort_due_to_error;
1712 }else{
1713 goto jump_to_p2;
1717 MemSetTypeFlag(pIn1, MEM_Int);
1718 break;
1721 #ifndef SQLITE_OMIT_FLOATING_POINT
1722 /* Opcode: RealAffinity P1 * * * *
1724 ** If register P1 holds an integer convert it to a real value.
1726 ** This opcode is used when extracting information from a column that
1727 ** has REAL affinity. Such column values may still be stored as
1728 ** integers, for space efficiency, but after extraction we want them
1729 ** to have only a real value.
1731 case OP_RealAffinity: { /* in1 */
1732 pIn1 = &aMem[pOp->p1];
1733 if( pIn1->flags & MEM_Int ){
1734 sqlite3VdbeMemRealify(pIn1);
1736 break;
1738 #endif
1740 #ifndef SQLITE_OMIT_CAST
1741 /* Opcode: Cast P1 P2 * * *
1742 ** Synopsis: affinity(r[P1])
1744 ** Force the value in register P1 to be the type defined by P2.
1746 ** <ul>
1747 ** <li> P2=='A' &rarr; BLOB
1748 ** <li> P2=='B' &rarr; TEXT
1749 ** <li> P2=='C' &rarr; NUMERIC
1750 ** <li> P2=='D' &rarr; INTEGER
1751 ** <li> P2=='E' &rarr; REAL
1752 ** </ul>
1754 ** A NULL value is not changed by this routine. It remains NULL.
1756 case OP_Cast: { /* in1 */
1757 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
1758 testcase( pOp->p2==SQLITE_AFF_TEXT );
1759 testcase( pOp->p2==SQLITE_AFF_BLOB );
1760 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
1761 testcase( pOp->p2==SQLITE_AFF_INTEGER );
1762 testcase( pOp->p2==SQLITE_AFF_REAL );
1763 pIn1 = &aMem[pOp->p1];
1764 memAboutToChange(p, pIn1);
1765 rc = ExpandBlob(pIn1);
1766 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
1767 UPDATE_MAX_BLOBSIZE(pIn1);
1768 if( rc ) goto abort_due_to_error;
1769 break;
1771 #endif /* SQLITE_OMIT_CAST */
1773 /* Opcode: Eq P1 P2 P3 P4 P5
1774 ** Synopsis: IF r[P3]==r[P1]
1776 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
1777 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
1778 ** store the result of comparison in register P2.
1780 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1781 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1782 ** to coerce both inputs according to this affinity before the
1783 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1784 ** affinity is used. Note that the affinity conversions are stored
1785 ** back into the input registers P1 and P3. So this opcode can cause
1786 ** persistent changes to registers P1 and P3.
1788 ** Once any conversions have taken place, and neither value is NULL,
1789 ** the values are compared. If both values are blobs then memcmp() is
1790 ** used to determine the results of the comparison. If both values
1791 ** are text, then the appropriate collating function specified in
1792 ** P4 is used to do the comparison. If P4 is not specified then
1793 ** memcmp() is used to compare text string. If both values are
1794 ** numeric, then a numeric comparison is used. If the two values
1795 ** are of different types, then numbers are considered less than
1796 ** strings and strings are considered less than blobs.
1798 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1799 ** true or false and is never NULL. If both operands are NULL then the result
1800 ** of comparison is true. If either operand is NULL then the result is false.
1801 ** If neither operand is NULL the result is the same as it would be if
1802 ** the SQLITE_NULLEQ flag were omitted from P5.
1804 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1805 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
1806 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
1808 /* Opcode: Ne P1 P2 P3 P4 P5
1809 ** Synopsis: IF r[P3]!=r[P1]
1811 ** This works just like the Eq opcode except that the jump is taken if
1812 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
1813 ** additional information.
1815 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1816 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
1817 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
1819 /* Opcode: Lt P1 P2 P3 P4 P5
1820 ** Synopsis: IF r[P3]<r[P1]
1822 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1823 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
1824 ** the result of comparison (0 or 1 or NULL) into register P2.
1826 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1827 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
1828 ** bit is clear then fall through if either operand is NULL.
1830 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1831 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1832 ** to coerce both inputs according to this affinity before the
1833 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1834 ** affinity is used. Note that the affinity conversions are stored
1835 ** back into the input registers P1 and P3. So this opcode can cause
1836 ** persistent changes to registers P1 and P3.
1838 ** Once any conversions have taken place, and neither value is NULL,
1839 ** the values are compared. If both values are blobs then memcmp() is
1840 ** used to determine the results of the comparison. If both values
1841 ** are text, then the appropriate collating function specified in
1842 ** P4 is used to do the comparison. If P4 is not specified then
1843 ** memcmp() is used to compare text string. If both values are
1844 ** numeric, then a numeric comparison is used. If the two values
1845 ** are of different types, then numbers are considered less than
1846 ** strings and strings are considered less than blobs.
1848 /* Opcode: Le P1 P2 P3 P4 P5
1849 ** Synopsis: IF r[P3]<=r[P1]
1851 ** This works just like the Lt opcode except that the jump is taken if
1852 ** the content of register P3 is less than or equal to the content of
1853 ** register P1. See the Lt opcode for additional information.
1855 /* Opcode: Gt P1 P2 P3 P4 P5
1856 ** Synopsis: IF r[P3]>r[P1]
1858 ** This works just like the Lt opcode except that the jump is taken if
1859 ** the content of register P3 is greater than the content of
1860 ** register P1. See the Lt opcode for additional information.
1862 /* Opcode: Ge P1 P2 P3 P4 P5
1863 ** Synopsis: IF r[P3]>=r[P1]
1865 ** This works just like the Lt opcode except that the jump is taken if
1866 ** the content of register P3 is greater than or equal to the content of
1867 ** register P1. See the Lt opcode for additional information.
1869 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
1870 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
1871 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
1872 case OP_Le: /* same as TK_LE, jump, in1, in3 */
1873 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
1874 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
1875 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
1876 char affinity; /* Affinity to use for comparison */
1877 u16 flags1; /* Copy of initial value of pIn1->flags */
1878 u16 flags3; /* Copy of initial value of pIn3->flags */
1880 pIn1 = &aMem[pOp->p1];
1881 pIn3 = &aMem[pOp->p3];
1882 flags1 = pIn1->flags;
1883 flags3 = pIn3->flags;
1884 if( (flags1 | flags3)&MEM_Null ){
1885 /* One or both operands are NULL */
1886 if( pOp->p5 & SQLITE_NULLEQ ){
1887 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1888 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1889 ** or not both operands are null.
1891 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
1892 assert( (flags1 & MEM_Cleared)==0 );
1893 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
1894 if( (flags1&flags3&MEM_Null)!=0
1895 && (flags3&MEM_Cleared)==0
1897 res = 0; /* Operands are equal */
1898 }else{
1899 res = 1; /* Operands are not equal */
1901 }else{
1902 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1903 ** then the result is always NULL.
1904 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1906 if( pOp->p5 & SQLITE_STOREP2 ){
1907 pOut = &aMem[pOp->p2];
1908 iCompare = 1; /* Operands are not equal */
1909 memAboutToChange(p, pOut);
1910 MemSetTypeFlag(pOut, MEM_Null);
1911 REGISTER_TRACE(pOp->p2, pOut);
1912 }else{
1913 VdbeBranchTaken(2,3);
1914 if( pOp->p5 & SQLITE_JUMPIFNULL ){
1915 goto jump_to_p2;
1918 break;
1920 }else{
1921 /* Neither operand is NULL. Do a comparison. */
1922 affinity = pOp->p5 & SQLITE_AFF_MASK;
1923 if( affinity>=SQLITE_AFF_NUMERIC ){
1924 if( (flags1 | flags3)&MEM_Str ){
1925 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1926 applyNumericAffinity(pIn1,0);
1927 testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
1928 flags3 = pIn3->flags;
1930 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1931 applyNumericAffinity(pIn3,0);
1934 /* Handle the common case of integer comparison here, as an
1935 ** optimization, to avoid a call to sqlite3MemCompare() */
1936 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
1937 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
1938 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
1939 res = 0;
1940 goto compare_op;
1942 }else if( affinity==SQLITE_AFF_TEXT ){
1943 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
1944 testcase( pIn1->flags & MEM_Int );
1945 testcase( pIn1->flags & MEM_Real );
1946 sqlite3VdbeMemStringify(pIn1, encoding, 1);
1947 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
1948 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
1949 assert( pIn1!=pIn3 );
1951 if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
1952 testcase( pIn3->flags & MEM_Int );
1953 testcase( pIn3->flags & MEM_Real );
1954 sqlite3VdbeMemStringify(pIn3, encoding, 1);
1955 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
1956 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
1959 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1960 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1962 compare_op:
1963 /* At this point, res is negative, zero, or positive if reg[P1] is
1964 ** less than, equal to, or greater than reg[P3], respectively. Compute
1965 ** the answer to this operator in res2, depending on what the comparison
1966 ** operator actually is. The next block of code depends on the fact
1967 ** that the 6 comparison operators are consecutive integers in this
1968 ** order: NE, EQ, GT, LE, LT, GE */
1969 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
1970 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
1971 if( res<0 ){ /* ne, eq, gt, le, lt, ge */
1972 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
1973 res2 = aLTb[pOp->opcode - OP_Ne];
1974 }else if( res==0 ){
1975 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
1976 res2 = aEQb[pOp->opcode - OP_Ne];
1977 }else{
1978 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
1979 res2 = aGTb[pOp->opcode - OP_Ne];
1982 /* Undo any changes made by applyAffinity() to the input registers. */
1983 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1984 pIn1->flags = flags1;
1985 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
1986 pIn3->flags = flags3;
1988 if( pOp->p5 & SQLITE_STOREP2 ){
1989 pOut = &aMem[pOp->p2];
1990 iCompare = res;
1991 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
1992 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
1993 ** and prevents OP_Ne from overwriting NULL with 0. This flag
1994 ** is only used in contexts where either:
1995 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
1996 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
1997 ** Therefore it is not necessary to check the content of r[P2] for
1998 ** NULL. */
1999 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
2000 assert( res2==0 || res2==1 );
2001 testcase( res2==0 && pOp->opcode==OP_Eq );
2002 testcase( res2==1 && pOp->opcode==OP_Eq );
2003 testcase( res2==0 && pOp->opcode==OP_Ne );
2004 testcase( res2==1 && pOp->opcode==OP_Ne );
2005 if( (pOp->opcode==OP_Eq)==res2 ) break;
2007 memAboutToChange(p, pOut);
2008 MemSetTypeFlag(pOut, MEM_Int);
2009 pOut->u.i = res2;
2010 REGISTER_TRACE(pOp->p2, pOut);
2011 }else{
2012 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2013 if( res2 ){
2014 goto jump_to_p2;
2017 break;
2020 /* Opcode: ElseNotEq * P2 * * *
2022 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
2023 ** If result of an OP_Eq comparison on the same two operands
2024 ** would have be NULL or false (0), then then jump to P2.
2025 ** If the result of an OP_Eq comparison on the two previous operands
2026 ** would have been true (1), then fall through.
2028 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
2029 assert( pOp>aOp );
2030 assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
2031 assert( pOp[-1].p5 & SQLITE_STOREP2 );
2032 VdbeBranchTaken(iCompare!=0, 2);
2033 if( iCompare!=0 ) goto jump_to_p2;
2034 break;
2038 /* Opcode: Permutation * * * P4 *
2040 ** Set the permutation used by the OP_Compare operator in the next
2041 ** instruction. The permutation is stored in the P4 operand.
2043 ** The permutation is only valid until the next OP_Compare that has
2044 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2045 ** occur immediately prior to the OP_Compare.
2047 ** The first integer in the P4 integer array is the length of the array
2048 ** and does not become part of the permutation.
2050 case OP_Permutation: {
2051 assert( pOp->p4type==P4_INTARRAY );
2052 assert( pOp->p4.ai );
2053 assert( pOp[1].opcode==OP_Compare );
2054 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2055 break;
2058 /* Opcode: Compare P1 P2 P3 P4 P5
2059 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2061 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2062 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2063 ** the comparison for use by the next OP_Jump instruct.
2065 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2066 ** determined by the most recent OP_Permutation operator. If the
2067 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2068 ** order.
2070 ** P4 is a KeyInfo structure that defines collating sequences and sort
2071 ** orders for the comparison. The permutation applies to registers
2072 ** only. The KeyInfo elements are used sequentially.
2074 ** The comparison is a sort comparison, so NULLs compare equal,
2075 ** NULLs are less than numbers, numbers are less than strings,
2076 ** and strings are less than blobs.
2078 case OP_Compare: {
2079 int n;
2080 int i;
2081 int p1;
2082 int p2;
2083 const KeyInfo *pKeyInfo;
2084 int idx;
2085 CollSeq *pColl; /* Collating sequence to use on this term */
2086 int bRev; /* True for DESCENDING sort order */
2087 int *aPermute; /* The permutation */
2089 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2090 aPermute = 0;
2091 }else{
2092 assert( pOp>aOp );
2093 assert( pOp[-1].opcode==OP_Permutation );
2094 assert( pOp[-1].p4type==P4_INTARRAY );
2095 aPermute = pOp[-1].p4.ai + 1;
2096 assert( aPermute!=0 );
2098 n = pOp->p3;
2099 pKeyInfo = pOp->p4.pKeyInfo;
2100 assert( n>0 );
2101 assert( pKeyInfo!=0 );
2102 p1 = pOp->p1;
2103 p2 = pOp->p2;
2104 #ifdef SQLITE_DEBUG
2105 if( aPermute ){
2106 int k, mx = 0;
2107 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
2108 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2109 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2110 }else{
2111 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2112 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2114 #endif /* SQLITE_DEBUG */
2115 for(i=0; i<n; i++){
2116 idx = aPermute ? aPermute[i] : i;
2117 assert( memIsValid(&aMem[p1+idx]) );
2118 assert( memIsValid(&aMem[p2+idx]) );
2119 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2120 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2121 assert( i<pKeyInfo->nKeyField );
2122 pColl = pKeyInfo->aColl[i];
2123 bRev = pKeyInfo->aSortOrder[i];
2124 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2125 if( iCompare ){
2126 if( bRev ) iCompare = -iCompare;
2127 break;
2130 break;
2133 /* Opcode: Jump P1 P2 P3 * *
2135 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2136 ** in the most recent OP_Compare instruction the P1 vector was less than
2137 ** equal to, or greater than the P2 vector, respectively.
2139 case OP_Jump: { /* jump */
2140 if( iCompare<0 ){
2141 VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
2142 }else if( iCompare==0 ){
2143 VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
2144 }else{
2145 VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
2147 break;
2150 /* Opcode: And P1 P2 P3 * *
2151 ** Synopsis: r[P3]=(r[P1] && r[P2])
2153 ** Take the logical AND of the values in registers P1 and P2 and
2154 ** write the result into register P3.
2156 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2157 ** the other input is NULL. A NULL and true or two NULLs give
2158 ** a NULL output.
2160 /* Opcode: Or P1 P2 P3 * *
2161 ** Synopsis: r[P3]=(r[P1] || r[P2])
2163 ** Take the logical OR of the values in register P1 and P2 and
2164 ** store the answer in register P3.
2166 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2167 ** even if the other input is NULL. A NULL and false or two NULLs
2168 ** give a NULL output.
2170 case OP_And: /* same as TK_AND, in1, in2, out3 */
2171 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2172 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2173 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2175 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2176 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2177 if( pOp->opcode==OP_And ){
2178 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2179 v1 = and_logic[v1*3+v2];
2180 }else{
2181 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2182 v1 = or_logic[v1*3+v2];
2184 pOut = &aMem[pOp->p3];
2185 if( v1==2 ){
2186 MemSetTypeFlag(pOut, MEM_Null);
2187 }else{
2188 pOut->u.i = v1;
2189 MemSetTypeFlag(pOut, MEM_Int);
2191 break;
2194 /* Opcode: IsTrue P1 P2 P3 P4 *
2195 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2197 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2198 ** IS NOT FALSE operators.
2200 ** Interpret the value in register P1 as a boolean value. Store that
2201 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2202 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2203 ** is 1.
2205 ** The logic is summarized like this:
2207 ** <ul>
2208 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2209 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2210 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2211 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2212 ** </ul>
2214 case OP_IsTrue: { /* in1, out2 */
2215 assert( pOp->p4type==P4_INT32 );
2216 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2217 assert( pOp->p3==0 || pOp->p3==1 );
2218 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2219 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2220 break;
2223 /* Opcode: Not P1 P2 * * *
2224 ** Synopsis: r[P2]= !r[P1]
2226 ** Interpret the value in register P1 as a boolean value. Store the
2227 ** boolean complement in register P2. If the value in register P1 is
2228 ** NULL, then a NULL is stored in P2.
2230 case OP_Not: { /* same as TK_NOT, in1, out2 */
2231 pIn1 = &aMem[pOp->p1];
2232 pOut = &aMem[pOp->p2];
2233 if( (pIn1->flags & MEM_Null)==0 ){
2234 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2235 }else{
2236 sqlite3VdbeMemSetNull(pOut);
2238 break;
2241 /* Opcode: BitNot P1 P2 * * *
2242 ** Synopsis: r[P1]= ~r[P1]
2244 ** Interpret the content of register P1 as an integer. Store the
2245 ** ones-complement of the P1 value into register P2. If P1 holds
2246 ** a NULL then store a NULL in P2.
2248 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2249 pIn1 = &aMem[pOp->p1];
2250 pOut = &aMem[pOp->p2];
2251 sqlite3VdbeMemSetNull(pOut);
2252 if( (pIn1->flags & MEM_Null)==0 ){
2253 pOut->flags = MEM_Int;
2254 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2256 break;
2259 /* Opcode: Once P1 P2 * * *
2261 ** Fall through to the next instruction the first time this opcode is
2262 ** encountered on each invocation of the byte-code program. Jump to P2
2263 ** on the second and all subsequent encounters during the same invocation.
2265 ** Top-level programs determine first invocation by comparing the P1
2266 ** operand against the P1 operand on the OP_Init opcode at the beginning
2267 ** of the program. If the P1 values differ, then fall through and make
2268 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2269 ** the same then take the jump.
2271 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2272 ** whether or not the jump should be taken. The bitmask is necessary
2273 ** because the self-altering code trick does not work for recursive
2274 ** triggers.
2276 case OP_Once: { /* jump */
2277 u32 iAddr; /* Address of this instruction */
2278 assert( p->aOp[0].opcode==OP_Init );
2279 if( p->pFrame ){
2280 iAddr = (int)(pOp - p->aOp);
2281 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2282 VdbeBranchTaken(1, 2);
2283 goto jump_to_p2;
2285 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2286 }else{
2287 if( p->aOp[0].p1==pOp->p1 ){
2288 VdbeBranchTaken(1, 2);
2289 goto jump_to_p2;
2292 VdbeBranchTaken(0, 2);
2293 pOp->p1 = p->aOp[0].p1;
2294 break;
2297 /* Opcode: If P1 P2 P3 * *
2299 ** Jump to P2 if the value in register P1 is true. The value
2300 ** is considered true if it is numeric and non-zero. If the value
2301 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2303 case OP_If: { /* jump, in1 */
2304 int c;
2305 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2306 VdbeBranchTaken(c!=0, 2);
2307 if( c ) goto jump_to_p2;
2308 break;
2311 /* Opcode: IfNot P1 P2 P3 * *
2313 ** Jump to P2 if the value in register P1 is False. The value
2314 ** is considered false if it has a numeric value of zero. If the value
2315 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2317 case OP_IfNot: { /* jump, in1 */
2318 int c;
2319 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2320 VdbeBranchTaken(c!=0, 2);
2321 if( c ) goto jump_to_p2;
2322 break;
2325 /* Opcode: IsNull P1 P2 * * *
2326 ** Synopsis: if r[P1]==NULL goto P2
2328 ** Jump to P2 if the value in register P1 is NULL.
2330 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2331 pIn1 = &aMem[pOp->p1];
2332 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2333 if( (pIn1->flags & MEM_Null)!=0 ){
2334 goto jump_to_p2;
2336 break;
2339 /* Opcode: NotNull P1 P2 * * *
2340 ** Synopsis: if r[P1]!=NULL goto P2
2342 ** Jump to P2 if the value in register P1 is not NULL.
2344 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2345 pIn1 = &aMem[pOp->p1];
2346 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2347 if( (pIn1->flags & MEM_Null)==0 ){
2348 goto jump_to_p2;
2350 break;
2353 /* Opcode: IfNullRow P1 P2 P3 * *
2354 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2356 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2357 ** If it is, then set register P3 to NULL and jump immediately to P2.
2358 ** If P1 is not on a NULL row, then fall through without making any
2359 ** changes.
2361 case OP_IfNullRow: { /* jump */
2362 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2363 assert( p->apCsr[pOp->p1]!=0 );
2364 if( p->apCsr[pOp->p1]->nullRow ){
2365 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2366 goto jump_to_p2;
2368 break;
2371 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2372 /* Opcode: Offset P1 P2 P3 * *
2373 ** Synopsis: r[P3] = sqlite_offset(P1)
2375 ** Store in register r[P3] the byte offset into the database file that is the
2376 ** start of the payload for the record at which that cursor P1 is currently
2377 ** pointing.
2379 ** P2 is the column number for the argument to the sqlite_offset() function.
2380 ** This opcode does not use P2 itself, but the P2 value is used by the
2381 ** code generator. The P1, P2, and P3 operands to this opcode are the
2382 ** same as for OP_Column.
2384 ** This opcode is only available if SQLite is compiled with the
2385 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2387 case OP_Offset: { /* out3 */
2388 VdbeCursor *pC; /* The VDBE cursor */
2389 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2390 pC = p->apCsr[pOp->p1];
2391 pOut = &p->aMem[pOp->p3];
2392 if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
2393 sqlite3VdbeMemSetNull(pOut);
2394 }else{
2395 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2397 break;
2399 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2401 /* Opcode: Column P1 P2 P3 P4 P5
2402 ** Synopsis: r[P3]=PX
2404 ** Interpret the data that cursor P1 points to as a structure built using
2405 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2406 ** information about the format of the data.) Extract the P2-th column
2407 ** from this record. If there are less that (P2+1)
2408 ** values in the record, extract a NULL.
2410 ** The value extracted is stored in register P3.
2412 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2413 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2414 ** the result.
2416 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2417 ** then the cache of the cursor is reset prior to extracting the column.
2418 ** The first OP_Column against a pseudo-table after the value of the content
2419 ** register has changed should have this bit set.
2421 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2422 ** the result is guaranteed to only be used as the argument of a length()
2423 ** or typeof() function, respectively. The loading of large blobs can be
2424 ** skipped for length() and all content loading can be skipped for typeof().
2426 case OP_Column: {
2427 int p2; /* column number to retrieve */
2428 VdbeCursor *pC; /* The VDBE cursor */
2429 BtCursor *pCrsr; /* The BTree cursor */
2430 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2431 int len; /* The length of the serialized data for the column */
2432 int i; /* Loop counter */
2433 Mem *pDest; /* Where to write the extracted value */
2434 Mem sMem; /* For storing the record being decoded */
2435 const u8 *zData; /* Part of the record being decoded */
2436 const u8 *zHdr; /* Next unparsed byte of the header */
2437 const u8 *zEndHdr; /* Pointer to first byte after the header */
2438 u64 offset64; /* 64-bit offset */
2439 u32 t; /* A type code from the record header */
2440 Mem *pReg; /* PseudoTable input register */
2442 pC = p->apCsr[pOp->p1];
2443 p2 = pOp->p2;
2445 /* If the cursor cache is stale (meaning it is not currently point at
2446 ** the correct row) then bring it up-to-date by doing the necessary
2447 ** B-Tree seek. */
2448 rc = sqlite3VdbeCursorMoveto(&pC, &p2);
2449 if( rc ) goto abort_due_to_error;
2451 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2452 pDest = &aMem[pOp->p3];
2453 memAboutToChange(p, pDest);
2454 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2455 assert( pC!=0 );
2456 assert( p2<pC->nField );
2457 aOffset = pC->aOffset;
2458 assert( pC->eCurType!=CURTYPE_VTAB );
2459 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2460 assert( pC->eCurType!=CURTYPE_SORTER );
2462 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2463 if( pC->nullRow ){
2464 if( pC->eCurType==CURTYPE_PSEUDO ){
2465 /* For the special case of as pseudo-cursor, the seekResult field
2466 ** identifies the register that holds the record */
2467 assert( pC->seekResult>0 );
2468 pReg = &aMem[pC->seekResult];
2469 assert( pReg->flags & MEM_Blob );
2470 assert( memIsValid(pReg) );
2471 pC->payloadSize = pC->szRow = pReg->n;
2472 pC->aRow = (u8*)pReg->z;
2473 }else{
2474 sqlite3VdbeMemSetNull(pDest);
2475 goto op_column_out;
2477 }else{
2478 pCrsr = pC->uc.pCursor;
2479 assert( pC->eCurType==CURTYPE_BTREE );
2480 assert( pCrsr );
2481 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2482 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2483 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2484 assert( pC->szRow<=pC->payloadSize );
2485 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2486 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2487 goto too_big;
2490 pC->cacheStatus = p->cacheCtr;
2491 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
2492 pC->nHdrParsed = 0;
2495 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2496 /* pC->aRow does not have to hold the entire row, but it does at least
2497 ** need to cover the header of the record. If pC->aRow does not contain
2498 ** the complete header, then set it to zero, forcing the header to be
2499 ** dynamically allocated. */
2500 pC->aRow = 0;
2501 pC->szRow = 0;
2503 /* Make sure a corrupt database has not given us an oversize header.
2504 ** Do this now to avoid an oversize memory allocation.
2506 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2507 ** types use so much data space that there can only be 4096 and 32 of
2508 ** them, respectively. So the maximum header length results from a
2509 ** 3-byte type for each of the maximum of 32768 columns plus three
2510 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2512 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2513 goto op_column_corrupt;
2515 }else{
2516 /* This is an optimization. By skipping over the first few tests
2517 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2518 ** measurable performance gain.
2520 ** This branch is taken even if aOffset[0]==0. Such a record is never
2521 ** generated by SQLite, and could be considered corruption, but we
2522 ** accept it for historical reasons. When aOffset[0]==0, the code this
2523 ** branch jumps to reads past the end of the record, but never more
2524 ** than a few bytes. Even if the record occurs at the end of the page
2525 ** content area, the "page header" comes after the page content and so
2526 ** this overread is harmless. Similar overreads can occur for a corrupt
2527 ** database file.
2529 zData = pC->aRow;
2530 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2531 testcase( aOffset[0]==0 );
2532 goto op_column_read_header;
2536 /* Make sure at least the first p2+1 entries of the header have been
2537 ** parsed and valid information is in aOffset[] and pC->aType[].
2539 if( pC->nHdrParsed<=p2 ){
2540 /* If there is more header available for parsing in the record, try
2541 ** to extract additional fields up through the p2+1-th field
2543 if( pC->iHdrOffset<aOffset[0] ){
2544 /* Make sure zData points to enough of the record to cover the header. */
2545 if( pC->aRow==0 ){
2546 memset(&sMem, 0, sizeof(sMem));
2547 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
2548 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2549 zData = (u8*)sMem.z;
2550 }else{
2551 zData = pC->aRow;
2554 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2555 op_column_read_header:
2556 i = pC->nHdrParsed;
2557 offset64 = aOffset[i];
2558 zHdr = zData + pC->iHdrOffset;
2559 zEndHdr = zData + aOffset[0];
2560 testcase( zHdr>=zEndHdr );
2562 if( (t = zHdr[0])<0x80 ){
2563 zHdr++;
2564 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2565 }else{
2566 zHdr += sqlite3GetVarint32(zHdr, &t);
2567 offset64 += sqlite3VdbeSerialTypeLen(t);
2569 pC->aType[i++] = t;
2570 aOffset[i] = (u32)(offset64 & 0xffffffff);
2571 }while( i<=p2 && zHdr<zEndHdr );
2573 /* The record is corrupt if any of the following are true:
2574 ** (1) the bytes of the header extend past the declared header size
2575 ** (2) the entire header was used but not all data was used
2576 ** (3) the end of the data extends beyond the end of the record.
2578 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2579 || (offset64 > pC->payloadSize)
2581 if( aOffset[0]==0 ){
2582 i = 0;
2583 zHdr = zEndHdr;
2584 }else{
2585 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2586 goto op_column_corrupt;
2590 pC->nHdrParsed = i;
2591 pC->iHdrOffset = (u32)(zHdr - zData);
2592 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2593 }else{
2594 t = 0;
2597 /* If after trying to extract new entries from the header, nHdrParsed is
2598 ** still not up to p2, that means that the record has fewer than p2
2599 ** columns. So the result will be either the default value or a NULL.
2601 if( pC->nHdrParsed<=p2 ){
2602 if( pOp->p4type==P4_MEM ){
2603 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2604 }else{
2605 sqlite3VdbeMemSetNull(pDest);
2607 goto op_column_out;
2609 }else{
2610 t = pC->aType[p2];
2613 /* Extract the content for the p2+1-th column. Control can only
2614 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2615 ** all valid.
2617 assert( p2<pC->nHdrParsed );
2618 assert( rc==SQLITE_OK );
2619 assert( sqlite3VdbeCheckMemInvariants(pDest) );
2620 if( VdbeMemDynamic(pDest) ){
2621 sqlite3VdbeMemSetNull(pDest);
2623 assert( t==pC->aType[p2] );
2624 if( pC->szRow>=aOffset[p2+1] ){
2625 /* This is the common case where the desired content fits on the original
2626 ** page - where the content is not on an overflow page */
2627 zData = pC->aRow + aOffset[p2];
2628 if( t<12 ){
2629 sqlite3VdbeSerialGet(zData, t, pDest);
2630 }else{
2631 /* If the column value is a string, we need a persistent value, not
2632 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2633 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2635 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
2636 pDest->n = len = (t-12)/2;
2637 pDest->enc = encoding;
2638 if( pDest->szMalloc < len+2 ){
2639 pDest->flags = MEM_Null;
2640 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
2641 }else{
2642 pDest->z = pDest->zMalloc;
2644 memcpy(pDest->z, zData, len);
2645 pDest->z[len] = 0;
2646 pDest->z[len+1] = 0;
2647 pDest->flags = aFlag[t&1];
2649 }else{
2650 pDest->enc = encoding;
2651 /* This branch happens only when content is on overflow pages */
2652 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2653 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2654 || (len = sqlite3VdbeSerialTypeLen(t))==0
2656 /* Content is irrelevant for
2657 ** 1. the typeof() function,
2658 ** 2. the length(X) function if X is a blob, and
2659 ** 3. if the content length is zero.
2660 ** So we might as well use bogus content rather than reading
2661 ** content from disk.
2663 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2664 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2665 ** read up to 16. So 16 bytes of bogus content is supplied.
2667 static u8 aZero[16]; /* This is the bogus content */
2668 sqlite3VdbeSerialGet(aZero, t, pDest);
2669 }else{
2670 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
2671 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2672 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2673 pDest->flags &= ~MEM_Ephem;
2677 op_column_out:
2678 UPDATE_MAX_BLOBSIZE(pDest);
2679 REGISTER_TRACE(pOp->p3, pDest);
2680 break;
2682 op_column_corrupt:
2683 if( aOp[0].p3>0 ){
2684 pOp = &aOp[aOp[0].p3-1];
2685 break;
2686 }else{
2687 rc = SQLITE_CORRUPT_BKPT;
2688 goto abort_due_to_error;
2692 /* Opcode: Affinity P1 P2 * P4 *
2693 ** Synopsis: affinity(r[P1@P2])
2695 ** Apply affinities to a range of P2 registers starting with P1.
2697 ** P4 is a string that is P2 characters long. The N-th character of the
2698 ** string indicates the column affinity that should be used for the N-th
2699 ** memory cell in the range.
2701 case OP_Affinity: {
2702 const char *zAffinity; /* The affinity to be applied */
2704 zAffinity = pOp->p4.z;
2705 assert( zAffinity!=0 );
2706 assert( pOp->p2>0 );
2707 assert( zAffinity[pOp->p2]==0 );
2708 pIn1 = &aMem[pOp->p1];
2710 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
2711 assert( memIsValid(pIn1) );
2712 applyAffinity(pIn1, *(zAffinity++), encoding);
2713 pIn1++;
2714 }while( zAffinity[0] );
2715 break;
2718 /* Opcode: MakeRecord P1 P2 P3 P4 *
2719 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2721 ** Convert P2 registers beginning with P1 into the [record format]
2722 ** use as a data record in a database table or as a key
2723 ** in an index. The OP_Column opcode can decode the record later.
2725 ** P4 may be a string that is P2 characters long. The N-th character of the
2726 ** string indicates the column affinity that should be used for the N-th
2727 ** field of the index key.
2729 ** The mapping from character to affinity is given by the SQLITE_AFF_
2730 ** macros defined in sqliteInt.h.
2732 ** If P4 is NULL then all index fields have the affinity BLOB.
2734 case OP_MakeRecord: {
2735 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2736 Mem *pRec; /* The new record */
2737 u64 nData; /* Number of bytes of data space */
2738 int nHdr; /* Number of bytes of header space */
2739 i64 nByte; /* Data space required for this record */
2740 i64 nZero; /* Number of zero bytes at the end of the record */
2741 int nVarint; /* Number of bytes in a varint */
2742 u32 serial_type; /* Type field */
2743 Mem *pData0; /* First field to be combined into the record */
2744 Mem *pLast; /* Last field of the record */
2745 int nField; /* Number of fields in the record */
2746 char *zAffinity; /* The affinity string for the record */
2747 int file_format; /* File format to use for encoding */
2748 int i; /* Space used in zNewRecord[] header */
2749 int j; /* Space used in zNewRecord[] content */
2750 u32 len; /* Length of a field */
2752 /* Assuming the record contains N fields, the record format looks
2753 ** like this:
2755 ** ------------------------------------------------------------------------
2756 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2757 ** ------------------------------------------------------------------------
2759 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2760 ** and so forth.
2762 ** Each type field is a varint representing the serial type of the
2763 ** corresponding data element (see sqlite3VdbeSerialType()). The
2764 ** hdr-size field is also a varint which is the offset from the beginning
2765 ** of the record to data0.
2767 nData = 0; /* Number of bytes of data space */
2768 nHdr = 0; /* Number of bytes of header space */
2769 nZero = 0; /* Number of zero bytes at the end of the record */
2770 nField = pOp->p1;
2771 zAffinity = pOp->p4.z;
2772 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
2773 pData0 = &aMem[nField];
2774 nField = pOp->p2;
2775 pLast = &pData0[nField-1];
2776 file_format = p->minWriteFileFormat;
2778 /* Identify the output register */
2779 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2780 pOut = &aMem[pOp->p3];
2781 memAboutToChange(p, pOut);
2783 /* Apply the requested affinity to all inputs
2785 assert( pData0<=pLast );
2786 if( zAffinity ){
2787 pRec = pData0;
2789 applyAffinity(pRec++, *(zAffinity++), encoding);
2790 assert( zAffinity[0]==0 || pRec<=pLast );
2791 }while( zAffinity[0] );
2794 #ifdef SQLITE_ENABLE_NULL_TRIM
2795 /* NULLs can be safely trimmed from the end of the record, as long as
2796 ** as the schema format is 2 or more and none of the omitted columns
2797 ** have a non-NULL default value. Also, the record must be left with
2798 ** at least one field. If P5>0 then it will be one more than the
2799 ** index of the right-most column with a non-NULL default value */
2800 if( pOp->p5 ){
2801 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
2802 pLast--;
2803 nField--;
2806 #endif
2808 /* Loop through the elements that will make up the record to figure
2809 ** out how much space is required for the new record.
2811 pRec = pLast;
2813 assert( memIsValid(pRec) );
2814 serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
2815 if( pRec->flags & MEM_Zero ){
2816 if( serial_type==0 ){
2817 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
2818 ** table methods that never invoke sqlite3_result_xxxxx() while
2819 ** computing an unchanging column value in an UPDATE statement.
2820 ** Give such values a special internal-use-only serial-type of 10
2821 ** so that they can be passed through to xUpdate and have
2822 ** a true sqlite3_value_nochange(). */
2823 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
2824 serial_type = 10;
2825 }else if( nData ){
2826 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
2827 }else{
2828 nZero += pRec->u.nZero;
2829 len -= pRec->u.nZero;
2832 nData += len;
2833 testcase( serial_type==127 );
2834 testcase( serial_type==128 );
2835 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
2836 pRec->uTemp = serial_type;
2837 if( pRec==pData0 ) break;
2838 pRec--;
2839 }while(1);
2841 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
2842 ** which determines the total number of bytes in the header. The varint
2843 ** value is the size of the header in bytes including the size varint
2844 ** itself. */
2845 testcase( nHdr==126 );
2846 testcase( nHdr==127 );
2847 if( nHdr<=126 ){
2848 /* The common case */
2849 nHdr += 1;
2850 }else{
2851 /* Rare case of a really large header */
2852 nVarint = sqlite3VarintLen(nHdr);
2853 nHdr += nVarint;
2854 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
2856 nByte = nHdr+nData;
2857 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2858 goto too_big;
2861 /* Make sure the output register has a buffer large enough to store
2862 ** the new record. The output register (pOp->p3) is not allowed to
2863 ** be one of the input registers (because the following call to
2864 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2866 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
2867 goto no_mem;
2869 zNewRecord = (u8 *)pOut->z;
2871 /* Write the record */
2872 i = putVarint32(zNewRecord, nHdr);
2873 j = nHdr;
2874 assert( pData0<=pLast );
2875 pRec = pData0;
2877 serial_type = pRec->uTemp;
2878 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
2879 ** additional varints, one per column. */
2880 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
2881 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
2882 ** immediately follow the header. */
2883 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
2884 }while( (++pRec)<=pLast );
2885 assert( i==nHdr );
2886 assert( j==nByte );
2888 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2889 pOut->n = (int)nByte;
2890 pOut->flags = MEM_Blob;
2891 if( nZero ){
2892 pOut->u.nZero = nZero;
2893 pOut->flags |= MEM_Zero;
2895 REGISTER_TRACE(pOp->p3, pOut);
2896 UPDATE_MAX_BLOBSIZE(pOut);
2897 break;
2900 /* Opcode: Count P1 P2 * * *
2901 ** Synopsis: r[P2]=count()
2903 ** Store the number of entries (an integer value) in the table or index
2904 ** opened by cursor P1 in register P2
2906 #ifndef SQLITE_OMIT_BTREECOUNT
2907 case OP_Count: { /* out2 */
2908 i64 nEntry;
2909 BtCursor *pCrsr;
2911 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
2912 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
2913 assert( pCrsr );
2914 nEntry = 0; /* Not needed. Only used to silence a warning. */
2915 rc = sqlite3BtreeCount(pCrsr, &nEntry);
2916 if( rc ) goto abort_due_to_error;
2917 pOut = out2Prerelease(p, pOp);
2918 pOut->u.i = nEntry;
2919 break;
2921 #endif
2923 /* Opcode: Savepoint P1 * * P4 *
2925 ** Open, release or rollback the savepoint named by parameter P4, depending
2926 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2927 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2929 case OP_Savepoint: {
2930 int p1; /* Value of P1 operand */
2931 char *zName; /* Name of savepoint */
2932 int nName;
2933 Savepoint *pNew;
2934 Savepoint *pSavepoint;
2935 Savepoint *pTmp;
2936 int iSavepoint;
2937 int ii;
2939 p1 = pOp->p1;
2940 zName = pOp->p4.z;
2942 /* Assert that the p1 parameter is valid. Also that if there is no open
2943 ** transaction, then there cannot be any savepoints.
2945 assert( db->pSavepoint==0 || db->autoCommit==0 );
2946 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
2947 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
2948 assert( checkSavepointCount(db) );
2949 assert( p->bIsReader );
2951 if( p1==SAVEPOINT_BEGIN ){
2952 if( db->nVdbeWrite>0 ){
2953 /* A new savepoint cannot be created if there are active write
2954 ** statements (i.e. open read/write incremental blob handles).
2956 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
2957 rc = SQLITE_BUSY;
2958 }else{
2959 nName = sqlite3Strlen30(zName);
2961 #ifndef SQLITE_OMIT_VIRTUALTABLE
2962 /* This call is Ok even if this savepoint is actually a transaction
2963 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2964 ** If this is a transaction savepoint being opened, it is guaranteed
2965 ** that the db->aVTrans[] array is empty. */
2966 assert( db->autoCommit==0 || db->nVTrans==0 );
2967 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
2968 db->nStatement+db->nSavepoint);
2969 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2970 #endif
2972 /* Create a new savepoint structure. */
2973 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
2974 if( pNew ){
2975 pNew->zName = (char *)&pNew[1];
2976 memcpy(pNew->zName, zName, nName+1);
2978 /* If there is no open transaction, then mark this as a special
2979 ** "transaction savepoint". */
2980 if( db->autoCommit ){
2981 db->autoCommit = 0;
2982 db->isTransactionSavepoint = 1;
2983 }else{
2984 db->nSavepoint++;
2987 /* Link the new savepoint into the database handle's list. */
2988 pNew->pNext = db->pSavepoint;
2989 db->pSavepoint = pNew;
2990 pNew->nDeferredCons = db->nDeferredCons;
2991 pNew->nDeferredImmCons = db->nDeferredImmCons;
2994 }else{
2995 iSavepoint = 0;
2997 /* Find the named savepoint. If there is no such savepoint, then an
2998 ** an error is returned to the user. */
2999 for(
3000 pSavepoint = db->pSavepoint;
3001 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3002 pSavepoint = pSavepoint->pNext
3004 iSavepoint++;
3006 if( !pSavepoint ){
3007 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3008 rc = SQLITE_ERROR;
3009 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3010 /* It is not possible to release (commit) a savepoint if there are
3011 ** active write statements.
3013 sqlite3VdbeError(p, "cannot release savepoint - "
3014 "SQL statements in progress");
3015 rc = SQLITE_BUSY;
3016 }else{
3018 /* Determine whether or not this is a transaction savepoint. If so,
3019 ** and this is a RELEASE command, then the current transaction
3020 ** is committed.
3022 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3023 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3024 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3025 goto vdbe_return;
3027 db->autoCommit = 1;
3028 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3029 p->pc = (int)(pOp - aOp);
3030 db->autoCommit = 0;
3031 p->rc = rc = SQLITE_BUSY;
3032 goto vdbe_return;
3034 db->isTransactionSavepoint = 0;
3035 rc = p->rc;
3036 }else{
3037 int isSchemaChange;
3038 iSavepoint = db->nSavepoint - iSavepoint - 1;
3039 if( p1==SAVEPOINT_ROLLBACK ){
3040 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3041 for(ii=0; ii<db->nDb; ii++){
3042 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3043 SQLITE_ABORT_ROLLBACK,
3044 isSchemaChange==0);
3045 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3047 }else{
3048 isSchemaChange = 0;
3050 for(ii=0; ii<db->nDb; ii++){
3051 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3052 if( rc!=SQLITE_OK ){
3053 goto abort_due_to_error;
3056 if( isSchemaChange ){
3057 sqlite3ExpirePreparedStatements(db);
3058 sqlite3ResetAllSchemasOfConnection(db);
3059 db->mDbFlags |= DBFLAG_SchemaChange;
3063 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3064 ** savepoints nested inside of the savepoint being operated on. */
3065 while( db->pSavepoint!=pSavepoint ){
3066 pTmp = db->pSavepoint;
3067 db->pSavepoint = pTmp->pNext;
3068 sqlite3DbFree(db, pTmp);
3069 db->nSavepoint--;
3072 /* If it is a RELEASE, then destroy the savepoint being operated on
3073 ** too. If it is a ROLLBACK TO, then set the number of deferred
3074 ** constraint violations present in the database to the value stored
3075 ** when the savepoint was created. */
3076 if( p1==SAVEPOINT_RELEASE ){
3077 assert( pSavepoint==db->pSavepoint );
3078 db->pSavepoint = pSavepoint->pNext;
3079 sqlite3DbFree(db, pSavepoint);
3080 if( !isTransaction ){
3081 db->nSavepoint--;
3083 }else{
3084 db->nDeferredCons = pSavepoint->nDeferredCons;
3085 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3088 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3089 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3090 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3094 if( rc ) goto abort_due_to_error;
3096 break;
3099 /* Opcode: AutoCommit P1 P2 * * *
3101 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3102 ** back any currently active btree transactions. If there are any active
3103 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3104 ** there are active writing VMs or active VMs that use shared cache.
3106 ** This instruction causes the VM to halt.
3108 case OP_AutoCommit: {
3109 int desiredAutoCommit;
3110 int iRollback;
3112 desiredAutoCommit = pOp->p1;
3113 iRollback = pOp->p2;
3114 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3115 assert( desiredAutoCommit==1 || iRollback==0 );
3116 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3117 assert( p->bIsReader );
3119 if( desiredAutoCommit!=db->autoCommit ){
3120 if( iRollback ){
3121 assert( desiredAutoCommit==1 );
3122 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3123 db->autoCommit = 1;
3124 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3125 /* If this instruction implements a COMMIT and other VMs are writing
3126 ** return an error indicating that the other VMs must complete first.
3128 sqlite3VdbeError(p, "cannot commit transaction - "
3129 "SQL statements in progress");
3130 rc = SQLITE_BUSY;
3131 goto abort_due_to_error;
3132 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3133 goto vdbe_return;
3134 }else{
3135 db->autoCommit = (u8)desiredAutoCommit;
3137 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3138 p->pc = (int)(pOp - aOp);
3139 db->autoCommit = (u8)(1-desiredAutoCommit);
3140 p->rc = rc = SQLITE_BUSY;
3141 goto vdbe_return;
3143 assert( db->nStatement==0 );
3144 sqlite3CloseSavepoints(db);
3145 if( p->rc==SQLITE_OK ){
3146 rc = SQLITE_DONE;
3147 }else{
3148 rc = SQLITE_ERROR;
3150 goto vdbe_return;
3151 }else{
3152 sqlite3VdbeError(p,
3153 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3154 (iRollback)?"cannot rollback - no transaction is active":
3155 "cannot commit - no transaction is active"));
3157 rc = SQLITE_ERROR;
3158 goto abort_due_to_error;
3160 break;
3163 /* Opcode: Transaction P1 P2 P3 P4 P5
3165 ** Begin a transaction on database P1 if a transaction is not already
3166 ** active.
3167 ** If P2 is non-zero, then a write-transaction is started, or if a
3168 ** read-transaction is already active, it is upgraded to a write-transaction.
3169 ** If P2 is zero, then a read-transaction is started.
3171 ** P1 is the index of the database file on which the transaction is
3172 ** started. Index 0 is the main database file and index 1 is the
3173 ** file used for temporary tables. Indices of 2 or more are used for
3174 ** attached databases.
3176 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3177 ** true (this flag is set if the Vdbe may modify more than one row and may
3178 ** throw an ABORT exception), a statement transaction may also be opened.
3179 ** More specifically, a statement transaction is opened iff the database
3180 ** connection is currently not in autocommit mode, or if there are other
3181 ** active statements. A statement transaction allows the changes made by this
3182 ** VDBE to be rolled back after an error without having to roll back the
3183 ** entire transaction. If no error is encountered, the statement transaction
3184 ** will automatically commit when the VDBE halts.
3186 ** If P5!=0 then this opcode also checks the schema cookie against P3
3187 ** and the schema generation counter against P4.
3188 ** The cookie changes its value whenever the database schema changes.
3189 ** This operation is used to detect when that the cookie has changed
3190 ** and that the current process needs to reread the schema. If the schema
3191 ** cookie in P3 differs from the schema cookie in the database header or
3192 ** if the schema generation counter in P4 differs from the current
3193 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3194 ** halts. The sqlite3_step() wrapper function might then reprepare the
3195 ** statement and rerun it from the beginning.
3197 case OP_Transaction: {
3198 Btree *pBt;
3199 int iMeta;
3200 int iGen;
3202 assert( p->bIsReader );
3203 assert( p->readOnly==0 || pOp->p2==0 );
3204 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3205 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3206 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3207 rc = SQLITE_READONLY;
3208 goto abort_due_to_error;
3210 pBt = db->aDb[pOp->p1].pBt;
3212 if( pBt ){
3213 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
3214 testcase( rc==SQLITE_BUSY_SNAPSHOT );
3215 testcase( rc==SQLITE_BUSY_RECOVERY );
3216 if( rc!=SQLITE_OK ){
3217 if( (rc&0xff)==SQLITE_BUSY ){
3218 p->pc = (int)(pOp - aOp);
3219 p->rc = rc;
3220 goto vdbe_return;
3222 goto abort_due_to_error;
3225 if( pOp->p2 && p->usesStmtJournal
3226 && (db->autoCommit==0 || db->nVdbeRead>1)
3228 assert( sqlite3BtreeIsInTrans(pBt) );
3229 if( p->iStatement==0 ){
3230 assert( db->nStatement>=0 && db->nSavepoint>=0 );
3231 db->nStatement++;
3232 p->iStatement = db->nSavepoint + db->nStatement;
3235 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3236 if( rc==SQLITE_OK ){
3237 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3240 /* Store the current value of the database handles deferred constraint
3241 ** counter. If the statement transaction needs to be rolled back,
3242 ** the value of this counter needs to be restored too. */
3243 p->nStmtDefCons = db->nDeferredCons;
3244 p->nStmtDefImmCons = db->nDeferredImmCons;
3247 /* Gather the schema version number for checking:
3248 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3249 ** version is checked to ensure that the schema has not changed since the
3250 ** SQL statement was prepared.
3252 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
3253 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
3254 }else{
3255 iGen = iMeta = 0;
3257 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3258 if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
3259 sqlite3DbFree(db, p->zErrMsg);
3260 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3261 /* If the schema-cookie from the database file matches the cookie
3262 ** stored with the in-memory representation of the schema, do
3263 ** not reload the schema from the database file.
3265 ** If virtual-tables are in use, this is not just an optimization.
3266 ** Often, v-tables store their data in other SQLite tables, which
3267 ** are queried from within xNext() and other v-table methods using
3268 ** prepared queries. If such a query is out-of-date, we do not want to
3269 ** discard the database schema, as the user code implementing the
3270 ** v-table would have to be ready for the sqlite3_vtab structure itself
3271 ** to be invalidated whenever sqlite3_step() is called from within
3272 ** a v-table method.
3274 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3275 sqlite3ResetOneSchema(db, pOp->p1);
3277 p->expired = 1;
3278 rc = SQLITE_SCHEMA;
3280 if( rc ) goto abort_due_to_error;
3281 break;
3284 /* Opcode: ReadCookie P1 P2 P3 * *
3286 ** Read cookie number P3 from database P1 and write it into register P2.
3287 ** P3==1 is the schema version. P3==2 is the database format.
3288 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3289 ** the main database file and P1==1 is the database file used to store
3290 ** temporary tables.
3292 ** There must be a read-lock on the database (either a transaction
3293 ** must be started or there must be an open cursor) before
3294 ** executing this instruction.
3296 case OP_ReadCookie: { /* out2 */
3297 int iMeta;
3298 int iDb;
3299 int iCookie;
3301 assert( p->bIsReader );
3302 iDb = pOp->p1;
3303 iCookie = pOp->p3;
3304 assert( pOp->p3<SQLITE_N_BTREE_META );
3305 assert( iDb>=0 && iDb<db->nDb );
3306 assert( db->aDb[iDb].pBt!=0 );
3307 assert( DbMaskTest(p->btreeMask, iDb) );
3309 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3310 pOut = out2Prerelease(p, pOp);
3311 pOut->u.i = iMeta;
3312 break;
3315 /* Opcode: SetCookie P1 P2 P3 * *
3317 ** Write the integer value P3 into cookie number P2 of database P1.
3318 ** P2==1 is the schema version. P2==2 is the database format.
3319 ** P2==3 is the recommended pager cache
3320 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3321 ** database file used to store temporary tables.
3323 ** A transaction must be started before executing this opcode.
3325 case OP_SetCookie: {
3326 Db *pDb;
3327 assert( pOp->p2<SQLITE_N_BTREE_META );
3328 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3329 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3330 assert( p->readOnly==0 );
3331 pDb = &db->aDb[pOp->p1];
3332 assert( pDb->pBt!=0 );
3333 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3334 /* See note about index shifting on OP_ReadCookie */
3335 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3336 if( pOp->p2==BTREE_SCHEMA_VERSION ){
3337 /* When the schema cookie changes, record the new cookie internally */
3338 pDb->pSchema->schema_cookie = pOp->p3;
3339 db->mDbFlags |= DBFLAG_SchemaChange;
3340 }else if( pOp->p2==BTREE_FILE_FORMAT ){
3341 /* Record changes in the file format */
3342 pDb->pSchema->file_format = pOp->p3;
3344 if( pOp->p1==1 ){
3345 /* Invalidate all prepared statements whenever the TEMP database
3346 ** schema is changed. Ticket #1644 */
3347 sqlite3ExpirePreparedStatements(db);
3348 p->expired = 0;
3350 if( rc ) goto abort_due_to_error;
3351 break;
3354 /* Opcode: OpenRead P1 P2 P3 P4 P5
3355 ** Synopsis: root=P2 iDb=P3
3357 ** Open a read-only cursor for the database table whose root page is
3358 ** P2 in a database file. The database file is determined by P3.
3359 ** P3==0 means the main database, P3==1 means the database used for
3360 ** temporary tables, and P3>1 means used the corresponding attached
3361 ** database. Give the new cursor an identifier of P1. The P1
3362 ** values need not be contiguous but all P1 values should be small integers.
3363 ** It is an error for P1 to be negative.
3365 ** If P5!=0 then use the content of register P2 as the root page, not
3366 ** the value of P2 itself.
3368 ** There will be a read lock on the database whenever there is an
3369 ** open cursor. If the database was unlocked prior to this instruction
3370 ** then a read lock is acquired as part of this instruction. A read
3371 ** lock allows other processes to read the database but prohibits
3372 ** any other process from modifying the database. The read lock is
3373 ** released when all cursors are closed. If this instruction attempts
3374 ** to get a read lock but fails, the script terminates with an
3375 ** SQLITE_BUSY error code.
3377 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3378 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3379 ** structure, then said structure defines the content and collating
3380 ** sequence of the index being opened. Otherwise, if P4 is an integer
3381 ** value, it is set to the number of columns in the table.
3383 ** See also: OpenWrite, ReopenIdx
3385 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3386 ** Synopsis: root=P2 iDb=P3
3388 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
3389 ** checks to see if the cursor on P1 is already open with a root page
3390 ** number of P2 and if it is this opcode becomes a no-op. In other words,
3391 ** if the cursor is already open, do not reopen it.
3393 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
3394 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
3395 ** every other ReopenIdx or OpenRead for the same cursor number.
3397 ** See the OpenRead opcode documentation for additional information.
3399 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3400 ** Synopsis: root=P2 iDb=P3
3402 ** Open a read/write cursor named P1 on the table or index whose root
3403 ** page is P2. Or if P5!=0 use the content of register P2 to find the
3404 ** root page.
3406 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3407 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3408 ** structure, then said structure defines the content and collating
3409 ** sequence of the index being opened. Otherwise, if P4 is an integer
3410 ** value, it is set to the number of columns in the table, or to the
3411 ** largest index of any column of the table that is actually used.
3413 ** This instruction works just like OpenRead except that it opens the cursor
3414 ** in read/write mode. For a given table, there can be one or more read-only
3415 ** cursors or a single read/write cursor but not both.
3417 ** See also OpenRead.
3419 case OP_ReopenIdx: {
3420 int nField;
3421 KeyInfo *pKeyInfo;
3422 int p2;
3423 int iDb;
3424 int wrFlag;
3425 Btree *pX;
3426 VdbeCursor *pCur;
3427 Db *pDb;
3429 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3430 assert( pOp->p4type==P4_KEYINFO );
3431 pCur = p->apCsr[pOp->p1];
3432 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3433 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
3434 goto open_cursor_set_hints;
3436 /* If the cursor is not currently open or is open on a different
3437 ** index, then fall through into OP_OpenRead to force a reopen */
3438 case OP_OpenRead:
3439 case OP_OpenWrite:
3441 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3442 assert( p->bIsReader );
3443 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3444 || p->readOnly==0 );
3446 if( p->expired ){
3447 rc = SQLITE_ABORT_ROLLBACK;
3448 goto abort_due_to_error;
3451 nField = 0;
3452 pKeyInfo = 0;
3453 p2 = pOp->p2;
3454 iDb = pOp->p3;
3455 assert( iDb>=0 && iDb<db->nDb );
3456 assert( DbMaskTest(p->btreeMask, iDb) );
3457 pDb = &db->aDb[iDb];
3458 pX = pDb->pBt;
3459 assert( pX!=0 );
3460 if( pOp->opcode==OP_OpenWrite ){
3461 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
3462 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
3463 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3464 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3465 p->minWriteFileFormat = pDb->pSchema->file_format;
3467 }else{
3468 wrFlag = 0;
3470 if( pOp->p5 & OPFLAG_P2ISREG ){
3471 assert( p2>0 );
3472 assert( p2<=(p->nMem+1 - p->nCursor) );
3473 pIn2 = &aMem[p2];
3474 assert( memIsValid(pIn2) );
3475 assert( (pIn2->flags & MEM_Int)!=0 );
3476 sqlite3VdbeMemIntegerify(pIn2);
3477 p2 = (int)pIn2->u.i;
3478 /* The p2 value always comes from a prior OP_CreateBtree opcode and
3479 ** that opcode will always set the p2 value to 2 or more or else fail.
3480 ** If there were a failure, the prepared statement would have halted
3481 ** before reaching this instruction. */
3482 assert( p2>=2 );
3484 if( pOp->p4type==P4_KEYINFO ){
3485 pKeyInfo = pOp->p4.pKeyInfo;
3486 assert( pKeyInfo->enc==ENC(db) );
3487 assert( pKeyInfo->db==db );
3488 nField = pKeyInfo->nAllField;
3489 }else if( pOp->p4type==P4_INT32 ){
3490 nField = pOp->p4.i;
3492 assert( pOp->p1>=0 );
3493 assert( nField>=0 );
3494 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3495 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
3496 if( pCur==0 ) goto no_mem;
3497 pCur->nullRow = 1;
3498 pCur->isOrdered = 1;
3499 pCur->pgnoRoot = p2;
3500 #ifdef SQLITE_DEBUG
3501 pCur->wrFlag = wrFlag;
3502 #endif
3503 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
3504 pCur->pKeyInfo = pKeyInfo;
3505 /* Set the VdbeCursor.isTable variable. Previous versions of
3506 ** SQLite used to check if the root-page flags were sane at this point
3507 ** and report database corruption if they were not, but this check has
3508 ** since moved into the btree layer. */
3509 pCur->isTable = pOp->p4type!=P4_KEYINFO;
3511 open_cursor_set_hints:
3512 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3513 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
3514 testcase( pOp->p5 & OPFLAG_BULKCSR );
3515 #ifdef SQLITE_ENABLE_CURSOR_HINTS
3516 testcase( pOp->p2 & OPFLAG_SEEKEQ );
3517 #endif
3518 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
3519 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
3520 if( rc ) goto abort_due_to_error;
3521 break;
3524 /* Opcode: OpenDup P1 P2 * * *
3526 ** Open a new cursor P1 that points to the same ephemeral table as
3527 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
3528 ** opcode. Only ephemeral cursors may be duplicated.
3530 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
3532 case OP_OpenDup: {
3533 VdbeCursor *pOrig; /* The original cursor to be duplicated */
3534 VdbeCursor *pCx; /* The new cursor */
3536 pOrig = p->apCsr[pOp->p2];
3537 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
3539 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
3540 if( pCx==0 ) goto no_mem;
3541 pCx->nullRow = 1;
3542 pCx->isEphemeral = 1;
3543 pCx->pKeyInfo = pOrig->pKeyInfo;
3544 pCx->isTable = pOrig->isTable;
3545 rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
3546 pCx->pKeyInfo, pCx->uc.pCursor);
3547 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
3548 ** opened for a database. Since there is already an open cursor when this
3549 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
3550 assert( rc==SQLITE_OK );
3551 break;
3555 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3556 ** Synopsis: nColumn=P2
3558 ** Open a new cursor P1 to a transient table.
3559 ** The cursor is always opened read/write even if
3560 ** the main database is read-only. The ephemeral
3561 ** table is deleted automatically when the cursor is closed.
3563 ** P2 is the number of columns in the ephemeral table.
3564 ** The cursor points to a BTree table if P4==0 and to a BTree index
3565 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3566 ** that defines the format of keys in the index.
3568 ** The P5 parameter can be a mask of the BTREE_* flags defined
3569 ** in btree.h. These flags control aspects of the operation of
3570 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3571 ** added automatically.
3573 /* Opcode: OpenAutoindex P1 P2 * P4 *
3574 ** Synopsis: nColumn=P2
3576 ** This opcode works the same as OP_OpenEphemeral. It has a
3577 ** different name to distinguish its use. Tables created using
3578 ** by this opcode will be used for automatically created transient
3579 ** indices in joins.
3581 case OP_OpenAutoindex:
3582 case OP_OpenEphemeral: {
3583 VdbeCursor *pCx;
3584 KeyInfo *pKeyInfo;
3586 static const int vfsFlags =
3587 SQLITE_OPEN_READWRITE |
3588 SQLITE_OPEN_CREATE |
3589 SQLITE_OPEN_EXCLUSIVE |
3590 SQLITE_OPEN_DELETEONCLOSE |
3591 SQLITE_OPEN_TRANSIENT_DB;
3592 assert( pOp->p1>=0 );
3593 assert( pOp->p2>=0 );
3594 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
3595 if( pCx==0 ) goto no_mem;
3596 pCx->nullRow = 1;
3597 pCx->isEphemeral = 1;
3598 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
3599 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
3600 if( rc==SQLITE_OK ){
3601 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
3603 if( rc==SQLITE_OK ){
3604 /* If a transient index is required, create it by calling
3605 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3606 ** opening it. If a transient table is required, just use the
3607 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3609 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3610 int pgno;
3611 assert( pOp->p4type==P4_KEYINFO );
3612 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
3613 if( rc==SQLITE_OK ){
3614 assert( pgno==MASTER_ROOT+1 );
3615 assert( pKeyInfo->db==db );
3616 assert( pKeyInfo->enc==ENC(db) );
3617 rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
3618 pKeyInfo, pCx->uc.pCursor);
3620 pCx->isTable = 0;
3621 }else{
3622 rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
3623 0, pCx->uc.pCursor);
3624 pCx->isTable = 1;
3627 if( rc ) goto abort_due_to_error;
3628 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3629 break;
3632 /* Opcode: SorterOpen P1 P2 P3 P4 *
3634 ** This opcode works like OP_OpenEphemeral except that it opens
3635 ** a transient index that is specifically designed to sort large
3636 ** tables using an external merge-sort algorithm.
3638 ** If argument P3 is non-zero, then it indicates that the sorter may
3639 ** assume that a stable sort considering the first P3 fields of each
3640 ** key is sufficient to produce the required results.
3642 case OP_SorterOpen: {
3643 VdbeCursor *pCx;
3645 assert( pOp->p1>=0 );
3646 assert( pOp->p2>=0 );
3647 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
3648 if( pCx==0 ) goto no_mem;
3649 pCx->pKeyInfo = pOp->p4.pKeyInfo;
3650 assert( pCx->pKeyInfo->db==db );
3651 assert( pCx->pKeyInfo->enc==ENC(db) );
3652 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
3653 if( rc ) goto abort_due_to_error;
3654 break;
3657 /* Opcode: SequenceTest P1 P2 * * *
3658 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3660 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3661 ** to P2. Regardless of whether or not the jump is taken, increment the
3662 ** the sequence value.
3664 case OP_SequenceTest: {
3665 VdbeCursor *pC;
3666 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3667 pC = p->apCsr[pOp->p1];
3668 assert( isSorter(pC) );
3669 if( (pC->seqCount++)==0 ){
3670 goto jump_to_p2;
3672 break;
3675 /* Opcode: OpenPseudo P1 P2 P3 * *
3676 ** Synopsis: P3 columns in r[P2]
3678 ** Open a new cursor that points to a fake table that contains a single
3679 ** row of data. The content of that one row is the content of memory
3680 ** register P2. In other words, cursor P1 becomes an alias for the
3681 ** MEM_Blob content contained in register P2.
3683 ** A pseudo-table created by this opcode is used to hold a single
3684 ** row output from the sorter so that the row can be decomposed into
3685 ** individual columns using the OP_Column opcode. The OP_Column opcode
3686 ** is the only cursor opcode that works with a pseudo-table.
3688 ** P3 is the number of fields in the records that will be stored by
3689 ** the pseudo-table.
3691 case OP_OpenPseudo: {
3692 VdbeCursor *pCx;
3694 assert( pOp->p1>=0 );
3695 assert( pOp->p3>=0 );
3696 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
3697 if( pCx==0 ) goto no_mem;
3698 pCx->nullRow = 1;
3699 pCx->seekResult = pOp->p2;
3700 pCx->isTable = 1;
3701 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
3702 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
3703 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
3704 ** which is a performance optimization */
3705 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
3706 assert( pOp->p5==0 );
3707 break;
3710 /* Opcode: Close P1 * * * *
3712 ** Close a cursor previously opened as P1. If P1 is not
3713 ** currently open, this instruction is a no-op.
3715 case OP_Close: {
3716 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3717 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
3718 p->apCsr[pOp->p1] = 0;
3719 break;
3722 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3723 /* Opcode: ColumnsUsed P1 * * P4 *
3725 ** This opcode (which only exists if SQLite was compiled with
3726 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
3727 ** table or index for cursor P1 are used. P4 is a 64-bit integer
3728 ** (P4_INT64) in which the first 63 bits are one for each of the
3729 ** first 63 columns of the table or index that are actually used
3730 ** by the cursor. The high-order bit is set if any column after
3731 ** the 64th is used.
3733 case OP_ColumnsUsed: {
3734 VdbeCursor *pC;
3735 pC = p->apCsr[pOp->p1];
3736 assert( pC->eCurType==CURTYPE_BTREE );
3737 pC->maskUsed = *(u64*)pOp->p4.pI64;
3738 break;
3740 #endif
3742 /* Opcode: SeekGE P1 P2 P3 P4 *
3743 ** Synopsis: key=r[P3@P4]
3745 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3746 ** use the value in register P3 as the key. If cursor P1 refers
3747 ** to an SQL index, then P3 is the first in an array of P4 registers
3748 ** that are used as an unpacked index key.
3750 ** Reposition cursor P1 so that it points to the smallest entry that
3751 ** is greater than or equal to the key value. If there are no records
3752 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3754 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3755 ** opcode will always land on a record that equally equals the key, or
3756 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3757 ** opcode must be followed by an IdxLE opcode with the same arguments.
3758 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
3759 ** IdxLE opcode will be used on subsequent loop iterations.
3761 ** This opcode leaves the cursor configured to move in forward order,
3762 ** from the beginning toward the end. In other words, the cursor is
3763 ** configured to use Next, not Prev.
3765 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3767 /* Opcode: SeekGT P1 P2 P3 P4 *
3768 ** Synopsis: key=r[P3@P4]
3770 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3771 ** use the value in register P3 as a key. If cursor P1 refers
3772 ** to an SQL index, then P3 is the first in an array of P4 registers
3773 ** that are used as an unpacked index key.
3775 ** Reposition cursor P1 so that it points to the smallest entry that
3776 ** is greater than the key value. If there are no records greater than
3777 ** the key and P2 is not zero, then jump to P2.
3779 ** This opcode leaves the cursor configured to move in forward order,
3780 ** from the beginning toward the end. In other words, the cursor is
3781 ** configured to use Next, not Prev.
3783 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3785 /* Opcode: SeekLT 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 a 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 largest entry that
3794 ** is less than the key value. If there are no records less than
3795 ** the key and P2 is not zero, then jump to P2.
3797 ** This opcode leaves the cursor configured to move in reverse order,
3798 ** from the end toward the beginning. In other words, the cursor is
3799 ** configured to use Prev, not Next.
3801 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3803 /* Opcode: SeekLE P1 P2 P3 P4 *
3804 ** Synopsis: key=r[P3@P4]
3806 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3807 ** use the value in register P3 as a key. If cursor P1 refers
3808 ** to an SQL index, then P3 is the first in an array of P4 registers
3809 ** that are used as an unpacked index key.
3811 ** Reposition cursor P1 so that it points to the largest entry that
3812 ** is less than or equal to the key value. If there are no records
3813 ** less than or equal to the key and P2 is not zero, then jump to P2.
3815 ** This opcode leaves the cursor configured to move in reverse order,
3816 ** from the end toward the beginning. In other words, the cursor is
3817 ** configured to use Prev, not Next.
3819 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3820 ** opcode will always land on a record that equally equals the key, or
3821 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3822 ** opcode must be followed by an IdxGE opcode with the same arguments.
3823 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
3824 ** IdxGE opcode will be used on subsequent loop iterations.
3826 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3828 case OP_SeekLT: /* jump, in3 */
3829 case OP_SeekLE: /* jump, in3 */
3830 case OP_SeekGE: /* jump, in3 */
3831 case OP_SeekGT: { /* jump, in3 */
3832 int res; /* Comparison result */
3833 int oc; /* Opcode */
3834 VdbeCursor *pC; /* The cursor to seek */
3835 UnpackedRecord r; /* The key to seek for */
3836 int nField; /* Number of columns or fields in the key */
3837 i64 iKey; /* The rowid we are to seek to */
3838 int eqOnly; /* Only interested in == results */
3840 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3841 assert( pOp->p2!=0 );
3842 pC = p->apCsr[pOp->p1];
3843 assert( pC!=0 );
3844 assert( pC->eCurType==CURTYPE_BTREE );
3845 assert( OP_SeekLE == OP_SeekLT+1 );
3846 assert( OP_SeekGE == OP_SeekLT+2 );
3847 assert( OP_SeekGT == OP_SeekLT+3 );
3848 assert( pC->isOrdered );
3849 assert( pC->uc.pCursor!=0 );
3850 oc = pOp->opcode;
3851 eqOnly = 0;
3852 pC->nullRow = 0;
3853 #ifdef SQLITE_DEBUG
3854 pC->seekOp = pOp->opcode;
3855 #endif
3857 if( pC->isTable ){
3858 /* The BTREE_SEEK_EQ flag is only set on index cursors */
3859 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
3860 || CORRUPT_DB );
3862 /* The input value in P3 might be of any type: integer, real, string,
3863 ** blob, or NULL. But it needs to be an integer before we can do
3864 ** the seek, so convert it. */
3865 pIn3 = &aMem[pOp->p3];
3866 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
3867 applyNumericAffinity(pIn3, 0);
3869 iKey = sqlite3VdbeIntValue(pIn3);
3871 /* If the P3 value could not be converted into an integer without
3872 ** loss of information, then special processing is required... */
3873 if( (pIn3->flags & MEM_Int)==0 ){
3874 if( (pIn3->flags & MEM_Real)==0 ){
3875 /* If the P3 value cannot be converted into any kind of a number,
3876 ** then the seek is not possible, so jump to P2 */
3877 VdbeBranchTaken(1,2); goto jump_to_p2;
3878 break;
3881 /* If the approximation iKey is larger than the actual real search
3882 ** term, substitute >= for > and < for <=. e.g. if the search term
3883 ** is 4.9 and the integer approximation 5:
3885 ** (x > 4.9) -> (x >= 5)
3886 ** (x <= 4.9) -> (x < 5)
3888 if( pIn3->u.r<(double)iKey ){
3889 assert( OP_SeekGE==(OP_SeekGT-1) );
3890 assert( OP_SeekLT==(OP_SeekLE-1) );
3891 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
3892 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
3895 /* If the approximation iKey is smaller than the actual real search
3896 ** term, substitute <= for < and > for >=. */
3897 else if( pIn3->u.r>(double)iKey ){
3898 assert( OP_SeekLE==(OP_SeekLT+1) );
3899 assert( OP_SeekGT==(OP_SeekGE+1) );
3900 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
3901 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
3904 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
3905 pC->movetoTarget = iKey; /* Used by OP_Delete */
3906 if( rc!=SQLITE_OK ){
3907 goto abort_due_to_error;
3909 }else{
3910 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
3911 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
3912 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
3914 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
3915 eqOnly = 1;
3916 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
3917 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
3918 assert( pOp[1].p1==pOp[0].p1 );
3919 assert( pOp[1].p2==pOp[0].p2 );
3920 assert( pOp[1].p3==pOp[0].p3 );
3921 assert( pOp[1].p4.i==pOp[0].p4.i );
3924 nField = pOp->p4.i;
3925 assert( pOp->p4type==P4_INT32 );
3926 assert( nField>0 );
3927 r.pKeyInfo = pC->pKeyInfo;
3928 r.nField = (u16)nField;
3930 /* The next line of code computes as follows, only faster:
3931 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3932 ** r.default_rc = -1;
3933 ** }else{
3934 ** r.default_rc = +1;
3935 ** }
3937 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
3938 assert( oc!=OP_SeekGT || r.default_rc==-1 );
3939 assert( oc!=OP_SeekLE || r.default_rc==-1 );
3940 assert( oc!=OP_SeekGE || r.default_rc==+1 );
3941 assert( oc!=OP_SeekLT || r.default_rc==+1 );
3943 r.aMem = &aMem[pOp->p3];
3944 #ifdef SQLITE_DEBUG
3945 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3946 #endif
3947 r.eqSeen = 0;
3948 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
3949 if( rc!=SQLITE_OK ){
3950 goto abort_due_to_error;
3952 if( eqOnly && r.eqSeen==0 ){
3953 assert( res!=0 );
3954 goto seek_not_found;
3957 pC->deferredMoveto = 0;
3958 pC->cacheStatus = CACHE_STALE;
3959 #ifdef SQLITE_TEST
3960 sqlite3_search_count++;
3961 #endif
3962 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
3963 if( res<0 || (res==0 && oc==OP_SeekGT) ){
3964 res = 0;
3965 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
3966 if( rc!=SQLITE_OK ){
3967 if( rc==SQLITE_DONE ){
3968 rc = SQLITE_OK;
3969 res = 1;
3970 }else{
3971 goto abort_due_to_error;
3974 }else{
3975 res = 0;
3977 }else{
3978 assert( oc==OP_SeekLT || oc==OP_SeekLE );
3979 if( res>0 || (res==0 && oc==OP_SeekLT) ){
3980 res = 0;
3981 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
3982 if( rc!=SQLITE_OK ){
3983 if( rc==SQLITE_DONE ){
3984 rc = SQLITE_OK;
3985 res = 1;
3986 }else{
3987 goto abort_due_to_error;
3990 }else{
3991 /* res might be negative because the table is empty. Check to
3992 ** see if this is the case.
3994 res = sqlite3BtreeEof(pC->uc.pCursor);
3997 seek_not_found:
3998 assert( pOp->p2>0 );
3999 VdbeBranchTaken(res!=0,2);
4000 if( res ){
4001 goto jump_to_p2;
4002 }else if( eqOnly ){
4003 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4004 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4006 break;
4009 /* Opcode: Found P1 P2 P3 P4 *
4010 ** Synopsis: key=r[P3@P4]
4012 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4013 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4014 ** record.
4016 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4017 ** is a prefix of any entry in P1 then a jump is made to P2 and
4018 ** P1 is left pointing at the matching entry.
4020 ** This operation leaves the cursor in a state where it can be
4021 ** advanced in the forward direction. The Next instruction will work,
4022 ** but not the Prev instruction.
4024 ** See also: NotFound, NoConflict, NotExists. SeekGe
4026 /* Opcode: NotFound P1 P2 P3 P4 *
4027 ** Synopsis: key=r[P3@P4]
4029 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4030 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4031 ** record.
4033 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4034 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
4035 ** does contain an entry whose prefix matches the P3/P4 record then control
4036 ** falls through to the next instruction and P1 is left pointing at the
4037 ** matching entry.
4039 ** This operation leaves the cursor in a state where it cannot be
4040 ** advanced in either direction. In other words, the Next and Prev
4041 ** opcodes do not work after this operation.
4043 ** See also: Found, NotExists, NoConflict
4045 /* Opcode: NoConflict P1 P2 P3 P4 *
4046 ** Synopsis: key=r[P3@P4]
4048 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4049 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4050 ** record.
4052 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4053 ** contains any NULL value, jump immediately to P2. If all terms of the
4054 ** record are not-NULL then a check is done to determine if any row in the
4055 ** P1 index btree has a matching key prefix. If there are no matches, jump
4056 ** immediately to P2. If there is a match, fall through and leave the P1
4057 ** cursor pointing to the matching row.
4059 ** This opcode is similar to OP_NotFound with the exceptions that the
4060 ** branch is always taken if any part of the search key input is NULL.
4062 ** This operation leaves the cursor in a state where it cannot be
4063 ** advanced in either direction. In other words, the Next and Prev
4064 ** opcodes do not work after this operation.
4066 ** See also: NotFound, Found, NotExists
4068 case OP_NoConflict: /* jump, in3 */
4069 case OP_NotFound: /* jump, in3 */
4070 case OP_Found: { /* jump, in3 */
4071 int alreadyExists;
4072 int takeJump;
4073 int ii;
4074 VdbeCursor *pC;
4075 int res;
4076 UnpackedRecord *pFree;
4077 UnpackedRecord *pIdxKey;
4078 UnpackedRecord r;
4080 #ifdef SQLITE_TEST
4081 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4082 #endif
4084 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4085 assert( pOp->p4type==P4_INT32 );
4086 pC = p->apCsr[pOp->p1];
4087 assert( pC!=0 );
4088 #ifdef SQLITE_DEBUG
4089 pC->seekOp = pOp->opcode;
4090 #endif
4091 pIn3 = &aMem[pOp->p3];
4092 assert( pC->eCurType==CURTYPE_BTREE );
4093 assert( pC->uc.pCursor!=0 );
4094 assert( pC->isTable==0 );
4095 if( pOp->p4.i>0 ){
4096 r.pKeyInfo = pC->pKeyInfo;
4097 r.nField = (u16)pOp->p4.i;
4098 r.aMem = pIn3;
4099 #ifdef SQLITE_DEBUG
4100 for(ii=0; ii<r.nField; ii++){
4101 assert( memIsValid(&r.aMem[ii]) );
4102 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4103 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4105 #endif
4106 pIdxKey = &r;
4107 pFree = 0;
4108 }else{
4109 assert( pIn3->flags & MEM_Blob );
4110 rc = ExpandBlob(pIn3);
4111 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4112 if( rc ) goto no_mem;
4113 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4114 if( pIdxKey==0 ) goto no_mem;
4115 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4117 pIdxKey->default_rc = 0;
4118 takeJump = 0;
4119 if( pOp->opcode==OP_NoConflict ){
4120 /* For the OP_NoConflict opcode, take the jump if any of the
4121 ** input fields are NULL, since any key with a NULL will not
4122 ** conflict */
4123 for(ii=0; ii<pIdxKey->nField; ii++){
4124 if( pIdxKey->aMem[ii].flags & MEM_Null ){
4125 takeJump = 1;
4126 break;
4130 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
4131 if( pFree ) sqlite3DbFreeNN(db, pFree);
4132 if( rc!=SQLITE_OK ){
4133 goto abort_due_to_error;
4135 pC->seekResult = res;
4136 alreadyExists = (res==0);
4137 pC->nullRow = 1-alreadyExists;
4138 pC->deferredMoveto = 0;
4139 pC->cacheStatus = CACHE_STALE;
4140 if( pOp->opcode==OP_Found ){
4141 VdbeBranchTaken(alreadyExists!=0,2);
4142 if( alreadyExists ) goto jump_to_p2;
4143 }else{
4144 VdbeBranchTaken(takeJump||alreadyExists==0,2);
4145 if( takeJump || !alreadyExists ) goto jump_to_p2;
4147 break;
4150 /* Opcode: SeekRowid P1 P2 P3 * *
4151 ** Synopsis: intkey=r[P3]
4153 ** P1 is the index of a cursor open on an SQL table btree (with integer
4154 ** keys). If register P3 does not contain an integer or if P1 does not
4155 ** contain a record with rowid P3 then jump immediately to P2.
4156 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4157 ** a record with rowid P3 then
4158 ** leave the cursor pointing at that record and fall through to the next
4159 ** instruction.
4161 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4162 ** the P3 register must be guaranteed to contain an integer value. With this
4163 ** opcode, register P3 might not contain an integer.
4165 ** The OP_NotFound opcode performs the same operation on index btrees
4166 ** (with arbitrary multi-value keys).
4168 ** This opcode leaves the cursor in a state where it cannot be advanced
4169 ** in either direction. In other words, the Next and Prev opcodes will
4170 ** not work following this opcode.
4172 ** See also: Found, NotFound, NoConflict, SeekRowid
4174 /* Opcode: NotExists P1 P2 P3 * *
4175 ** Synopsis: intkey=r[P3]
4177 ** P1 is the index of a cursor open on an SQL table btree (with integer
4178 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4179 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4180 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4181 ** leave the cursor pointing at that record and fall through to the next
4182 ** instruction.
4184 ** The OP_SeekRowid opcode performs the same operation but also allows the
4185 ** P3 register to contain a non-integer value, in which case the jump is
4186 ** always taken. This opcode requires that P3 always contain an integer.
4188 ** The OP_NotFound opcode performs the same operation on index btrees
4189 ** (with arbitrary multi-value keys).
4191 ** This opcode leaves the cursor in a state where it cannot be advanced
4192 ** in either direction. In other words, the Next and Prev opcodes will
4193 ** not work following this opcode.
4195 ** See also: Found, NotFound, NoConflict, SeekRowid
4197 case OP_SeekRowid: { /* jump, in3 */
4198 VdbeCursor *pC;
4199 BtCursor *pCrsr;
4200 int res;
4201 u64 iKey;
4203 pIn3 = &aMem[pOp->p3];
4204 if( (pIn3->flags & MEM_Int)==0 ){
4205 applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
4206 if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
4208 /* Fall through into OP_NotExists */
4209 case OP_NotExists: /* jump, in3 */
4210 pIn3 = &aMem[pOp->p3];
4211 assert( pIn3->flags & MEM_Int );
4212 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4213 pC = p->apCsr[pOp->p1];
4214 assert( pC!=0 );
4215 #ifdef SQLITE_DEBUG
4216 pC->seekOp = 0;
4217 #endif
4218 assert( pC->isTable );
4219 assert( pC->eCurType==CURTYPE_BTREE );
4220 pCrsr = pC->uc.pCursor;
4221 assert( pCrsr!=0 );
4222 res = 0;
4223 iKey = pIn3->u.i;
4224 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
4225 assert( rc==SQLITE_OK || res==0 );
4226 pC->movetoTarget = iKey; /* Used by OP_Delete */
4227 pC->nullRow = 0;
4228 pC->cacheStatus = CACHE_STALE;
4229 pC->deferredMoveto = 0;
4230 VdbeBranchTaken(res!=0,2);
4231 pC->seekResult = res;
4232 if( res!=0 ){
4233 assert( rc==SQLITE_OK );
4234 if( pOp->p2==0 ){
4235 rc = SQLITE_CORRUPT_BKPT;
4236 }else{
4237 goto jump_to_p2;
4240 if( rc ) goto abort_due_to_error;
4241 break;
4244 /* Opcode: Sequence P1 P2 * * *
4245 ** Synopsis: r[P2]=cursor[P1].ctr++
4247 ** Find the next available sequence number for cursor P1.
4248 ** Write the sequence number into register P2.
4249 ** The sequence number on the cursor is incremented after this
4250 ** instruction.
4252 case OP_Sequence: { /* out2 */
4253 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4254 assert( p->apCsr[pOp->p1]!=0 );
4255 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
4256 pOut = out2Prerelease(p, pOp);
4257 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
4258 break;
4262 /* Opcode: NewRowid P1 P2 P3 * *
4263 ** Synopsis: r[P2]=rowid
4265 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4266 ** The record number is not previously used as a key in the database
4267 ** table that cursor P1 points to. The new record number is written
4268 ** written to register P2.
4270 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4271 ** the largest previously generated record number. No new record numbers are
4272 ** allowed to be less than this value. When this value reaches its maximum,
4273 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4274 ** generated record number. This P3 mechanism is used to help implement the
4275 ** AUTOINCREMENT feature.
4277 case OP_NewRowid: { /* out2 */
4278 i64 v; /* The new rowid */
4279 VdbeCursor *pC; /* Cursor of table to get the new rowid */
4280 int res; /* Result of an sqlite3BtreeLast() */
4281 int cnt; /* Counter to limit the number of searches */
4282 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
4283 VdbeFrame *pFrame; /* Root frame of VDBE */
4285 v = 0;
4286 res = 0;
4287 pOut = out2Prerelease(p, pOp);
4288 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4289 pC = p->apCsr[pOp->p1];
4290 if( !pC->isTable ){
4291 rc = SQLITE_CORRUPT_BKPT;
4292 goto abort_due_to_error;
4294 assert( pC!=0 );
4295 assert( pC->eCurType==CURTYPE_BTREE );
4296 assert( pC->uc.pCursor!=0 );
4298 /* The next rowid or record number (different terms for the same
4299 ** thing) is obtained in a two-step algorithm.
4301 ** First we attempt to find the largest existing rowid and add one
4302 ** to that. But if the largest existing rowid is already the maximum
4303 ** positive integer, we have to fall through to the second
4304 ** probabilistic algorithm
4306 ** The second algorithm is to select a rowid at random and see if
4307 ** it already exists in the table. If it does not exist, we have
4308 ** succeeded. If the random rowid does exist, we select a new one
4309 ** and try again, up to 100 times.
4311 assert( pC->isTable );
4313 #ifdef SQLITE_32BIT_ROWID
4314 # define MAX_ROWID 0x7fffffff
4315 #else
4316 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4317 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4318 ** to provide the constant while making all compilers happy.
4320 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4321 #endif
4323 if( !pC->useRandomRowid ){
4324 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4325 if( rc!=SQLITE_OK ){
4326 goto abort_due_to_error;
4328 if( res ){
4329 v = 1; /* IMP: R-61914-48074 */
4330 }else{
4331 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
4332 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4333 if( v>=MAX_ROWID ){
4334 pC->useRandomRowid = 1;
4335 }else{
4336 v++; /* IMP: R-29538-34987 */
4341 #ifndef SQLITE_OMIT_AUTOINCREMENT
4342 if( pOp->p3 ){
4343 /* Assert that P3 is a valid memory cell. */
4344 assert( pOp->p3>0 );
4345 if( p->pFrame ){
4346 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4347 /* Assert that P3 is a valid memory cell. */
4348 assert( pOp->p3<=pFrame->nMem );
4349 pMem = &pFrame->aMem[pOp->p3];
4350 }else{
4351 /* Assert that P3 is a valid memory cell. */
4352 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
4353 pMem = &aMem[pOp->p3];
4354 memAboutToChange(p, pMem);
4356 assert( memIsValid(pMem) );
4358 REGISTER_TRACE(pOp->p3, pMem);
4359 sqlite3VdbeMemIntegerify(pMem);
4360 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
4361 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4362 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
4363 goto abort_due_to_error;
4365 if( v<pMem->u.i+1 ){
4366 v = pMem->u.i + 1;
4368 pMem->u.i = v;
4370 #endif
4371 if( pC->useRandomRowid ){
4372 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4373 ** largest possible integer (9223372036854775807) then the database
4374 ** engine starts picking positive candidate ROWIDs at random until
4375 ** it finds one that is not previously used. */
4376 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
4377 ** an AUTOINCREMENT table. */
4378 cnt = 0;
4380 sqlite3_randomness(sizeof(v), &v);
4381 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
4382 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
4383 0, &res))==SQLITE_OK)
4384 && (res==0)
4385 && (++cnt<100));
4386 if( rc ) goto abort_due_to_error;
4387 if( res==0 ){
4388 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
4389 goto abort_due_to_error;
4391 assert( v>0 ); /* EV: R-40812-03570 */
4393 pC->deferredMoveto = 0;
4394 pC->cacheStatus = CACHE_STALE;
4396 pOut->u.i = v;
4397 break;
4400 /* Opcode: Insert P1 P2 P3 P4 P5
4401 ** Synopsis: intkey=r[P3] data=r[P2]
4403 ** Write an entry into the table of cursor P1. A new entry is
4404 ** created if it doesn't already exist or the data for an existing
4405 ** entry is overwritten. The data is the value MEM_Blob stored in register
4406 ** number P2. The key is stored in register P3. The key must
4407 ** be a MEM_Int.
4409 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4410 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
4411 ** then rowid is stored for subsequent return by the
4412 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4414 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
4415 ** run faster by avoiding an unnecessary seek on cursor P1. However,
4416 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
4417 ** seeks on the cursor or if the most recent seek used a key equal to P3.
4419 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4420 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
4421 ** is part of an INSERT operation. The difference is only important to
4422 ** the update hook.
4424 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
4425 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
4426 ** following a successful insert.
4428 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4429 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4430 ** and register P2 becomes ephemeral. If the cursor is changed, the
4431 ** value of register P2 will then change. Make sure this does not
4432 ** cause any problems.)
4434 ** This instruction only works on tables. The equivalent instruction
4435 ** for indices is OP_IdxInsert.
4437 /* Opcode: InsertInt P1 P2 P3 P4 P5
4438 ** Synopsis: intkey=P3 data=r[P2]
4440 ** This works exactly like OP_Insert except that the key is the
4441 ** integer value P3, not the value of the integer stored in register P3.
4443 case OP_Insert:
4444 case OP_InsertInt: {
4445 Mem *pData; /* MEM cell holding data for the record to be inserted */
4446 Mem *pKey; /* MEM cell holding key for the record */
4447 VdbeCursor *pC; /* Cursor to table into which insert is written */
4448 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
4449 const char *zDb; /* database name - used by the update hook */
4450 Table *pTab; /* Table structure - used by update and pre-update hooks */
4451 BtreePayload x; /* Payload to be inserted */
4453 pData = &aMem[pOp->p2];
4454 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4455 assert( memIsValid(pData) );
4456 pC = p->apCsr[pOp->p1];
4457 assert( pC!=0 );
4458 assert( pC->eCurType==CURTYPE_BTREE );
4459 assert( pC->uc.pCursor!=0 );
4460 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
4461 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
4462 REGISTER_TRACE(pOp->p2, pData);
4464 if( pOp->opcode==OP_Insert ){
4465 pKey = &aMem[pOp->p3];
4466 assert( pKey->flags & MEM_Int );
4467 assert( memIsValid(pKey) );
4468 REGISTER_TRACE(pOp->p3, pKey);
4469 x.nKey = pKey->u.i;
4470 }else{
4471 assert( pOp->opcode==OP_InsertInt );
4472 x.nKey = pOp->p3;
4475 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4476 assert( pC->iDb>=0 );
4477 zDb = db->aDb[pC->iDb].zDbSName;
4478 pTab = pOp->p4.pTab;
4479 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
4480 }else{
4481 pTab = 0;
4482 zDb = 0; /* Not needed. Silence a compiler warning. */
4485 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4486 /* Invoke the pre-update hook, if any */
4487 if( pTab ){
4488 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
4489 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
4491 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
4492 /* Prevent post-update hook from running in cases when it should not */
4493 pTab = 0;
4496 if( pOp->p5 & OPFLAG_ISNOOP ) break;
4497 #endif
4499 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4500 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
4501 assert( pData->flags & (MEM_Blob|MEM_Str) );
4502 x.pData = pData->z;
4503 x.nData = pData->n;
4504 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
4505 if( pData->flags & MEM_Zero ){
4506 x.nZero = pData->u.nZero;
4507 }else{
4508 x.nZero = 0;
4510 x.pKey = 0;
4511 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
4512 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
4514 pC->deferredMoveto = 0;
4515 pC->cacheStatus = CACHE_STALE;
4517 /* Invoke the update-hook if required. */
4518 if( rc ) goto abort_due_to_error;
4519 if( pTab ){
4520 assert( db->xUpdateCallback!=0 );
4521 assert( pTab->aCol!=0 );
4522 db->xUpdateCallback(db->pUpdateArg,
4523 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
4524 zDb, pTab->zName, x.nKey);
4526 break;
4529 /* Opcode: Delete P1 P2 P3 P4 P5
4531 ** Delete the record at which the P1 cursor is currently pointing.
4533 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
4534 ** the cursor will be left pointing at either the next or the previous
4535 ** record in the table. If it is left pointing at the next record, then
4536 ** the next Next instruction will be a no-op. As a result, in this case
4537 ** it is ok to delete a record from within a Next loop. If
4538 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
4539 ** left in an undefined state.
4541 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
4542 ** delete one of several associated with deleting a table row and all its
4543 ** associated index entries. Exactly one of those deletes is the "primary"
4544 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
4545 ** marked with the AUXDELETE flag.
4547 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
4548 ** change count is incremented (otherwise not).
4550 ** P1 must not be pseudo-table. It has to be a real table with
4551 ** multiple rows.
4553 ** If P4 is not NULL then it points to a Table object. In this case either
4554 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
4555 ** have been positioned using OP_NotFound prior to invoking this opcode in
4556 ** this case. Specifically, if one is configured, the pre-update hook is
4557 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
4558 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
4560 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
4561 ** of the memory cell that contains the value that the rowid of the row will
4562 ** be set to by the update.
4564 case OP_Delete: {
4565 VdbeCursor *pC;
4566 const char *zDb;
4567 Table *pTab;
4568 int opflags;
4570 opflags = pOp->p2;
4571 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4572 pC = p->apCsr[pOp->p1];
4573 assert( pC!=0 );
4574 assert( pC->eCurType==CURTYPE_BTREE );
4575 assert( pC->uc.pCursor!=0 );
4576 assert( pC->deferredMoveto==0 );
4578 #ifdef SQLITE_DEBUG
4579 if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
4580 /* If p5 is zero, the seek operation that positioned the cursor prior to
4581 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
4582 ** the row that is being deleted */
4583 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4584 assert( pC->movetoTarget==iKey );
4586 #endif
4588 /* If the update-hook or pre-update-hook will be invoked, set zDb to
4589 ** the name of the db to pass as to it. Also set local pTab to a copy
4590 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
4591 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
4592 ** VdbeCursor.movetoTarget to the current rowid. */
4593 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4594 assert( pC->iDb>=0 );
4595 assert( pOp->p4.pTab!=0 );
4596 zDb = db->aDb[pC->iDb].zDbSName;
4597 pTab = pOp->p4.pTab;
4598 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
4599 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4601 }else{
4602 zDb = 0; /* Not needed. Silence a compiler warning. */
4603 pTab = 0; /* Not needed. Silence a compiler warning. */
4606 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4607 /* Invoke the pre-update-hook if required. */
4608 if( db->xPreUpdateCallback && pOp->p4.pTab ){
4609 assert( !(opflags & OPFLAG_ISUPDATE)
4610 || HasRowid(pTab)==0
4611 || (aMem[pOp->p3].flags & MEM_Int)
4613 sqlite3VdbePreUpdateHook(p, pC,
4614 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
4615 zDb, pTab, pC->movetoTarget,
4616 pOp->p3
4619 if( opflags & OPFLAG_ISNOOP ) break;
4620 #endif
4622 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
4623 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
4624 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
4625 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
4627 #ifdef SQLITE_DEBUG
4628 if( p->pFrame==0 ){
4629 if( pC->isEphemeral==0
4630 && (pOp->p5 & OPFLAG_AUXDELETE)==0
4631 && (pC->wrFlag & OPFLAG_FORDELETE)==0
4633 nExtraDelete++;
4635 if( pOp->p2 & OPFLAG_NCHANGE ){
4636 nExtraDelete--;
4639 #endif
4641 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
4642 pC->cacheStatus = CACHE_STALE;
4643 pC->seekResult = 0;
4644 if( rc ) goto abort_due_to_error;
4646 /* Invoke the update-hook if required. */
4647 if( opflags & OPFLAG_NCHANGE ){
4648 p->nChange++;
4649 if( db->xUpdateCallback && HasRowid(pTab) ){
4650 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
4651 pC->movetoTarget);
4652 assert( pC->iDb>=0 );
4656 break;
4658 /* Opcode: ResetCount * * * * *
4660 ** The value of the change counter is copied to the database handle
4661 ** change counter (returned by subsequent calls to sqlite3_changes()).
4662 ** Then the VMs internal change counter resets to 0.
4663 ** This is used by trigger programs.
4665 case OP_ResetCount: {
4666 sqlite3VdbeSetChanges(db, p->nChange);
4667 p->nChange = 0;
4668 break;
4671 /* Opcode: SorterCompare P1 P2 P3 P4
4672 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4674 ** P1 is a sorter cursor. This instruction compares a prefix of the
4675 ** record blob in register P3 against a prefix of the entry that
4676 ** the sorter cursor currently points to. Only the first P4 fields
4677 ** of r[P3] and the sorter record are compared.
4679 ** If either P3 or the sorter contains a NULL in one of their significant
4680 ** fields (not counting the P4 fields at the end which are ignored) then
4681 ** the comparison is assumed to be equal.
4683 ** Fall through to next instruction if the two records compare equal to
4684 ** each other. Jump to P2 if they are different.
4686 case OP_SorterCompare: {
4687 VdbeCursor *pC;
4688 int res;
4689 int nKeyCol;
4691 pC = p->apCsr[pOp->p1];
4692 assert( isSorter(pC) );
4693 assert( pOp->p4type==P4_INT32 );
4694 pIn3 = &aMem[pOp->p3];
4695 nKeyCol = pOp->p4.i;
4696 res = 0;
4697 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
4698 VdbeBranchTaken(res!=0,2);
4699 if( rc ) goto abort_due_to_error;
4700 if( res ) goto jump_to_p2;
4701 break;
4704 /* Opcode: SorterData P1 P2 P3 * *
4705 ** Synopsis: r[P2]=data
4707 ** Write into register P2 the current sorter data for sorter cursor P1.
4708 ** Then clear the column header cache on cursor P3.
4710 ** This opcode is normally use to move a record out of the sorter and into
4711 ** a register that is the source for a pseudo-table cursor created using
4712 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4713 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4714 ** us from having to issue a separate NullRow instruction to clear that cache.
4716 case OP_SorterData: {
4717 VdbeCursor *pC;
4719 pOut = &aMem[pOp->p2];
4720 pC = p->apCsr[pOp->p1];
4721 assert( isSorter(pC) );
4722 rc = sqlite3VdbeSorterRowkey(pC, pOut);
4723 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
4724 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4725 if( rc ) goto abort_due_to_error;
4726 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
4727 break;
4730 /* Opcode: RowData P1 P2 P3 * *
4731 ** Synopsis: r[P2]=data
4733 ** Write into register P2 the complete row content for the row at
4734 ** which cursor P1 is currently pointing.
4735 ** There is no interpretation of the data.
4736 ** It is just copied onto the P2 register exactly as
4737 ** it is found in the database file.
4739 ** If cursor P1 is an index, then the content is the key of the row.
4740 ** If cursor P2 is a table, then the content extracted is the data.
4742 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4743 ** of a real table, not a pseudo-table.
4745 ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
4746 ** into the database page. That means that the content of the output
4747 ** register will be invalidated as soon as the cursor moves - including
4748 ** moves caused by other cursors that "save" the the current cursors
4749 ** position in order that they can write to the same table. If P3==0
4750 ** then a copy of the data is made into memory. P3!=0 is faster, but
4751 ** P3==0 is safer.
4753 ** If P3!=0 then the content of the P2 register is unsuitable for use
4754 ** in OP_Result and any OP_Result will invalidate the P2 register content.
4755 ** The P2 register content is invalidated by opcodes like OP_Function or
4756 ** by any use of another cursor pointing to the same table.
4758 case OP_RowData: {
4759 VdbeCursor *pC;
4760 BtCursor *pCrsr;
4761 u32 n;
4763 pOut = out2Prerelease(p, pOp);
4765 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4766 pC = p->apCsr[pOp->p1];
4767 assert( pC!=0 );
4768 assert( pC->eCurType==CURTYPE_BTREE );
4769 assert( isSorter(pC)==0 );
4770 assert( pC->nullRow==0 );
4771 assert( pC->uc.pCursor!=0 );
4772 pCrsr = pC->uc.pCursor;
4774 /* The OP_RowData opcodes always follow OP_NotExists or
4775 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
4776 ** that might invalidate the cursor.
4777 ** If this where not the case, on of the following assert()s
4778 ** would fail. Should this ever change (because of changes in the code
4779 ** generator) then the fix would be to insert a call to
4780 ** sqlite3VdbeCursorMoveto().
4782 assert( pC->deferredMoveto==0 );
4783 assert( sqlite3BtreeCursorIsValid(pCrsr) );
4784 #if 0 /* Not required due to the previous to assert() statements */
4785 rc = sqlite3VdbeCursorMoveto(pC);
4786 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4787 #endif
4789 n = sqlite3BtreePayloadSize(pCrsr);
4790 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
4791 goto too_big;
4793 testcase( n==0 );
4794 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
4795 if( rc ) goto abort_due_to_error;
4796 if( !pOp->p3 ) Deephemeralize(pOut);
4797 UPDATE_MAX_BLOBSIZE(pOut);
4798 REGISTER_TRACE(pOp->p2, pOut);
4799 break;
4802 /* Opcode: Rowid P1 P2 * * *
4803 ** Synopsis: r[P2]=rowid
4805 ** Store in register P2 an integer which is the key of the table entry that
4806 ** P1 is currently point to.
4808 ** P1 can be either an ordinary table or a virtual table. There used to
4809 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4810 ** one opcode now works for both table types.
4812 case OP_Rowid: { /* out2 */
4813 VdbeCursor *pC;
4814 i64 v;
4815 sqlite3_vtab *pVtab;
4816 const sqlite3_module *pModule;
4818 pOut = out2Prerelease(p, pOp);
4819 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4820 pC = p->apCsr[pOp->p1];
4821 assert( pC!=0 );
4822 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
4823 if( pC->nullRow ){
4824 pOut->flags = MEM_Null;
4825 break;
4826 }else if( pC->deferredMoveto ){
4827 v = pC->movetoTarget;
4828 #ifndef SQLITE_OMIT_VIRTUALTABLE
4829 }else if( pC->eCurType==CURTYPE_VTAB ){
4830 assert( pC->uc.pVCur!=0 );
4831 pVtab = pC->uc.pVCur->pVtab;
4832 pModule = pVtab->pModule;
4833 assert( pModule->xRowid );
4834 rc = pModule->xRowid(pC->uc.pVCur, &v);
4835 sqlite3VtabImportErrmsg(p, pVtab);
4836 if( rc ) goto abort_due_to_error;
4837 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4838 }else{
4839 assert( pC->eCurType==CURTYPE_BTREE );
4840 assert( pC->uc.pCursor!=0 );
4841 rc = sqlite3VdbeCursorRestore(pC);
4842 if( rc ) goto abort_due_to_error;
4843 if( pC->nullRow ){
4844 pOut->flags = MEM_Null;
4845 break;
4847 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4849 pOut->u.i = v;
4850 break;
4853 /* Opcode: NullRow P1 * * * *
4855 ** Move the cursor P1 to a null row. Any OP_Column operations
4856 ** that occur while the cursor is on the null row will always
4857 ** write a NULL.
4859 case OP_NullRow: {
4860 VdbeCursor *pC;
4862 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4863 pC = p->apCsr[pOp->p1];
4864 assert( pC!=0 );
4865 pC->nullRow = 1;
4866 pC->cacheStatus = CACHE_STALE;
4867 if( pC->eCurType==CURTYPE_BTREE ){
4868 assert( pC->uc.pCursor!=0 );
4869 sqlite3BtreeClearCursor(pC->uc.pCursor);
4871 break;
4874 /* Opcode: SeekEnd P1 * * * *
4876 ** Position cursor P1 at the end of the btree for the purpose of
4877 ** appending a new entry onto the btree.
4879 ** It is assumed that the cursor is used only for appending and so
4880 ** if the cursor is valid, then the cursor must already be pointing
4881 ** at the end of the btree and so no changes are made to
4882 ** the cursor.
4884 /* Opcode: Last P1 P2 * * *
4886 ** The next use of the Rowid or Column or Prev instruction for P1
4887 ** will refer to the last entry in the database table or index.
4888 ** If the table or index is empty and P2>0, then jump immediately to P2.
4889 ** If P2 is 0 or if the table or index is not empty, fall through
4890 ** to the following instruction.
4892 ** This opcode leaves the cursor configured to move in reverse order,
4893 ** from the end toward the beginning. In other words, the cursor is
4894 ** configured to use Prev, not Next.
4896 case OP_SeekEnd:
4897 case OP_Last: { /* jump */
4898 VdbeCursor *pC;
4899 BtCursor *pCrsr;
4900 int res;
4902 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4903 pC = p->apCsr[pOp->p1];
4904 assert( pC!=0 );
4905 assert( pC->eCurType==CURTYPE_BTREE );
4906 pCrsr = pC->uc.pCursor;
4907 res = 0;
4908 assert( pCrsr!=0 );
4909 #ifdef SQLITE_DEBUG
4910 pC->seekOp = pOp->opcode;
4911 #endif
4912 if( pOp->opcode==OP_SeekEnd ){
4913 assert( pOp->p2==0 );
4914 pC->seekResult = -1;
4915 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
4916 break;
4919 rc = sqlite3BtreeLast(pCrsr, &res);
4920 pC->nullRow = (u8)res;
4921 pC->deferredMoveto = 0;
4922 pC->cacheStatus = CACHE_STALE;
4923 if( rc ) goto abort_due_to_error;
4924 if( pOp->p2>0 ){
4925 VdbeBranchTaken(res!=0,2);
4926 if( res ) goto jump_to_p2;
4928 break;
4931 /* Opcode: IfSmaller P1 P2 P3 * *
4933 ** Estimate the number of rows in the table P1. Jump to P2 if that
4934 ** estimate is less than approximately 2**(0.1*P3).
4936 case OP_IfSmaller: { /* jump */
4937 VdbeCursor *pC;
4938 BtCursor *pCrsr;
4939 int res;
4940 i64 sz;
4942 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4943 pC = p->apCsr[pOp->p1];
4944 assert( pC!=0 );
4945 pCrsr = pC->uc.pCursor;
4946 assert( pCrsr );
4947 rc = sqlite3BtreeFirst(pCrsr, &res);
4948 if( rc ) goto abort_due_to_error;
4949 if( res==0 ){
4950 sz = sqlite3BtreeRowCountEst(pCrsr);
4951 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
4953 VdbeBranchTaken(res!=0,2);
4954 if( res ) goto jump_to_p2;
4955 break;
4959 /* Opcode: SorterSort P1 P2 * * *
4961 ** After all records have been inserted into the Sorter object
4962 ** identified by P1, invoke this opcode to actually do the sorting.
4963 ** Jump to P2 if there are no records to be sorted.
4965 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
4966 ** for Sorter objects.
4968 /* Opcode: Sort P1 P2 * * *
4970 ** This opcode does exactly the same thing as OP_Rewind except that
4971 ** it increments an undocumented global variable used for testing.
4973 ** Sorting is accomplished by writing records into a sorting index,
4974 ** then rewinding that index and playing it back from beginning to
4975 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
4976 ** rewinding so that the global variable will be incremented and
4977 ** regression tests can determine whether or not the optimizer is
4978 ** correctly optimizing out sorts.
4980 case OP_SorterSort: /* jump */
4981 case OP_Sort: { /* jump */
4982 #ifdef SQLITE_TEST
4983 sqlite3_sort_count++;
4984 sqlite3_search_count--;
4985 #endif
4986 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
4987 /* Fall through into OP_Rewind */
4989 /* Opcode: Rewind P1 P2 * * *
4991 ** The next use of the Rowid or Column or Next instruction for P1
4992 ** will refer to the first entry in the database table or index.
4993 ** If the table or index is empty, jump immediately to P2.
4994 ** If the table or index is not empty, fall through to the following
4995 ** instruction.
4997 ** This opcode leaves the cursor configured to move in forward order,
4998 ** from the beginning toward the end. In other words, the cursor is
4999 ** configured to use Next, not Prev.
5001 case OP_Rewind: { /* jump */
5002 VdbeCursor *pC;
5003 BtCursor *pCrsr;
5004 int res;
5006 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5007 pC = p->apCsr[pOp->p1];
5008 assert( pC!=0 );
5009 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5010 res = 1;
5011 #ifdef SQLITE_DEBUG
5012 pC->seekOp = OP_Rewind;
5013 #endif
5014 if( isSorter(pC) ){
5015 rc = sqlite3VdbeSorterRewind(pC, &res);
5016 }else{
5017 assert( pC->eCurType==CURTYPE_BTREE );
5018 pCrsr = pC->uc.pCursor;
5019 assert( pCrsr );
5020 rc = sqlite3BtreeFirst(pCrsr, &res);
5021 pC->deferredMoveto = 0;
5022 pC->cacheStatus = CACHE_STALE;
5024 if( rc ) goto abort_due_to_error;
5025 pC->nullRow = (u8)res;
5026 assert( pOp->p2>0 && pOp->p2<p->nOp );
5027 VdbeBranchTaken(res!=0,2);
5028 if( res ) goto jump_to_p2;
5029 break;
5032 /* Opcode: Next P1 P2 P3 P4 P5
5034 ** Advance cursor P1 so that it points to the next key/data pair in its
5035 ** table or index. If there are no more key/value pairs then fall through
5036 ** to the following instruction. But if the cursor advance was successful,
5037 ** jump immediately to P2.
5039 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5040 ** OP_Rewind opcode used to position the cursor. Next is not allowed
5041 ** to follow SeekLT, SeekLE, or OP_Last.
5043 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
5044 ** been opened prior to this opcode or the program will segfault.
5046 ** The P3 value is a hint to the btree implementation. If P3==1, that
5047 ** means P1 is an SQL index and that this instruction could have been
5048 ** omitted if that index had been unique. P3 is usually 0. P3 is
5049 ** always either 0 or 1.
5051 ** P4 is always of type P4_ADVANCE. The function pointer points to
5052 ** sqlite3BtreeNext().
5054 ** If P5 is positive and the jump is taken, then event counter
5055 ** number P5-1 in the prepared statement is incremented.
5057 ** See also: Prev, NextIfOpen
5059 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
5061 ** This opcode works just like Next except that if cursor P1 is not
5062 ** open it behaves a no-op.
5064 /* Opcode: Prev P1 P2 P3 P4 P5
5066 ** Back up cursor P1 so that it points to the previous key/data pair in its
5067 ** table or index. If there is no previous key/value pairs then fall through
5068 ** to the following instruction. But if the cursor backup was successful,
5069 ** jump immediately to P2.
5072 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5073 ** OP_Last opcode used to position the cursor. Prev is not allowed
5074 ** to follow SeekGT, SeekGE, or OP_Rewind.
5076 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
5077 ** not open then the behavior is undefined.
5079 ** The P3 value is a hint to the btree implementation. If P3==1, that
5080 ** means P1 is an SQL index and that this instruction could have been
5081 ** omitted if that index had been unique. P3 is usually 0. P3 is
5082 ** always either 0 or 1.
5084 ** P4 is always of type P4_ADVANCE. The function pointer points to
5085 ** sqlite3BtreePrevious().
5087 ** If P5 is positive and the jump is taken, then event counter
5088 ** number P5-1 in the prepared statement is incremented.
5090 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
5092 ** This opcode works just like Prev except that if cursor P1 is not
5093 ** open it behaves a no-op.
5095 /* Opcode: SorterNext P1 P2 * * P5
5097 ** This opcode works just like OP_Next except that P1 must be a
5098 ** sorter object for which the OP_SorterSort opcode has been
5099 ** invoked. This opcode advances the cursor to the next sorted
5100 ** record, or jumps to P2 if there are no more sorted records.
5102 case OP_SorterNext: { /* jump */
5103 VdbeCursor *pC;
5105 pC = p->apCsr[pOp->p1];
5106 assert( isSorter(pC) );
5107 rc = sqlite3VdbeSorterNext(db, pC);
5108 goto next_tail;
5109 case OP_PrevIfOpen: /* jump */
5110 case OP_NextIfOpen: /* jump */
5111 if( p->apCsr[pOp->p1]==0 ) break;
5112 /* Fall through */
5113 case OP_Prev: /* jump */
5114 case OP_Next: /* jump */
5115 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5116 assert( pOp->p5<ArraySize(p->aCounter) );
5117 pC = p->apCsr[pOp->p1];
5118 assert( pC!=0 );
5119 assert( pC->deferredMoveto==0 );
5120 assert( pC->eCurType==CURTYPE_BTREE );
5121 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5122 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5123 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
5124 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
5126 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
5127 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5128 assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
5129 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5130 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
5131 assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
5132 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5133 || pC->seekOp==OP_Last );
5135 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5136 next_tail:
5137 pC->cacheStatus = CACHE_STALE;
5138 VdbeBranchTaken(rc==SQLITE_OK,2);
5139 if( rc==SQLITE_OK ){
5140 pC->nullRow = 0;
5141 p->aCounter[pOp->p5]++;
5142 #ifdef SQLITE_TEST
5143 sqlite3_search_count++;
5144 #endif
5145 goto jump_to_p2_and_check_for_interrupt;
5147 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5148 rc = SQLITE_OK;
5149 pC->nullRow = 1;
5150 goto check_for_interrupt;
5153 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5154 ** Synopsis: key=r[P2]
5156 ** Register P2 holds an SQL index key made using the
5157 ** MakeRecord instructions. This opcode writes that key
5158 ** into the index P1. Data for the entry is nil.
5160 ** If P4 is not zero, then it is the number of values in the unpacked
5161 ** key of reg(P2). In that case, P3 is the index of the first register
5162 ** for the unpacked key. The availability of the unpacked key can sometimes
5163 ** be an optimization.
5165 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5166 ** that this insert is likely to be an append.
5168 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5169 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
5170 ** then the change counter is unchanged.
5172 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5173 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5174 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5175 ** seeks on the cursor or if the most recent seek used a key equivalent
5176 ** to P2.
5178 ** This instruction only works for indices. The equivalent instruction
5179 ** for tables is OP_Insert.
5181 /* Opcode: SorterInsert P1 P2 * * *
5182 ** Synopsis: key=r[P2]
5184 ** Register P2 holds an SQL index key made using the
5185 ** MakeRecord instructions. This opcode writes that key
5186 ** into the sorter P1. Data for the entry is nil.
5188 case OP_SorterInsert: /* in2 */
5189 case OP_IdxInsert: { /* in2 */
5190 VdbeCursor *pC;
5191 BtreePayload x;
5193 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5194 pC = p->apCsr[pOp->p1];
5195 assert( pC!=0 );
5196 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
5197 pIn2 = &aMem[pOp->p2];
5198 assert( pIn2->flags & MEM_Blob );
5199 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5200 assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
5201 assert( pC->isTable==0 );
5202 rc = ExpandBlob(pIn2);
5203 if( rc ) goto abort_due_to_error;
5204 if( pOp->opcode==OP_SorterInsert ){
5205 rc = sqlite3VdbeSorterWrite(pC, pIn2);
5206 }else{
5207 x.nKey = pIn2->n;
5208 x.pKey = pIn2->z;
5209 x.aMem = aMem + pOp->p3;
5210 x.nMem = (u16)pOp->p4.i;
5211 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5212 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
5213 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
5215 assert( pC->deferredMoveto==0 );
5216 pC->cacheStatus = CACHE_STALE;
5218 if( rc) goto abort_due_to_error;
5219 break;
5222 /* Opcode: IdxDelete P1 P2 P3 * *
5223 ** Synopsis: key=r[P2@P3]
5225 ** The content of P3 registers starting at register P2 form
5226 ** an unpacked index key. This opcode removes that entry from the
5227 ** index opened by cursor P1.
5229 case OP_IdxDelete: {
5230 VdbeCursor *pC;
5231 BtCursor *pCrsr;
5232 int res;
5233 UnpackedRecord r;
5235 assert( pOp->p3>0 );
5236 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
5237 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5238 pC = p->apCsr[pOp->p1];
5239 assert( pC!=0 );
5240 assert( pC->eCurType==CURTYPE_BTREE );
5241 pCrsr = pC->uc.pCursor;
5242 assert( pCrsr!=0 );
5243 assert( pOp->p5==0 );
5244 r.pKeyInfo = pC->pKeyInfo;
5245 r.nField = (u16)pOp->p3;
5246 r.default_rc = 0;
5247 r.aMem = &aMem[pOp->p2];
5248 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
5249 if( rc ) goto abort_due_to_error;
5250 if( res==0 ){
5251 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
5252 if( rc ) goto abort_due_to_error;
5254 assert( pC->deferredMoveto==0 );
5255 pC->cacheStatus = CACHE_STALE;
5256 pC->seekResult = 0;
5257 break;
5260 /* Opcode: DeferredSeek P1 * P3 P4 *
5261 ** Synopsis: Move P3 to P1.rowid if needed
5263 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5264 ** table. This opcode does a deferred seek of the P3 table cursor
5265 ** to the row that corresponds to the current row of P1.
5267 ** This is a deferred seek. Nothing actually happens until
5268 ** the cursor is used to read a record. That way, if no reads
5269 ** occur, no unnecessary I/O happens.
5271 ** P4 may be an array of integers (type P4_INTARRAY) containing
5272 ** one entry for each column in the P3 table. If array entry a(i)
5273 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5274 ** equivalent to performing the deferred seek and then reading column i
5275 ** from P1. This information is stored in P3 and used to redirect
5276 ** reads against P3 over to P1, thus possibly avoiding the need to
5277 ** seek and read cursor P3.
5279 /* Opcode: IdxRowid P1 P2 * * *
5280 ** Synopsis: r[P2]=rowid
5282 ** Write into register P2 an integer which is the last entry in the record at
5283 ** the end of the index key pointed to by cursor P1. This integer should be
5284 ** the rowid of the table entry to which this index entry points.
5286 ** See also: Rowid, MakeRecord.
5288 case OP_DeferredSeek:
5289 case OP_IdxRowid: { /* out2 */
5290 VdbeCursor *pC; /* The P1 index cursor */
5291 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
5292 i64 rowid; /* Rowid that P1 current points to */
5294 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5295 pC = p->apCsr[pOp->p1];
5296 assert( pC!=0 );
5297 assert( pC->eCurType==CURTYPE_BTREE );
5298 assert( pC->uc.pCursor!=0 );
5299 assert( pC->isTable==0 );
5300 assert( pC->deferredMoveto==0 );
5301 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
5303 /* The IdxRowid and Seek opcodes are combined because of the commonality
5304 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5305 rc = sqlite3VdbeCursorRestore(pC);
5307 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5308 ** out from under the cursor. That will never happens for an IdxRowid
5309 ** or Seek opcode */
5310 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
5312 if( !pC->nullRow ){
5313 rowid = 0; /* Not needed. Only used to silence a warning. */
5314 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
5315 if( rc!=SQLITE_OK ){
5316 goto abort_due_to_error;
5318 if( pOp->opcode==OP_DeferredSeek ){
5319 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
5320 pTabCur = p->apCsr[pOp->p3];
5321 assert( pTabCur!=0 );
5322 assert( pTabCur->eCurType==CURTYPE_BTREE );
5323 assert( pTabCur->uc.pCursor!=0 );
5324 assert( pTabCur->isTable );
5325 pTabCur->nullRow = 0;
5326 pTabCur->movetoTarget = rowid;
5327 pTabCur->deferredMoveto = 1;
5328 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
5329 pTabCur->aAltMap = pOp->p4.ai;
5330 pTabCur->pAltCursor = pC;
5331 }else{
5332 pOut = out2Prerelease(p, pOp);
5333 pOut->u.i = rowid;
5335 }else{
5336 assert( pOp->opcode==OP_IdxRowid );
5337 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
5339 break;
5342 /* Opcode: IdxGE P1 P2 P3 P4 P5
5343 ** Synopsis: key=r[P3@P4]
5345 ** The P4 register values beginning with P3 form an unpacked index
5346 ** key that omits the PRIMARY KEY. Compare this key value against the index
5347 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5348 ** fields at the end.
5350 ** If the P1 index entry is greater than or equal to the key value
5351 ** then jump to P2. Otherwise fall through to the next instruction.
5353 /* Opcode: IdxGT P1 P2 P3 P4 P5
5354 ** Synopsis: key=r[P3@P4]
5356 ** The P4 register values beginning with P3 form an unpacked index
5357 ** key that omits the PRIMARY KEY. Compare this key value against the index
5358 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5359 ** fields at the end.
5361 ** If the P1 index entry is greater than the key value
5362 ** then jump to P2. Otherwise fall through to the next instruction.
5364 /* Opcode: IdxLT P1 P2 P3 P4 P5
5365 ** Synopsis: key=r[P3@P4]
5367 ** The P4 register values beginning with P3 form an unpacked index
5368 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5369 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5370 ** ROWID on the P1 index.
5372 ** If the P1 index entry is less than the key value then jump to P2.
5373 ** Otherwise fall through to the next instruction.
5375 /* Opcode: IdxLE P1 P2 P3 P4 P5
5376 ** Synopsis: key=r[P3@P4]
5378 ** The P4 register values beginning with P3 form an unpacked index
5379 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5380 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5381 ** ROWID on the P1 index.
5383 ** If the P1 index entry is less than or equal to the key value then jump
5384 ** to P2. Otherwise fall through to the next instruction.
5386 case OP_IdxLE: /* jump */
5387 case OP_IdxGT: /* jump */
5388 case OP_IdxLT: /* jump */
5389 case OP_IdxGE: { /* jump */
5390 VdbeCursor *pC;
5391 int res;
5392 UnpackedRecord r;
5394 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5395 pC = p->apCsr[pOp->p1];
5396 assert( pC!=0 );
5397 assert( pC->isOrdered );
5398 assert( pC->eCurType==CURTYPE_BTREE );
5399 assert( pC->uc.pCursor!=0);
5400 assert( pC->deferredMoveto==0 );
5401 assert( pOp->p5==0 || pOp->p5==1 );
5402 assert( pOp->p4type==P4_INT32 );
5403 r.pKeyInfo = pC->pKeyInfo;
5404 r.nField = (u16)pOp->p4.i;
5405 if( pOp->opcode<OP_IdxLT ){
5406 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
5407 r.default_rc = -1;
5408 }else{
5409 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
5410 r.default_rc = 0;
5412 r.aMem = &aMem[pOp->p3];
5413 #ifdef SQLITE_DEBUG
5414 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
5415 #endif
5416 res = 0; /* Not needed. Only used to silence a warning. */
5417 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5418 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
5419 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
5420 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
5421 res = -res;
5422 }else{
5423 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
5424 res++;
5426 VdbeBranchTaken(res>0,2);
5427 if( rc ) goto abort_due_to_error;
5428 if( res>0 ) goto jump_to_p2;
5429 break;
5432 /* Opcode: Destroy P1 P2 P3 * *
5434 ** Delete an entire database table or index whose root page in the database
5435 ** file is given by P1.
5437 ** The table being destroyed is in the main database file if P3==0. If
5438 ** P3==1 then the table to be clear is in the auxiliary database file
5439 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5441 ** If AUTOVACUUM is enabled then it is possible that another root page
5442 ** might be moved into the newly deleted root page in order to keep all
5443 ** root pages contiguous at the beginning of the database. The former
5444 ** value of the root page that moved - its value before the move occurred -
5445 ** is stored in register P2. If no page movement was required (because the
5446 ** table being dropped was already the last one in the database) then a
5447 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
5448 ** is stored in register P2.
5450 ** This opcode throws an error if there are any active reader VMs when
5451 ** it is invoked. This is done to avoid the difficulty associated with
5452 ** updating existing cursors when a root page is moved in an AUTOVACUUM
5453 ** database. This error is thrown even if the database is not an AUTOVACUUM
5454 ** db in order to avoid introducing an incompatibility between autovacuum
5455 ** and non-autovacuum modes.
5457 ** See also: Clear
5459 case OP_Destroy: { /* out2 */
5460 int iMoved;
5461 int iDb;
5463 assert( p->readOnly==0 );
5464 assert( pOp->p1>1 );
5465 pOut = out2Prerelease(p, pOp);
5466 pOut->flags = MEM_Null;
5467 if( db->nVdbeRead > db->nVDestroy+1 ){
5468 rc = SQLITE_LOCKED;
5469 p->errorAction = OE_Abort;
5470 goto abort_due_to_error;
5471 }else{
5472 iDb = pOp->p3;
5473 assert( DbMaskTest(p->btreeMask, iDb) );
5474 iMoved = 0; /* Not needed. Only to silence a warning. */
5475 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
5476 pOut->flags = MEM_Int;
5477 pOut->u.i = iMoved;
5478 if( rc ) goto abort_due_to_error;
5479 #ifndef SQLITE_OMIT_AUTOVACUUM
5480 if( iMoved!=0 ){
5481 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
5482 /* All OP_Destroy operations occur on the same btree */
5483 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
5484 resetSchemaOnFault = iDb+1;
5486 #endif
5488 break;
5491 /* Opcode: Clear P1 P2 P3
5493 ** Delete all contents of the database table or index whose root page
5494 ** in the database file is given by P1. But, unlike Destroy, do not
5495 ** remove the table or index from the database file.
5497 ** The table being clear is in the main database file if P2==0. If
5498 ** P2==1 then the table to be clear is in the auxiliary database file
5499 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5501 ** If the P3 value is non-zero, then the table referred to must be an
5502 ** intkey table (an SQL table, not an index). In this case the row change
5503 ** count is incremented by the number of rows in the table being cleared.
5504 ** If P3 is greater than zero, then the value stored in register P3 is
5505 ** also incremented by the number of rows in the table being cleared.
5507 ** See also: Destroy
5509 case OP_Clear: {
5510 int nChange;
5512 nChange = 0;
5513 assert( p->readOnly==0 );
5514 assert( DbMaskTest(p->btreeMask, pOp->p2) );
5515 rc = sqlite3BtreeClearTable(
5516 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
5518 if( pOp->p3 ){
5519 p->nChange += nChange;
5520 if( pOp->p3>0 ){
5521 assert( memIsValid(&aMem[pOp->p3]) );
5522 memAboutToChange(p, &aMem[pOp->p3]);
5523 aMem[pOp->p3].u.i += nChange;
5526 if( rc ) goto abort_due_to_error;
5527 break;
5530 /* Opcode: ResetSorter P1 * * * *
5532 ** Delete all contents from the ephemeral table or sorter
5533 ** that is open on cursor P1.
5535 ** This opcode only works for cursors used for sorting and
5536 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5538 case OP_ResetSorter: {
5539 VdbeCursor *pC;
5541 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5542 pC = p->apCsr[pOp->p1];
5543 assert( pC!=0 );
5544 if( isSorter(pC) ){
5545 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
5546 }else{
5547 assert( pC->eCurType==CURTYPE_BTREE );
5548 assert( pC->isEphemeral );
5549 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
5550 if( rc ) goto abort_due_to_error;
5552 break;
5555 /* Opcode: CreateBtree P1 P2 P3 * *
5556 ** Synopsis: r[P2]=root iDb=P1 flags=P3
5558 ** Allocate a new b-tree in the main database file if P1==0 or in the
5559 ** TEMP database file if P1==1 or in an attached database if
5560 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
5561 ** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
5562 ** The root page number of the new b-tree is stored in register P2.
5564 case OP_CreateBtree: { /* out2 */
5565 int pgno;
5566 Db *pDb;
5568 pOut = out2Prerelease(p, pOp);
5569 pgno = 0;
5570 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
5571 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5572 assert( DbMaskTest(p->btreeMask, pOp->p1) );
5573 assert( p->readOnly==0 );
5574 pDb = &db->aDb[pOp->p1];
5575 assert( pDb->pBt!=0 );
5576 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
5577 if( rc ) goto abort_due_to_error;
5578 pOut->u.i = pgno;
5579 break;
5582 /* Opcode: SqlExec * * * P4 *
5584 ** Run the SQL statement or statements specified in the P4 string.
5586 case OP_SqlExec: {
5587 db->nSqlExec++;
5588 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
5589 db->nSqlExec--;
5590 if( rc ) goto abort_due_to_error;
5591 break;
5594 /* Opcode: ParseSchema P1 * * P4 *
5596 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5597 ** that match the WHERE clause P4.
5599 ** This opcode invokes the parser to create a new virtual machine,
5600 ** then runs the new virtual machine. It is thus a re-entrant opcode.
5602 case OP_ParseSchema: {
5603 int iDb;
5604 const char *zMaster;
5605 char *zSql;
5606 InitData initData;
5608 /* Any prepared statement that invokes this opcode will hold mutexes
5609 ** on every btree. This is a prerequisite for invoking
5610 ** sqlite3InitCallback().
5612 #ifdef SQLITE_DEBUG
5613 for(iDb=0; iDb<db->nDb; iDb++){
5614 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
5616 #endif
5618 iDb = pOp->p1;
5619 assert( iDb>=0 && iDb<db->nDb );
5620 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
5621 /* Used to be a conditional */ {
5622 zMaster = MASTER_NAME;
5623 initData.db = db;
5624 initData.iDb = pOp->p1;
5625 initData.pzErrMsg = &p->zErrMsg;
5626 zSql = sqlite3MPrintf(db,
5627 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5628 db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
5629 if( zSql==0 ){
5630 rc = SQLITE_NOMEM_BKPT;
5631 }else{
5632 assert( db->init.busy==0 );
5633 db->init.busy = 1;
5634 initData.rc = SQLITE_OK;
5635 assert( !db->mallocFailed );
5636 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
5637 if( rc==SQLITE_OK ) rc = initData.rc;
5638 sqlite3DbFreeNN(db, zSql);
5639 db->init.busy = 0;
5642 if( rc ){
5643 sqlite3ResetAllSchemasOfConnection(db);
5644 if( rc==SQLITE_NOMEM ){
5645 goto no_mem;
5647 goto abort_due_to_error;
5649 break;
5652 #if !defined(SQLITE_OMIT_ANALYZE)
5653 /* Opcode: LoadAnalysis P1 * * * *
5655 ** Read the sqlite_stat1 table for database P1 and load the content
5656 ** of that table into the internal index hash table. This will cause
5657 ** the analysis to be used when preparing all subsequent queries.
5659 case OP_LoadAnalysis: {
5660 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5661 rc = sqlite3AnalysisLoad(db, pOp->p1);
5662 if( rc ) goto abort_due_to_error;
5663 break;
5665 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5667 /* Opcode: DropTable P1 * * P4 *
5669 ** Remove the internal (in-memory) data structures that describe
5670 ** the table named P4 in database P1. This is called after a table
5671 ** is dropped from disk (using the Destroy opcode) in order to keep
5672 ** the internal representation of the
5673 ** schema consistent with what is on disk.
5675 case OP_DropTable: {
5676 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
5677 break;
5680 /* Opcode: DropIndex P1 * * P4 *
5682 ** Remove the internal (in-memory) data structures that describe
5683 ** the index named P4 in database P1. This is called after an index
5684 ** is dropped from disk (using the Destroy opcode)
5685 ** in order to keep the internal representation of the
5686 ** schema consistent with what is on disk.
5688 case OP_DropIndex: {
5689 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
5690 break;
5693 /* Opcode: DropTrigger P1 * * P4 *
5695 ** Remove the internal (in-memory) data structures that describe
5696 ** the trigger named P4 in database P1. This is called after a trigger
5697 ** is dropped from disk (using the Destroy opcode) in order to keep
5698 ** the internal representation of the
5699 ** schema consistent with what is on disk.
5701 case OP_DropTrigger: {
5702 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
5703 break;
5707 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5708 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
5710 ** Do an analysis of the currently open database. Store in
5711 ** register P1 the text of an error message describing any problems.
5712 ** If no problems are found, store a NULL in register P1.
5714 ** The register P3 contains one less than the maximum number of allowed errors.
5715 ** At most reg(P3) errors will be reported.
5716 ** In other words, the analysis stops as soon as reg(P1) errors are
5717 ** seen. Reg(P1) is updated with the number of errors remaining.
5719 ** The root page numbers of all tables in the database are integers
5720 ** stored in P4_INTARRAY argument.
5722 ** If P5 is not zero, the check is done on the auxiliary database
5723 ** file, not the main database file.
5725 ** This opcode is used to implement the integrity_check pragma.
5727 case OP_IntegrityCk: {
5728 int nRoot; /* Number of tables to check. (Number of root pages.) */
5729 int *aRoot; /* Array of rootpage numbers for tables to be checked */
5730 int nErr; /* Number of errors reported */
5731 char *z; /* Text of the error report */
5732 Mem *pnErr; /* Register keeping track of errors remaining */
5734 assert( p->bIsReader );
5735 nRoot = pOp->p2;
5736 aRoot = pOp->p4.ai;
5737 assert( nRoot>0 );
5738 assert( aRoot[0]==nRoot );
5739 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
5740 pnErr = &aMem[pOp->p3];
5741 assert( (pnErr->flags & MEM_Int)!=0 );
5742 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
5743 pIn1 = &aMem[pOp->p1];
5744 assert( pOp->p5<db->nDb );
5745 assert( DbMaskTest(p->btreeMask, pOp->p5) );
5746 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
5747 (int)pnErr->u.i+1, &nErr);
5748 sqlite3VdbeMemSetNull(pIn1);
5749 if( nErr==0 ){
5750 assert( z==0 );
5751 }else if( z==0 ){
5752 goto no_mem;
5753 }else{
5754 pnErr->u.i -= nErr-1;
5755 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
5757 UPDATE_MAX_BLOBSIZE(pIn1);
5758 sqlite3VdbeChangeEncoding(pIn1, encoding);
5759 break;
5761 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5763 /* Opcode: RowSetAdd P1 P2 * * *
5764 ** Synopsis: rowset(P1)=r[P2]
5766 ** Insert the integer value held by register P2 into a RowSet object
5767 ** held in register P1.
5769 ** An assertion fails if P2 is not an integer.
5771 case OP_RowSetAdd: { /* in1, in2 */
5772 pIn1 = &aMem[pOp->p1];
5773 pIn2 = &aMem[pOp->p2];
5774 assert( (pIn2->flags & MEM_Int)!=0 );
5775 if( (pIn1->flags & MEM_RowSet)==0 ){
5776 sqlite3VdbeMemSetRowSet(pIn1);
5777 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5779 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
5780 break;
5783 /* Opcode: RowSetRead P1 P2 P3 * *
5784 ** Synopsis: r[P3]=rowset(P1)
5786 ** Extract the smallest value from the RowSet object in P1
5787 ** and put that value into register P3.
5788 ** Or, if RowSet object P1 is initially empty, leave P3
5789 ** unchanged and jump to instruction P2.
5791 case OP_RowSetRead: { /* jump, in1, out3 */
5792 i64 val;
5794 pIn1 = &aMem[pOp->p1];
5795 if( (pIn1->flags & MEM_RowSet)==0
5796 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
5798 /* The boolean index is empty */
5799 sqlite3VdbeMemSetNull(pIn1);
5800 VdbeBranchTaken(1,2);
5801 goto jump_to_p2_and_check_for_interrupt;
5802 }else{
5803 /* A value was pulled from the index */
5804 VdbeBranchTaken(0,2);
5805 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
5807 goto check_for_interrupt;
5810 /* Opcode: RowSetTest P1 P2 P3 P4
5811 ** Synopsis: if r[P3] in rowset(P1) goto P2
5813 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5814 ** contains a RowSet object and that RowSet object contains
5815 ** the value held in P3, jump to register P2. Otherwise, insert the
5816 ** integer in P3 into the RowSet and continue on to the
5817 ** next opcode.
5819 ** The RowSet object is optimized for the case where sets of integers
5820 ** are inserted in distinct phases, which each set contains no duplicates.
5821 ** Each set is identified by a unique P4 value. The first set
5822 ** must have P4==0, the final set must have P4==-1, and for all other sets
5823 ** must have P4>0.
5825 ** This allows optimizations: (a) when P4==0 there is no need to test
5826 ** the RowSet object for P3, as it is guaranteed not to contain it,
5827 ** (b) when P4==-1 there is no need to insert the value, as it will
5828 ** never be tested for, and (c) when a value that is part of set X is
5829 ** inserted, there is no need to search to see if the same value was
5830 ** previously inserted as part of set X (only if it was previously
5831 ** inserted as part of some other set).
5833 case OP_RowSetTest: { /* jump, in1, in3 */
5834 int iSet;
5835 int exists;
5837 pIn1 = &aMem[pOp->p1];
5838 pIn3 = &aMem[pOp->p3];
5839 iSet = pOp->p4.i;
5840 assert( pIn3->flags&MEM_Int );
5842 /* If there is anything other than a rowset object in memory cell P1,
5843 ** delete it now and initialize P1 with an empty rowset
5845 if( (pIn1->flags & MEM_RowSet)==0 ){
5846 sqlite3VdbeMemSetRowSet(pIn1);
5847 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5850 assert( pOp->p4type==P4_INT32 );
5851 assert( iSet==-1 || iSet>=0 );
5852 if( iSet ){
5853 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
5854 VdbeBranchTaken(exists!=0,2);
5855 if( exists ) goto jump_to_p2;
5857 if( iSet>=0 ){
5858 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
5860 break;
5864 #ifndef SQLITE_OMIT_TRIGGER
5866 /* Opcode: Program P1 P2 P3 P4 P5
5868 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5870 ** P1 contains the address of the memory cell that contains the first memory
5871 ** cell in an array of values used as arguments to the sub-program. P2
5872 ** contains the address to jump to if the sub-program throws an IGNORE
5873 ** exception using the RAISE() function. Register P3 contains the address
5874 ** of a memory cell in this (the parent) VM that is used to allocate the
5875 ** memory required by the sub-vdbe at runtime.
5877 ** P4 is a pointer to the VM containing the trigger program.
5879 ** If P5 is non-zero, then recursive program invocation is enabled.
5881 case OP_Program: { /* jump */
5882 int nMem; /* Number of memory registers for sub-program */
5883 int nByte; /* Bytes of runtime space required for sub-program */
5884 Mem *pRt; /* Register to allocate runtime space */
5885 Mem *pMem; /* Used to iterate through memory cells */
5886 Mem *pEnd; /* Last memory cell in new array */
5887 VdbeFrame *pFrame; /* New vdbe frame to execute in */
5888 SubProgram *pProgram; /* Sub-program to execute */
5889 void *t; /* Token identifying trigger */
5891 pProgram = pOp->p4.pProgram;
5892 pRt = &aMem[pOp->p3];
5893 assert( pProgram->nOp>0 );
5895 /* If the p5 flag is clear, then recursive invocation of triggers is
5896 ** disabled for backwards compatibility (p5 is set if this sub-program
5897 ** is really a trigger, not a foreign key action, and the flag set
5898 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
5900 ** It is recursive invocation of triggers, at the SQL level, that is
5901 ** disabled. In some cases a single trigger may generate more than one
5902 ** SubProgram (if the trigger may be executed with more than one different
5903 ** ON CONFLICT algorithm). SubProgram structures associated with a
5904 ** single trigger all have the same value for the SubProgram.token
5905 ** variable. */
5906 if( pOp->p5 ){
5907 t = pProgram->token;
5908 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
5909 if( pFrame ) break;
5912 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
5913 rc = SQLITE_ERROR;
5914 sqlite3VdbeError(p, "too many levels of trigger recursion");
5915 goto abort_due_to_error;
5918 /* Register pRt is used to store the memory required to save the state
5919 ** of the current program, and the memory required at runtime to execute
5920 ** the trigger program. If this trigger has been fired before, then pRt
5921 ** is already allocated. Otherwise, it must be initialized. */
5922 if( (pRt->flags&MEM_Frame)==0 ){
5923 /* SubProgram.nMem is set to the number of memory cells used by the
5924 ** program stored in SubProgram.aOp. As well as these, one memory
5925 ** cell is required for each cursor used by the program. Set local
5926 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
5928 nMem = pProgram->nMem + pProgram->nCsr;
5929 assert( nMem>0 );
5930 if( pProgram->nCsr==0 ) nMem++;
5931 nByte = ROUND8(sizeof(VdbeFrame))
5932 + nMem * sizeof(Mem)
5933 + pProgram->nCsr * sizeof(VdbeCursor*)
5934 + (pProgram->nOp + 7)/8;
5935 pFrame = sqlite3DbMallocZero(db, nByte);
5936 if( !pFrame ){
5937 goto no_mem;
5939 sqlite3VdbeMemRelease(pRt);
5940 pRt->flags = MEM_Frame;
5941 pRt->u.pFrame = pFrame;
5943 pFrame->v = p;
5944 pFrame->nChildMem = nMem;
5945 pFrame->nChildCsr = pProgram->nCsr;
5946 pFrame->pc = (int)(pOp - aOp);
5947 pFrame->aMem = p->aMem;
5948 pFrame->nMem = p->nMem;
5949 pFrame->apCsr = p->apCsr;
5950 pFrame->nCursor = p->nCursor;
5951 pFrame->aOp = p->aOp;
5952 pFrame->nOp = p->nOp;
5953 pFrame->token = pProgram->token;
5954 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
5955 pFrame->anExec = p->anExec;
5956 #endif
5958 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
5959 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
5960 pMem->flags = MEM_Undefined;
5961 pMem->db = db;
5963 }else{
5964 pFrame = pRt->u.pFrame;
5965 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
5966 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
5967 assert( pProgram->nCsr==pFrame->nChildCsr );
5968 assert( (int)(pOp - aOp)==pFrame->pc );
5971 p->nFrame++;
5972 pFrame->pParent = p->pFrame;
5973 pFrame->lastRowid = db->lastRowid;
5974 pFrame->nChange = p->nChange;
5975 pFrame->nDbChange = p->db->nChange;
5976 assert( pFrame->pAuxData==0 );
5977 pFrame->pAuxData = p->pAuxData;
5978 p->pAuxData = 0;
5979 p->nChange = 0;
5980 p->pFrame = pFrame;
5981 p->aMem = aMem = VdbeFrameMem(pFrame);
5982 p->nMem = pFrame->nChildMem;
5983 p->nCursor = (u16)pFrame->nChildCsr;
5984 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
5985 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
5986 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
5987 p->aOp = aOp = pProgram->aOp;
5988 p->nOp = pProgram->nOp;
5989 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
5990 p->anExec = 0;
5991 #endif
5992 pOp = &aOp[-1];
5994 break;
5997 /* Opcode: Param P1 P2 * * *
5999 ** This opcode is only ever present in sub-programs called via the
6000 ** OP_Program instruction. Copy a value currently stored in a memory
6001 ** cell of the calling (parent) frame to cell P2 in the current frames
6002 ** address space. This is used by trigger programs to access the new.*
6003 ** and old.* values.
6005 ** The address of the cell in the parent frame is determined by adding
6006 ** the value of the P1 argument to the value of the P1 argument to the
6007 ** calling OP_Program instruction.
6009 case OP_Param: { /* out2 */
6010 VdbeFrame *pFrame;
6011 Mem *pIn;
6012 pOut = out2Prerelease(p, pOp);
6013 pFrame = p->pFrame;
6014 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
6015 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
6016 break;
6019 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6021 #ifndef SQLITE_OMIT_FOREIGN_KEY
6022 /* Opcode: FkCounter P1 P2 * * *
6023 ** Synopsis: fkctr[P1]+=P2
6025 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6026 ** If P1 is non-zero, the database constraint counter is incremented
6027 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6028 ** statement counter is incremented (immediate foreign key constraints).
6030 case OP_FkCounter: {
6031 if( db->flags & SQLITE_DeferFKs ){
6032 db->nDeferredImmCons += pOp->p2;
6033 }else if( pOp->p1 ){
6034 db->nDeferredCons += pOp->p2;
6035 }else{
6036 p->nFkConstraint += pOp->p2;
6038 break;
6041 /* Opcode: FkIfZero P1 P2 * * *
6042 ** Synopsis: if fkctr[P1]==0 goto P2
6044 ** This opcode tests if a foreign key constraint-counter is currently zero.
6045 ** If so, jump to instruction P2. Otherwise, fall through to the next
6046 ** instruction.
6048 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6049 ** is zero (the one that counts deferred constraint violations). If P1 is
6050 ** zero, the jump is taken if the statement constraint-counter is zero
6051 ** (immediate foreign key constraint violations).
6053 case OP_FkIfZero: { /* jump */
6054 if( pOp->p1 ){
6055 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6056 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6057 }else{
6058 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6059 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6061 break;
6063 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6065 #ifndef SQLITE_OMIT_AUTOINCREMENT
6066 /* Opcode: MemMax P1 P2 * * *
6067 ** Synopsis: r[P1]=max(r[P1],r[P2])
6069 ** P1 is a register in the root frame of this VM (the root frame is
6070 ** different from the current frame if this instruction is being executed
6071 ** within a sub-program). Set the value of register P1 to the maximum of
6072 ** its current value and the value in register P2.
6074 ** This instruction throws an error if the memory cell is not initially
6075 ** an integer.
6077 case OP_MemMax: { /* in2 */
6078 VdbeFrame *pFrame;
6079 if( p->pFrame ){
6080 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
6081 pIn1 = &pFrame->aMem[pOp->p1];
6082 }else{
6083 pIn1 = &aMem[pOp->p1];
6085 assert( memIsValid(pIn1) );
6086 sqlite3VdbeMemIntegerify(pIn1);
6087 pIn2 = &aMem[pOp->p2];
6088 sqlite3VdbeMemIntegerify(pIn2);
6089 if( pIn1->u.i<pIn2->u.i){
6090 pIn1->u.i = pIn2->u.i;
6092 break;
6094 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6096 /* Opcode: IfPos P1 P2 P3 * *
6097 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6099 ** Register P1 must contain an integer.
6100 ** If the value of register P1 is 1 or greater, subtract P3 from the
6101 ** value in P1 and jump to P2.
6103 ** If the initial value of register P1 is less than 1, then the
6104 ** value is unchanged and control passes through to the next instruction.
6106 case OP_IfPos: { /* jump, in1 */
6107 pIn1 = &aMem[pOp->p1];
6108 assert( pIn1->flags&MEM_Int );
6109 VdbeBranchTaken( pIn1->u.i>0, 2);
6110 if( pIn1->u.i>0 ){
6111 pIn1->u.i -= pOp->p3;
6112 goto jump_to_p2;
6114 break;
6117 /* Opcode: OffsetLimit P1 P2 P3 * *
6118 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6120 ** This opcode performs a commonly used computation associated with
6121 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
6122 ** holds the offset counter. The opcode computes the combined value
6123 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
6124 ** value computed is the total number of rows that will need to be
6125 ** visited in order to complete the query.
6127 ** If r[P3] is zero or negative, that means there is no OFFSET
6128 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6130 ** if r[P1] is zero or negative, that means there is no LIMIT
6131 ** and r[P2] is set to -1.
6133 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6135 case OP_OffsetLimit: { /* in1, out2, in3 */
6136 i64 x;
6137 pIn1 = &aMem[pOp->p1];
6138 pIn3 = &aMem[pOp->p3];
6139 pOut = out2Prerelease(p, pOp);
6140 assert( pIn1->flags & MEM_Int );
6141 assert( pIn3->flags & MEM_Int );
6142 x = pIn1->u.i;
6143 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
6144 /* If the LIMIT is less than or equal to zero, loop forever. This
6145 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
6146 ** also loop forever. This is undocumented. In fact, one could argue
6147 ** that the loop should terminate. But assuming 1 billion iterations
6148 ** per second (far exceeding the capabilities of any current hardware)
6149 ** it would take nearly 300 years to actually reach the limit. So
6150 ** looping forever is a reasonable approximation. */
6151 pOut->u.i = -1;
6152 }else{
6153 pOut->u.i = x;
6155 break;
6158 /* Opcode: IfNotZero P1 P2 * * *
6159 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6161 ** Register P1 must contain an integer. If the content of register P1 is
6162 ** initially greater than zero, then decrement the value in register P1.
6163 ** If it is non-zero (negative or positive) and then also jump to P2.
6164 ** If register P1 is initially zero, leave it unchanged and fall through.
6166 case OP_IfNotZero: { /* jump, in1 */
6167 pIn1 = &aMem[pOp->p1];
6168 assert( pIn1->flags&MEM_Int );
6169 VdbeBranchTaken(pIn1->u.i<0, 2);
6170 if( pIn1->u.i ){
6171 if( pIn1->u.i>0 ) pIn1->u.i--;
6172 goto jump_to_p2;
6174 break;
6177 /* Opcode: DecrJumpZero P1 P2 * * *
6178 ** Synopsis: if (--r[P1])==0 goto P2
6180 ** Register P1 must hold an integer. Decrement the value in P1
6181 ** and jump to P2 if the new value is exactly zero.
6183 case OP_DecrJumpZero: { /* jump, in1 */
6184 pIn1 = &aMem[pOp->p1];
6185 assert( pIn1->flags&MEM_Int );
6186 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
6187 VdbeBranchTaken(pIn1->u.i==0, 2);
6188 if( pIn1->u.i==0 ) goto jump_to_p2;
6189 break;
6193 /* Opcode: AggStep0 * P2 P3 P4 P5
6194 ** Synopsis: accum=r[P3] step(r[P2@P5])
6196 ** Execute the step function for an aggregate. The
6197 ** function has P5 arguments. P4 is a pointer to the FuncDef
6198 ** structure that specifies the function. Register P3 is the
6199 ** accumulator.
6201 ** The P5 arguments are taken from register P2 and its
6202 ** successors.
6204 /* Opcode: AggStep * P2 P3 P4 P5
6205 ** Synopsis: accum=r[P3] step(r[P2@P5])
6207 ** Execute the step function for an aggregate. The
6208 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
6209 ** object that is used to run the function. Register P3 is
6210 ** as the accumulator.
6212 ** The P5 arguments are taken from register P2 and its
6213 ** successors.
6215 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6216 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6217 ** the opcode is changed. In this way, the initialization of the
6218 ** sqlite3_context only happens once, instead of on each call to the
6219 ** step function.
6221 case OP_AggStep0: {
6222 int n;
6223 sqlite3_context *pCtx;
6225 assert( pOp->p4type==P4_FUNCDEF );
6226 n = pOp->p5;
6227 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6228 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
6229 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
6230 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
6231 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
6232 if( pCtx==0 ) goto no_mem;
6233 pCtx->pMem = 0;
6234 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
6235 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
6236 pCtx->pFunc = pOp->p4.pFunc;
6237 pCtx->iOp = (int)(pOp - aOp);
6238 pCtx->pVdbe = p;
6239 pCtx->skipFlag = 0;
6240 pCtx->isError = 0;
6241 pCtx->argc = n;
6242 pOp->p4type = P4_FUNCCTX;
6243 pOp->p4.pCtx = pCtx;
6244 pOp->opcode = OP_AggStep;
6245 /* Fall through into OP_AggStep */
6247 case OP_AggStep: {
6248 int i;
6249 sqlite3_context *pCtx;
6250 Mem *pMem;
6252 assert( pOp->p4type==P4_FUNCCTX );
6253 pCtx = pOp->p4.pCtx;
6254 pMem = &aMem[pOp->p3];
6256 /* If this function is inside of a trigger, the register array in aMem[]
6257 ** might change from one evaluation to the next. The next block of code
6258 ** checks to see if the register array has changed, and if so it
6259 ** reinitializes the relavant parts of the sqlite3_context object */
6260 if( pCtx->pMem != pMem ){
6261 pCtx->pMem = pMem;
6262 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
6265 #ifdef SQLITE_DEBUG
6266 for(i=0; i<pCtx->argc; i++){
6267 assert( memIsValid(pCtx->argv[i]) );
6268 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
6270 #endif
6272 pMem->n++;
6273 assert( pCtx->pOut->flags==MEM_Null );
6274 assert( pCtx->isError==0 );
6275 assert( pCtx->skipFlag==0 );
6276 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
6277 if( pCtx->isError ){
6278 if( pCtx->isError>0 ){
6279 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
6280 rc = pCtx->isError;
6282 if( pCtx->skipFlag ){
6283 assert( pOp[-1].opcode==OP_CollSeq );
6284 i = pOp[-1].p1;
6285 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
6286 pCtx->skipFlag = 0;
6288 sqlite3VdbeMemRelease(pCtx->pOut);
6289 pCtx->pOut->flags = MEM_Null;
6290 pCtx->isError = 0;
6291 if( rc ) goto abort_due_to_error;
6293 assert( pCtx->pOut->flags==MEM_Null );
6294 assert( pCtx->skipFlag==0 );
6295 break;
6298 /* Opcode: AggFinal P1 P2 * P4 *
6299 ** Synopsis: accum=r[P1] N=P2
6301 ** Execute the finalizer function for an aggregate. P1 is
6302 ** the memory location that is the accumulator for the aggregate.
6304 ** P2 is the number of arguments that the step function takes and
6305 ** P4 is a pointer to the FuncDef for this function. The P2
6306 ** argument is not used by this opcode. It is only there to disambiguate
6307 ** functions that can take varying numbers of arguments. The
6308 ** P4 argument is only needed for the degenerate case where
6309 ** the step function was not previously called.
6311 case OP_AggFinal: {
6312 Mem *pMem;
6313 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
6314 pMem = &aMem[pOp->p1];
6315 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
6316 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
6317 if( rc ){
6318 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
6319 goto abort_due_to_error;
6321 sqlite3VdbeChangeEncoding(pMem, encoding);
6322 UPDATE_MAX_BLOBSIZE(pMem);
6323 if( sqlite3VdbeMemTooBig(pMem) ){
6324 goto too_big;
6326 break;
6329 #ifndef SQLITE_OMIT_WAL
6330 /* Opcode: Checkpoint P1 P2 P3 * *
6332 ** Checkpoint database P1. This is a no-op if P1 is not currently in
6333 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
6334 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
6335 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
6336 ** WAL after the checkpoint into mem[P3+1] and the number of pages
6337 ** in the WAL that have been checkpointed after the checkpoint
6338 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
6339 ** mem[P3+2] are initialized to -1.
6341 case OP_Checkpoint: {
6342 int i; /* Loop counter */
6343 int aRes[3]; /* Results */
6344 Mem *pMem; /* Write results here */
6346 assert( p->readOnly==0 );
6347 aRes[0] = 0;
6348 aRes[1] = aRes[2] = -1;
6349 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
6350 || pOp->p2==SQLITE_CHECKPOINT_FULL
6351 || pOp->p2==SQLITE_CHECKPOINT_RESTART
6352 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
6354 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
6355 if( rc ){
6356 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
6357 rc = SQLITE_OK;
6358 aRes[0] = 1;
6360 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
6361 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
6363 break;
6365 #endif
6367 #ifndef SQLITE_OMIT_PRAGMA
6368 /* Opcode: JournalMode P1 P2 P3 * *
6370 ** Change the journal mode of database P1 to P3. P3 must be one of the
6371 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
6372 ** modes (delete, truncate, persist, off and memory), this is a simple
6373 ** operation. No IO is required.
6375 ** If changing into or out of WAL mode the procedure is more complicated.
6377 ** Write a string containing the final journal-mode to register P2.
6379 case OP_JournalMode: { /* out2 */
6380 Btree *pBt; /* Btree to change journal mode of */
6381 Pager *pPager; /* Pager associated with pBt */
6382 int eNew; /* New journal mode */
6383 int eOld; /* The old journal mode */
6384 #ifndef SQLITE_OMIT_WAL
6385 const char *zFilename; /* Name of database file for pPager */
6386 #endif
6388 pOut = out2Prerelease(p, pOp);
6389 eNew = pOp->p3;
6390 assert( eNew==PAGER_JOURNALMODE_DELETE
6391 || eNew==PAGER_JOURNALMODE_TRUNCATE
6392 || eNew==PAGER_JOURNALMODE_PERSIST
6393 || eNew==PAGER_JOURNALMODE_OFF
6394 || eNew==PAGER_JOURNALMODE_MEMORY
6395 || eNew==PAGER_JOURNALMODE_WAL
6396 || eNew==PAGER_JOURNALMODE_QUERY
6398 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6399 assert( p->readOnly==0 );
6401 pBt = db->aDb[pOp->p1].pBt;
6402 pPager = sqlite3BtreePager(pBt);
6403 eOld = sqlite3PagerGetJournalMode(pPager);
6404 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
6405 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
6407 #ifndef SQLITE_OMIT_WAL
6408 zFilename = sqlite3PagerFilename(pPager, 1);
6410 /* Do not allow a transition to journal_mode=WAL for a database
6411 ** in temporary storage or if the VFS does not support shared memory
6413 if( eNew==PAGER_JOURNALMODE_WAL
6414 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
6415 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
6417 eNew = eOld;
6420 if( (eNew!=eOld)
6421 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
6423 if( !db->autoCommit || db->nVdbeRead>1 ){
6424 rc = SQLITE_ERROR;
6425 sqlite3VdbeError(p,
6426 "cannot change %s wal mode from within a transaction",
6427 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
6429 goto abort_due_to_error;
6430 }else{
6432 if( eOld==PAGER_JOURNALMODE_WAL ){
6433 /* If leaving WAL mode, close the log file. If successful, the call
6434 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
6435 ** file. An EXCLUSIVE lock may still be held on the database file
6436 ** after a successful return.
6438 rc = sqlite3PagerCloseWal(pPager, db);
6439 if( rc==SQLITE_OK ){
6440 sqlite3PagerSetJournalMode(pPager, eNew);
6442 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
6443 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
6444 ** as an intermediate */
6445 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
6448 /* Open a transaction on the database file. Regardless of the journal
6449 ** mode, this transaction always uses a rollback journal.
6451 assert( sqlite3BtreeIsInTrans(pBt)==0 );
6452 if( rc==SQLITE_OK ){
6453 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
6457 #endif /* ifndef SQLITE_OMIT_WAL */
6459 if( rc ) eNew = eOld;
6460 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
6462 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
6463 pOut->z = (char *)sqlite3JournalModename(eNew);
6464 pOut->n = sqlite3Strlen30(pOut->z);
6465 pOut->enc = SQLITE_UTF8;
6466 sqlite3VdbeChangeEncoding(pOut, encoding);
6467 if( rc ) goto abort_due_to_error;
6468 break;
6470 #endif /* SQLITE_OMIT_PRAGMA */
6472 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
6473 /* Opcode: Vacuum P1 * * * *
6475 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
6476 ** for an attached database. The "temp" database may not be vacuumed.
6478 case OP_Vacuum: {
6479 assert( p->readOnly==0 );
6480 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
6481 if( rc ) goto abort_due_to_error;
6482 break;
6484 #endif
6486 #if !defined(SQLITE_OMIT_AUTOVACUUM)
6487 /* Opcode: IncrVacuum P1 P2 * * *
6489 ** Perform a single step of the incremental vacuum procedure on
6490 ** the P1 database. If the vacuum has finished, jump to instruction
6491 ** P2. Otherwise, fall through to the next instruction.
6493 case OP_IncrVacuum: { /* jump */
6494 Btree *pBt;
6496 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6497 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6498 assert( p->readOnly==0 );
6499 pBt = db->aDb[pOp->p1].pBt;
6500 rc = sqlite3BtreeIncrVacuum(pBt);
6501 VdbeBranchTaken(rc==SQLITE_DONE,2);
6502 if( rc ){
6503 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6504 rc = SQLITE_OK;
6505 goto jump_to_p2;
6507 break;
6509 #endif
6511 /* Opcode: Expire P1 * * * *
6513 ** Cause precompiled statements to expire. When an expired statement
6514 ** is executed using sqlite3_step() it will either automatically
6515 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
6516 ** or it will fail with SQLITE_SCHEMA.
6518 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
6519 ** then only the currently executing statement is expired.
6521 case OP_Expire: {
6522 if( !pOp->p1 ){
6523 sqlite3ExpirePreparedStatements(db);
6524 }else{
6525 p->expired = 1;
6527 break;
6530 #ifndef SQLITE_OMIT_SHARED_CACHE
6531 /* Opcode: TableLock P1 P2 P3 P4 *
6532 ** Synopsis: iDb=P1 root=P2 write=P3
6534 ** Obtain a lock on a particular table. This instruction is only used when
6535 ** the shared-cache feature is enabled.
6537 ** P1 is the index of the database in sqlite3.aDb[] of the database
6538 ** on which the lock is acquired. A readlock is obtained if P3==0 or
6539 ** a write lock if P3==1.
6541 ** P2 contains the root-page of the table to lock.
6543 ** P4 contains a pointer to the name of the table being locked. This is only
6544 ** used to generate an error message if the lock cannot be obtained.
6546 case OP_TableLock: {
6547 u8 isWriteLock = (u8)pOp->p3;
6548 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
6549 int p1 = pOp->p1;
6550 assert( p1>=0 && p1<db->nDb );
6551 assert( DbMaskTest(p->btreeMask, p1) );
6552 assert( isWriteLock==0 || isWriteLock==1 );
6553 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
6554 if( rc ){
6555 if( (rc&0xFF)==SQLITE_LOCKED ){
6556 const char *z = pOp->p4.z;
6557 sqlite3VdbeError(p, "database table is locked: %s", z);
6559 goto abort_due_to_error;
6562 break;
6564 #endif /* SQLITE_OMIT_SHARED_CACHE */
6566 #ifndef SQLITE_OMIT_VIRTUALTABLE
6567 /* Opcode: VBegin * * * P4 *
6569 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
6570 ** xBegin method for that table.
6572 ** Also, whether or not P4 is set, check that this is not being called from
6573 ** within a callback to a virtual table xSync() method. If it is, the error
6574 ** code will be set to SQLITE_LOCKED.
6576 case OP_VBegin: {
6577 VTable *pVTab;
6578 pVTab = pOp->p4.pVtab;
6579 rc = sqlite3VtabBegin(db, pVTab);
6580 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
6581 if( rc ) goto abort_due_to_error;
6582 break;
6584 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6586 #ifndef SQLITE_OMIT_VIRTUALTABLE
6587 /* Opcode: VCreate P1 P2 * * *
6589 ** P2 is a register that holds the name of a virtual table in database
6590 ** P1. Call the xCreate method for that table.
6592 case OP_VCreate: {
6593 Mem sMem; /* For storing the record being decoded */
6594 const char *zTab; /* Name of the virtual table */
6596 memset(&sMem, 0, sizeof(sMem));
6597 sMem.db = db;
6598 /* Because P2 is always a static string, it is impossible for the
6599 ** sqlite3VdbeMemCopy() to fail */
6600 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
6601 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
6602 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
6603 assert( rc==SQLITE_OK );
6604 zTab = (const char*)sqlite3_value_text(&sMem);
6605 assert( zTab || db->mallocFailed );
6606 if( zTab ){
6607 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
6609 sqlite3VdbeMemRelease(&sMem);
6610 if( rc ) goto abort_due_to_error;
6611 break;
6613 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6615 #ifndef SQLITE_OMIT_VIRTUALTABLE
6616 /* Opcode: VDestroy P1 * * P4 *
6618 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
6619 ** of that table.
6621 case OP_VDestroy: {
6622 db->nVDestroy++;
6623 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
6624 db->nVDestroy--;
6625 if( rc ) goto abort_due_to_error;
6626 break;
6628 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6630 #ifndef SQLITE_OMIT_VIRTUALTABLE
6631 /* Opcode: VOpen P1 * * P4 *
6633 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6634 ** P1 is a cursor number. This opcode opens a cursor to the virtual
6635 ** table and stores that cursor in P1.
6637 case OP_VOpen: {
6638 VdbeCursor *pCur;
6639 sqlite3_vtab_cursor *pVCur;
6640 sqlite3_vtab *pVtab;
6641 const sqlite3_module *pModule;
6643 assert( p->bIsReader );
6644 pCur = 0;
6645 pVCur = 0;
6646 pVtab = pOp->p4.pVtab->pVtab;
6647 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6648 rc = SQLITE_LOCKED;
6649 goto abort_due_to_error;
6651 pModule = pVtab->pModule;
6652 rc = pModule->xOpen(pVtab, &pVCur);
6653 sqlite3VtabImportErrmsg(p, pVtab);
6654 if( rc ) goto abort_due_to_error;
6656 /* Initialize sqlite3_vtab_cursor base class */
6657 pVCur->pVtab = pVtab;
6659 /* Initialize vdbe cursor object */
6660 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
6661 if( pCur ){
6662 pCur->uc.pVCur = pVCur;
6663 pVtab->nRef++;
6664 }else{
6665 assert( db->mallocFailed );
6666 pModule->xClose(pVCur);
6667 goto no_mem;
6669 break;
6671 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6673 #ifndef SQLITE_OMIT_VIRTUALTABLE
6674 /* Opcode: VFilter P1 P2 P3 P4 *
6675 ** Synopsis: iplan=r[P3] zplan='P4'
6677 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
6678 ** the filtered result set is empty.
6680 ** P4 is either NULL or a string that was generated by the xBestIndex
6681 ** method of the module. The interpretation of the P4 string is left
6682 ** to the module implementation.
6684 ** This opcode invokes the xFilter method on the virtual table specified
6685 ** by P1. The integer query plan parameter to xFilter is stored in register
6686 ** P3. Register P3+1 stores the argc parameter to be passed to the
6687 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6688 ** additional parameters which are passed to
6689 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6691 ** A jump is made to P2 if the result set after filtering would be empty.
6693 case OP_VFilter: { /* jump */
6694 int nArg;
6695 int iQuery;
6696 const sqlite3_module *pModule;
6697 Mem *pQuery;
6698 Mem *pArgc;
6699 sqlite3_vtab_cursor *pVCur;
6700 sqlite3_vtab *pVtab;
6701 VdbeCursor *pCur;
6702 int res;
6703 int i;
6704 Mem **apArg;
6706 pQuery = &aMem[pOp->p3];
6707 pArgc = &pQuery[1];
6708 pCur = p->apCsr[pOp->p1];
6709 assert( memIsValid(pQuery) );
6710 REGISTER_TRACE(pOp->p3, pQuery);
6711 assert( pCur->eCurType==CURTYPE_VTAB );
6712 pVCur = pCur->uc.pVCur;
6713 pVtab = pVCur->pVtab;
6714 pModule = pVtab->pModule;
6716 /* Grab the index number and argc parameters */
6717 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
6718 nArg = (int)pArgc->u.i;
6719 iQuery = (int)pQuery->u.i;
6721 /* Invoke the xFilter method */
6722 res = 0;
6723 apArg = p->apArg;
6724 for(i = 0; i<nArg; i++){
6725 apArg[i] = &pArgc[i+1];
6727 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
6728 sqlite3VtabImportErrmsg(p, pVtab);
6729 if( rc ) goto abort_due_to_error;
6730 res = pModule->xEof(pVCur);
6731 pCur->nullRow = 0;
6732 VdbeBranchTaken(res!=0,2);
6733 if( res ) goto jump_to_p2;
6734 break;
6736 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6738 #ifndef SQLITE_OMIT_VIRTUALTABLE
6739 /* Opcode: VColumn P1 P2 P3 * P5
6740 ** Synopsis: r[P3]=vcolumn(P2)
6742 ** Store in register P3 the value of the P2-th column of
6743 ** the current row of the virtual-table of cursor P1.
6745 ** If the VColumn opcode is being used to fetch the value of
6746 ** an unchanging column during an UPDATE operation, then the P5
6747 ** value is 1. Otherwise, P5 is 0. The P5 value is returned
6748 ** by sqlite3_vtab_nochange() routine can can be used
6749 ** by virtual table implementations to return special "no-change"
6750 ** marks which can be more efficient, depending on the virtual table.
6752 case OP_VColumn: {
6753 sqlite3_vtab *pVtab;
6754 const sqlite3_module *pModule;
6755 Mem *pDest;
6756 sqlite3_context sContext;
6758 VdbeCursor *pCur = p->apCsr[pOp->p1];
6759 assert( pCur->eCurType==CURTYPE_VTAB );
6760 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6761 pDest = &aMem[pOp->p3];
6762 memAboutToChange(p, pDest);
6763 if( pCur->nullRow ){
6764 sqlite3VdbeMemSetNull(pDest);
6765 break;
6767 pVtab = pCur->uc.pVCur->pVtab;
6768 pModule = pVtab->pModule;
6769 assert( pModule->xColumn );
6770 memset(&sContext, 0, sizeof(sContext));
6771 sContext.pOut = pDest;
6772 if( pOp->p5 ){
6773 sqlite3VdbeMemSetNull(pDest);
6774 pDest->flags = MEM_Null|MEM_Zero;
6775 pDest->u.nZero = 0;
6776 }else{
6777 MemSetTypeFlag(pDest, MEM_Null);
6779 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
6780 sqlite3VtabImportErrmsg(p, pVtab);
6781 if( sContext.isError>0 ){
6782 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
6783 rc = sContext.isError;
6785 sqlite3VdbeChangeEncoding(pDest, encoding);
6786 REGISTER_TRACE(pOp->p3, pDest);
6787 UPDATE_MAX_BLOBSIZE(pDest);
6789 if( sqlite3VdbeMemTooBig(pDest) ){
6790 goto too_big;
6792 if( rc ) goto abort_due_to_error;
6793 break;
6795 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6797 #ifndef SQLITE_OMIT_VIRTUALTABLE
6798 /* Opcode: VNext P1 P2 * * *
6800 ** Advance virtual table P1 to the next row in its result set and
6801 ** jump to instruction P2. Or, if the virtual table has reached
6802 ** the end of its result set, then fall through to the next instruction.
6804 case OP_VNext: { /* jump */
6805 sqlite3_vtab *pVtab;
6806 const sqlite3_module *pModule;
6807 int res;
6808 VdbeCursor *pCur;
6810 res = 0;
6811 pCur = p->apCsr[pOp->p1];
6812 assert( pCur->eCurType==CURTYPE_VTAB );
6813 if( pCur->nullRow ){
6814 break;
6816 pVtab = pCur->uc.pVCur->pVtab;
6817 pModule = pVtab->pModule;
6818 assert( pModule->xNext );
6820 /* Invoke the xNext() method of the module. There is no way for the
6821 ** underlying implementation to return an error if one occurs during
6822 ** xNext(). Instead, if an error occurs, true is returned (indicating that
6823 ** data is available) and the error code returned when xColumn or
6824 ** some other method is next invoked on the save virtual table cursor.
6826 rc = pModule->xNext(pCur->uc.pVCur);
6827 sqlite3VtabImportErrmsg(p, pVtab);
6828 if( rc ) goto abort_due_to_error;
6829 res = pModule->xEof(pCur->uc.pVCur);
6830 VdbeBranchTaken(!res,2);
6831 if( !res ){
6832 /* If there is data, jump to P2 */
6833 goto jump_to_p2_and_check_for_interrupt;
6835 goto check_for_interrupt;
6837 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6839 #ifndef SQLITE_OMIT_VIRTUALTABLE
6840 /* Opcode: VRename P1 * * P4 *
6842 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6843 ** This opcode invokes the corresponding xRename method. The value
6844 ** in register P1 is passed as the zName argument to the xRename method.
6846 case OP_VRename: {
6847 sqlite3_vtab *pVtab;
6848 Mem *pName;
6850 pVtab = pOp->p4.pVtab->pVtab;
6851 pName = &aMem[pOp->p1];
6852 assert( pVtab->pModule->xRename );
6853 assert( memIsValid(pName) );
6854 assert( p->readOnly==0 );
6855 REGISTER_TRACE(pOp->p1, pName);
6856 assert( pName->flags & MEM_Str );
6857 testcase( pName->enc==SQLITE_UTF8 );
6858 testcase( pName->enc==SQLITE_UTF16BE );
6859 testcase( pName->enc==SQLITE_UTF16LE );
6860 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
6861 if( rc ) goto abort_due_to_error;
6862 rc = pVtab->pModule->xRename(pVtab, pName->z);
6863 sqlite3VtabImportErrmsg(p, pVtab);
6864 p->expired = 0;
6865 if( rc ) goto abort_due_to_error;
6866 break;
6868 #endif
6870 #ifndef SQLITE_OMIT_VIRTUALTABLE
6871 /* Opcode: VUpdate P1 P2 P3 P4 P5
6872 ** Synopsis: data=r[P3@P2]
6874 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6875 ** This opcode invokes the corresponding xUpdate method. P2 values
6876 ** are contiguous memory cells starting at P3 to pass to the xUpdate
6877 ** invocation. The value in register (P3+P2-1) corresponds to the
6878 ** p2th element of the argv array passed to xUpdate.
6880 ** The xUpdate method will do a DELETE or an INSERT or both.
6881 ** The argv[0] element (which corresponds to memory cell P3)
6882 ** is the rowid of a row to delete. If argv[0] is NULL then no
6883 ** deletion occurs. The argv[1] element is the rowid of the new
6884 ** row. This can be NULL to have the virtual table select the new
6885 ** rowid for itself. The subsequent elements in the array are
6886 ** the values of columns in the new row.
6888 ** If P2==1 then no insert is performed. argv[0] is the rowid of
6889 ** a row to delete.
6891 ** P1 is a boolean flag. If it is set to true and the xUpdate call
6892 ** is successful, then the value returned by sqlite3_last_insert_rowid()
6893 ** is set to the value of the rowid for the row just inserted.
6895 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
6896 ** apply in the case of a constraint failure on an insert or update.
6898 case OP_VUpdate: {
6899 sqlite3_vtab *pVtab;
6900 const sqlite3_module *pModule;
6901 int nArg;
6902 int i;
6903 sqlite_int64 rowid;
6904 Mem **apArg;
6905 Mem *pX;
6907 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
6908 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
6910 assert( p->readOnly==0 );
6911 pVtab = pOp->p4.pVtab->pVtab;
6912 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6913 rc = SQLITE_LOCKED;
6914 goto abort_due_to_error;
6916 pModule = pVtab->pModule;
6917 nArg = pOp->p2;
6918 assert( pOp->p4type==P4_VTAB );
6919 if( ALWAYS(pModule->xUpdate) ){
6920 u8 vtabOnConflict = db->vtabOnConflict;
6921 apArg = p->apArg;
6922 pX = &aMem[pOp->p3];
6923 for(i=0; i<nArg; i++){
6924 assert( memIsValid(pX) );
6925 memAboutToChange(p, pX);
6926 apArg[i] = pX;
6927 pX++;
6929 db->vtabOnConflict = pOp->p5;
6930 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
6931 db->vtabOnConflict = vtabOnConflict;
6932 sqlite3VtabImportErrmsg(p, pVtab);
6933 if( rc==SQLITE_OK && pOp->p1 ){
6934 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
6935 db->lastRowid = rowid;
6937 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
6938 if( pOp->p5==OE_Ignore ){
6939 rc = SQLITE_OK;
6940 }else{
6941 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
6943 }else{
6944 p->nChange++;
6946 if( rc ) goto abort_due_to_error;
6948 break;
6950 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6952 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6953 /* Opcode: Pagecount P1 P2 * * *
6955 ** Write the current number of pages in database P1 to memory cell P2.
6957 case OP_Pagecount: { /* out2 */
6958 pOut = out2Prerelease(p, pOp);
6959 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
6960 break;
6962 #endif
6965 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6966 /* Opcode: MaxPgcnt P1 P2 P3 * *
6968 ** Try to set the maximum page count for database P1 to the value in P3.
6969 ** Do not let the maximum page count fall below the current page count and
6970 ** do not change the maximum page count value if P3==0.
6972 ** Store the maximum page count after the change in register P2.
6974 case OP_MaxPgcnt: { /* out2 */
6975 unsigned int newMax;
6976 Btree *pBt;
6978 pOut = out2Prerelease(p, pOp);
6979 pBt = db->aDb[pOp->p1].pBt;
6980 newMax = 0;
6981 if( pOp->p3 ){
6982 newMax = sqlite3BtreeLastPage(pBt);
6983 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
6985 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
6986 break;
6988 #endif
6990 /* Opcode: Function0 P1 P2 P3 P4 P5
6991 ** Synopsis: r[P3]=func(r[P2@P5])
6993 ** Invoke a user function (P4 is a pointer to a FuncDef object that
6994 ** defines the function) with P5 arguments taken from register P2 and
6995 ** successors. The result of the function is stored in register P3.
6996 ** Register P3 must not be one of the function inputs.
6998 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
6999 ** function was determined to be constant at compile time. If the first
7000 ** argument was constant then bit 0 of P1 is set. This is used to determine
7001 ** whether meta data associated with a user function argument using the
7002 ** sqlite3_set_auxdata() API may be safely retained until the next
7003 ** invocation of this opcode.
7005 ** See also: Function, AggStep, AggFinal
7007 /* Opcode: Function P1 P2 P3 P4 P5
7008 ** Synopsis: r[P3]=func(r[P2@P5])
7010 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7011 ** contains a pointer to the function to be run) with P5 arguments taken
7012 ** from register P2 and successors. The result of the function is stored
7013 ** in register P3. Register P3 must not be one of the function inputs.
7015 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7016 ** function was determined to be constant at compile time. If the first
7017 ** argument was constant then bit 0 of P1 is set. This is used to determine
7018 ** whether meta data associated with a user function argument using the
7019 ** sqlite3_set_auxdata() API may be safely retained until the next
7020 ** invocation of this opcode.
7022 ** SQL functions are initially coded as OP_Function0 with P4 pointing
7023 ** to a FuncDef object. But on first evaluation, the P4 operand is
7024 ** automatically converted into an sqlite3_context object and the operation
7025 ** changed to this OP_Function opcode. In this way, the initialization of
7026 ** the sqlite3_context object occurs only once, rather than once for each
7027 ** evaluation of the function.
7029 ** See also: Function0, AggStep, AggFinal
7031 case OP_PureFunc0:
7032 case OP_Function0: {
7033 int n;
7034 sqlite3_context *pCtx;
7036 assert( pOp->p4type==P4_FUNCDEF );
7037 n = pOp->p5;
7038 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7039 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7040 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7041 pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
7042 if( pCtx==0 ) goto no_mem;
7043 pCtx->pOut = 0;
7044 pCtx->pFunc = pOp->p4.pFunc;
7045 pCtx->iOp = (int)(pOp - aOp);
7046 pCtx->pVdbe = p;
7047 pCtx->isError = 0;
7048 pCtx->argc = n;
7049 pOp->p4type = P4_FUNCCTX;
7050 pOp->p4.pCtx = pCtx;
7051 assert( OP_PureFunc == OP_PureFunc0+2 );
7052 assert( OP_Function == OP_Function0+2 );
7053 pOp->opcode += 2;
7054 /* Fall through into OP_Function */
7056 case OP_PureFunc:
7057 case OP_Function: {
7058 int i;
7059 sqlite3_context *pCtx;
7061 assert( pOp->p4type==P4_FUNCCTX );
7062 pCtx = pOp->p4.pCtx;
7064 /* If this function is inside of a trigger, the register array in aMem[]
7065 ** might change from one evaluation to the next. The next block of code
7066 ** checks to see if the register array has changed, and if so it
7067 ** reinitializes the relavant parts of the sqlite3_context object */
7068 pOut = &aMem[pOp->p3];
7069 if( pCtx->pOut != pOut ){
7070 pCtx->pOut = pOut;
7071 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7074 memAboutToChange(p, pOut);
7075 #ifdef SQLITE_DEBUG
7076 for(i=0; i<pCtx->argc; i++){
7077 assert( memIsValid(pCtx->argv[i]) );
7078 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7080 #endif
7081 MemSetTypeFlag(pOut, MEM_Null);
7082 assert( pCtx->isError==0 );
7083 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
7085 /* If the function returned an error, throw an exception */
7086 if( pCtx->isError ){
7087 if( pCtx->isError>0 ){
7088 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
7089 rc = pCtx->isError;
7091 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
7092 pCtx->isError = 0;
7093 if( rc ) goto abort_due_to_error;
7096 /* Copy the result of the function into register P3 */
7097 if( pOut->flags & (MEM_Str|MEM_Blob) ){
7098 sqlite3VdbeChangeEncoding(pOut, encoding);
7099 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
7102 REGISTER_TRACE(pOp->p3, pOut);
7103 UPDATE_MAX_BLOBSIZE(pOut);
7104 break;
7107 /* Opcode: Trace P1 P2 * P4 *
7109 ** Write P4 on the statement trace output if statement tracing is
7110 ** enabled.
7112 ** Operand P1 must be 0x7fffffff and P2 must positive.
7114 /* Opcode: Init P1 P2 P3 P4 *
7115 ** Synopsis: Start at P2
7117 ** Programs contain a single instance of this opcode as the very first
7118 ** opcode.
7120 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7121 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7122 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7124 ** If P2 is not zero, jump to instruction P2.
7126 ** Increment the value of P1 so that OP_Once opcodes will jump the
7127 ** first time they are evaluated for this run.
7129 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7130 ** error is encountered.
7132 case OP_Trace:
7133 case OP_Init: { /* jump */
7134 int i;
7135 #ifndef SQLITE_OMIT_TRACE
7136 char *zTrace;
7137 #endif
7139 /* If the P4 argument is not NULL, then it must be an SQL comment string.
7140 ** The "--" string is broken up to prevent false-positives with srcck1.c.
7142 ** This assert() provides evidence for:
7143 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7144 ** would have been returned by the legacy sqlite3_trace() interface by
7145 ** using the X argument when X begins with "--" and invoking
7146 ** sqlite3_expanded_sql(P) otherwise.
7148 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
7150 /* OP_Init is always instruction 0 */
7151 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
7153 #ifndef SQLITE_OMIT_TRACE
7154 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
7155 && !p->doingRerun
7156 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7158 #ifndef SQLITE_OMIT_DEPRECATED
7159 if( db->mTrace & SQLITE_TRACE_LEGACY ){
7160 void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
7161 char *z = sqlite3VdbeExpandSql(p, zTrace);
7162 x(db->pTraceArg, z);
7163 sqlite3_free(z);
7164 }else
7165 #endif
7166 if( db->nVdbeExec>1 ){
7167 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
7168 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
7169 sqlite3DbFree(db, z);
7170 }else{
7171 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
7174 #ifdef SQLITE_USE_FCNTL_TRACE
7175 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
7176 if( zTrace ){
7177 int j;
7178 for(j=0; j<db->nDb; j++){
7179 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
7180 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
7183 #endif /* SQLITE_USE_FCNTL_TRACE */
7184 #ifdef SQLITE_DEBUG
7185 if( (db->flags & SQLITE_SqlTrace)!=0
7186 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7188 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
7190 #endif /* SQLITE_DEBUG */
7191 #endif /* SQLITE_OMIT_TRACE */
7192 assert( pOp->p2>0 );
7193 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
7194 if( pOp->opcode==OP_Trace ) break;
7195 for(i=1; i<p->nOp; i++){
7196 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
7198 pOp->p1 = 0;
7200 pOp->p1++;
7201 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
7202 goto jump_to_p2;
7205 #ifdef SQLITE_ENABLE_CURSOR_HINTS
7206 /* Opcode: CursorHint P1 * * P4 *
7208 ** Provide a hint to cursor P1 that it only needs to return rows that
7209 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
7210 ** to values currently held in registers. TK_COLUMN terms in the P4
7211 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
7213 case OP_CursorHint: {
7214 VdbeCursor *pC;
7216 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7217 assert( pOp->p4type==P4_EXPR );
7218 pC = p->apCsr[pOp->p1];
7219 if( pC ){
7220 assert( pC->eCurType==CURTYPE_BTREE );
7221 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
7222 pOp->p4.pExpr, aMem);
7224 break;
7226 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
7228 /* Opcode: Noop * * * * *
7230 ** Do nothing. This instruction is often useful as a jump
7231 ** destination.
7234 ** The magic Explain opcode are only inserted when explain==2 (which
7235 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
7236 ** This opcode records information from the optimizer. It is the
7237 ** the same as a no-op. This opcodesnever appears in a real VM program.
7239 default: { /* This is really OP_Noop and OP_Explain */
7240 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
7241 break;
7244 /*****************************************************************************
7245 ** The cases of the switch statement above this line should all be indented
7246 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
7247 ** readability. From this point on down, the normal indentation rules are
7248 ** restored.
7249 *****************************************************************************/
7252 #ifdef VDBE_PROFILE
7254 u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
7255 if( endTime>start ) pOrigOp->cycles += endTime - start;
7256 pOrigOp->cnt++;
7258 #endif
7260 /* The following code adds nothing to the actual functionality
7261 ** of the program. It is only here for testing and debugging.
7262 ** On the other hand, it does burn CPU cycles every time through
7263 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
7265 #ifndef NDEBUG
7266 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
7268 #ifdef SQLITE_DEBUG
7269 if( db->flags & SQLITE_VdbeTrace ){
7270 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
7271 if( rc!=0 ) printf("rc=%d\n",rc);
7272 if( opProperty & (OPFLG_OUT2) ){
7273 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
7275 if( opProperty & OPFLG_OUT3 ){
7276 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
7279 #endif /* SQLITE_DEBUG */
7280 #endif /* NDEBUG */
7281 } /* The end of the for(;;) loop the loops through opcodes */
7283 /* If we reach this point, it means that execution is finished with
7284 ** an error of some kind.
7286 abort_due_to_error:
7287 if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
7288 assert( rc );
7289 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
7290 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7292 p->rc = rc;
7293 sqlite3SystemError(db, rc);
7294 testcase( sqlite3GlobalConfig.xLog!=0 );
7295 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
7296 (int)(pOp - aOp), p->zSql, p->zErrMsg);
7297 sqlite3VdbeHalt(p);
7298 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
7299 rc = SQLITE_ERROR;
7300 if( resetSchemaOnFault>0 ){
7301 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
7304 /* This is the only way out of this procedure. We have to
7305 ** release the mutexes on btrees that were acquired at the
7306 ** top. */
7307 vdbe_return:
7308 testcase( nVmStep>0 );
7309 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
7310 sqlite3VdbeLeave(p);
7311 assert( rc!=SQLITE_OK || nExtraDelete==0
7312 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
7314 return rc;
7316 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
7317 ** is encountered.
7319 too_big:
7320 sqlite3VdbeError(p, "string or blob too big");
7321 rc = SQLITE_TOOBIG;
7322 goto abort_due_to_error;
7324 /* Jump to here if a malloc() fails.
7326 no_mem:
7327 sqlite3OomFault(db);
7328 sqlite3VdbeError(p, "out of memory");
7329 rc = SQLITE_NOMEM_BKPT;
7330 goto abort_due_to_error;
7332 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
7333 ** flag.
7335 abort_due_to_interrupt:
7336 assert( db->u1.isInterrupted );
7337 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
7338 p->rc = rc;
7339 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7340 goto abort_due_to_error;