Ensure that sqlite3AuthRead() is only call for TK_COLUMN and TK_TRIGGER
[sqlite.git] / src / vdbe.c
blobcab69b56b4c7a4f3d2d13035d058cb041ef0106e
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 #ifdef SQLITE_DEBUG
919 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
920 #endif
921 if( (pIn3->flags & MEM_Null)==0 ) break;
922 /* Fall through into OP_Halt */
925 /* Opcode: Halt P1 P2 * P4 P5
927 ** Exit immediately. All open cursors, etc are closed
928 ** automatically.
930 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
931 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
932 ** For errors, it can be some other value. If P1!=0 then P2 will determine
933 ** whether or not to rollback the current transaction. Do not rollback
934 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
935 ** then back out all changes that have occurred during this execution of the
936 ** VDBE, but do not rollback the transaction.
938 ** If P4 is not null then it is an error message string.
940 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
942 ** 0: (no change)
943 ** 1: NOT NULL contraint failed: P4
944 ** 2: UNIQUE constraint failed: P4
945 ** 3: CHECK constraint failed: P4
946 ** 4: FOREIGN KEY constraint failed: P4
948 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
949 ** omitted.
951 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
952 ** every program. So a jump past the last instruction of the program
953 ** is the same as executing Halt.
955 case OP_Halt: {
956 VdbeFrame *pFrame;
957 int pcx;
959 pcx = (int)(pOp - aOp);
960 #ifdef SQLITE_DEBUG
961 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
962 #endif
963 if( pOp->p1==SQLITE_OK && p->pFrame ){
964 /* Halt the sub-program. Return control to the parent frame. */
965 pFrame = p->pFrame;
966 p->pFrame = pFrame->pParent;
967 p->nFrame--;
968 sqlite3VdbeSetChanges(db, p->nChange);
969 pcx = sqlite3VdbeFrameRestore(pFrame);
970 if( pOp->p2==OE_Ignore ){
971 /* Instruction pcx is the OP_Program that invoked the sub-program
972 ** currently being halted. If the p2 instruction of this OP_Halt
973 ** instruction is set to OE_Ignore, then the sub-program is throwing
974 ** an IGNORE exception. In this case jump to the address specified
975 ** as the p2 of the calling OP_Program. */
976 pcx = p->aOp[pcx].p2-1;
978 aOp = p->aOp;
979 aMem = p->aMem;
980 pOp = &aOp[pcx];
981 break;
983 p->rc = pOp->p1;
984 p->errorAction = (u8)pOp->p2;
985 p->pc = pcx;
986 assert( pOp->p5<=4 );
987 if( p->rc ){
988 if( pOp->p5 ){
989 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
990 "FOREIGN KEY" };
991 testcase( pOp->p5==1 );
992 testcase( pOp->p5==2 );
993 testcase( pOp->p5==3 );
994 testcase( pOp->p5==4 );
995 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
996 if( pOp->p4.z ){
997 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
999 }else{
1000 sqlite3VdbeError(p, "%s", pOp->p4.z);
1002 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
1004 rc = sqlite3VdbeHalt(p);
1005 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1006 if( rc==SQLITE_BUSY ){
1007 p->rc = SQLITE_BUSY;
1008 }else{
1009 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1010 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1011 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1013 goto vdbe_return;
1016 /* Opcode: Integer P1 P2 * * *
1017 ** Synopsis: r[P2]=P1
1019 ** The 32-bit integer value P1 is written into register P2.
1021 case OP_Integer: { /* out2 */
1022 pOut = out2Prerelease(p, pOp);
1023 pOut->u.i = pOp->p1;
1024 break;
1027 /* Opcode: Int64 * P2 * P4 *
1028 ** Synopsis: r[P2]=P4
1030 ** P4 is a pointer to a 64-bit integer value.
1031 ** Write that value into register P2.
1033 case OP_Int64: { /* out2 */
1034 pOut = out2Prerelease(p, pOp);
1035 assert( pOp->p4.pI64!=0 );
1036 pOut->u.i = *pOp->p4.pI64;
1037 break;
1040 #ifndef SQLITE_OMIT_FLOATING_POINT
1041 /* Opcode: Real * P2 * P4 *
1042 ** Synopsis: r[P2]=P4
1044 ** P4 is a pointer to a 64-bit floating point value.
1045 ** Write that value into register P2.
1047 case OP_Real: { /* same as TK_FLOAT, out2 */
1048 pOut = out2Prerelease(p, pOp);
1049 pOut->flags = MEM_Real;
1050 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1051 pOut->u.r = *pOp->p4.pReal;
1052 break;
1054 #endif
1056 /* Opcode: String8 * P2 * P4 *
1057 ** Synopsis: r[P2]='P4'
1059 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1060 ** into a String opcode before it is executed for the first time. During
1061 ** this transformation, the length of string P4 is computed and stored
1062 ** as the P1 parameter.
1064 case OP_String8: { /* same as TK_STRING, out2 */
1065 assert( pOp->p4.z!=0 );
1066 pOut = out2Prerelease(p, pOp);
1067 pOp->opcode = OP_String;
1068 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1070 #ifndef SQLITE_OMIT_UTF16
1071 if( encoding!=SQLITE_UTF8 ){
1072 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1073 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1074 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1075 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1076 assert( VdbeMemDynamic(pOut)==0 );
1077 pOut->szMalloc = 0;
1078 pOut->flags |= MEM_Static;
1079 if( pOp->p4type==P4_DYNAMIC ){
1080 sqlite3DbFree(db, pOp->p4.z);
1082 pOp->p4type = P4_DYNAMIC;
1083 pOp->p4.z = pOut->z;
1084 pOp->p1 = pOut->n;
1086 testcase( rc==SQLITE_TOOBIG );
1087 #endif
1088 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1089 goto too_big;
1091 assert( rc==SQLITE_OK );
1092 /* Fall through to the next case, OP_String */
1095 /* Opcode: String P1 P2 P3 P4 P5
1096 ** Synopsis: r[P2]='P4' (len=P1)
1098 ** The string value P4 of length P1 (bytes) is stored in register P2.
1100 ** If P3 is not zero and the content of register P3 is equal to P5, then
1101 ** the datatype of the register P2 is converted to BLOB. The content is
1102 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1103 ** of a string, as if it had been CAST. In other words:
1105 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1107 case OP_String: { /* out2 */
1108 assert( pOp->p4.z!=0 );
1109 pOut = out2Prerelease(p, pOp);
1110 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1111 pOut->z = pOp->p4.z;
1112 pOut->n = pOp->p1;
1113 pOut->enc = encoding;
1114 UPDATE_MAX_BLOBSIZE(pOut);
1115 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1116 if( pOp->p3>0 ){
1117 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1118 pIn3 = &aMem[pOp->p3];
1119 assert( pIn3->flags & MEM_Int );
1120 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1122 #endif
1123 break;
1126 /* Opcode: Null P1 P2 P3 * *
1127 ** Synopsis: r[P2..P3]=NULL
1129 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1130 ** NULL into register P3 and every register in between P2 and P3. If P3
1131 ** is less than P2 (typically P3 is zero) then only register P2 is
1132 ** set to NULL.
1134 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1135 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1136 ** OP_Ne or OP_Eq.
1138 case OP_Null: { /* out2 */
1139 int cnt;
1140 u16 nullFlag;
1141 pOut = out2Prerelease(p, pOp);
1142 cnt = pOp->p3-pOp->p2;
1143 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1144 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1145 pOut->n = 0;
1146 while( cnt>0 ){
1147 pOut++;
1148 memAboutToChange(p, pOut);
1149 sqlite3VdbeMemSetNull(pOut);
1150 pOut->flags = nullFlag;
1151 pOut->n = 0;
1152 cnt--;
1154 break;
1157 /* Opcode: SoftNull P1 * * * *
1158 ** Synopsis: r[P1]=NULL
1160 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1161 ** instruction, but do not free any string or blob memory associated with
1162 ** the register, so that if the value was a string or blob that was
1163 ** previously copied using OP_SCopy, the copies will continue to be valid.
1165 case OP_SoftNull: {
1166 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1167 pOut = &aMem[pOp->p1];
1168 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1169 break;
1172 /* Opcode: Blob P1 P2 * P4 *
1173 ** Synopsis: r[P2]=P4 (len=P1)
1175 ** P4 points to a blob of data P1 bytes long. Store this
1176 ** blob in register P2.
1178 case OP_Blob: { /* out2 */
1179 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1180 pOut = out2Prerelease(p, pOp);
1181 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1182 pOut->enc = encoding;
1183 UPDATE_MAX_BLOBSIZE(pOut);
1184 break;
1187 /* Opcode: Variable P1 P2 * P4 *
1188 ** Synopsis: r[P2]=parameter(P1,P4)
1190 ** Transfer the values of bound parameter P1 into register P2
1192 ** If the parameter is named, then its name appears in P4.
1193 ** The P4 value is used by sqlite3_bind_parameter_name().
1195 case OP_Variable: { /* out2 */
1196 Mem *pVar; /* Value being transferred */
1198 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1199 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1200 pVar = &p->aVar[pOp->p1 - 1];
1201 if( sqlite3VdbeMemTooBig(pVar) ){
1202 goto too_big;
1204 pOut = &aMem[pOp->p2];
1205 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
1206 UPDATE_MAX_BLOBSIZE(pOut);
1207 break;
1210 /* Opcode: Move P1 P2 P3 * *
1211 ** Synopsis: r[P2@P3]=r[P1@P3]
1213 ** Move the P3 values in register P1..P1+P3-1 over into
1214 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1215 ** left holding a NULL. It is an error for register ranges
1216 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1217 ** for P3 to be less than 1.
1219 case OP_Move: {
1220 int n; /* Number of registers left to copy */
1221 int p1; /* Register to copy from */
1222 int p2; /* Register to copy to */
1224 n = pOp->p3;
1225 p1 = pOp->p1;
1226 p2 = pOp->p2;
1227 assert( n>0 && p1>0 && p2>0 );
1228 assert( p1+n<=p2 || p2+n<=p1 );
1230 pIn1 = &aMem[p1];
1231 pOut = &aMem[p2];
1233 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1234 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1235 assert( memIsValid(pIn1) );
1236 memAboutToChange(p, pOut);
1237 sqlite3VdbeMemMove(pOut, pIn1);
1238 #ifdef SQLITE_DEBUG
1239 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
1240 pOut->pScopyFrom += pOp->p2 - p1;
1242 #endif
1243 Deephemeralize(pOut);
1244 REGISTER_TRACE(p2++, pOut);
1245 pIn1++;
1246 pOut++;
1247 }while( --n );
1248 break;
1251 /* Opcode: Copy P1 P2 P3 * *
1252 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1254 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1256 ** This instruction makes a deep copy of the value. A duplicate
1257 ** is made of any string or blob constant. See also OP_SCopy.
1259 case OP_Copy: {
1260 int n;
1262 n = pOp->p3;
1263 pIn1 = &aMem[pOp->p1];
1264 pOut = &aMem[pOp->p2];
1265 assert( pOut!=pIn1 );
1266 while( 1 ){
1267 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1268 Deephemeralize(pOut);
1269 #ifdef SQLITE_DEBUG
1270 pOut->pScopyFrom = 0;
1271 #endif
1272 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1273 if( (n--)==0 ) break;
1274 pOut++;
1275 pIn1++;
1277 break;
1280 /* Opcode: SCopy P1 P2 * * *
1281 ** Synopsis: r[P2]=r[P1]
1283 ** Make a shallow copy of register P1 into register P2.
1285 ** This instruction makes a shallow copy of the value. If the value
1286 ** is a string or blob, then the copy is only a pointer to the
1287 ** original and hence if the original changes so will the copy.
1288 ** Worse, if the original is deallocated, the copy becomes invalid.
1289 ** Thus the program must guarantee that the original will not change
1290 ** during the lifetime of the copy. Use OP_Copy to make a complete
1291 ** copy.
1293 case OP_SCopy: { /* out2 */
1294 pIn1 = &aMem[pOp->p1];
1295 pOut = &aMem[pOp->p2];
1296 assert( pOut!=pIn1 );
1297 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1298 #ifdef SQLITE_DEBUG
1299 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
1300 #endif
1301 break;
1304 /* Opcode: IntCopy P1 P2 * * *
1305 ** Synopsis: r[P2]=r[P1]
1307 ** Transfer the integer value held in register P1 into register P2.
1309 ** This is an optimized version of SCopy that works only for integer
1310 ** values.
1312 case OP_IntCopy: { /* out2 */
1313 pIn1 = &aMem[pOp->p1];
1314 assert( (pIn1->flags & MEM_Int)!=0 );
1315 pOut = &aMem[pOp->p2];
1316 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1317 break;
1320 /* Opcode: ResultRow P1 P2 * * *
1321 ** Synopsis: output=r[P1@P2]
1323 ** The registers P1 through P1+P2-1 contain a single row of
1324 ** results. This opcode causes the sqlite3_step() call to terminate
1325 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1326 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1327 ** the result row.
1329 case OP_ResultRow: {
1330 Mem *pMem;
1331 int i;
1332 assert( p->nResColumn==pOp->p2 );
1333 assert( pOp->p1>0 );
1334 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1336 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1337 /* Run the progress counter just before returning.
1339 if( db->xProgress!=0
1340 && nVmStep>=nProgressLimit
1341 && db->xProgress(db->pProgressArg)!=0
1343 rc = SQLITE_INTERRUPT;
1344 goto abort_due_to_error;
1346 #endif
1348 /* If this statement has violated immediate foreign key constraints, do
1349 ** not return the number of rows modified. And do not RELEASE the statement
1350 ** transaction. It needs to be rolled back. */
1351 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
1352 assert( db->flags&SQLITE_CountRows );
1353 assert( p->usesStmtJournal );
1354 goto abort_due_to_error;
1357 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1358 ** DML statements invoke this opcode to return the number of rows
1359 ** modified to the user. This is the only way that a VM that
1360 ** opens a statement transaction may invoke this opcode.
1362 ** In case this is such a statement, close any statement transaction
1363 ** opened by this VM before returning control to the user. This is to
1364 ** ensure that statement-transactions are always nested, not overlapping.
1365 ** If the open statement-transaction is not closed here, then the user
1366 ** may step another VM that opens its own statement transaction. This
1367 ** may lead to overlapping statement transactions.
1369 ** The statement transaction is never a top-level transaction. Hence
1370 ** the RELEASE call below can never fail.
1372 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
1373 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
1374 assert( rc==SQLITE_OK );
1376 /* Invalidate all ephemeral cursor row caches */
1377 p->cacheCtr = (p->cacheCtr + 2)|1;
1379 /* Make sure the results of the current row are \000 terminated
1380 ** and have an assigned type. The results are de-ephemeralized as
1381 ** a side effect.
1383 pMem = p->pResultSet = &aMem[pOp->p1];
1384 for(i=0; i<pOp->p2; i++){
1385 assert( memIsValid(&pMem[i]) );
1386 Deephemeralize(&pMem[i]);
1387 assert( (pMem[i].flags & MEM_Ephem)==0
1388 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1389 sqlite3VdbeMemNulTerminate(&pMem[i]);
1390 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1392 if( db->mallocFailed ) goto no_mem;
1394 if( db->mTrace & SQLITE_TRACE_ROW ){
1395 db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1398 /* Return SQLITE_ROW
1400 p->pc = (int)(pOp - aOp) + 1;
1401 rc = SQLITE_ROW;
1402 goto vdbe_return;
1405 /* Opcode: Concat P1 P2 P3 * *
1406 ** Synopsis: r[P3]=r[P2]+r[P1]
1408 ** Add the text in register P1 onto the end of the text in
1409 ** register P2 and store the result in register P3.
1410 ** If either the P1 or P2 text are NULL then store NULL in P3.
1412 ** P3 = P2 || P1
1414 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1415 ** if P3 is the same register as P2, the implementation is able
1416 ** to avoid a memcpy().
1418 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1419 i64 nByte;
1421 pIn1 = &aMem[pOp->p1];
1422 pIn2 = &aMem[pOp->p2];
1423 pOut = &aMem[pOp->p3];
1424 assert( pIn1!=pOut );
1425 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1426 sqlite3VdbeMemSetNull(pOut);
1427 break;
1429 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
1430 Stringify(pIn1, encoding);
1431 Stringify(pIn2, encoding);
1432 nByte = pIn1->n + pIn2->n;
1433 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1434 goto too_big;
1436 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1437 goto no_mem;
1439 MemSetTypeFlag(pOut, MEM_Str);
1440 if( pOut!=pIn2 ){
1441 memcpy(pOut->z, pIn2->z, pIn2->n);
1443 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1444 pOut->z[nByte]=0;
1445 pOut->z[nByte+1] = 0;
1446 pOut->flags |= MEM_Term;
1447 pOut->n = (int)nByte;
1448 pOut->enc = encoding;
1449 UPDATE_MAX_BLOBSIZE(pOut);
1450 break;
1453 /* Opcode: Add P1 P2 P3 * *
1454 ** Synopsis: r[P3]=r[P1]+r[P2]
1456 ** Add the value in register P1 to the value in register P2
1457 ** and store the result in register P3.
1458 ** If either input is NULL, the result is NULL.
1460 /* Opcode: Multiply P1 P2 P3 * *
1461 ** Synopsis: r[P3]=r[P1]*r[P2]
1464 ** Multiply the value in register P1 by the value in register P2
1465 ** and store the result in register P3.
1466 ** If either input is NULL, the result is NULL.
1468 /* Opcode: Subtract P1 P2 P3 * *
1469 ** Synopsis: r[P3]=r[P2]-r[P1]
1471 ** Subtract the value in register P1 from the value in register P2
1472 ** and store the result in register P3.
1473 ** If either input is NULL, the result is NULL.
1475 /* Opcode: Divide P1 P2 P3 * *
1476 ** Synopsis: r[P3]=r[P2]/r[P1]
1478 ** Divide the value in register P1 by the value in register P2
1479 ** and store the result in register P3 (P3=P2/P1). If the value in
1480 ** register P1 is zero, then the result is NULL. If either input is
1481 ** NULL, the result is NULL.
1483 /* Opcode: Remainder P1 P2 P3 * *
1484 ** Synopsis: r[P3]=r[P2]%r[P1]
1486 ** Compute the remainder after integer register P2 is divided by
1487 ** register P1 and store the result in register P3.
1488 ** If the value in register P1 is zero the result is NULL.
1489 ** If either operand is NULL, the result is NULL.
1491 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1492 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1493 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1494 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1495 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1496 char bIntint; /* Started out as two integer operands */
1497 u16 flags; /* Combined MEM_* flags from both inputs */
1498 u16 type1; /* Numeric type of left operand */
1499 u16 type2; /* Numeric type of right operand */
1500 i64 iA; /* Integer value of left operand */
1501 i64 iB; /* Integer value of right operand */
1502 double rA; /* Real value of left operand */
1503 double rB; /* Real value of right operand */
1505 pIn1 = &aMem[pOp->p1];
1506 type1 = numericType(pIn1);
1507 pIn2 = &aMem[pOp->p2];
1508 type2 = numericType(pIn2);
1509 pOut = &aMem[pOp->p3];
1510 flags = pIn1->flags | pIn2->flags;
1511 if( (type1 & type2 & MEM_Int)!=0 ){
1512 iA = pIn1->u.i;
1513 iB = pIn2->u.i;
1514 bIntint = 1;
1515 switch( pOp->opcode ){
1516 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1517 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1518 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1519 case OP_Divide: {
1520 if( iA==0 ) goto arithmetic_result_is_null;
1521 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1522 iB /= iA;
1523 break;
1525 default: {
1526 if( iA==0 ) goto arithmetic_result_is_null;
1527 if( iA==-1 ) iA = 1;
1528 iB %= iA;
1529 break;
1532 pOut->u.i = iB;
1533 MemSetTypeFlag(pOut, MEM_Int);
1534 }else if( (flags & MEM_Null)!=0 ){
1535 goto arithmetic_result_is_null;
1536 }else{
1537 bIntint = 0;
1538 fp_math:
1539 rA = sqlite3VdbeRealValue(pIn1);
1540 rB = sqlite3VdbeRealValue(pIn2);
1541 switch( pOp->opcode ){
1542 case OP_Add: rB += rA; break;
1543 case OP_Subtract: rB -= rA; break;
1544 case OP_Multiply: rB *= rA; break;
1545 case OP_Divide: {
1546 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1547 if( rA==(double)0 ) goto arithmetic_result_is_null;
1548 rB /= rA;
1549 break;
1551 default: {
1552 iA = (i64)rA;
1553 iB = (i64)rB;
1554 if( iA==0 ) goto arithmetic_result_is_null;
1555 if( iA==-1 ) iA = 1;
1556 rB = (double)(iB % iA);
1557 break;
1560 #ifdef SQLITE_OMIT_FLOATING_POINT
1561 pOut->u.i = rB;
1562 MemSetTypeFlag(pOut, MEM_Int);
1563 #else
1564 if( sqlite3IsNaN(rB) ){
1565 goto arithmetic_result_is_null;
1567 pOut->u.r = rB;
1568 MemSetTypeFlag(pOut, MEM_Real);
1569 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
1570 sqlite3VdbeIntegerAffinity(pOut);
1572 #endif
1574 break;
1576 arithmetic_result_is_null:
1577 sqlite3VdbeMemSetNull(pOut);
1578 break;
1581 /* Opcode: CollSeq P1 * * P4
1583 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1584 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1585 ** be returned. This is used by the built-in min(), max() and nullif()
1586 ** functions.
1588 ** If P1 is not zero, then it is a register that a subsequent min() or
1589 ** max() aggregate will set to 1 if the current row is not the minimum or
1590 ** maximum. The P1 register is initialized to 0 by this instruction.
1592 ** The interface used by the implementation of the aforementioned functions
1593 ** to retrieve the collation sequence set by this opcode is not available
1594 ** publicly. Only built-in functions have access to this feature.
1596 case OP_CollSeq: {
1597 assert( pOp->p4type==P4_COLLSEQ );
1598 if( pOp->p1 ){
1599 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1601 break;
1604 /* Opcode: BitAnd P1 P2 P3 * *
1605 ** Synopsis: r[P3]=r[P1]&r[P2]
1607 ** Take the bit-wise AND of the values in register P1 and P2 and
1608 ** store the result in register P3.
1609 ** If either input is NULL, the result is NULL.
1611 /* Opcode: BitOr P1 P2 P3 * *
1612 ** Synopsis: r[P3]=r[P1]|r[P2]
1614 ** Take the bit-wise OR of the values in register P1 and P2 and
1615 ** store the result in register P3.
1616 ** If either input is NULL, the result is NULL.
1618 /* Opcode: ShiftLeft P1 P2 P3 * *
1619 ** Synopsis: r[P3]=r[P2]<<r[P1]
1621 ** Shift the integer value in register P2 to the left by the
1622 ** number of bits specified by the integer in register P1.
1623 ** Store the result in register P3.
1624 ** If either input is NULL, the result is NULL.
1626 /* Opcode: ShiftRight P1 P2 P3 * *
1627 ** Synopsis: r[P3]=r[P2]>>r[P1]
1629 ** Shift the integer value in register P2 to the right by the
1630 ** number of bits specified by the integer in register P1.
1631 ** Store the result in register P3.
1632 ** If either input is NULL, the result is NULL.
1634 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1635 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1636 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1637 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1638 i64 iA;
1639 u64 uA;
1640 i64 iB;
1641 u8 op;
1643 pIn1 = &aMem[pOp->p1];
1644 pIn2 = &aMem[pOp->p2];
1645 pOut = &aMem[pOp->p3];
1646 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1647 sqlite3VdbeMemSetNull(pOut);
1648 break;
1650 iA = sqlite3VdbeIntValue(pIn2);
1651 iB = sqlite3VdbeIntValue(pIn1);
1652 op = pOp->opcode;
1653 if( op==OP_BitAnd ){
1654 iA &= iB;
1655 }else if( op==OP_BitOr ){
1656 iA |= iB;
1657 }else if( iB!=0 ){
1658 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1660 /* If shifting by a negative amount, shift in the other direction */
1661 if( iB<0 ){
1662 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1663 op = 2*OP_ShiftLeft + 1 - op;
1664 iB = iB>(-64) ? -iB : 64;
1667 if( iB>=64 ){
1668 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1669 }else{
1670 memcpy(&uA, &iA, sizeof(uA));
1671 if( op==OP_ShiftLeft ){
1672 uA <<= iB;
1673 }else{
1674 uA >>= iB;
1675 /* Sign-extend on a right shift of a negative number */
1676 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1678 memcpy(&iA, &uA, sizeof(iA));
1681 pOut->u.i = iA;
1682 MemSetTypeFlag(pOut, MEM_Int);
1683 break;
1686 /* Opcode: AddImm P1 P2 * * *
1687 ** Synopsis: r[P1]=r[P1]+P2
1689 ** Add the constant P2 to the value in register P1.
1690 ** The result is always an integer.
1692 ** To force any register to be an integer, just add 0.
1694 case OP_AddImm: { /* in1 */
1695 pIn1 = &aMem[pOp->p1];
1696 memAboutToChange(p, pIn1);
1697 sqlite3VdbeMemIntegerify(pIn1);
1698 pIn1->u.i += pOp->p2;
1699 break;
1702 /* Opcode: MustBeInt P1 P2 * * *
1704 ** Force the value in register P1 to be an integer. If the value
1705 ** in P1 is not an integer and cannot be converted into an integer
1706 ** without data loss, then jump immediately to P2, or if P2==0
1707 ** raise an SQLITE_MISMATCH exception.
1709 case OP_MustBeInt: { /* jump, in1 */
1710 pIn1 = &aMem[pOp->p1];
1711 if( (pIn1->flags & MEM_Int)==0 ){
1712 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1713 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
1714 if( (pIn1->flags & MEM_Int)==0 ){
1715 if( pOp->p2==0 ){
1716 rc = SQLITE_MISMATCH;
1717 goto abort_due_to_error;
1718 }else{
1719 goto jump_to_p2;
1723 MemSetTypeFlag(pIn1, MEM_Int);
1724 break;
1727 #ifndef SQLITE_OMIT_FLOATING_POINT
1728 /* Opcode: RealAffinity P1 * * * *
1730 ** If register P1 holds an integer convert it to a real value.
1732 ** This opcode is used when extracting information from a column that
1733 ** has REAL affinity. Such column values may still be stored as
1734 ** integers, for space efficiency, but after extraction we want them
1735 ** to have only a real value.
1737 case OP_RealAffinity: { /* in1 */
1738 pIn1 = &aMem[pOp->p1];
1739 if( pIn1->flags & MEM_Int ){
1740 sqlite3VdbeMemRealify(pIn1);
1742 break;
1744 #endif
1746 #ifndef SQLITE_OMIT_CAST
1747 /* Opcode: Cast P1 P2 * * *
1748 ** Synopsis: affinity(r[P1])
1750 ** Force the value in register P1 to be the type defined by P2.
1752 ** <ul>
1753 ** <li> P2=='A' &rarr; BLOB
1754 ** <li> P2=='B' &rarr; TEXT
1755 ** <li> P2=='C' &rarr; NUMERIC
1756 ** <li> P2=='D' &rarr; INTEGER
1757 ** <li> P2=='E' &rarr; REAL
1758 ** </ul>
1760 ** A NULL value is not changed by this routine. It remains NULL.
1762 case OP_Cast: { /* in1 */
1763 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
1764 testcase( pOp->p2==SQLITE_AFF_TEXT );
1765 testcase( pOp->p2==SQLITE_AFF_BLOB );
1766 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
1767 testcase( pOp->p2==SQLITE_AFF_INTEGER );
1768 testcase( pOp->p2==SQLITE_AFF_REAL );
1769 pIn1 = &aMem[pOp->p1];
1770 memAboutToChange(p, pIn1);
1771 rc = ExpandBlob(pIn1);
1772 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
1773 UPDATE_MAX_BLOBSIZE(pIn1);
1774 if( rc ) goto abort_due_to_error;
1775 break;
1777 #endif /* SQLITE_OMIT_CAST */
1779 /* Opcode: Eq P1 P2 P3 P4 P5
1780 ** Synopsis: IF r[P3]==r[P1]
1782 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
1783 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
1784 ** store the result of comparison in register P2.
1786 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1787 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1788 ** to coerce both inputs according to this affinity before the
1789 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1790 ** affinity is used. Note that the affinity conversions are stored
1791 ** back into the input registers P1 and P3. So this opcode can cause
1792 ** persistent changes to registers P1 and P3.
1794 ** Once any conversions have taken place, and neither value is NULL,
1795 ** the values are compared. If both values are blobs then memcmp() is
1796 ** used to determine the results of the comparison. If both values
1797 ** are text, then the appropriate collating function specified in
1798 ** P4 is used to do the comparison. If P4 is not specified then
1799 ** memcmp() is used to compare text string. If both values are
1800 ** numeric, then a numeric comparison is used. If the two values
1801 ** are of different types, then numbers are considered less than
1802 ** strings and strings are considered less than blobs.
1804 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1805 ** true or false and is never NULL. If both operands are NULL then the result
1806 ** of comparison is true. If either operand is NULL then the result is false.
1807 ** If neither operand is NULL the result is the same as it would be if
1808 ** the SQLITE_NULLEQ flag were omitted from P5.
1810 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1811 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
1812 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
1814 /* Opcode: Ne P1 P2 P3 P4 P5
1815 ** Synopsis: IF r[P3]!=r[P1]
1817 ** This works just like the Eq opcode except that the jump is taken if
1818 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
1819 ** additional information.
1821 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1822 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
1823 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
1825 /* Opcode: Lt P1 P2 P3 P4 P5
1826 ** Synopsis: IF r[P3]<r[P1]
1828 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1829 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
1830 ** the result of comparison (0 or 1 or NULL) into register P2.
1832 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1833 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
1834 ** bit is clear then fall through if either operand is NULL.
1836 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1837 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1838 ** to coerce both inputs according to this affinity before the
1839 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1840 ** affinity is used. Note that the affinity conversions are stored
1841 ** back into the input registers P1 and P3. So this opcode can cause
1842 ** persistent changes to registers P1 and P3.
1844 ** Once any conversions have taken place, and neither value is NULL,
1845 ** the values are compared. If both values are blobs then memcmp() is
1846 ** used to determine the results of the comparison. If both values
1847 ** are text, then the appropriate collating function specified in
1848 ** P4 is used to do the comparison. If P4 is not specified then
1849 ** memcmp() is used to compare text string. If both values are
1850 ** numeric, then a numeric comparison is used. If the two values
1851 ** are of different types, then numbers are considered less than
1852 ** strings and strings are considered less than blobs.
1854 /* Opcode: Le P1 P2 P3 P4 P5
1855 ** Synopsis: IF r[P3]<=r[P1]
1857 ** This works just like the Lt opcode except that the jump is taken if
1858 ** the content of register P3 is less than or equal to the content of
1859 ** register P1. See the Lt opcode for additional information.
1861 /* Opcode: Gt P1 P2 P3 P4 P5
1862 ** Synopsis: IF r[P3]>r[P1]
1864 ** This works just like the Lt opcode except that the jump is taken if
1865 ** the content of register P3 is greater than the content of
1866 ** register P1. See the Lt opcode for additional information.
1868 /* Opcode: Ge P1 P2 P3 P4 P5
1869 ** Synopsis: IF r[P3]>=r[P1]
1871 ** This works just like the Lt opcode except that the jump is taken if
1872 ** the content of register P3 is greater than or equal to the content of
1873 ** register P1. See the Lt opcode for additional information.
1875 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
1876 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
1877 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
1878 case OP_Le: /* same as TK_LE, jump, in1, in3 */
1879 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
1880 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
1881 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
1882 char affinity; /* Affinity to use for comparison */
1883 u16 flags1; /* Copy of initial value of pIn1->flags */
1884 u16 flags3; /* Copy of initial value of pIn3->flags */
1886 pIn1 = &aMem[pOp->p1];
1887 pIn3 = &aMem[pOp->p3];
1888 flags1 = pIn1->flags;
1889 flags3 = pIn3->flags;
1890 if( (flags1 | flags3)&MEM_Null ){
1891 /* One or both operands are NULL */
1892 if( pOp->p5 & SQLITE_NULLEQ ){
1893 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1894 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1895 ** or not both operands are null.
1897 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
1898 assert( (flags1 & MEM_Cleared)==0 );
1899 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
1900 if( (flags1&flags3&MEM_Null)!=0
1901 && (flags3&MEM_Cleared)==0
1903 res = 0; /* Operands are equal */
1904 }else{
1905 res = 1; /* Operands are not equal */
1907 }else{
1908 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1909 ** then the result is always NULL.
1910 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1912 if( pOp->p5 & SQLITE_STOREP2 ){
1913 pOut = &aMem[pOp->p2];
1914 iCompare = 1; /* Operands are not equal */
1915 memAboutToChange(p, pOut);
1916 MemSetTypeFlag(pOut, MEM_Null);
1917 REGISTER_TRACE(pOp->p2, pOut);
1918 }else{
1919 VdbeBranchTaken(2,3);
1920 if( pOp->p5 & SQLITE_JUMPIFNULL ){
1921 goto jump_to_p2;
1924 break;
1926 }else{
1927 /* Neither operand is NULL. Do a comparison. */
1928 affinity = pOp->p5 & SQLITE_AFF_MASK;
1929 if( affinity>=SQLITE_AFF_NUMERIC ){
1930 if( (flags1 | flags3)&MEM_Str ){
1931 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1932 applyNumericAffinity(pIn1,0);
1933 testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
1934 flags3 = pIn3->flags;
1936 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1937 applyNumericAffinity(pIn3,0);
1940 /* Handle the common case of integer comparison here, as an
1941 ** optimization, to avoid a call to sqlite3MemCompare() */
1942 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
1943 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
1944 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
1945 res = 0;
1946 goto compare_op;
1948 }else if( affinity==SQLITE_AFF_TEXT ){
1949 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
1950 testcase( pIn1->flags & MEM_Int );
1951 testcase( pIn1->flags & MEM_Real );
1952 sqlite3VdbeMemStringify(pIn1, encoding, 1);
1953 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
1954 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
1955 assert( pIn1!=pIn3 );
1957 if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
1958 testcase( pIn3->flags & MEM_Int );
1959 testcase( pIn3->flags & MEM_Real );
1960 sqlite3VdbeMemStringify(pIn3, encoding, 1);
1961 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
1962 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
1965 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1966 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1968 compare_op:
1969 /* At this point, res is negative, zero, or positive if reg[P1] is
1970 ** less than, equal to, or greater than reg[P3], respectively. Compute
1971 ** the answer to this operator in res2, depending on what the comparison
1972 ** operator actually is. The next block of code depends on the fact
1973 ** that the 6 comparison operators are consecutive integers in this
1974 ** order: NE, EQ, GT, LE, LT, GE */
1975 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
1976 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
1977 if( res<0 ){ /* ne, eq, gt, le, lt, ge */
1978 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
1979 res2 = aLTb[pOp->opcode - OP_Ne];
1980 }else if( res==0 ){
1981 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
1982 res2 = aEQb[pOp->opcode - OP_Ne];
1983 }else{
1984 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
1985 res2 = aGTb[pOp->opcode - OP_Ne];
1988 /* Undo any changes made by applyAffinity() to the input registers. */
1989 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1990 pIn1->flags = flags1;
1991 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
1992 pIn3->flags = flags3;
1994 if( pOp->p5 & SQLITE_STOREP2 ){
1995 pOut = &aMem[pOp->p2];
1996 iCompare = res;
1997 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
1998 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
1999 ** and prevents OP_Ne from overwriting NULL with 0. This flag
2000 ** is only used in contexts where either:
2001 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
2002 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
2003 ** Therefore it is not necessary to check the content of r[P2] for
2004 ** NULL. */
2005 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
2006 assert( res2==0 || res2==1 );
2007 testcase( res2==0 && pOp->opcode==OP_Eq );
2008 testcase( res2==1 && pOp->opcode==OP_Eq );
2009 testcase( res2==0 && pOp->opcode==OP_Ne );
2010 testcase( res2==1 && pOp->opcode==OP_Ne );
2011 if( (pOp->opcode==OP_Eq)==res2 ) break;
2013 memAboutToChange(p, pOut);
2014 MemSetTypeFlag(pOut, MEM_Int);
2015 pOut->u.i = res2;
2016 REGISTER_TRACE(pOp->p2, pOut);
2017 }else{
2018 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2019 if( res2 ){
2020 goto jump_to_p2;
2023 break;
2026 /* Opcode: ElseNotEq * P2 * * *
2028 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
2029 ** If result of an OP_Eq comparison on the same two operands
2030 ** would have be NULL or false (0), then then jump to P2.
2031 ** If the result of an OP_Eq comparison on the two previous operands
2032 ** would have been true (1), then fall through.
2034 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
2035 assert( pOp>aOp );
2036 assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
2037 assert( pOp[-1].p5 & SQLITE_STOREP2 );
2038 VdbeBranchTaken(iCompare!=0, 2);
2039 if( iCompare!=0 ) goto jump_to_p2;
2040 break;
2044 /* Opcode: Permutation * * * P4 *
2046 ** Set the permutation used by the OP_Compare operator in the next
2047 ** instruction. The permutation is stored in the P4 operand.
2049 ** The permutation is only valid until the next OP_Compare that has
2050 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2051 ** occur immediately prior to the OP_Compare.
2053 ** The first integer in the P4 integer array is the length of the array
2054 ** and does not become part of the permutation.
2056 case OP_Permutation: {
2057 assert( pOp->p4type==P4_INTARRAY );
2058 assert( pOp->p4.ai );
2059 assert( pOp[1].opcode==OP_Compare );
2060 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2061 break;
2064 /* Opcode: Compare P1 P2 P3 P4 P5
2065 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2067 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2068 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2069 ** the comparison for use by the next OP_Jump instruct.
2071 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2072 ** determined by the most recent OP_Permutation operator. If the
2073 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2074 ** order.
2076 ** P4 is a KeyInfo structure that defines collating sequences and sort
2077 ** orders for the comparison. The permutation applies to registers
2078 ** only. The KeyInfo elements are used sequentially.
2080 ** The comparison is a sort comparison, so NULLs compare equal,
2081 ** NULLs are less than numbers, numbers are less than strings,
2082 ** and strings are less than blobs.
2084 case OP_Compare: {
2085 int n;
2086 int i;
2087 int p1;
2088 int p2;
2089 const KeyInfo *pKeyInfo;
2090 int idx;
2091 CollSeq *pColl; /* Collating sequence to use on this term */
2092 int bRev; /* True for DESCENDING sort order */
2093 int *aPermute; /* The permutation */
2095 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2096 aPermute = 0;
2097 }else{
2098 assert( pOp>aOp );
2099 assert( pOp[-1].opcode==OP_Permutation );
2100 assert( pOp[-1].p4type==P4_INTARRAY );
2101 aPermute = pOp[-1].p4.ai + 1;
2102 assert( aPermute!=0 );
2104 n = pOp->p3;
2105 pKeyInfo = pOp->p4.pKeyInfo;
2106 assert( n>0 );
2107 assert( pKeyInfo!=0 );
2108 p1 = pOp->p1;
2109 p2 = pOp->p2;
2110 #ifdef SQLITE_DEBUG
2111 if( aPermute ){
2112 int k, mx = 0;
2113 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
2114 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2115 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2116 }else{
2117 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2118 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2120 #endif /* SQLITE_DEBUG */
2121 for(i=0; i<n; i++){
2122 idx = aPermute ? aPermute[i] : i;
2123 assert( memIsValid(&aMem[p1+idx]) );
2124 assert( memIsValid(&aMem[p2+idx]) );
2125 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2126 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2127 assert( i<pKeyInfo->nKeyField );
2128 pColl = pKeyInfo->aColl[i];
2129 bRev = pKeyInfo->aSortOrder[i];
2130 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2131 if( iCompare ){
2132 if( bRev ) iCompare = -iCompare;
2133 break;
2136 break;
2139 /* Opcode: Jump P1 P2 P3 * *
2141 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2142 ** in the most recent OP_Compare instruction the P1 vector was less than
2143 ** equal to, or greater than the P2 vector, respectively.
2145 case OP_Jump: { /* jump */
2146 if( iCompare<0 ){
2147 VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
2148 }else if( iCompare==0 ){
2149 VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
2150 }else{
2151 VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
2153 break;
2156 /* Opcode: And P1 P2 P3 * *
2157 ** Synopsis: r[P3]=(r[P1] && r[P2])
2159 ** Take the logical AND of the values in registers P1 and P2 and
2160 ** write the result into register P3.
2162 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2163 ** the other input is NULL. A NULL and true or two NULLs give
2164 ** a NULL output.
2166 /* Opcode: Or P1 P2 P3 * *
2167 ** Synopsis: r[P3]=(r[P1] || r[P2])
2169 ** Take the logical OR of the values in register P1 and P2 and
2170 ** store the answer in register P3.
2172 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2173 ** even if the other input is NULL. A NULL and false or two NULLs
2174 ** give a NULL output.
2176 case OP_And: /* same as TK_AND, in1, in2, out3 */
2177 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2178 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2179 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2181 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2182 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2183 if( pOp->opcode==OP_And ){
2184 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2185 v1 = and_logic[v1*3+v2];
2186 }else{
2187 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2188 v1 = or_logic[v1*3+v2];
2190 pOut = &aMem[pOp->p3];
2191 if( v1==2 ){
2192 MemSetTypeFlag(pOut, MEM_Null);
2193 }else{
2194 pOut->u.i = v1;
2195 MemSetTypeFlag(pOut, MEM_Int);
2197 break;
2200 /* Opcode: IsTrue P1 P2 P3 P4 *
2201 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2203 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2204 ** IS NOT FALSE operators.
2206 ** Interpret the value in register P1 as a boolean value. Store that
2207 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2208 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2209 ** is 1.
2211 ** The logic is summarized like this:
2213 ** <ul>
2214 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2215 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2216 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2217 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2218 ** </ul>
2220 case OP_IsTrue: { /* in1, out2 */
2221 assert( pOp->p4type==P4_INT32 );
2222 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2223 assert( pOp->p3==0 || pOp->p3==1 );
2224 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2225 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2226 break;
2229 /* Opcode: Not P1 P2 * * *
2230 ** Synopsis: r[P2]= !r[P1]
2232 ** Interpret the value in register P1 as a boolean value. Store the
2233 ** boolean complement in register P2. If the value in register P1 is
2234 ** NULL, then a NULL is stored in P2.
2236 case OP_Not: { /* same as TK_NOT, in1, out2 */
2237 pIn1 = &aMem[pOp->p1];
2238 pOut = &aMem[pOp->p2];
2239 if( (pIn1->flags & MEM_Null)==0 ){
2240 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2241 }else{
2242 sqlite3VdbeMemSetNull(pOut);
2244 break;
2247 /* Opcode: BitNot P1 P2 * * *
2248 ** Synopsis: r[P1]= ~r[P1]
2250 ** Interpret the content of register P1 as an integer. Store the
2251 ** ones-complement of the P1 value into register P2. If P1 holds
2252 ** a NULL then store a NULL in P2.
2254 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2255 pIn1 = &aMem[pOp->p1];
2256 pOut = &aMem[pOp->p2];
2257 sqlite3VdbeMemSetNull(pOut);
2258 if( (pIn1->flags & MEM_Null)==0 ){
2259 pOut->flags = MEM_Int;
2260 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2262 break;
2265 /* Opcode: Once P1 P2 * * *
2267 ** Fall through to the next instruction the first time this opcode is
2268 ** encountered on each invocation of the byte-code program. Jump to P2
2269 ** on the second and all subsequent encounters during the same invocation.
2271 ** Top-level programs determine first invocation by comparing the P1
2272 ** operand against the P1 operand on the OP_Init opcode at the beginning
2273 ** of the program. If the P1 values differ, then fall through and make
2274 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2275 ** the same then take the jump.
2277 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2278 ** whether or not the jump should be taken. The bitmask is necessary
2279 ** because the self-altering code trick does not work for recursive
2280 ** triggers.
2282 case OP_Once: { /* jump */
2283 u32 iAddr; /* Address of this instruction */
2284 assert( p->aOp[0].opcode==OP_Init );
2285 if( p->pFrame ){
2286 iAddr = (int)(pOp - p->aOp);
2287 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2288 VdbeBranchTaken(1, 2);
2289 goto jump_to_p2;
2291 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2292 }else{
2293 if( p->aOp[0].p1==pOp->p1 ){
2294 VdbeBranchTaken(1, 2);
2295 goto jump_to_p2;
2298 VdbeBranchTaken(0, 2);
2299 pOp->p1 = p->aOp[0].p1;
2300 break;
2303 /* Opcode: If P1 P2 P3 * *
2305 ** Jump to P2 if the value in register P1 is true. The value
2306 ** is considered true if it is numeric and non-zero. If the value
2307 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2309 case OP_If: { /* jump, in1 */
2310 int c;
2311 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2312 VdbeBranchTaken(c!=0, 2);
2313 if( c ) goto jump_to_p2;
2314 break;
2317 /* Opcode: IfNot P1 P2 P3 * *
2319 ** Jump to P2 if the value in register P1 is False. The value
2320 ** is considered false if it has a numeric value of zero. If the value
2321 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2323 case OP_IfNot: { /* jump, in1 */
2324 int c;
2325 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2326 VdbeBranchTaken(c!=0, 2);
2327 if( c ) goto jump_to_p2;
2328 break;
2331 /* Opcode: IsNull P1 P2 * * *
2332 ** Synopsis: if r[P1]==NULL goto P2
2334 ** Jump to P2 if the value in register P1 is NULL.
2336 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2337 pIn1 = &aMem[pOp->p1];
2338 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2339 if( (pIn1->flags & MEM_Null)!=0 ){
2340 goto jump_to_p2;
2342 break;
2345 /* Opcode: NotNull P1 P2 * * *
2346 ** Synopsis: if r[P1]!=NULL goto P2
2348 ** Jump to P2 if the value in register P1 is not NULL.
2350 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2351 pIn1 = &aMem[pOp->p1];
2352 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2353 if( (pIn1->flags & MEM_Null)==0 ){
2354 goto jump_to_p2;
2356 break;
2359 /* Opcode: IfNullRow P1 P2 P3 * *
2360 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2362 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2363 ** If it is, then set register P3 to NULL and jump immediately to P2.
2364 ** If P1 is not on a NULL row, then fall through without making any
2365 ** changes.
2367 case OP_IfNullRow: { /* jump */
2368 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2369 assert( p->apCsr[pOp->p1]!=0 );
2370 if( p->apCsr[pOp->p1]->nullRow ){
2371 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2372 goto jump_to_p2;
2374 break;
2377 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2378 /* Opcode: Offset P1 P2 P3 * *
2379 ** Synopsis: r[P3] = sqlite_offset(P1)
2381 ** Store in register r[P3] the byte offset into the database file that is the
2382 ** start of the payload for the record at which that cursor P1 is currently
2383 ** pointing.
2385 ** P2 is the column number for the argument to the sqlite_offset() function.
2386 ** This opcode does not use P2 itself, but the P2 value is used by the
2387 ** code generator. The P1, P2, and P3 operands to this opcode are the
2388 ** same as for OP_Column.
2390 ** This opcode is only available if SQLite is compiled with the
2391 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2393 case OP_Offset: { /* out3 */
2394 VdbeCursor *pC; /* The VDBE cursor */
2395 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2396 pC = p->apCsr[pOp->p1];
2397 pOut = &p->aMem[pOp->p3];
2398 if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
2399 sqlite3VdbeMemSetNull(pOut);
2400 }else{
2401 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2403 break;
2405 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2407 /* Opcode: Column P1 P2 P3 P4 P5
2408 ** Synopsis: r[P3]=PX
2410 ** Interpret the data that cursor P1 points to as a structure built using
2411 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2412 ** information about the format of the data.) Extract the P2-th column
2413 ** from this record. If there are less that (P2+1)
2414 ** values in the record, extract a NULL.
2416 ** The value extracted is stored in register P3.
2418 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2419 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2420 ** the result.
2422 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2423 ** then the cache of the cursor is reset prior to extracting the column.
2424 ** The first OP_Column against a pseudo-table after the value of the content
2425 ** register has changed should have this bit set.
2427 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2428 ** the result is guaranteed to only be used as the argument of a length()
2429 ** or typeof() function, respectively. The loading of large blobs can be
2430 ** skipped for length() and all content loading can be skipped for typeof().
2432 case OP_Column: {
2433 int p2; /* column number to retrieve */
2434 VdbeCursor *pC; /* The VDBE cursor */
2435 BtCursor *pCrsr; /* The BTree cursor */
2436 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2437 int len; /* The length of the serialized data for the column */
2438 int i; /* Loop counter */
2439 Mem *pDest; /* Where to write the extracted value */
2440 Mem sMem; /* For storing the record being decoded */
2441 const u8 *zData; /* Part of the record being decoded */
2442 const u8 *zHdr; /* Next unparsed byte of the header */
2443 const u8 *zEndHdr; /* Pointer to first byte after the header */
2444 u64 offset64; /* 64-bit offset */
2445 u32 t; /* A type code from the record header */
2446 Mem *pReg; /* PseudoTable input register */
2448 pC = p->apCsr[pOp->p1];
2449 p2 = pOp->p2;
2451 /* If the cursor cache is stale (meaning it is not currently point at
2452 ** the correct row) then bring it up-to-date by doing the necessary
2453 ** B-Tree seek. */
2454 rc = sqlite3VdbeCursorMoveto(&pC, &p2);
2455 if( rc ) goto abort_due_to_error;
2457 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2458 pDest = &aMem[pOp->p3];
2459 memAboutToChange(p, pDest);
2460 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2461 assert( pC!=0 );
2462 assert( p2<pC->nField );
2463 aOffset = pC->aOffset;
2464 assert( pC->eCurType!=CURTYPE_VTAB );
2465 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2466 assert( pC->eCurType!=CURTYPE_SORTER );
2468 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2469 if( pC->nullRow ){
2470 if( pC->eCurType==CURTYPE_PSEUDO ){
2471 /* For the special case of as pseudo-cursor, the seekResult field
2472 ** identifies the register that holds the record */
2473 assert( pC->seekResult>0 );
2474 pReg = &aMem[pC->seekResult];
2475 assert( pReg->flags & MEM_Blob );
2476 assert( memIsValid(pReg) );
2477 pC->payloadSize = pC->szRow = pReg->n;
2478 pC->aRow = (u8*)pReg->z;
2479 }else{
2480 sqlite3VdbeMemSetNull(pDest);
2481 goto op_column_out;
2483 }else{
2484 pCrsr = pC->uc.pCursor;
2485 assert( pC->eCurType==CURTYPE_BTREE );
2486 assert( pCrsr );
2487 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2488 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2489 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2490 assert( pC->szRow<=pC->payloadSize );
2491 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2492 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2493 goto too_big;
2496 pC->cacheStatus = p->cacheCtr;
2497 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
2498 pC->nHdrParsed = 0;
2501 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2502 /* pC->aRow does not have to hold the entire row, but it does at least
2503 ** need to cover the header of the record. If pC->aRow does not contain
2504 ** the complete header, then set it to zero, forcing the header to be
2505 ** dynamically allocated. */
2506 pC->aRow = 0;
2507 pC->szRow = 0;
2509 /* Make sure a corrupt database has not given us an oversize header.
2510 ** Do this now to avoid an oversize memory allocation.
2512 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2513 ** types use so much data space that there can only be 4096 and 32 of
2514 ** them, respectively. So the maximum header length results from a
2515 ** 3-byte type for each of the maximum of 32768 columns plus three
2516 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2518 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2519 goto op_column_corrupt;
2521 }else{
2522 /* This is an optimization. By skipping over the first few tests
2523 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2524 ** measurable performance gain.
2526 ** This branch is taken even if aOffset[0]==0. Such a record is never
2527 ** generated by SQLite, and could be considered corruption, but we
2528 ** accept it for historical reasons. When aOffset[0]==0, the code this
2529 ** branch jumps to reads past the end of the record, but never more
2530 ** than a few bytes. Even if the record occurs at the end of the page
2531 ** content area, the "page header" comes after the page content and so
2532 ** this overread is harmless. Similar overreads can occur for a corrupt
2533 ** database file.
2535 zData = pC->aRow;
2536 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2537 testcase( aOffset[0]==0 );
2538 goto op_column_read_header;
2542 /* Make sure at least the first p2+1 entries of the header have been
2543 ** parsed and valid information is in aOffset[] and pC->aType[].
2545 if( pC->nHdrParsed<=p2 ){
2546 /* If there is more header available for parsing in the record, try
2547 ** to extract additional fields up through the p2+1-th field
2549 if( pC->iHdrOffset<aOffset[0] ){
2550 /* Make sure zData points to enough of the record to cover the header. */
2551 if( pC->aRow==0 ){
2552 memset(&sMem, 0, sizeof(sMem));
2553 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
2554 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2555 zData = (u8*)sMem.z;
2556 }else{
2557 zData = pC->aRow;
2560 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2561 op_column_read_header:
2562 i = pC->nHdrParsed;
2563 offset64 = aOffset[i];
2564 zHdr = zData + pC->iHdrOffset;
2565 zEndHdr = zData + aOffset[0];
2566 testcase( zHdr>=zEndHdr );
2568 if( (t = zHdr[0])<0x80 ){
2569 zHdr++;
2570 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2571 }else{
2572 zHdr += sqlite3GetVarint32(zHdr, &t);
2573 offset64 += sqlite3VdbeSerialTypeLen(t);
2575 pC->aType[i++] = t;
2576 aOffset[i] = (u32)(offset64 & 0xffffffff);
2577 }while( i<=p2 && zHdr<zEndHdr );
2579 /* The record is corrupt if any of the following are true:
2580 ** (1) the bytes of the header extend past the declared header size
2581 ** (2) the entire header was used but not all data was used
2582 ** (3) the end of the data extends beyond the end of the record.
2584 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2585 || (offset64 > pC->payloadSize)
2587 if( aOffset[0]==0 ){
2588 i = 0;
2589 zHdr = zEndHdr;
2590 }else{
2591 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2592 goto op_column_corrupt;
2596 pC->nHdrParsed = i;
2597 pC->iHdrOffset = (u32)(zHdr - zData);
2598 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2599 }else{
2600 t = 0;
2603 /* If after trying to extract new entries from the header, nHdrParsed is
2604 ** still not up to p2, that means that the record has fewer than p2
2605 ** columns. So the result will be either the default value or a NULL.
2607 if( pC->nHdrParsed<=p2 ){
2608 if( pOp->p4type==P4_MEM ){
2609 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2610 }else{
2611 sqlite3VdbeMemSetNull(pDest);
2613 goto op_column_out;
2615 }else{
2616 t = pC->aType[p2];
2619 /* Extract the content for the p2+1-th column. Control can only
2620 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2621 ** all valid.
2623 assert( p2<pC->nHdrParsed );
2624 assert( rc==SQLITE_OK );
2625 assert( sqlite3VdbeCheckMemInvariants(pDest) );
2626 if( VdbeMemDynamic(pDest) ){
2627 sqlite3VdbeMemSetNull(pDest);
2629 assert( t==pC->aType[p2] );
2630 if( pC->szRow>=aOffset[p2+1] ){
2631 /* This is the common case where the desired content fits on the original
2632 ** page - where the content is not on an overflow page */
2633 zData = pC->aRow + aOffset[p2];
2634 if( t<12 ){
2635 sqlite3VdbeSerialGet(zData, t, pDest);
2636 }else{
2637 /* If the column value is a string, we need a persistent value, not
2638 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2639 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2641 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
2642 pDest->n = len = (t-12)/2;
2643 pDest->enc = encoding;
2644 if( pDest->szMalloc < len+2 ){
2645 pDest->flags = MEM_Null;
2646 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
2647 }else{
2648 pDest->z = pDest->zMalloc;
2650 memcpy(pDest->z, zData, len);
2651 pDest->z[len] = 0;
2652 pDest->z[len+1] = 0;
2653 pDest->flags = aFlag[t&1];
2655 }else{
2656 pDest->enc = encoding;
2657 /* This branch happens only when content is on overflow pages */
2658 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2659 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2660 || (len = sqlite3VdbeSerialTypeLen(t))==0
2662 /* Content is irrelevant for
2663 ** 1. the typeof() function,
2664 ** 2. the length(X) function if X is a blob, and
2665 ** 3. if the content length is zero.
2666 ** So we might as well use bogus content rather than reading
2667 ** content from disk.
2669 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2670 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2671 ** read up to 16. So 16 bytes of bogus content is supplied.
2673 static u8 aZero[16]; /* This is the bogus content */
2674 sqlite3VdbeSerialGet(aZero, t, pDest);
2675 }else{
2676 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
2677 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2678 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2679 pDest->flags &= ~MEM_Ephem;
2683 op_column_out:
2684 UPDATE_MAX_BLOBSIZE(pDest);
2685 REGISTER_TRACE(pOp->p3, pDest);
2686 break;
2688 op_column_corrupt:
2689 if( aOp[0].p3>0 ){
2690 pOp = &aOp[aOp[0].p3-1];
2691 break;
2692 }else{
2693 rc = SQLITE_CORRUPT_BKPT;
2694 goto abort_due_to_error;
2698 /* Opcode: Affinity P1 P2 * P4 *
2699 ** Synopsis: affinity(r[P1@P2])
2701 ** Apply affinities to a range of P2 registers starting with P1.
2703 ** P4 is a string that is P2 characters long. The N-th character of the
2704 ** string indicates the column affinity that should be used for the N-th
2705 ** memory cell in the range.
2707 case OP_Affinity: {
2708 const char *zAffinity; /* The affinity to be applied */
2710 zAffinity = pOp->p4.z;
2711 assert( zAffinity!=0 );
2712 assert( pOp->p2>0 );
2713 assert( zAffinity[pOp->p2]==0 );
2714 pIn1 = &aMem[pOp->p1];
2716 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
2717 assert( memIsValid(pIn1) );
2718 applyAffinity(pIn1, *(zAffinity++), encoding);
2719 pIn1++;
2720 }while( zAffinity[0] );
2721 break;
2724 /* Opcode: MakeRecord P1 P2 P3 P4 *
2725 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2727 ** Convert P2 registers beginning with P1 into the [record format]
2728 ** use as a data record in a database table or as a key
2729 ** in an index. The OP_Column opcode can decode the record later.
2731 ** P4 may be a string that is P2 characters long. The N-th character of the
2732 ** string indicates the column affinity that should be used for the N-th
2733 ** field of the index key.
2735 ** The mapping from character to affinity is given by the SQLITE_AFF_
2736 ** macros defined in sqliteInt.h.
2738 ** If P4 is NULL then all index fields have the affinity BLOB.
2740 case OP_MakeRecord: {
2741 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2742 Mem *pRec; /* The new record */
2743 u64 nData; /* Number of bytes of data space */
2744 int nHdr; /* Number of bytes of header space */
2745 i64 nByte; /* Data space required for this record */
2746 i64 nZero; /* Number of zero bytes at the end of the record */
2747 int nVarint; /* Number of bytes in a varint */
2748 u32 serial_type; /* Type field */
2749 Mem *pData0; /* First field to be combined into the record */
2750 Mem *pLast; /* Last field of the record */
2751 int nField; /* Number of fields in the record */
2752 char *zAffinity; /* The affinity string for the record */
2753 int file_format; /* File format to use for encoding */
2754 int i; /* Space used in zNewRecord[] header */
2755 int j; /* Space used in zNewRecord[] content */
2756 u32 len; /* Length of a field */
2758 /* Assuming the record contains N fields, the record format looks
2759 ** like this:
2761 ** ------------------------------------------------------------------------
2762 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2763 ** ------------------------------------------------------------------------
2765 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2766 ** and so forth.
2768 ** Each type field is a varint representing the serial type of the
2769 ** corresponding data element (see sqlite3VdbeSerialType()). The
2770 ** hdr-size field is also a varint which is the offset from the beginning
2771 ** of the record to data0.
2773 nData = 0; /* Number of bytes of data space */
2774 nHdr = 0; /* Number of bytes of header space */
2775 nZero = 0; /* Number of zero bytes at the end of the record */
2776 nField = pOp->p1;
2777 zAffinity = pOp->p4.z;
2778 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
2779 pData0 = &aMem[nField];
2780 nField = pOp->p2;
2781 pLast = &pData0[nField-1];
2782 file_format = p->minWriteFileFormat;
2784 /* Identify the output register */
2785 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2786 pOut = &aMem[pOp->p3];
2787 memAboutToChange(p, pOut);
2789 /* Apply the requested affinity to all inputs
2791 assert( pData0<=pLast );
2792 if( zAffinity ){
2793 pRec = pData0;
2795 applyAffinity(pRec++, *(zAffinity++), encoding);
2796 assert( zAffinity[0]==0 || pRec<=pLast );
2797 }while( zAffinity[0] );
2800 #ifdef SQLITE_ENABLE_NULL_TRIM
2801 /* NULLs can be safely trimmed from the end of the record, as long as
2802 ** as the schema format is 2 or more and none of the omitted columns
2803 ** have a non-NULL default value. Also, the record must be left with
2804 ** at least one field. If P5>0 then it will be one more than the
2805 ** index of the right-most column with a non-NULL default value */
2806 if( pOp->p5 ){
2807 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
2808 pLast--;
2809 nField--;
2812 #endif
2814 /* Loop through the elements that will make up the record to figure
2815 ** out how much space is required for the new record.
2817 pRec = pLast;
2819 assert( memIsValid(pRec) );
2820 serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
2821 if( pRec->flags & MEM_Zero ){
2822 if( serial_type==0 ){
2823 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
2824 ** table methods that never invoke sqlite3_result_xxxxx() while
2825 ** computing an unchanging column value in an UPDATE statement.
2826 ** Give such values a special internal-use-only serial-type of 10
2827 ** so that they can be passed through to xUpdate and have
2828 ** a true sqlite3_value_nochange(). */
2829 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
2830 serial_type = 10;
2831 }else if( nData ){
2832 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
2833 }else{
2834 nZero += pRec->u.nZero;
2835 len -= pRec->u.nZero;
2838 nData += len;
2839 testcase( serial_type==127 );
2840 testcase( serial_type==128 );
2841 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
2842 pRec->uTemp = serial_type;
2843 if( pRec==pData0 ) break;
2844 pRec--;
2845 }while(1);
2847 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
2848 ** which determines the total number of bytes in the header. The varint
2849 ** value is the size of the header in bytes including the size varint
2850 ** itself. */
2851 testcase( nHdr==126 );
2852 testcase( nHdr==127 );
2853 if( nHdr<=126 ){
2854 /* The common case */
2855 nHdr += 1;
2856 }else{
2857 /* Rare case of a really large header */
2858 nVarint = sqlite3VarintLen(nHdr);
2859 nHdr += nVarint;
2860 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
2862 nByte = nHdr+nData;
2863 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2864 goto too_big;
2867 /* Make sure the output register has a buffer large enough to store
2868 ** the new record. The output register (pOp->p3) is not allowed to
2869 ** be one of the input registers (because the following call to
2870 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2872 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
2873 goto no_mem;
2875 zNewRecord = (u8 *)pOut->z;
2877 /* Write the record */
2878 i = putVarint32(zNewRecord, nHdr);
2879 j = nHdr;
2880 assert( pData0<=pLast );
2881 pRec = pData0;
2883 serial_type = pRec->uTemp;
2884 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
2885 ** additional varints, one per column. */
2886 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
2887 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
2888 ** immediately follow the header. */
2889 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
2890 }while( (++pRec)<=pLast );
2891 assert( i==nHdr );
2892 assert( j==nByte );
2894 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2895 pOut->n = (int)nByte;
2896 pOut->flags = MEM_Blob;
2897 if( nZero ){
2898 pOut->u.nZero = nZero;
2899 pOut->flags |= MEM_Zero;
2901 REGISTER_TRACE(pOp->p3, pOut);
2902 UPDATE_MAX_BLOBSIZE(pOut);
2903 break;
2906 /* Opcode: Count P1 P2 * * *
2907 ** Synopsis: r[P2]=count()
2909 ** Store the number of entries (an integer value) in the table or index
2910 ** opened by cursor P1 in register P2
2912 #ifndef SQLITE_OMIT_BTREECOUNT
2913 case OP_Count: { /* out2 */
2914 i64 nEntry;
2915 BtCursor *pCrsr;
2917 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
2918 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
2919 assert( pCrsr );
2920 nEntry = 0; /* Not needed. Only used to silence a warning. */
2921 rc = sqlite3BtreeCount(pCrsr, &nEntry);
2922 if( rc ) goto abort_due_to_error;
2923 pOut = out2Prerelease(p, pOp);
2924 pOut->u.i = nEntry;
2925 break;
2927 #endif
2929 /* Opcode: Savepoint P1 * * P4 *
2931 ** Open, release or rollback the savepoint named by parameter P4, depending
2932 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2933 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2935 case OP_Savepoint: {
2936 int p1; /* Value of P1 operand */
2937 char *zName; /* Name of savepoint */
2938 int nName;
2939 Savepoint *pNew;
2940 Savepoint *pSavepoint;
2941 Savepoint *pTmp;
2942 int iSavepoint;
2943 int ii;
2945 p1 = pOp->p1;
2946 zName = pOp->p4.z;
2948 /* Assert that the p1 parameter is valid. Also that if there is no open
2949 ** transaction, then there cannot be any savepoints.
2951 assert( db->pSavepoint==0 || db->autoCommit==0 );
2952 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
2953 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
2954 assert( checkSavepointCount(db) );
2955 assert( p->bIsReader );
2957 if( p1==SAVEPOINT_BEGIN ){
2958 if( db->nVdbeWrite>0 ){
2959 /* A new savepoint cannot be created if there are active write
2960 ** statements (i.e. open read/write incremental blob handles).
2962 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
2963 rc = SQLITE_BUSY;
2964 }else{
2965 nName = sqlite3Strlen30(zName);
2967 #ifndef SQLITE_OMIT_VIRTUALTABLE
2968 /* This call is Ok even if this savepoint is actually a transaction
2969 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2970 ** If this is a transaction savepoint being opened, it is guaranteed
2971 ** that the db->aVTrans[] array is empty. */
2972 assert( db->autoCommit==0 || db->nVTrans==0 );
2973 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
2974 db->nStatement+db->nSavepoint);
2975 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2976 #endif
2978 /* Create a new savepoint structure. */
2979 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
2980 if( pNew ){
2981 pNew->zName = (char *)&pNew[1];
2982 memcpy(pNew->zName, zName, nName+1);
2984 /* If there is no open transaction, then mark this as a special
2985 ** "transaction savepoint". */
2986 if( db->autoCommit ){
2987 db->autoCommit = 0;
2988 db->isTransactionSavepoint = 1;
2989 }else{
2990 db->nSavepoint++;
2993 /* Link the new savepoint into the database handle's list. */
2994 pNew->pNext = db->pSavepoint;
2995 db->pSavepoint = pNew;
2996 pNew->nDeferredCons = db->nDeferredCons;
2997 pNew->nDeferredImmCons = db->nDeferredImmCons;
3000 }else{
3001 iSavepoint = 0;
3003 /* Find the named savepoint. If there is no such savepoint, then an
3004 ** an error is returned to the user. */
3005 for(
3006 pSavepoint = db->pSavepoint;
3007 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3008 pSavepoint = pSavepoint->pNext
3010 iSavepoint++;
3012 if( !pSavepoint ){
3013 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3014 rc = SQLITE_ERROR;
3015 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3016 /* It is not possible to release (commit) a savepoint if there are
3017 ** active write statements.
3019 sqlite3VdbeError(p, "cannot release savepoint - "
3020 "SQL statements in progress");
3021 rc = SQLITE_BUSY;
3022 }else{
3024 /* Determine whether or not this is a transaction savepoint. If so,
3025 ** and this is a RELEASE command, then the current transaction
3026 ** is committed.
3028 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3029 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3030 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3031 goto vdbe_return;
3033 db->autoCommit = 1;
3034 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3035 p->pc = (int)(pOp - aOp);
3036 db->autoCommit = 0;
3037 p->rc = rc = SQLITE_BUSY;
3038 goto vdbe_return;
3040 db->isTransactionSavepoint = 0;
3041 rc = p->rc;
3042 }else{
3043 int isSchemaChange;
3044 iSavepoint = db->nSavepoint - iSavepoint - 1;
3045 if( p1==SAVEPOINT_ROLLBACK ){
3046 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3047 for(ii=0; ii<db->nDb; ii++){
3048 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3049 SQLITE_ABORT_ROLLBACK,
3050 isSchemaChange==0);
3051 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3053 }else{
3054 isSchemaChange = 0;
3056 for(ii=0; ii<db->nDb; ii++){
3057 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3058 if( rc!=SQLITE_OK ){
3059 goto abort_due_to_error;
3062 if( isSchemaChange ){
3063 sqlite3ExpirePreparedStatements(db);
3064 sqlite3ResetAllSchemasOfConnection(db);
3065 db->mDbFlags |= DBFLAG_SchemaChange;
3069 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3070 ** savepoints nested inside of the savepoint being operated on. */
3071 while( db->pSavepoint!=pSavepoint ){
3072 pTmp = db->pSavepoint;
3073 db->pSavepoint = pTmp->pNext;
3074 sqlite3DbFree(db, pTmp);
3075 db->nSavepoint--;
3078 /* If it is a RELEASE, then destroy the savepoint being operated on
3079 ** too. If it is a ROLLBACK TO, then set the number of deferred
3080 ** constraint violations present in the database to the value stored
3081 ** when the savepoint was created. */
3082 if( p1==SAVEPOINT_RELEASE ){
3083 assert( pSavepoint==db->pSavepoint );
3084 db->pSavepoint = pSavepoint->pNext;
3085 sqlite3DbFree(db, pSavepoint);
3086 if( !isTransaction ){
3087 db->nSavepoint--;
3089 }else{
3090 db->nDeferredCons = pSavepoint->nDeferredCons;
3091 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3094 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3095 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3096 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3100 if( rc ) goto abort_due_to_error;
3102 break;
3105 /* Opcode: AutoCommit P1 P2 * * *
3107 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3108 ** back any currently active btree transactions. If there are any active
3109 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3110 ** there are active writing VMs or active VMs that use shared cache.
3112 ** This instruction causes the VM to halt.
3114 case OP_AutoCommit: {
3115 int desiredAutoCommit;
3116 int iRollback;
3118 desiredAutoCommit = pOp->p1;
3119 iRollback = pOp->p2;
3120 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3121 assert( desiredAutoCommit==1 || iRollback==0 );
3122 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3123 assert( p->bIsReader );
3125 if( desiredAutoCommit!=db->autoCommit ){
3126 if( iRollback ){
3127 assert( desiredAutoCommit==1 );
3128 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3129 db->autoCommit = 1;
3130 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3131 /* If this instruction implements a COMMIT and other VMs are writing
3132 ** return an error indicating that the other VMs must complete first.
3134 sqlite3VdbeError(p, "cannot commit transaction - "
3135 "SQL statements in progress");
3136 rc = SQLITE_BUSY;
3137 goto abort_due_to_error;
3138 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3139 goto vdbe_return;
3140 }else{
3141 db->autoCommit = (u8)desiredAutoCommit;
3143 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3144 p->pc = (int)(pOp - aOp);
3145 db->autoCommit = (u8)(1-desiredAutoCommit);
3146 p->rc = rc = SQLITE_BUSY;
3147 goto vdbe_return;
3149 assert( db->nStatement==0 );
3150 sqlite3CloseSavepoints(db);
3151 if( p->rc==SQLITE_OK ){
3152 rc = SQLITE_DONE;
3153 }else{
3154 rc = SQLITE_ERROR;
3156 goto vdbe_return;
3157 }else{
3158 sqlite3VdbeError(p,
3159 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3160 (iRollback)?"cannot rollback - no transaction is active":
3161 "cannot commit - no transaction is active"));
3163 rc = SQLITE_ERROR;
3164 goto abort_due_to_error;
3166 break;
3169 /* Opcode: Transaction P1 P2 P3 P4 P5
3171 ** Begin a transaction on database P1 if a transaction is not already
3172 ** active.
3173 ** If P2 is non-zero, then a write-transaction is started, or if a
3174 ** read-transaction is already active, it is upgraded to a write-transaction.
3175 ** If P2 is zero, then a read-transaction is started.
3177 ** P1 is the index of the database file on which the transaction is
3178 ** started. Index 0 is the main database file and index 1 is the
3179 ** file used for temporary tables. Indices of 2 or more are used for
3180 ** attached databases.
3182 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3183 ** true (this flag is set if the Vdbe may modify more than one row and may
3184 ** throw an ABORT exception), a statement transaction may also be opened.
3185 ** More specifically, a statement transaction is opened iff the database
3186 ** connection is currently not in autocommit mode, or if there are other
3187 ** active statements. A statement transaction allows the changes made by this
3188 ** VDBE to be rolled back after an error without having to roll back the
3189 ** entire transaction. If no error is encountered, the statement transaction
3190 ** will automatically commit when the VDBE halts.
3192 ** If P5!=0 then this opcode also checks the schema cookie against P3
3193 ** and the schema generation counter against P4.
3194 ** The cookie changes its value whenever the database schema changes.
3195 ** This operation is used to detect when that the cookie has changed
3196 ** and that the current process needs to reread the schema. If the schema
3197 ** cookie in P3 differs from the schema cookie in the database header or
3198 ** if the schema generation counter in P4 differs from the current
3199 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3200 ** halts. The sqlite3_step() wrapper function might then reprepare the
3201 ** statement and rerun it from the beginning.
3203 case OP_Transaction: {
3204 Btree *pBt;
3205 int iMeta;
3206 int iGen;
3208 assert( p->bIsReader );
3209 assert( p->readOnly==0 || pOp->p2==0 );
3210 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3211 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3212 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3213 rc = SQLITE_READONLY;
3214 goto abort_due_to_error;
3216 pBt = db->aDb[pOp->p1].pBt;
3218 if( pBt ){
3219 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
3220 testcase( rc==SQLITE_BUSY_SNAPSHOT );
3221 testcase( rc==SQLITE_BUSY_RECOVERY );
3222 if( rc!=SQLITE_OK ){
3223 if( (rc&0xff)==SQLITE_BUSY ){
3224 p->pc = (int)(pOp - aOp);
3225 p->rc = rc;
3226 goto vdbe_return;
3228 goto abort_due_to_error;
3231 if( pOp->p2 && p->usesStmtJournal
3232 && (db->autoCommit==0 || db->nVdbeRead>1)
3234 assert( sqlite3BtreeIsInTrans(pBt) );
3235 if( p->iStatement==0 ){
3236 assert( db->nStatement>=0 && db->nSavepoint>=0 );
3237 db->nStatement++;
3238 p->iStatement = db->nSavepoint + db->nStatement;
3241 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3242 if( rc==SQLITE_OK ){
3243 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3246 /* Store the current value of the database handles deferred constraint
3247 ** counter. If the statement transaction needs to be rolled back,
3248 ** the value of this counter needs to be restored too. */
3249 p->nStmtDefCons = db->nDeferredCons;
3250 p->nStmtDefImmCons = db->nDeferredImmCons;
3253 /* Gather the schema version number for checking:
3254 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3255 ** version is checked to ensure that the schema has not changed since the
3256 ** SQL statement was prepared.
3258 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
3259 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
3260 }else{
3261 iGen = iMeta = 0;
3263 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3264 if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
3265 sqlite3DbFree(db, p->zErrMsg);
3266 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3267 /* If the schema-cookie from the database file matches the cookie
3268 ** stored with the in-memory representation of the schema, do
3269 ** not reload the schema from the database file.
3271 ** If virtual-tables are in use, this is not just an optimization.
3272 ** Often, v-tables store their data in other SQLite tables, which
3273 ** are queried from within xNext() and other v-table methods using
3274 ** prepared queries. If such a query is out-of-date, we do not want to
3275 ** discard the database schema, as the user code implementing the
3276 ** v-table would have to be ready for the sqlite3_vtab structure itself
3277 ** to be invalidated whenever sqlite3_step() is called from within
3278 ** a v-table method.
3280 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3281 sqlite3ResetOneSchema(db, pOp->p1);
3283 p->expired = 1;
3284 rc = SQLITE_SCHEMA;
3286 if( rc ) goto abort_due_to_error;
3287 break;
3290 /* Opcode: ReadCookie P1 P2 P3 * *
3292 ** Read cookie number P3 from database P1 and write it into register P2.
3293 ** P3==1 is the schema version. P3==2 is the database format.
3294 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3295 ** the main database file and P1==1 is the database file used to store
3296 ** temporary tables.
3298 ** There must be a read-lock on the database (either a transaction
3299 ** must be started or there must be an open cursor) before
3300 ** executing this instruction.
3302 case OP_ReadCookie: { /* out2 */
3303 int iMeta;
3304 int iDb;
3305 int iCookie;
3307 assert( p->bIsReader );
3308 iDb = pOp->p1;
3309 iCookie = pOp->p3;
3310 assert( pOp->p3<SQLITE_N_BTREE_META );
3311 assert( iDb>=0 && iDb<db->nDb );
3312 assert( db->aDb[iDb].pBt!=0 );
3313 assert( DbMaskTest(p->btreeMask, iDb) );
3315 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3316 pOut = out2Prerelease(p, pOp);
3317 pOut->u.i = iMeta;
3318 break;
3321 /* Opcode: SetCookie P1 P2 P3 * *
3323 ** Write the integer value P3 into cookie number P2 of database P1.
3324 ** P2==1 is the schema version. P2==2 is the database format.
3325 ** P2==3 is the recommended pager cache
3326 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3327 ** database file used to store temporary tables.
3329 ** A transaction must be started before executing this opcode.
3331 case OP_SetCookie: {
3332 Db *pDb;
3334 sqlite3VdbeIncrWriteCounter(p, 0);
3335 assert( pOp->p2<SQLITE_N_BTREE_META );
3336 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3337 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3338 assert( p->readOnly==0 );
3339 pDb = &db->aDb[pOp->p1];
3340 assert( pDb->pBt!=0 );
3341 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3342 /* See note about index shifting on OP_ReadCookie */
3343 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3344 if( pOp->p2==BTREE_SCHEMA_VERSION ){
3345 /* When the schema cookie changes, record the new cookie internally */
3346 pDb->pSchema->schema_cookie = pOp->p3;
3347 db->mDbFlags |= DBFLAG_SchemaChange;
3348 }else if( pOp->p2==BTREE_FILE_FORMAT ){
3349 /* Record changes in the file format */
3350 pDb->pSchema->file_format = pOp->p3;
3352 if( pOp->p1==1 ){
3353 /* Invalidate all prepared statements whenever the TEMP database
3354 ** schema is changed. Ticket #1644 */
3355 sqlite3ExpirePreparedStatements(db);
3356 p->expired = 0;
3358 if( rc ) goto abort_due_to_error;
3359 break;
3362 /* Opcode: OpenRead P1 P2 P3 P4 P5
3363 ** Synopsis: root=P2 iDb=P3
3365 ** Open a read-only cursor for the database table whose root page is
3366 ** P2 in a database file. The database file is determined by P3.
3367 ** P3==0 means the main database, P3==1 means the database used for
3368 ** temporary tables, and P3>1 means used the corresponding attached
3369 ** database. Give the new cursor an identifier of P1. The P1
3370 ** values need not be contiguous but all P1 values should be small integers.
3371 ** It is an error for P1 to be negative.
3373 ** If P5!=0 then use the content of register P2 as the root page, not
3374 ** the value of P2 itself.
3376 ** There will be a read lock on the database whenever there is an
3377 ** open cursor. If the database was unlocked prior to this instruction
3378 ** then a read lock is acquired as part of this instruction. A read
3379 ** lock allows other processes to read the database but prohibits
3380 ** any other process from modifying the database. The read lock is
3381 ** released when all cursors are closed. If this instruction attempts
3382 ** to get a read lock but fails, the script terminates with an
3383 ** SQLITE_BUSY error code.
3385 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3386 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3387 ** structure, then said structure defines the content and collating
3388 ** sequence of the index being opened. Otherwise, if P4 is an integer
3389 ** value, it is set to the number of columns in the table.
3391 ** See also: OpenWrite, ReopenIdx
3393 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3394 ** Synopsis: root=P2 iDb=P3
3396 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
3397 ** checks to see if the cursor on P1 is already open with a root page
3398 ** number of P2 and if it is this opcode becomes a no-op. In other words,
3399 ** if the cursor is already open, do not reopen it.
3401 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
3402 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
3403 ** every other ReopenIdx or OpenRead for the same cursor number.
3405 ** See the OpenRead opcode documentation for additional information.
3407 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3408 ** Synopsis: root=P2 iDb=P3
3410 ** Open a read/write cursor named P1 on the table or index whose root
3411 ** page is P2. Or if P5!=0 use the content of register P2 to find the
3412 ** root page.
3414 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3415 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3416 ** structure, then said structure defines the content and collating
3417 ** sequence of the index being opened. Otherwise, if P4 is an integer
3418 ** value, it is set to the number of columns in the table, or to the
3419 ** largest index of any column of the table that is actually used.
3421 ** This instruction works just like OpenRead except that it opens the cursor
3422 ** in read/write mode. For a given table, there can be one or more read-only
3423 ** cursors or a single read/write cursor but not both.
3425 ** See also OpenRead.
3427 case OP_ReopenIdx: {
3428 int nField;
3429 KeyInfo *pKeyInfo;
3430 int p2;
3431 int iDb;
3432 int wrFlag;
3433 Btree *pX;
3434 VdbeCursor *pCur;
3435 Db *pDb;
3437 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3438 assert( pOp->p4type==P4_KEYINFO );
3439 pCur = p->apCsr[pOp->p1];
3440 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3441 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
3442 goto open_cursor_set_hints;
3444 /* If the cursor is not currently open or is open on a different
3445 ** index, then fall through into OP_OpenRead to force a reopen */
3446 case OP_OpenRead:
3447 case OP_OpenWrite:
3449 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3450 assert( p->bIsReader );
3451 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3452 || p->readOnly==0 );
3454 if( p->expired ){
3455 rc = SQLITE_ABORT_ROLLBACK;
3456 goto abort_due_to_error;
3459 nField = 0;
3460 pKeyInfo = 0;
3461 p2 = pOp->p2;
3462 iDb = pOp->p3;
3463 assert( iDb>=0 && iDb<db->nDb );
3464 assert( DbMaskTest(p->btreeMask, iDb) );
3465 pDb = &db->aDb[iDb];
3466 pX = pDb->pBt;
3467 assert( pX!=0 );
3468 if( pOp->opcode==OP_OpenWrite ){
3469 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
3470 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
3471 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3472 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3473 p->minWriteFileFormat = pDb->pSchema->file_format;
3475 }else{
3476 wrFlag = 0;
3478 if( pOp->p5 & OPFLAG_P2ISREG ){
3479 assert( p2>0 );
3480 assert( p2<=(p->nMem+1 - p->nCursor) );
3481 pIn2 = &aMem[p2];
3482 assert( memIsValid(pIn2) );
3483 assert( (pIn2->flags & MEM_Int)!=0 );
3484 sqlite3VdbeMemIntegerify(pIn2);
3485 p2 = (int)pIn2->u.i;
3486 /* The p2 value always comes from a prior OP_CreateBtree opcode and
3487 ** that opcode will always set the p2 value to 2 or more or else fail.
3488 ** If there were a failure, the prepared statement would have halted
3489 ** before reaching this instruction. */
3490 assert( p2>=2 );
3492 if( pOp->p4type==P4_KEYINFO ){
3493 pKeyInfo = pOp->p4.pKeyInfo;
3494 assert( pKeyInfo->enc==ENC(db) );
3495 assert( pKeyInfo->db==db );
3496 nField = pKeyInfo->nAllField;
3497 }else if( pOp->p4type==P4_INT32 ){
3498 nField = pOp->p4.i;
3500 assert( pOp->p1>=0 );
3501 assert( nField>=0 );
3502 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3503 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
3504 if( pCur==0 ) goto no_mem;
3505 pCur->nullRow = 1;
3506 pCur->isOrdered = 1;
3507 pCur->pgnoRoot = p2;
3508 #ifdef SQLITE_DEBUG
3509 pCur->wrFlag = wrFlag;
3510 #endif
3511 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
3512 pCur->pKeyInfo = pKeyInfo;
3513 /* Set the VdbeCursor.isTable variable. Previous versions of
3514 ** SQLite used to check if the root-page flags were sane at this point
3515 ** and report database corruption if they were not, but this check has
3516 ** since moved into the btree layer. */
3517 pCur->isTable = pOp->p4type!=P4_KEYINFO;
3519 open_cursor_set_hints:
3520 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3521 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
3522 testcase( pOp->p5 & OPFLAG_BULKCSR );
3523 #ifdef SQLITE_ENABLE_CURSOR_HINTS
3524 testcase( pOp->p2 & OPFLAG_SEEKEQ );
3525 #endif
3526 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
3527 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
3528 if( rc ) goto abort_due_to_error;
3529 break;
3532 /* Opcode: OpenDup P1 P2 * * *
3534 ** Open a new cursor P1 that points to the same ephemeral table as
3535 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
3536 ** opcode. Only ephemeral cursors may be duplicated.
3538 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
3540 case OP_OpenDup: {
3541 VdbeCursor *pOrig; /* The original cursor to be duplicated */
3542 VdbeCursor *pCx; /* The new cursor */
3544 pOrig = p->apCsr[pOp->p2];
3545 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
3547 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
3548 if( pCx==0 ) goto no_mem;
3549 pCx->nullRow = 1;
3550 pCx->isEphemeral = 1;
3551 pCx->pKeyInfo = pOrig->pKeyInfo;
3552 pCx->isTable = pOrig->isTable;
3553 rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
3554 pCx->pKeyInfo, pCx->uc.pCursor);
3555 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
3556 ** opened for a database. Since there is already an open cursor when this
3557 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
3558 assert( rc==SQLITE_OK );
3559 break;
3563 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3564 ** Synopsis: nColumn=P2
3566 ** Open a new cursor P1 to a transient table.
3567 ** The cursor is always opened read/write even if
3568 ** the main database is read-only. The ephemeral
3569 ** table is deleted automatically when the cursor is closed.
3571 ** P2 is the number of columns in the ephemeral table.
3572 ** The cursor points to a BTree table if P4==0 and to a BTree index
3573 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3574 ** that defines the format of keys in the index.
3576 ** The P5 parameter can be a mask of the BTREE_* flags defined
3577 ** in btree.h. These flags control aspects of the operation of
3578 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3579 ** added automatically.
3581 /* Opcode: OpenAutoindex P1 P2 * P4 *
3582 ** Synopsis: nColumn=P2
3584 ** This opcode works the same as OP_OpenEphemeral. It has a
3585 ** different name to distinguish its use. Tables created using
3586 ** by this opcode will be used for automatically created transient
3587 ** indices in joins.
3589 case OP_OpenAutoindex:
3590 case OP_OpenEphemeral: {
3591 VdbeCursor *pCx;
3592 KeyInfo *pKeyInfo;
3594 static const int vfsFlags =
3595 SQLITE_OPEN_READWRITE |
3596 SQLITE_OPEN_CREATE |
3597 SQLITE_OPEN_EXCLUSIVE |
3598 SQLITE_OPEN_DELETEONCLOSE |
3599 SQLITE_OPEN_TRANSIENT_DB;
3600 assert( pOp->p1>=0 );
3601 assert( pOp->p2>=0 );
3602 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
3603 if( pCx==0 ) goto no_mem;
3604 pCx->nullRow = 1;
3605 pCx->isEphemeral = 1;
3606 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
3607 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
3608 if( rc==SQLITE_OK ){
3609 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
3611 if( rc==SQLITE_OK ){
3612 /* If a transient index is required, create it by calling
3613 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3614 ** opening it. If a transient table is required, just use the
3615 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3617 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3618 int pgno;
3619 assert( pOp->p4type==P4_KEYINFO );
3620 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
3621 if( rc==SQLITE_OK ){
3622 assert( pgno==MASTER_ROOT+1 );
3623 assert( pKeyInfo->db==db );
3624 assert( pKeyInfo->enc==ENC(db) );
3625 rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
3626 pKeyInfo, pCx->uc.pCursor);
3628 pCx->isTable = 0;
3629 }else{
3630 rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
3631 0, pCx->uc.pCursor);
3632 pCx->isTable = 1;
3635 if( rc ) goto abort_due_to_error;
3636 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3637 break;
3640 /* Opcode: SorterOpen P1 P2 P3 P4 *
3642 ** This opcode works like OP_OpenEphemeral except that it opens
3643 ** a transient index that is specifically designed to sort large
3644 ** tables using an external merge-sort algorithm.
3646 ** If argument P3 is non-zero, then it indicates that the sorter may
3647 ** assume that a stable sort considering the first P3 fields of each
3648 ** key is sufficient to produce the required results.
3650 case OP_SorterOpen: {
3651 VdbeCursor *pCx;
3653 assert( pOp->p1>=0 );
3654 assert( pOp->p2>=0 );
3655 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
3656 if( pCx==0 ) goto no_mem;
3657 pCx->pKeyInfo = pOp->p4.pKeyInfo;
3658 assert( pCx->pKeyInfo->db==db );
3659 assert( pCx->pKeyInfo->enc==ENC(db) );
3660 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
3661 if( rc ) goto abort_due_to_error;
3662 break;
3665 /* Opcode: SequenceTest P1 P2 * * *
3666 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3668 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3669 ** to P2. Regardless of whether or not the jump is taken, increment the
3670 ** the sequence value.
3672 case OP_SequenceTest: {
3673 VdbeCursor *pC;
3674 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3675 pC = p->apCsr[pOp->p1];
3676 assert( isSorter(pC) );
3677 if( (pC->seqCount++)==0 ){
3678 goto jump_to_p2;
3680 break;
3683 /* Opcode: OpenPseudo P1 P2 P3 * *
3684 ** Synopsis: P3 columns in r[P2]
3686 ** Open a new cursor that points to a fake table that contains a single
3687 ** row of data. The content of that one row is the content of memory
3688 ** register P2. In other words, cursor P1 becomes an alias for the
3689 ** MEM_Blob content contained in register P2.
3691 ** A pseudo-table created by this opcode is used to hold a single
3692 ** row output from the sorter so that the row can be decomposed into
3693 ** individual columns using the OP_Column opcode. The OP_Column opcode
3694 ** is the only cursor opcode that works with a pseudo-table.
3696 ** P3 is the number of fields in the records that will be stored by
3697 ** the pseudo-table.
3699 case OP_OpenPseudo: {
3700 VdbeCursor *pCx;
3702 assert( pOp->p1>=0 );
3703 assert( pOp->p3>=0 );
3704 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
3705 if( pCx==0 ) goto no_mem;
3706 pCx->nullRow = 1;
3707 pCx->seekResult = pOp->p2;
3708 pCx->isTable = 1;
3709 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
3710 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
3711 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
3712 ** which is a performance optimization */
3713 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
3714 assert( pOp->p5==0 );
3715 break;
3718 /* Opcode: Close P1 * * * *
3720 ** Close a cursor previously opened as P1. If P1 is not
3721 ** currently open, this instruction is a no-op.
3723 case OP_Close: {
3724 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3725 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
3726 p->apCsr[pOp->p1] = 0;
3727 break;
3730 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3731 /* Opcode: ColumnsUsed P1 * * P4 *
3733 ** This opcode (which only exists if SQLite was compiled with
3734 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
3735 ** table or index for cursor P1 are used. P4 is a 64-bit integer
3736 ** (P4_INT64) in which the first 63 bits are one for each of the
3737 ** first 63 columns of the table or index that are actually used
3738 ** by the cursor. The high-order bit is set if any column after
3739 ** the 64th is used.
3741 case OP_ColumnsUsed: {
3742 VdbeCursor *pC;
3743 pC = p->apCsr[pOp->p1];
3744 assert( pC->eCurType==CURTYPE_BTREE );
3745 pC->maskUsed = *(u64*)pOp->p4.pI64;
3746 break;
3748 #endif
3750 /* Opcode: SeekGE P1 P2 P3 P4 *
3751 ** Synopsis: key=r[P3@P4]
3753 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3754 ** use the value in register P3 as the key. If cursor P1 refers
3755 ** to an SQL index, then P3 is the first in an array of P4 registers
3756 ** that are used as an unpacked index key.
3758 ** Reposition cursor P1 so that it points to the smallest entry that
3759 ** is greater than or equal to the key value. If there are no records
3760 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3762 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3763 ** opcode will always land on a record that equally equals the key, or
3764 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3765 ** opcode must be followed by an IdxLE opcode with the same arguments.
3766 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
3767 ** IdxLE opcode will be used on subsequent loop iterations.
3769 ** This opcode leaves the cursor configured to move in forward order,
3770 ** from the beginning toward the end. In other words, the cursor is
3771 ** configured to use Next, not Prev.
3773 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3775 /* Opcode: SeekGT P1 P2 P3 P4 *
3776 ** Synopsis: key=r[P3@P4]
3778 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3779 ** use the value in register P3 as a key. If cursor P1 refers
3780 ** to an SQL index, then P3 is the first in an array of P4 registers
3781 ** that are used as an unpacked index key.
3783 ** Reposition cursor P1 so that it points to the smallest entry that
3784 ** is greater than the key value. If there are no records greater than
3785 ** the key and P2 is not zero, then jump to P2.
3787 ** This opcode leaves the cursor configured to move in forward order,
3788 ** from the beginning toward the end. In other words, the cursor is
3789 ** configured to use Next, not Prev.
3791 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3793 /* Opcode: SeekLT P1 P2 P3 P4 *
3794 ** Synopsis: key=r[P3@P4]
3796 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3797 ** use the value in register P3 as a key. If cursor P1 refers
3798 ** to an SQL index, then P3 is the first in an array of P4 registers
3799 ** that are used as an unpacked index key.
3801 ** Reposition cursor P1 so that it points to the largest entry that
3802 ** is less than the key value. If there are no records less than
3803 ** the key and P2 is not zero, then jump to P2.
3805 ** This opcode leaves the cursor configured to move in reverse order,
3806 ** from the end toward the beginning. In other words, the cursor is
3807 ** configured to use Prev, not Next.
3809 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3811 /* Opcode: SeekLE P1 P2 P3 P4 *
3812 ** Synopsis: key=r[P3@P4]
3814 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3815 ** use the value in register P3 as a key. If cursor P1 refers
3816 ** to an SQL index, then P3 is the first in an array of P4 registers
3817 ** that are used as an unpacked index key.
3819 ** Reposition cursor P1 so that it points to the largest entry that
3820 ** is less than or equal to the key value. If there are no records
3821 ** less than or equal to the key and P2 is not zero, then jump to P2.
3823 ** This opcode leaves the cursor configured to move in reverse order,
3824 ** from the end toward the beginning. In other words, the cursor is
3825 ** configured to use Prev, not Next.
3827 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3828 ** opcode will always land on a record that equally equals the key, or
3829 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3830 ** opcode must be followed by an IdxGE opcode with the same arguments.
3831 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
3832 ** IdxGE opcode will be used on subsequent loop iterations.
3834 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3836 case OP_SeekLT: /* jump, in3 */
3837 case OP_SeekLE: /* jump, in3 */
3838 case OP_SeekGE: /* jump, in3 */
3839 case OP_SeekGT: { /* jump, in3 */
3840 int res; /* Comparison result */
3841 int oc; /* Opcode */
3842 VdbeCursor *pC; /* The cursor to seek */
3843 UnpackedRecord r; /* The key to seek for */
3844 int nField; /* Number of columns or fields in the key */
3845 i64 iKey; /* The rowid we are to seek to */
3846 int eqOnly; /* Only interested in == results */
3848 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3849 assert( pOp->p2!=0 );
3850 pC = p->apCsr[pOp->p1];
3851 assert( pC!=0 );
3852 assert( pC->eCurType==CURTYPE_BTREE );
3853 assert( OP_SeekLE == OP_SeekLT+1 );
3854 assert( OP_SeekGE == OP_SeekLT+2 );
3855 assert( OP_SeekGT == OP_SeekLT+3 );
3856 assert( pC->isOrdered );
3857 assert( pC->uc.pCursor!=0 );
3858 oc = pOp->opcode;
3859 eqOnly = 0;
3860 pC->nullRow = 0;
3861 #ifdef SQLITE_DEBUG
3862 pC->seekOp = pOp->opcode;
3863 #endif
3865 if( pC->isTable ){
3866 /* The BTREE_SEEK_EQ flag is only set on index cursors */
3867 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
3868 || CORRUPT_DB );
3870 /* The input value in P3 might be of any type: integer, real, string,
3871 ** blob, or NULL. But it needs to be an integer before we can do
3872 ** the seek, so convert it. */
3873 pIn3 = &aMem[pOp->p3];
3874 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
3875 applyNumericAffinity(pIn3, 0);
3877 iKey = sqlite3VdbeIntValue(pIn3);
3879 /* If the P3 value could not be converted into an integer without
3880 ** loss of information, then special processing is required... */
3881 if( (pIn3->flags & MEM_Int)==0 ){
3882 if( (pIn3->flags & MEM_Real)==0 ){
3883 /* If the P3 value cannot be converted into any kind of a number,
3884 ** then the seek is not possible, so jump to P2 */
3885 VdbeBranchTaken(1,2); goto jump_to_p2;
3886 break;
3889 /* If the approximation iKey is larger than the actual real search
3890 ** term, substitute >= for > and < for <=. e.g. if the search term
3891 ** is 4.9 and the integer approximation 5:
3893 ** (x > 4.9) -> (x >= 5)
3894 ** (x <= 4.9) -> (x < 5)
3896 if( pIn3->u.r<(double)iKey ){
3897 assert( OP_SeekGE==(OP_SeekGT-1) );
3898 assert( OP_SeekLT==(OP_SeekLE-1) );
3899 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
3900 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
3903 /* If the approximation iKey is smaller than the actual real search
3904 ** term, substitute <= for < and > for >=. */
3905 else if( pIn3->u.r>(double)iKey ){
3906 assert( OP_SeekLE==(OP_SeekLT+1) );
3907 assert( OP_SeekGT==(OP_SeekGE+1) );
3908 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
3909 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
3912 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
3913 pC->movetoTarget = iKey; /* Used by OP_Delete */
3914 if( rc!=SQLITE_OK ){
3915 goto abort_due_to_error;
3917 }else{
3918 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
3919 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
3920 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
3922 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
3923 eqOnly = 1;
3924 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
3925 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
3926 assert( pOp[1].p1==pOp[0].p1 );
3927 assert( pOp[1].p2==pOp[0].p2 );
3928 assert( pOp[1].p3==pOp[0].p3 );
3929 assert( pOp[1].p4.i==pOp[0].p4.i );
3932 nField = pOp->p4.i;
3933 assert( pOp->p4type==P4_INT32 );
3934 assert( nField>0 );
3935 r.pKeyInfo = pC->pKeyInfo;
3936 r.nField = (u16)nField;
3938 /* The next line of code computes as follows, only faster:
3939 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3940 ** r.default_rc = -1;
3941 ** }else{
3942 ** r.default_rc = +1;
3943 ** }
3945 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
3946 assert( oc!=OP_SeekGT || r.default_rc==-1 );
3947 assert( oc!=OP_SeekLE || r.default_rc==-1 );
3948 assert( oc!=OP_SeekGE || r.default_rc==+1 );
3949 assert( oc!=OP_SeekLT || r.default_rc==+1 );
3951 r.aMem = &aMem[pOp->p3];
3952 #ifdef SQLITE_DEBUG
3953 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3954 #endif
3955 r.eqSeen = 0;
3956 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
3957 if( rc!=SQLITE_OK ){
3958 goto abort_due_to_error;
3960 if( eqOnly && r.eqSeen==0 ){
3961 assert( res!=0 );
3962 goto seek_not_found;
3965 pC->deferredMoveto = 0;
3966 pC->cacheStatus = CACHE_STALE;
3967 #ifdef SQLITE_TEST
3968 sqlite3_search_count++;
3969 #endif
3970 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
3971 if( res<0 || (res==0 && oc==OP_SeekGT) ){
3972 res = 0;
3973 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
3974 if( rc!=SQLITE_OK ){
3975 if( rc==SQLITE_DONE ){
3976 rc = SQLITE_OK;
3977 res = 1;
3978 }else{
3979 goto abort_due_to_error;
3982 }else{
3983 res = 0;
3985 }else{
3986 assert( oc==OP_SeekLT || oc==OP_SeekLE );
3987 if( res>0 || (res==0 && oc==OP_SeekLT) ){
3988 res = 0;
3989 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
3990 if( rc!=SQLITE_OK ){
3991 if( rc==SQLITE_DONE ){
3992 rc = SQLITE_OK;
3993 res = 1;
3994 }else{
3995 goto abort_due_to_error;
3998 }else{
3999 /* res might be negative because the table is empty. Check to
4000 ** see if this is the case.
4002 res = sqlite3BtreeEof(pC->uc.pCursor);
4005 seek_not_found:
4006 assert( pOp->p2>0 );
4007 VdbeBranchTaken(res!=0,2);
4008 if( res ){
4009 goto jump_to_p2;
4010 }else if( eqOnly ){
4011 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4012 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4014 break;
4017 /* Opcode: Found P1 P2 P3 P4 *
4018 ** Synopsis: key=r[P3@P4]
4020 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4021 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4022 ** record.
4024 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4025 ** is a prefix of any entry in P1 then a jump is made to P2 and
4026 ** P1 is left pointing at the matching entry.
4028 ** This operation leaves the cursor in a state where it can be
4029 ** advanced in the forward direction. The Next instruction will work,
4030 ** but not the Prev instruction.
4032 ** See also: NotFound, NoConflict, NotExists. SeekGe
4034 /* Opcode: NotFound P1 P2 P3 P4 *
4035 ** Synopsis: key=r[P3@P4]
4037 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4038 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4039 ** record.
4041 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4042 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
4043 ** does contain an entry whose prefix matches the P3/P4 record then control
4044 ** falls through to the next instruction and P1 is left pointing at the
4045 ** matching entry.
4047 ** This operation leaves the cursor in a state where it cannot be
4048 ** advanced in either direction. In other words, the Next and Prev
4049 ** opcodes do not work after this operation.
4051 ** See also: Found, NotExists, NoConflict
4053 /* Opcode: NoConflict P1 P2 P3 P4 *
4054 ** Synopsis: key=r[P3@P4]
4056 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4057 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4058 ** record.
4060 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4061 ** contains any NULL value, jump immediately to P2. If all terms of the
4062 ** record are not-NULL then a check is done to determine if any row in the
4063 ** P1 index btree has a matching key prefix. If there are no matches, jump
4064 ** immediately to P2. If there is a match, fall through and leave the P1
4065 ** cursor pointing to the matching row.
4067 ** This opcode is similar to OP_NotFound with the exceptions that the
4068 ** branch is always taken if any part of the search key input is NULL.
4070 ** This operation leaves the cursor in a state where it cannot be
4071 ** advanced in either direction. In other words, the Next and Prev
4072 ** opcodes do not work after this operation.
4074 ** See also: NotFound, Found, NotExists
4076 case OP_NoConflict: /* jump, in3 */
4077 case OP_NotFound: /* jump, in3 */
4078 case OP_Found: { /* jump, in3 */
4079 int alreadyExists;
4080 int takeJump;
4081 int ii;
4082 VdbeCursor *pC;
4083 int res;
4084 UnpackedRecord *pFree;
4085 UnpackedRecord *pIdxKey;
4086 UnpackedRecord r;
4088 #ifdef SQLITE_TEST
4089 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4090 #endif
4092 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4093 assert( pOp->p4type==P4_INT32 );
4094 pC = p->apCsr[pOp->p1];
4095 assert( pC!=0 );
4096 #ifdef SQLITE_DEBUG
4097 pC->seekOp = pOp->opcode;
4098 #endif
4099 pIn3 = &aMem[pOp->p3];
4100 assert( pC->eCurType==CURTYPE_BTREE );
4101 assert( pC->uc.pCursor!=0 );
4102 assert( pC->isTable==0 );
4103 if( pOp->p4.i>0 ){
4104 r.pKeyInfo = pC->pKeyInfo;
4105 r.nField = (u16)pOp->p4.i;
4106 r.aMem = pIn3;
4107 #ifdef SQLITE_DEBUG
4108 for(ii=0; ii<r.nField; ii++){
4109 assert( memIsValid(&r.aMem[ii]) );
4110 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4111 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4113 #endif
4114 pIdxKey = &r;
4115 pFree = 0;
4116 }else{
4117 assert( pIn3->flags & MEM_Blob );
4118 rc = ExpandBlob(pIn3);
4119 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4120 if( rc ) goto no_mem;
4121 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4122 if( pIdxKey==0 ) goto no_mem;
4123 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4125 pIdxKey->default_rc = 0;
4126 takeJump = 0;
4127 if( pOp->opcode==OP_NoConflict ){
4128 /* For the OP_NoConflict opcode, take the jump if any of the
4129 ** input fields are NULL, since any key with a NULL will not
4130 ** conflict */
4131 for(ii=0; ii<pIdxKey->nField; ii++){
4132 if( pIdxKey->aMem[ii].flags & MEM_Null ){
4133 takeJump = 1;
4134 break;
4138 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
4139 if( pFree ) sqlite3DbFreeNN(db, pFree);
4140 if( rc!=SQLITE_OK ){
4141 goto abort_due_to_error;
4143 pC->seekResult = res;
4144 alreadyExists = (res==0);
4145 pC->nullRow = 1-alreadyExists;
4146 pC->deferredMoveto = 0;
4147 pC->cacheStatus = CACHE_STALE;
4148 if( pOp->opcode==OP_Found ){
4149 VdbeBranchTaken(alreadyExists!=0,2);
4150 if( alreadyExists ) goto jump_to_p2;
4151 }else{
4152 VdbeBranchTaken(takeJump||alreadyExists==0,2);
4153 if( takeJump || !alreadyExists ) goto jump_to_p2;
4155 break;
4158 /* Opcode: SeekRowid P1 P2 P3 * *
4159 ** Synopsis: intkey=r[P3]
4161 ** P1 is the index of a cursor open on an SQL table btree (with integer
4162 ** keys). If register P3 does not contain an integer or if P1 does not
4163 ** contain a record with rowid P3 then jump immediately to P2.
4164 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4165 ** a record with rowid P3 then
4166 ** leave the cursor pointing at that record and fall through to the next
4167 ** instruction.
4169 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4170 ** the P3 register must be guaranteed to contain an integer value. With this
4171 ** opcode, register P3 might not contain an integer.
4173 ** The OP_NotFound opcode performs the same operation on index btrees
4174 ** (with arbitrary multi-value keys).
4176 ** This opcode leaves the cursor in a state where it cannot be advanced
4177 ** in either direction. In other words, the Next and Prev opcodes will
4178 ** not work following this opcode.
4180 ** See also: Found, NotFound, NoConflict, SeekRowid
4182 /* Opcode: NotExists P1 P2 P3 * *
4183 ** Synopsis: intkey=r[P3]
4185 ** P1 is the index of a cursor open on an SQL table btree (with integer
4186 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4187 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4188 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4189 ** leave the cursor pointing at that record and fall through to the next
4190 ** instruction.
4192 ** The OP_SeekRowid opcode performs the same operation but also allows the
4193 ** P3 register to contain a non-integer value, in which case the jump is
4194 ** always taken. This opcode requires that P3 always contain an integer.
4196 ** The OP_NotFound opcode performs the same operation on index btrees
4197 ** (with arbitrary multi-value keys).
4199 ** This opcode leaves the cursor in a state where it cannot be advanced
4200 ** in either direction. In other words, the Next and Prev opcodes will
4201 ** not work following this opcode.
4203 ** See also: Found, NotFound, NoConflict, SeekRowid
4205 case OP_SeekRowid: { /* jump, in3 */
4206 VdbeCursor *pC;
4207 BtCursor *pCrsr;
4208 int res;
4209 u64 iKey;
4211 pIn3 = &aMem[pOp->p3];
4212 if( (pIn3->flags & MEM_Int)==0 ){
4213 applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
4214 if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
4216 /* Fall through into OP_NotExists */
4217 case OP_NotExists: /* jump, in3 */
4218 pIn3 = &aMem[pOp->p3];
4219 assert( pIn3->flags & MEM_Int );
4220 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4221 pC = p->apCsr[pOp->p1];
4222 assert( pC!=0 );
4223 #ifdef SQLITE_DEBUG
4224 pC->seekOp = 0;
4225 #endif
4226 assert( pC->isTable );
4227 assert( pC->eCurType==CURTYPE_BTREE );
4228 pCrsr = pC->uc.pCursor;
4229 assert( pCrsr!=0 );
4230 res = 0;
4231 iKey = pIn3->u.i;
4232 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
4233 assert( rc==SQLITE_OK || res==0 );
4234 pC->movetoTarget = iKey; /* Used by OP_Delete */
4235 pC->nullRow = 0;
4236 pC->cacheStatus = CACHE_STALE;
4237 pC->deferredMoveto = 0;
4238 VdbeBranchTaken(res!=0,2);
4239 pC->seekResult = res;
4240 if( res!=0 ){
4241 assert( rc==SQLITE_OK );
4242 if( pOp->p2==0 ){
4243 rc = SQLITE_CORRUPT_BKPT;
4244 }else{
4245 goto jump_to_p2;
4248 if( rc ) goto abort_due_to_error;
4249 break;
4252 /* Opcode: Sequence P1 P2 * * *
4253 ** Synopsis: r[P2]=cursor[P1].ctr++
4255 ** Find the next available sequence number for cursor P1.
4256 ** Write the sequence number into register P2.
4257 ** The sequence number on the cursor is incremented after this
4258 ** instruction.
4260 case OP_Sequence: { /* out2 */
4261 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4262 assert( p->apCsr[pOp->p1]!=0 );
4263 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
4264 pOut = out2Prerelease(p, pOp);
4265 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
4266 break;
4270 /* Opcode: NewRowid P1 P2 P3 * *
4271 ** Synopsis: r[P2]=rowid
4273 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4274 ** The record number is not previously used as a key in the database
4275 ** table that cursor P1 points to. The new record number is written
4276 ** written to register P2.
4278 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4279 ** the largest previously generated record number. No new record numbers are
4280 ** allowed to be less than this value. When this value reaches its maximum,
4281 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4282 ** generated record number. This P3 mechanism is used to help implement the
4283 ** AUTOINCREMENT feature.
4285 case OP_NewRowid: { /* out2 */
4286 i64 v; /* The new rowid */
4287 VdbeCursor *pC; /* Cursor of table to get the new rowid */
4288 int res; /* Result of an sqlite3BtreeLast() */
4289 int cnt; /* Counter to limit the number of searches */
4290 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
4291 VdbeFrame *pFrame; /* Root frame of VDBE */
4293 v = 0;
4294 res = 0;
4295 pOut = out2Prerelease(p, pOp);
4296 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4297 pC = p->apCsr[pOp->p1];
4298 assert( pC!=0 );
4299 assert( pC->isTable );
4300 assert( pC->eCurType==CURTYPE_BTREE );
4301 assert( pC->uc.pCursor!=0 );
4303 /* The next rowid or record number (different terms for the same
4304 ** thing) is obtained in a two-step algorithm.
4306 ** First we attempt to find the largest existing rowid and add one
4307 ** to that. But if the largest existing rowid is already the maximum
4308 ** positive integer, we have to fall through to the second
4309 ** probabilistic algorithm
4311 ** The second algorithm is to select a rowid at random and see if
4312 ** it already exists in the table. If it does not exist, we have
4313 ** succeeded. If the random rowid does exist, we select a new one
4314 ** and try again, up to 100 times.
4316 assert( pC->isTable );
4318 #ifdef SQLITE_32BIT_ROWID
4319 # define MAX_ROWID 0x7fffffff
4320 #else
4321 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4322 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4323 ** to provide the constant while making all compilers happy.
4325 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4326 #endif
4328 if( !pC->useRandomRowid ){
4329 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4330 if( rc!=SQLITE_OK ){
4331 goto abort_due_to_error;
4333 if( res ){
4334 v = 1; /* IMP: R-61914-48074 */
4335 }else{
4336 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
4337 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4338 if( v>=MAX_ROWID ){
4339 pC->useRandomRowid = 1;
4340 }else{
4341 v++; /* IMP: R-29538-34987 */
4346 #ifndef SQLITE_OMIT_AUTOINCREMENT
4347 if( pOp->p3 ){
4348 /* Assert that P3 is a valid memory cell. */
4349 assert( pOp->p3>0 );
4350 if( p->pFrame ){
4351 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4352 /* Assert that P3 is a valid memory cell. */
4353 assert( pOp->p3<=pFrame->nMem );
4354 pMem = &pFrame->aMem[pOp->p3];
4355 }else{
4356 /* Assert that P3 is a valid memory cell. */
4357 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
4358 pMem = &aMem[pOp->p3];
4359 memAboutToChange(p, pMem);
4361 assert( memIsValid(pMem) );
4363 REGISTER_TRACE(pOp->p3, pMem);
4364 sqlite3VdbeMemIntegerify(pMem);
4365 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
4366 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4367 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
4368 goto abort_due_to_error;
4370 if( v<pMem->u.i+1 ){
4371 v = pMem->u.i + 1;
4373 pMem->u.i = v;
4375 #endif
4376 if( pC->useRandomRowid ){
4377 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4378 ** largest possible integer (9223372036854775807) then the database
4379 ** engine starts picking positive candidate ROWIDs at random until
4380 ** it finds one that is not previously used. */
4381 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
4382 ** an AUTOINCREMENT table. */
4383 cnt = 0;
4385 sqlite3_randomness(sizeof(v), &v);
4386 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
4387 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
4388 0, &res))==SQLITE_OK)
4389 && (res==0)
4390 && (++cnt<100));
4391 if( rc ) goto abort_due_to_error;
4392 if( res==0 ){
4393 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
4394 goto abort_due_to_error;
4396 assert( v>0 ); /* EV: R-40812-03570 */
4398 pC->deferredMoveto = 0;
4399 pC->cacheStatus = CACHE_STALE;
4401 pOut->u.i = v;
4402 break;
4405 /* Opcode: Insert P1 P2 P3 P4 P5
4406 ** Synopsis: intkey=r[P3] data=r[P2]
4408 ** Write an entry into the table of cursor P1. A new entry is
4409 ** created if it doesn't already exist or the data for an existing
4410 ** entry is overwritten. The data is the value MEM_Blob stored in register
4411 ** number P2. The key is stored in register P3. The key must
4412 ** be a MEM_Int.
4414 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4415 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
4416 ** then rowid is stored for subsequent return by the
4417 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4419 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
4420 ** run faster by avoiding an unnecessary seek on cursor P1. However,
4421 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
4422 ** seeks on the cursor or if the most recent seek used a key equal to P3.
4424 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4425 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
4426 ** is part of an INSERT operation. The difference is only important to
4427 ** the update hook.
4429 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
4430 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
4431 ** following a successful insert.
4433 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4434 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4435 ** and register P2 becomes ephemeral. If the cursor is changed, the
4436 ** value of register P2 will then change. Make sure this does not
4437 ** cause any problems.)
4439 ** This instruction only works on tables. The equivalent instruction
4440 ** for indices is OP_IdxInsert.
4442 /* Opcode: InsertInt P1 P2 P3 P4 P5
4443 ** Synopsis: intkey=P3 data=r[P2]
4445 ** This works exactly like OP_Insert except that the key is the
4446 ** integer value P3, not the value of the integer stored in register P3.
4448 case OP_Insert:
4449 case OP_InsertInt: {
4450 Mem *pData; /* MEM cell holding data for the record to be inserted */
4451 Mem *pKey; /* MEM cell holding key for the record */
4452 VdbeCursor *pC; /* Cursor to table into which insert is written */
4453 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
4454 const char *zDb; /* database name - used by the update hook */
4455 Table *pTab; /* Table structure - used by update and pre-update hooks */
4456 BtreePayload x; /* Payload to be inserted */
4458 pData = &aMem[pOp->p2];
4459 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4460 assert( memIsValid(pData) );
4461 pC = p->apCsr[pOp->p1];
4462 assert( pC!=0 );
4463 assert( pC->eCurType==CURTYPE_BTREE );
4464 assert( pC->uc.pCursor!=0 );
4465 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
4466 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
4467 REGISTER_TRACE(pOp->p2, pData);
4468 sqlite3VdbeIncrWriteCounter(p, pC);
4470 if( pOp->opcode==OP_Insert ){
4471 pKey = &aMem[pOp->p3];
4472 assert( pKey->flags & MEM_Int );
4473 assert( memIsValid(pKey) );
4474 REGISTER_TRACE(pOp->p3, pKey);
4475 x.nKey = pKey->u.i;
4476 }else{
4477 assert( pOp->opcode==OP_InsertInt );
4478 x.nKey = pOp->p3;
4481 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4482 assert( pC->iDb>=0 );
4483 zDb = db->aDb[pC->iDb].zDbSName;
4484 pTab = pOp->p4.pTab;
4485 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
4486 }else{
4487 pTab = 0;
4488 zDb = 0; /* Not needed. Silence a compiler warning. */
4491 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4492 /* Invoke the pre-update hook, if any */
4493 if( pTab ){
4494 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
4495 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
4497 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
4498 /* Prevent post-update hook from running in cases when it should not */
4499 pTab = 0;
4502 if( pOp->p5 & OPFLAG_ISNOOP ) break;
4503 #endif
4505 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4506 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
4507 assert( pData->flags & (MEM_Blob|MEM_Str) );
4508 x.pData = pData->z;
4509 x.nData = pData->n;
4510 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
4511 if( pData->flags & MEM_Zero ){
4512 x.nZero = pData->u.nZero;
4513 }else{
4514 x.nZero = 0;
4516 x.pKey = 0;
4517 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
4518 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
4520 pC->deferredMoveto = 0;
4521 pC->cacheStatus = CACHE_STALE;
4523 /* Invoke the update-hook if required. */
4524 if( rc ) goto abort_due_to_error;
4525 if( pTab ){
4526 assert( db->xUpdateCallback!=0 );
4527 assert( pTab->aCol!=0 );
4528 db->xUpdateCallback(db->pUpdateArg,
4529 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
4530 zDb, pTab->zName, x.nKey);
4532 break;
4535 /* Opcode: Delete P1 P2 P3 P4 P5
4537 ** Delete the record at which the P1 cursor is currently pointing.
4539 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
4540 ** the cursor will be left pointing at either the next or the previous
4541 ** record in the table. If it is left pointing at the next record, then
4542 ** the next Next instruction will be a no-op. As a result, in this case
4543 ** it is ok to delete a record from within a Next loop. If
4544 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
4545 ** left in an undefined state.
4547 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
4548 ** delete one of several associated with deleting a table row and all its
4549 ** associated index entries. Exactly one of those deletes is the "primary"
4550 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
4551 ** marked with the AUXDELETE flag.
4553 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
4554 ** change count is incremented (otherwise not).
4556 ** P1 must not be pseudo-table. It has to be a real table with
4557 ** multiple rows.
4559 ** If P4 is not NULL then it points to a Table object. In this case either
4560 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
4561 ** have been positioned using OP_NotFound prior to invoking this opcode in
4562 ** this case. Specifically, if one is configured, the pre-update hook is
4563 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
4564 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
4566 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
4567 ** of the memory cell that contains the value that the rowid of the row will
4568 ** be set to by the update.
4570 case OP_Delete: {
4571 VdbeCursor *pC;
4572 const char *zDb;
4573 Table *pTab;
4574 int opflags;
4576 opflags = pOp->p2;
4577 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4578 pC = p->apCsr[pOp->p1];
4579 assert( pC!=0 );
4580 assert( pC->eCurType==CURTYPE_BTREE );
4581 assert( pC->uc.pCursor!=0 );
4582 assert( pC->deferredMoveto==0 );
4583 sqlite3VdbeIncrWriteCounter(p, pC);
4585 #ifdef SQLITE_DEBUG
4586 if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
4587 /* If p5 is zero, the seek operation that positioned the cursor prior to
4588 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
4589 ** the row that is being deleted */
4590 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4591 assert( pC->movetoTarget==iKey );
4593 #endif
4595 /* If the update-hook or pre-update-hook will be invoked, set zDb to
4596 ** the name of the db to pass as to it. Also set local pTab to a copy
4597 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
4598 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
4599 ** VdbeCursor.movetoTarget to the current rowid. */
4600 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4601 assert( pC->iDb>=0 );
4602 assert( pOp->p4.pTab!=0 );
4603 zDb = db->aDb[pC->iDb].zDbSName;
4604 pTab = pOp->p4.pTab;
4605 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
4606 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4608 }else{
4609 zDb = 0; /* Not needed. Silence a compiler warning. */
4610 pTab = 0; /* Not needed. Silence a compiler warning. */
4613 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4614 /* Invoke the pre-update-hook if required. */
4615 if( db->xPreUpdateCallback && pOp->p4.pTab ){
4616 assert( !(opflags & OPFLAG_ISUPDATE)
4617 || HasRowid(pTab)==0
4618 || (aMem[pOp->p3].flags & MEM_Int)
4620 sqlite3VdbePreUpdateHook(p, pC,
4621 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
4622 zDb, pTab, pC->movetoTarget,
4623 pOp->p3
4626 if( opflags & OPFLAG_ISNOOP ) break;
4627 #endif
4629 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
4630 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
4631 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
4632 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
4634 #ifdef SQLITE_DEBUG
4635 if( p->pFrame==0 ){
4636 if( pC->isEphemeral==0
4637 && (pOp->p5 & OPFLAG_AUXDELETE)==0
4638 && (pC->wrFlag & OPFLAG_FORDELETE)==0
4640 nExtraDelete++;
4642 if( pOp->p2 & OPFLAG_NCHANGE ){
4643 nExtraDelete--;
4646 #endif
4648 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
4649 pC->cacheStatus = CACHE_STALE;
4650 pC->seekResult = 0;
4651 if( rc ) goto abort_due_to_error;
4653 /* Invoke the update-hook if required. */
4654 if( opflags & OPFLAG_NCHANGE ){
4655 p->nChange++;
4656 if( db->xUpdateCallback && HasRowid(pTab) ){
4657 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
4658 pC->movetoTarget);
4659 assert( pC->iDb>=0 );
4663 break;
4665 /* Opcode: ResetCount * * * * *
4667 ** The value of the change counter is copied to the database handle
4668 ** change counter (returned by subsequent calls to sqlite3_changes()).
4669 ** Then the VMs internal change counter resets to 0.
4670 ** This is used by trigger programs.
4672 case OP_ResetCount: {
4673 sqlite3VdbeSetChanges(db, p->nChange);
4674 p->nChange = 0;
4675 break;
4678 /* Opcode: SorterCompare P1 P2 P3 P4
4679 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4681 ** P1 is a sorter cursor. This instruction compares a prefix of the
4682 ** record blob in register P3 against a prefix of the entry that
4683 ** the sorter cursor currently points to. Only the first P4 fields
4684 ** of r[P3] and the sorter record are compared.
4686 ** If either P3 or the sorter contains a NULL in one of their significant
4687 ** fields (not counting the P4 fields at the end which are ignored) then
4688 ** the comparison is assumed to be equal.
4690 ** Fall through to next instruction if the two records compare equal to
4691 ** each other. Jump to P2 if they are different.
4693 case OP_SorterCompare: {
4694 VdbeCursor *pC;
4695 int res;
4696 int nKeyCol;
4698 pC = p->apCsr[pOp->p1];
4699 assert( isSorter(pC) );
4700 assert( pOp->p4type==P4_INT32 );
4701 pIn3 = &aMem[pOp->p3];
4702 nKeyCol = pOp->p4.i;
4703 res = 0;
4704 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
4705 VdbeBranchTaken(res!=0,2);
4706 if( rc ) goto abort_due_to_error;
4707 if( res ) goto jump_to_p2;
4708 break;
4711 /* Opcode: SorterData P1 P2 P3 * *
4712 ** Synopsis: r[P2]=data
4714 ** Write into register P2 the current sorter data for sorter cursor P1.
4715 ** Then clear the column header cache on cursor P3.
4717 ** This opcode is normally use to move a record out of the sorter and into
4718 ** a register that is the source for a pseudo-table cursor created using
4719 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4720 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4721 ** us from having to issue a separate NullRow instruction to clear that cache.
4723 case OP_SorterData: {
4724 VdbeCursor *pC;
4726 pOut = &aMem[pOp->p2];
4727 pC = p->apCsr[pOp->p1];
4728 assert( isSorter(pC) );
4729 rc = sqlite3VdbeSorterRowkey(pC, pOut);
4730 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
4731 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4732 if( rc ) goto abort_due_to_error;
4733 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
4734 break;
4737 /* Opcode: RowData P1 P2 P3 * *
4738 ** Synopsis: r[P2]=data
4740 ** Write into register P2 the complete row content for the row at
4741 ** which cursor P1 is currently pointing.
4742 ** There is no interpretation of the data.
4743 ** It is just copied onto the P2 register exactly as
4744 ** it is found in the database file.
4746 ** If cursor P1 is an index, then the content is the key of the row.
4747 ** If cursor P2 is a table, then the content extracted is the data.
4749 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4750 ** of a real table, not a pseudo-table.
4752 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
4753 ** into the database page. That means that the content of the output
4754 ** register will be invalidated as soon as the cursor moves - including
4755 ** moves caused by other cursors that "save" the current cursors
4756 ** position in order that they can write to the same table. If P3==0
4757 ** then a copy of the data is made into memory. P3!=0 is faster, but
4758 ** P3==0 is safer.
4760 ** If P3!=0 then the content of the P2 register is unsuitable for use
4761 ** in OP_Result and any OP_Result will invalidate the P2 register content.
4762 ** The P2 register content is invalidated by opcodes like OP_Function or
4763 ** by any use of another cursor pointing to the same table.
4765 case OP_RowData: {
4766 VdbeCursor *pC;
4767 BtCursor *pCrsr;
4768 u32 n;
4770 pOut = out2Prerelease(p, pOp);
4772 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4773 pC = p->apCsr[pOp->p1];
4774 assert( pC!=0 );
4775 assert( pC->eCurType==CURTYPE_BTREE );
4776 assert( isSorter(pC)==0 );
4777 assert( pC->nullRow==0 );
4778 assert( pC->uc.pCursor!=0 );
4779 pCrsr = pC->uc.pCursor;
4781 /* The OP_RowData opcodes always follow OP_NotExists or
4782 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
4783 ** that might invalidate the cursor.
4784 ** If this where not the case, on of the following assert()s
4785 ** would fail. Should this ever change (because of changes in the code
4786 ** generator) then the fix would be to insert a call to
4787 ** sqlite3VdbeCursorMoveto().
4789 assert( pC->deferredMoveto==0 );
4790 assert( sqlite3BtreeCursorIsValid(pCrsr) );
4791 #if 0 /* Not required due to the previous to assert() statements */
4792 rc = sqlite3VdbeCursorMoveto(pC);
4793 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4794 #endif
4796 n = sqlite3BtreePayloadSize(pCrsr);
4797 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
4798 goto too_big;
4800 testcase( n==0 );
4801 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
4802 if( rc ) goto abort_due_to_error;
4803 if( !pOp->p3 ) Deephemeralize(pOut);
4804 UPDATE_MAX_BLOBSIZE(pOut);
4805 REGISTER_TRACE(pOp->p2, pOut);
4806 break;
4809 /* Opcode: Rowid P1 P2 * * *
4810 ** Synopsis: r[P2]=rowid
4812 ** Store in register P2 an integer which is the key of the table entry that
4813 ** P1 is currently point to.
4815 ** P1 can be either an ordinary table or a virtual table. There used to
4816 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4817 ** one opcode now works for both table types.
4819 case OP_Rowid: { /* out2 */
4820 VdbeCursor *pC;
4821 i64 v;
4822 sqlite3_vtab *pVtab;
4823 const sqlite3_module *pModule;
4825 pOut = out2Prerelease(p, pOp);
4826 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4827 pC = p->apCsr[pOp->p1];
4828 assert( pC!=0 );
4829 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
4830 if( pC->nullRow ){
4831 pOut->flags = MEM_Null;
4832 break;
4833 }else if( pC->deferredMoveto ){
4834 v = pC->movetoTarget;
4835 #ifndef SQLITE_OMIT_VIRTUALTABLE
4836 }else if( pC->eCurType==CURTYPE_VTAB ){
4837 assert( pC->uc.pVCur!=0 );
4838 pVtab = pC->uc.pVCur->pVtab;
4839 pModule = pVtab->pModule;
4840 assert( pModule->xRowid );
4841 rc = pModule->xRowid(pC->uc.pVCur, &v);
4842 sqlite3VtabImportErrmsg(p, pVtab);
4843 if( rc ) goto abort_due_to_error;
4844 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4845 }else{
4846 assert( pC->eCurType==CURTYPE_BTREE );
4847 assert( pC->uc.pCursor!=0 );
4848 rc = sqlite3VdbeCursorRestore(pC);
4849 if( rc ) goto abort_due_to_error;
4850 if( pC->nullRow ){
4851 pOut->flags = MEM_Null;
4852 break;
4854 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4856 pOut->u.i = v;
4857 break;
4860 /* Opcode: NullRow P1 * * * *
4862 ** Move the cursor P1 to a null row. Any OP_Column operations
4863 ** that occur while the cursor is on the null row will always
4864 ** write a NULL.
4866 case OP_NullRow: {
4867 VdbeCursor *pC;
4869 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4870 pC = p->apCsr[pOp->p1];
4871 assert( pC!=0 );
4872 pC->nullRow = 1;
4873 pC->cacheStatus = CACHE_STALE;
4874 if( pC->eCurType==CURTYPE_BTREE ){
4875 assert( pC->uc.pCursor!=0 );
4876 sqlite3BtreeClearCursor(pC->uc.pCursor);
4878 break;
4881 /* Opcode: SeekEnd P1 * * * *
4883 ** Position cursor P1 at the end of the btree for the purpose of
4884 ** appending a new entry onto the btree.
4886 ** It is assumed that the cursor is used only for appending and so
4887 ** if the cursor is valid, then the cursor must already be pointing
4888 ** at the end of the btree and so no changes are made to
4889 ** the cursor.
4891 /* Opcode: Last P1 P2 * * *
4893 ** The next use of the Rowid or Column or Prev instruction for P1
4894 ** will refer to the last entry in the database table or index.
4895 ** If the table or index is empty and P2>0, then jump immediately to P2.
4896 ** If P2 is 0 or if the table or index is not empty, fall through
4897 ** to the following instruction.
4899 ** This opcode leaves the cursor configured to move in reverse order,
4900 ** from the end toward the beginning. In other words, the cursor is
4901 ** configured to use Prev, not Next.
4903 case OP_SeekEnd:
4904 case OP_Last: { /* jump */
4905 VdbeCursor *pC;
4906 BtCursor *pCrsr;
4907 int res;
4909 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4910 pC = p->apCsr[pOp->p1];
4911 assert( pC!=0 );
4912 assert( pC->eCurType==CURTYPE_BTREE );
4913 pCrsr = pC->uc.pCursor;
4914 res = 0;
4915 assert( pCrsr!=0 );
4916 #ifdef SQLITE_DEBUG
4917 pC->seekOp = pOp->opcode;
4918 #endif
4919 if( pOp->opcode==OP_SeekEnd ){
4920 assert( pOp->p2==0 );
4921 pC->seekResult = -1;
4922 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
4923 break;
4926 rc = sqlite3BtreeLast(pCrsr, &res);
4927 pC->nullRow = (u8)res;
4928 pC->deferredMoveto = 0;
4929 pC->cacheStatus = CACHE_STALE;
4930 if( rc ) goto abort_due_to_error;
4931 if( pOp->p2>0 ){
4932 VdbeBranchTaken(res!=0,2);
4933 if( res ) goto jump_to_p2;
4935 break;
4938 /* Opcode: IfSmaller P1 P2 P3 * *
4940 ** Estimate the number of rows in the table P1. Jump to P2 if that
4941 ** estimate is less than approximately 2**(0.1*P3).
4943 case OP_IfSmaller: { /* jump */
4944 VdbeCursor *pC;
4945 BtCursor *pCrsr;
4946 int res;
4947 i64 sz;
4949 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4950 pC = p->apCsr[pOp->p1];
4951 assert( pC!=0 );
4952 pCrsr = pC->uc.pCursor;
4953 assert( pCrsr );
4954 rc = sqlite3BtreeFirst(pCrsr, &res);
4955 if( rc ) goto abort_due_to_error;
4956 if( res==0 ){
4957 sz = sqlite3BtreeRowCountEst(pCrsr);
4958 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
4960 VdbeBranchTaken(res!=0,2);
4961 if( res ) goto jump_to_p2;
4962 break;
4966 /* Opcode: SorterSort P1 P2 * * *
4968 ** After all records have been inserted into the Sorter object
4969 ** identified by P1, invoke this opcode to actually do the sorting.
4970 ** Jump to P2 if there are no records to be sorted.
4972 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
4973 ** for Sorter objects.
4975 /* Opcode: Sort P1 P2 * * *
4977 ** This opcode does exactly the same thing as OP_Rewind except that
4978 ** it increments an undocumented global variable used for testing.
4980 ** Sorting is accomplished by writing records into a sorting index,
4981 ** then rewinding that index and playing it back from beginning to
4982 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
4983 ** rewinding so that the global variable will be incremented and
4984 ** regression tests can determine whether or not the optimizer is
4985 ** correctly optimizing out sorts.
4987 case OP_SorterSort: /* jump */
4988 case OP_Sort: { /* jump */
4989 #ifdef SQLITE_TEST
4990 sqlite3_sort_count++;
4991 sqlite3_search_count--;
4992 #endif
4993 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
4994 /* Fall through into OP_Rewind */
4996 /* Opcode: Rewind P1 P2 * * *
4998 ** The next use of the Rowid or Column or Next instruction for P1
4999 ** will refer to the first entry in the database table or index.
5000 ** If the table or index is empty, jump immediately to P2.
5001 ** If the table or index is not empty, fall through to the following
5002 ** instruction.
5004 ** This opcode leaves the cursor configured to move in forward order,
5005 ** from the beginning toward the end. In other words, the cursor is
5006 ** configured to use Next, not Prev.
5008 case OP_Rewind: { /* jump */
5009 VdbeCursor *pC;
5010 BtCursor *pCrsr;
5011 int res;
5013 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5014 pC = p->apCsr[pOp->p1];
5015 assert( pC!=0 );
5016 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5017 res = 1;
5018 #ifdef SQLITE_DEBUG
5019 pC->seekOp = OP_Rewind;
5020 #endif
5021 if( isSorter(pC) ){
5022 rc = sqlite3VdbeSorterRewind(pC, &res);
5023 }else{
5024 assert( pC->eCurType==CURTYPE_BTREE );
5025 pCrsr = pC->uc.pCursor;
5026 assert( pCrsr );
5027 rc = sqlite3BtreeFirst(pCrsr, &res);
5028 pC->deferredMoveto = 0;
5029 pC->cacheStatus = CACHE_STALE;
5031 if( rc ) goto abort_due_to_error;
5032 pC->nullRow = (u8)res;
5033 assert( pOp->p2>0 && pOp->p2<p->nOp );
5034 VdbeBranchTaken(res!=0,2);
5035 if( res ) goto jump_to_p2;
5036 break;
5039 /* Opcode: Next P1 P2 P3 P4 P5
5041 ** Advance cursor P1 so that it points to the next key/data pair in its
5042 ** table or index. If there are no more key/value pairs then fall through
5043 ** to the following instruction. But if the cursor advance was successful,
5044 ** jump immediately to P2.
5046 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5047 ** OP_Rewind opcode used to position the cursor. Next is not allowed
5048 ** to follow SeekLT, SeekLE, or OP_Last.
5050 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
5051 ** been opened prior to this opcode or the program will segfault.
5053 ** The P3 value is a hint to the btree implementation. If P3==1, that
5054 ** means P1 is an SQL index and that this instruction could have been
5055 ** omitted if that index had been unique. P3 is usually 0. P3 is
5056 ** always either 0 or 1.
5058 ** P4 is always of type P4_ADVANCE. The function pointer points to
5059 ** sqlite3BtreeNext().
5061 ** If P5 is positive and the jump is taken, then event counter
5062 ** number P5-1 in the prepared statement is incremented.
5064 ** See also: Prev, NextIfOpen
5066 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
5068 ** This opcode works just like Next except that if cursor P1 is not
5069 ** open it behaves a no-op.
5071 /* Opcode: Prev P1 P2 P3 P4 P5
5073 ** Back up cursor P1 so that it points to the previous key/data pair in its
5074 ** table or index. If there is no previous key/value pairs then fall through
5075 ** to the following instruction. But if the cursor backup was successful,
5076 ** jump immediately to P2.
5079 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5080 ** OP_Last opcode used to position the cursor. Prev is not allowed
5081 ** to follow SeekGT, SeekGE, or OP_Rewind.
5083 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
5084 ** not open then the behavior is undefined.
5086 ** The P3 value is a hint to the btree implementation. If P3==1, that
5087 ** means P1 is an SQL index and that this instruction could have been
5088 ** omitted if that index had been unique. P3 is usually 0. P3 is
5089 ** always either 0 or 1.
5091 ** P4 is always of type P4_ADVANCE. The function pointer points to
5092 ** sqlite3BtreePrevious().
5094 ** If P5 is positive and the jump is taken, then event counter
5095 ** number P5-1 in the prepared statement is incremented.
5097 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
5099 ** This opcode works just like Prev except that if cursor P1 is not
5100 ** open it behaves a no-op.
5102 /* Opcode: SorterNext P1 P2 * * P5
5104 ** This opcode works just like OP_Next except that P1 must be a
5105 ** sorter object for which the OP_SorterSort opcode has been
5106 ** invoked. This opcode advances the cursor to the next sorted
5107 ** record, or jumps to P2 if there are no more sorted records.
5109 case OP_SorterNext: { /* jump */
5110 VdbeCursor *pC;
5112 pC = p->apCsr[pOp->p1];
5113 assert( isSorter(pC) );
5114 rc = sqlite3VdbeSorterNext(db, pC);
5115 goto next_tail;
5116 case OP_PrevIfOpen: /* jump */
5117 case OP_NextIfOpen: /* jump */
5118 if( p->apCsr[pOp->p1]==0 ) break;
5119 /* Fall through */
5120 case OP_Prev: /* jump */
5121 case OP_Next: /* jump */
5122 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5123 assert( pOp->p5<ArraySize(p->aCounter) );
5124 pC = p->apCsr[pOp->p1];
5125 assert( pC!=0 );
5126 assert( pC->deferredMoveto==0 );
5127 assert( pC->eCurType==CURTYPE_BTREE );
5128 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5129 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5130 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
5131 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
5133 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
5134 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5135 assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
5136 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5137 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
5138 assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
5139 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5140 || pC->seekOp==OP_Last );
5142 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5143 next_tail:
5144 pC->cacheStatus = CACHE_STALE;
5145 VdbeBranchTaken(rc==SQLITE_OK,2);
5146 if( rc==SQLITE_OK ){
5147 pC->nullRow = 0;
5148 p->aCounter[pOp->p5]++;
5149 #ifdef SQLITE_TEST
5150 sqlite3_search_count++;
5151 #endif
5152 goto jump_to_p2_and_check_for_interrupt;
5154 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5155 rc = SQLITE_OK;
5156 pC->nullRow = 1;
5157 goto check_for_interrupt;
5160 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5161 ** Synopsis: key=r[P2]
5163 ** Register P2 holds an SQL index key made using the
5164 ** MakeRecord instructions. This opcode writes that key
5165 ** into the index P1. Data for the entry is nil.
5167 ** If P4 is not zero, then it is the number of values in the unpacked
5168 ** key of reg(P2). In that case, P3 is the index of the first register
5169 ** for the unpacked key. The availability of the unpacked key can sometimes
5170 ** be an optimization.
5172 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5173 ** that this insert is likely to be an append.
5175 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5176 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
5177 ** then the change counter is unchanged.
5179 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5180 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5181 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5182 ** seeks on the cursor or if the most recent seek used a key equivalent
5183 ** to P2.
5185 ** This instruction only works for indices. The equivalent instruction
5186 ** for tables is OP_Insert.
5188 /* Opcode: SorterInsert P1 P2 * * *
5189 ** Synopsis: key=r[P2]
5191 ** Register P2 holds an SQL index key made using the
5192 ** MakeRecord instructions. This opcode writes that key
5193 ** into the sorter P1. Data for the entry is nil.
5195 case OP_SorterInsert: /* in2 */
5196 case OP_IdxInsert: { /* in2 */
5197 VdbeCursor *pC;
5198 BtreePayload x;
5200 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5201 pC = p->apCsr[pOp->p1];
5202 sqlite3VdbeIncrWriteCounter(p, pC);
5203 assert( pC!=0 );
5204 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
5205 pIn2 = &aMem[pOp->p2];
5206 assert( pIn2->flags & MEM_Blob );
5207 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5208 assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
5209 assert( pC->isTable==0 );
5210 rc = ExpandBlob(pIn2);
5211 if( rc ) goto abort_due_to_error;
5212 if( pOp->opcode==OP_SorterInsert ){
5213 rc = sqlite3VdbeSorterWrite(pC, pIn2);
5214 }else{
5215 x.nKey = pIn2->n;
5216 x.pKey = pIn2->z;
5217 x.aMem = aMem + pOp->p3;
5218 x.nMem = (u16)pOp->p4.i;
5219 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5220 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
5221 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
5223 assert( pC->deferredMoveto==0 );
5224 pC->cacheStatus = CACHE_STALE;
5226 if( rc) goto abort_due_to_error;
5227 break;
5230 /* Opcode: IdxDelete P1 P2 P3 * *
5231 ** Synopsis: key=r[P2@P3]
5233 ** The content of P3 registers starting at register P2 form
5234 ** an unpacked index key. This opcode removes that entry from the
5235 ** index opened by cursor P1.
5237 case OP_IdxDelete: {
5238 VdbeCursor *pC;
5239 BtCursor *pCrsr;
5240 int res;
5241 UnpackedRecord r;
5243 assert( pOp->p3>0 );
5244 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
5245 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5246 pC = p->apCsr[pOp->p1];
5247 assert( pC!=0 );
5248 assert( pC->eCurType==CURTYPE_BTREE );
5249 sqlite3VdbeIncrWriteCounter(p, pC);
5250 pCrsr = pC->uc.pCursor;
5251 assert( pCrsr!=0 );
5252 assert( pOp->p5==0 );
5253 r.pKeyInfo = pC->pKeyInfo;
5254 r.nField = (u16)pOp->p3;
5255 r.default_rc = 0;
5256 r.aMem = &aMem[pOp->p2];
5257 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
5258 if( rc ) goto abort_due_to_error;
5259 if( res==0 ){
5260 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
5261 if( rc ) goto abort_due_to_error;
5263 assert( pC->deferredMoveto==0 );
5264 pC->cacheStatus = CACHE_STALE;
5265 pC->seekResult = 0;
5266 break;
5269 /* Opcode: DeferredSeek P1 * P3 P4 *
5270 ** Synopsis: Move P3 to P1.rowid if needed
5272 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5273 ** table. This opcode does a deferred seek of the P3 table cursor
5274 ** to the row that corresponds to the current row of P1.
5276 ** This is a deferred seek. Nothing actually happens until
5277 ** the cursor is used to read a record. That way, if no reads
5278 ** occur, no unnecessary I/O happens.
5280 ** P4 may be an array of integers (type P4_INTARRAY) containing
5281 ** one entry for each column in the P3 table. If array entry a(i)
5282 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5283 ** equivalent to performing the deferred seek and then reading column i
5284 ** from P1. This information is stored in P3 and used to redirect
5285 ** reads against P3 over to P1, thus possibly avoiding the need to
5286 ** seek and read cursor P3.
5288 /* Opcode: IdxRowid P1 P2 * * *
5289 ** Synopsis: r[P2]=rowid
5291 ** Write into register P2 an integer which is the last entry in the record at
5292 ** the end of the index key pointed to by cursor P1. This integer should be
5293 ** the rowid of the table entry to which this index entry points.
5295 ** See also: Rowid, MakeRecord.
5297 case OP_DeferredSeek:
5298 case OP_IdxRowid: { /* out2 */
5299 VdbeCursor *pC; /* The P1 index cursor */
5300 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
5301 i64 rowid; /* Rowid that P1 current points to */
5303 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5304 pC = p->apCsr[pOp->p1];
5305 assert( pC!=0 );
5306 assert( pC->eCurType==CURTYPE_BTREE );
5307 assert( pC->uc.pCursor!=0 );
5308 assert( pC->isTable==0 );
5309 assert( pC->deferredMoveto==0 );
5310 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
5312 /* The IdxRowid and Seek opcodes are combined because of the commonality
5313 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5314 rc = sqlite3VdbeCursorRestore(pC);
5316 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5317 ** out from under the cursor. That will never happens for an IdxRowid
5318 ** or Seek opcode */
5319 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
5321 if( !pC->nullRow ){
5322 rowid = 0; /* Not needed. Only used to silence a warning. */
5323 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
5324 if( rc!=SQLITE_OK ){
5325 goto abort_due_to_error;
5327 if( pOp->opcode==OP_DeferredSeek ){
5328 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
5329 pTabCur = p->apCsr[pOp->p3];
5330 assert( pTabCur!=0 );
5331 assert( pTabCur->eCurType==CURTYPE_BTREE );
5332 assert( pTabCur->uc.pCursor!=0 );
5333 assert( pTabCur->isTable );
5334 pTabCur->nullRow = 0;
5335 pTabCur->movetoTarget = rowid;
5336 pTabCur->deferredMoveto = 1;
5337 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
5338 pTabCur->aAltMap = pOp->p4.ai;
5339 pTabCur->pAltCursor = pC;
5340 }else{
5341 pOut = out2Prerelease(p, pOp);
5342 pOut->u.i = rowid;
5344 }else{
5345 assert( pOp->opcode==OP_IdxRowid );
5346 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
5348 break;
5351 /* Opcode: IdxGE P1 P2 P3 P4 P5
5352 ** Synopsis: key=r[P3@P4]
5354 ** The P4 register values beginning with P3 form an unpacked index
5355 ** key that omits the PRIMARY KEY. Compare this key value against the index
5356 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5357 ** fields at the end.
5359 ** If the P1 index entry is greater than or equal to the key value
5360 ** then jump to P2. Otherwise fall through to the next instruction.
5362 /* Opcode: IdxGT P1 P2 P3 P4 P5
5363 ** Synopsis: key=r[P3@P4]
5365 ** The P4 register values beginning with P3 form an unpacked index
5366 ** key that omits the PRIMARY KEY. Compare this key value against the index
5367 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5368 ** fields at the end.
5370 ** If the P1 index entry is greater than the key value
5371 ** then jump to P2. Otherwise fall through to the next instruction.
5373 /* Opcode: IdxLT P1 P2 P3 P4 P5
5374 ** Synopsis: key=r[P3@P4]
5376 ** The P4 register values beginning with P3 form an unpacked index
5377 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5378 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5379 ** ROWID on the P1 index.
5381 ** If the P1 index entry is less than the key value then jump to P2.
5382 ** Otherwise fall through to the next instruction.
5384 /* Opcode: IdxLE P1 P2 P3 P4 P5
5385 ** Synopsis: key=r[P3@P4]
5387 ** The P4 register values beginning with P3 form an unpacked index
5388 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5389 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5390 ** ROWID on the P1 index.
5392 ** If the P1 index entry is less than or equal to the key value then jump
5393 ** to P2. Otherwise fall through to the next instruction.
5395 case OP_IdxLE: /* jump */
5396 case OP_IdxGT: /* jump */
5397 case OP_IdxLT: /* jump */
5398 case OP_IdxGE: { /* jump */
5399 VdbeCursor *pC;
5400 int res;
5401 UnpackedRecord r;
5403 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5404 pC = p->apCsr[pOp->p1];
5405 assert( pC!=0 );
5406 assert( pC->isOrdered );
5407 assert( pC->eCurType==CURTYPE_BTREE );
5408 assert( pC->uc.pCursor!=0);
5409 assert( pC->deferredMoveto==0 );
5410 assert( pOp->p5==0 || pOp->p5==1 );
5411 assert( pOp->p4type==P4_INT32 );
5412 r.pKeyInfo = pC->pKeyInfo;
5413 r.nField = (u16)pOp->p4.i;
5414 if( pOp->opcode<OP_IdxLT ){
5415 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
5416 r.default_rc = -1;
5417 }else{
5418 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
5419 r.default_rc = 0;
5421 r.aMem = &aMem[pOp->p3];
5422 #ifdef SQLITE_DEBUG
5423 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
5424 #endif
5425 res = 0; /* Not needed. Only used to silence a warning. */
5426 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5427 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
5428 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
5429 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
5430 res = -res;
5431 }else{
5432 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
5433 res++;
5435 VdbeBranchTaken(res>0,2);
5436 if( rc ) goto abort_due_to_error;
5437 if( res>0 ) goto jump_to_p2;
5438 break;
5441 /* Opcode: Destroy P1 P2 P3 * *
5443 ** Delete an entire database table or index whose root page in the database
5444 ** file is given by P1.
5446 ** The table being destroyed is in the main database file if P3==0. If
5447 ** P3==1 then the table to be clear is in the auxiliary database file
5448 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5450 ** If AUTOVACUUM is enabled then it is possible that another root page
5451 ** might be moved into the newly deleted root page in order to keep all
5452 ** root pages contiguous at the beginning of the database. The former
5453 ** value of the root page that moved - its value before the move occurred -
5454 ** is stored in register P2. If no page movement was required (because the
5455 ** table being dropped was already the last one in the database) then a
5456 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
5457 ** is stored in register P2.
5459 ** This opcode throws an error if there are any active reader VMs when
5460 ** it is invoked. This is done to avoid the difficulty associated with
5461 ** updating existing cursors when a root page is moved in an AUTOVACUUM
5462 ** database. This error is thrown even if the database is not an AUTOVACUUM
5463 ** db in order to avoid introducing an incompatibility between autovacuum
5464 ** and non-autovacuum modes.
5466 ** See also: Clear
5468 case OP_Destroy: { /* out2 */
5469 int iMoved;
5470 int iDb;
5472 sqlite3VdbeIncrWriteCounter(p, 0);
5473 assert( p->readOnly==0 );
5474 assert( pOp->p1>1 );
5475 pOut = out2Prerelease(p, pOp);
5476 pOut->flags = MEM_Null;
5477 if( db->nVdbeRead > db->nVDestroy+1 ){
5478 rc = SQLITE_LOCKED;
5479 p->errorAction = OE_Abort;
5480 goto abort_due_to_error;
5481 }else{
5482 iDb = pOp->p3;
5483 assert( DbMaskTest(p->btreeMask, iDb) );
5484 iMoved = 0; /* Not needed. Only to silence a warning. */
5485 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
5486 pOut->flags = MEM_Int;
5487 pOut->u.i = iMoved;
5488 if( rc ) goto abort_due_to_error;
5489 #ifndef SQLITE_OMIT_AUTOVACUUM
5490 if( iMoved!=0 ){
5491 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
5492 /* All OP_Destroy operations occur on the same btree */
5493 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
5494 resetSchemaOnFault = iDb+1;
5496 #endif
5498 break;
5501 /* Opcode: Clear P1 P2 P3
5503 ** Delete all contents of the database table or index whose root page
5504 ** in the database file is given by P1. But, unlike Destroy, do not
5505 ** remove the table or index from the database file.
5507 ** The table being clear is in the main database file if P2==0. If
5508 ** P2==1 then the table to be clear is in the auxiliary database file
5509 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5511 ** If the P3 value is non-zero, then the table referred to must be an
5512 ** intkey table (an SQL table, not an index). In this case the row change
5513 ** count is incremented by the number of rows in the table being cleared.
5514 ** If P3 is greater than zero, then the value stored in register P3 is
5515 ** also incremented by the number of rows in the table being cleared.
5517 ** See also: Destroy
5519 case OP_Clear: {
5520 int nChange;
5522 sqlite3VdbeIncrWriteCounter(p, 0);
5523 nChange = 0;
5524 assert( p->readOnly==0 );
5525 assert( DbMaskTest(p->btreeMask, pOp->p2) );
5526 rc = sqlite3BtreeClearTable(
5527 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
5529 if( pOp->p3 ){
5530 p->nChange += nChange;
5531 if( pOp->p3>0 ){
5532 assert( memIsValid(&aMem[pOp->p3]) );
5533 memAboutToChange(p, &aMem[pOp->p3]);
5534 aMem[pOp->p3].u.i += nChange;
5537 if( rc ) goto abort_due_to_error;
5538 break;
5541 /* Opcode: ResetSorter P1 * * * *
5543 ** Delete all contents from the ephemeral table or sorter
5544 ** that is open on cursor P1.
5546 ** This opcode only works for cursors used for sorting and
5547 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5549 case OP_ResetSorter: {
5550 VdbeCursor *pC;
5552 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5553 pC = p->apCsr[pOp->p1];
5554 assert( pC!=0 );
5555 if( isSorter(pC) ){
5556 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
5557 }else{
5558 assert( pC->eCurType==CURTYPE_BTREE );
5559 assert( pC->isEphemeral );
5560 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
5561 if( rc ) goto abort_due_to_error;
5563 break;
5566 /* Opcode: CreateBtree P1 P2 P3 * *
5567 ** Synopsis: r[P2]=root iDb=P1 flags=P3
5569 ** Allocate a new b-tree in the main database file if P1==0 or in the
5570 ** TEMP database file if P1==1 or in an attached database if
5571 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
5572 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
5573 ** The root page number of the new b-tree is stored in register P2.
5575 case OP_CreateBtree: { /* out2 */
5576 int pgno;
5577 Db *pDb;
5579 sqlite3VdbeIncrWriteCounter(p, 0);
5580 pOut = out2Prerelease(p, pOp);
5581 pgno = 0;
5582 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
5583 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5584 assert( DbMaskTest(p->btreeMask, pOp->p1) );
5585 assert( p->readOnly==0 );
5586 pDb = &db->aDb[pOp->p1];
5587 assert( pDb->pBt!=0 );
5588 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
5589 if( rc ) goto abort_due_to_error;
5590 pOut->u.i = pgno;
5591 break;
5594 /* Opcode: SqlExec * * * P4 *
5596 ** Run the SQL statement or statements specified in the P4 string.
5598 case OP_SqlExec: {
5599 sqlite3VdbeIncrWriteCounter(p, 0);
5600 db->nSqlExec++;
5601 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
5602 db->nSqlExec--;
5603 if( rc ) goto abort_due_to_error;
5604 break;
5607 /* Opcode: ParseSchema P1 * * P4 *
5609 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5610 ** that match the WHERE clause P4.
5612 ** This opcode invokes the parser to create a new virtual machine,
5613 ** then runs the new virtual machine. It is thus a re-entrant opcode.
5615 case OP_ParseSchema: {
5616 int iDb;
5617 const char *zMaster;
5618 char *zSql;
5619 InitData initData;
5621 /* Any prepared statement that invokes this opcode will hold mutexes
5622 ** on every btree. This is a prerequisite for invoking
5623 ** sqlite3InitCallback().
5625 #ifdef SQLITE_DEBUG
5626 for(iDb=0; iDb<db->nDb; iDb++){
5627 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
5629 #endif
5631 iDb = pOp->p1;
5632 assert( iDb>=0 && iDb<db->nDb );
5633 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
5634 /* Used to be a conditional */ {
5635 zMaster = MASTER_NAME;
5636 initData.db = db;
5637 initData.iDb = pOp->p1;
5638 initData.pzErrMsg = &p->zErrMsg;
5639 zSql = sqlite3MPrintf(db,
5640 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5641 db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
5642 if( zSql==0 ){
5643 rc = SQLITE_NOMEM_BKPT;
5644 }else{
5645 assert( db->init.busy==0 );
5646 db->init.busy = 1;
5647 initData.rc = SQLITE_OK;
5648 assert( !db->mallocFailed );
5649 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
5650 if( rc==SQLITE_OK ) rc = initData.rc;
5651 sqlite3DbFreeNN(db, zSql);
5652 db->init.busy = 0;
5655 if( rc ){
5656 sqlite3ResetAllSchemasOfConnection(db);
5657 if( rc==SQLITE_NOMEM ){
5658 goto no_mem;
5660 goto abort_due_to_error;
5662 break;
5665 #if !defined(SQLITE_OMIT_ANALYZE)
5666 /* Opcode: LoadAnalysis P1 * * * *
5668 ** Read the sqlite_stat1 table for database P1 and load the content
5669 ** of that table into the internal index hash table. This will cause
5670 ** the analysis to be used when preparing all subsequent queries.
5672 case OP_LoadAnalysis: {
5673 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5674 rc = sqlite3AnalysisLoad(db, pOp->p1);
5675 if( rc ) goto abort_due_to_error;
5676 break;
5678 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5680 /* Opcode: DropTable P1 * * P4 *
5682 ** Remove the internal (in-memory) data structures that describe
5683 ** the table named P4 in database P1. This is called after a table
5684 ** is dropped from disk (using the Destroy opcode) in order to keep
5685 ** the internal representation of the
5686 ** schema consistent with what is on disk.
5688 case OP_DropTable: {
5689 sqlite3VdbeIncrWriteCounter(p, 0);
5690 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
5691 break;
5694 /* Opcode: DropIndex P1 * * P4 *
5696 ** Remove the internal (in-memory) data structures that describe
5697 ** the index named P4 in database P1. This is called after an index
5698 ** is dropped from disk (using the Destroy opcode)
5699 ** in order to keep the internal representation of the
5700 ** schema consistent with what is on disk.
5702 case OP_DropIndex: {
5703 sqlite3VdbeIncrWriteCounter(p, 0);
5704 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
5705 break;
5708 /* Opcode: DropTrigger P1 * * P4 *
5710 ** Remove the internal (in-memory) data structures that describe
5711 ** the trigger named P4 in database P1. This is called after a trigger
5712 ** is dropped from disk (using the Destroy opcode) in order to keep
5713 ** the internal representation of the
5714 ** schema consistent with what is on disk.
5716 case OP_DropTrigger: {
5717 sqlite3VdbeIncrWriteCounter(p, 0);
5718 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
5719 break;
5723 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5724 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
5726 ** Do an analysis of the currently open database. Store in
5727 ** register P1 the text of an error message describing any problems.
5728 ** If no problems are found, store a NULL in register P1.
5730 ** The register P3 contains one less than the maximum number of allowed errors.
5731 ** At most reg(P3) errors will be reported.
5732 ** In other words, the analysis stops as soon as reg(P1) errors are
5733 ** seen. Reg(P1) is updated with the number of errors remaining.
5735 ** The root page numbers of all tables in the database are integers
5736 ** stored in P4_INTARRAY argument.
5738 ** If P5 is not zero, the check is done on the auxiliary database
5739 ** file, not the main database file.
5741 ** This opcode is used to implement the integrity_check pragma.
5743 case OP_IntegrityCk: {
5744 int nRoot; /* Number of tables to check. (Number of root pages.) */
5745 int *aRoot; /* Array of rootpage numbers for tables to be checked */
5746 int nErr; /* Number of errors reported */
5747 char *z; /* Text of the error report */
5748 Mem *pnErr; /* Register keeping track of errors remaining */
5750 assert( p->bIsReader );
5751 nRoot = pOp->p2;
5752 aRoot = pOp->p4.ai;
5753 assert( nRoot>0 );
5754 assert( aRoot[0]==nRoot );
5755 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
5756 pnErr = &aMem[pOp->p3];
5757 assert( (pnErr->flags & MEM_Int)!=0 );
5758 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
5759 pIn1 = &aMem[pOp->p1];
5760 assert( pOp->p5<db->nDb );
5761 assert( DbMaskTest(p->btreeMask, pOp->p5) );
5762 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
5763 (int)pnErr->u.i+1, &nErr);
5764 sqlite3VdbeMemSetNull(pIn1);
5765 if( nErr==0 ){
5766 assert( z==0 );
5767 }else if( z==0 ){
5768 goto no_mem;
5769 }else{
5770 pnErr->u.i -= nErr-1;
5771 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
5773 UPDATE_MAX_BLOBSIZE(pIn1);
5774 sqlite3VdbeChangeEncoding(pIn1, encoding);
5775 break;
5777 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5779 /* Opcode: RowSetAdd P1 P2 * * *
5780 ** Synopsis: rowset(P1)=r[P2]
5782 ** Insert the integer value held by register P2 into a RowSet object
5783 ** held in register P1.
5785 ** An assertion fails if P2 is not an integer.
5787 case OP_RowSetAdd: { /* in1, in2 */
5788 pIn1 = &aMem[pOp->p1];
5789 pIn2 = &aMem[pOp->p2];
5790 assert( (pIn2->flags & MEM_Int)!=0 );
5791 if( (pIn1->flags & MEM_RowSet)==0 ){
5792 sqlite3VdbeMemSetRowSet(pIn1);
5793 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5795 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
5796 break;
5799 /* Opcode: RowSetRead P1 P2 P3 * *
5800 ** Synopsis: r[P3]=rowset(P1)
5802 ** Extract the smallest value from the RowSet object in P1
5803 ** and put that value into register P3.
5804 ** Or, if RowSet object P1 is initially empty, leave P3
5805 ** unchanged and jump to instruction P2.
5807 case OP_RowSetRead: { /* jump, in1, out3 */
5808 i64 val;
5810 pIn1 = &aMem[pOp->p1];
5811 if( (pIn1->flags & MEM_RowSet)==0
5812 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
5814 /* The boolean index is empty */
5815 sqlite3VdbeMemSetNull(pIn1);
5816 VdbeBranchTaken(1,2);
5817 goto jump_to_p2_and_check_for_interrupt;
5818 }else{
5819 /* A value was pulled from the index */
5820 VdbeBranchTaken(0,2);
5821 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
5823 goto check_for_interrupt;
5826 /* Opcode: RowSetTest P1 P2 P3 P4
5827 ** Synopsis: if r[P3] in rowset(P1) goto P2
5829 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5830 ** contains a RowSet object and that RowSet object contains
5831 ** the value held in P3, jump to register P2. Otherwise, insert the
5832 ** integer in P3 into the RowSet and continue on to the
5833 ** next opcode.
5835 ** The RowSet object is optimized for the case where sets of integers
5836 ** are inserted in distinct phases, which each set contains no duplicates.
5837 ** Each set is identified by a unique P4 value. The first set
5838 ** must have P4==0, the final set must have P4==-1, and for all other sets
5839 ** must have P4>0.
5841 ** This allows optimizations: (a) when P4==0 there is no need to test
5842 ** the RowSet object for P3, as it is guaranteed not to contain it,
5843 ** (b) when P4==-1 there is no need to insert the value, as it will
5844 ** never be tested for, and (c) when a value that is part of set X is
5845 ** inserted, there is no need to search to see if the same value was
5846 ** previously inserted as part of set X (only if it was previously
5847 ** inserted as part of some other set).
5849 case OP_RowSetTest: { /* jump, in1, in3 */
5850 int iSet;
5851 int exists;
5853 pIn1 = &aMem[pOp->p1];
5854 pIn3 = &aMem[pOp->p3];
5855 iSet = pOp->p4.i;
5856 assert( pIn3->flags&MEM_Int );
5858 /* If there is anything other than a rowset object in memory cell P1,
5859 ** delete it now and initialize P1 with an empty rowset
5861 if( (pIn1->flags & MEM_RowSet)==0 ){
5862 sqlite3VdbeMemSetRowSet(pIn1);
5863 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5866 assert( pOp->p4type==P4_INT32 );
5867 assert( iSet==-1 || iSet>=0 );
5868 if( iSet ){
5869 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
5870 VdbeBranchTaken(exists!=0,2);
5871 if( exists ) goto jump_to_p2;
5873 if( iSet>=0 ){
5874 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
5876 break;
5880 #ifndef SQLITE_OMIT_TRIGGER
5882 /* Opcode: Program P1 P2 P3 P4 P5
5884 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5886 ** P1 contains the address of the memory cell that contains the first memory
5887 ** cell in an array of values used as arguments to the sub-program. P2
5888 ** contains the address to jump to if the sub-program throws an IGNORE
5889 ** exception using the RAISE() function. Register P3 contains the address
5890 ** of a memory cell in this (the parent) VM that is used to allocate the
5891 ** memory required by the sub-vdbe at runtime.
5893 ** P4 is a pointer to the VM containing the trigger program.
5895 ** If P5 is non-zero, then recursive program invocation is enabled.
5897 case OP_Program: { /* jump */
5898 int nMem; /* Number of memory registers for sub-program */
5899 int nByte; /* Bytes of runtime space required for sub-program */
5900 Mem *pRt; /* Register to allocate runtime space */
5901 Mem *pMem; /* Used to iterate through memory cells */
5902 Mem *pEnd; /* Last memory cell in new array */
5903 VdbeFrame *pFrame; /* New vdbe frame to execute in */
5904 SubProgram *pProgram; /* Sub-program to execute */
5905 void *t; /* Token identifying trigger */
5907 pProgram = pOp->p4.pProgram;
5908 pRt = &aMem[pOp->p3];
5909 assert( pProgram->nOp>0 );
5911 /* If the p5 flag is clear, then recursive invocation of triggers is
5912 ** disabled for backwards compatibility (p5 is set if this sub-program
5913 ** is really a trigger, not a foreign key action, and the flag set
5914 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
5916 ** It is recursive invocation of triggers, at the SQL level, that is
5917 ** disabled. In some cases a single trigger may generate more than one
5918 ** SubProgram (if the trigger may be executed with more than one different
5919 ** ON CONFLICT algorithm). SubProgram structures associated with a
5920 ** single trigger all have the same value for the SubProgram.token
5921 ** variable. */
5922 if( pOp->p5 ){
5923 t = pProgram->token;
5924 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
5925 if( pFrame ) break;
5928 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
5929 rc = SQLITE_ERROR;
5930 sqlite3VdbeError(p, "too many levels of trigger recursion");
5931 goto abort_due_to_error;
5934 /* Register pRt is used to store the memory required to save the state
5935 ** of the current program, and the memory required at runtime to execute
5936 ** the trigger program. If this trigger has been fired before, then pRt
5937 ** is already allocated. Otherwise, it must be initialized. */
5938 if( (pRt->flags&MEM_Frame)==0 ){
5939 /* SubProgram.nMem is set to the number of memory cells used by the
5940 ** program stored in SubProgram.aOp. As well as these, one memory
5941 ** cell is required for each cursor used by the program. Set local
5942 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
5944 nMem = pProgram->nMem + pProgram->nCsr;
5945 assert( nMem>0 );
5946 if( pProgram->nCsr==0 ) nMem++;
5947 nByte = ROUND8(sizeof(VdbeFrame))
5948 + nMem * sizeof(Mem)
5949 + pProgram->nCsr * sizeof(VdbeCursor*)
5950 + (pProgram->nOp + 7)/8;
5951 pFrame = sqlite3DbMallocZero(db, nByte);
5952 if( !pFrame ){
5953 goto no_mem;
5955 sqlite3VdbeMemRelease(pRt);
5956 pRt->flags = MEM_Frame;
5957 pRt->u.pFrame = pFrame;
5959 pFrame->v = p;
5960 pFrame->nChildMem = nMem;
5961 pFrame->nChildCsr = pProgram->nCsr;
5962 pFrame->pc = (int)(pOp - aOp);
5963 pFrame->aMem = p->aMem;
5964 pFrame->nMem = p->nMem;
5965 pFrame->apCsr = p->apCsr;
5966 pFrame->nCursor = p->nCursor;
5967 pFrame->aOp = p->aOp;
5968 pFrame->nOp = p->nOp;
5969 pFrame->token = pProgram->token;
5970 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
5971 pFrame->anExec = p->anExec;
5972 #endif
5974 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
5975 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
5976 pMem->flags = MEM_Undefined;
5977 pMem->db = db;
5979 }else{
5980 pFrame = pRt->u.pFrame;
5981 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
5982 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
5983 assert( pProgram->nCsr==pFrame->nChildCsr );
5984 assert( (int)(pOp - aOp)==pFrame->pc );
5987 p->nFrame++;
5988 pFrame->pParent = p->pFrame;
5989 pFrame->lastRowid = db->lastRowid;
5990 pFrame->nChange = p->nChange;
5991 pFrame->nDbChange = p->db->nChange;
5992 assert( pFrame->pAuxData==0 );
5993 pFrame->pAuxData = p->pAuxData;
5994 p->pAuxData = 0;
5995 p->nChange = 0;
5996 p->pFrame = pFrame;
5997 p->aMem = aMem = VdbeFrameMem(pFrame);
5998 p->nMem = pFrame->nChildMem;
5999 p->nCursor = (u16)pFrame->nChildCsr;
6000 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
6001 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
6002 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
6003 p->aOp = aOp = pProgram->aOp;
6004 p->nOp = pProgram->nOp;
6005 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6006 p->anExec = 0;
6007 #endif
6008 pOp = &aOp[-1];
6010 break;
6013 /* Opcode: Param P1 P2 * * *
6015 ** This opcode is only ever present in sub-programs called via the
6016 ** OP_Program instruction. Copy a value currently stored in a memory
6017 ** cell of the calling (parent) frame to cell P2 in the current frames
6018 ** address space. This is used by trigger programs to access the new.*
6019 ** and old.* values.
6021 ** The address of the cell in the parent frame is determined by adding
6022 ** the value of the P1 argument to the value of the P1 argument to the
6023 ** calling OP_Program instruction.
6025 case OP_Param: { /* out2 */
6026 VdbeFrame *pFrame;
6027 Mem *pIn;
6028 pOut = out2Prerelease(p, pOp);
6029 pFrame = p->pFrame;
6030 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
6031 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
6032 break;
6035 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6037 #ifndef SQLITE_OMIT_FOREIGN_KEY
6038 /* Opcode: FkCounter P1 P2 * * *
6039 ** Synopsis: fkctr[P1]+=P2
6041 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6042 ** If P1 is non-zero, the database constraint counter is incremented
6043 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6044 ** statement counter is incremented (immediate foreign key constraints).
6046 case OP_FkCounter: {
6047 if( db->flags & SQLITE_DeferFKs ){
6048 db->nDeferredImmCons += pOp->p2;
6049 }else if( pOp->p1 ){
6050 db->nDeferredCons += pOp->p2;
6051 }else{
6052 p->nFkConstraint += pOp->p2;
6054 break;
6057 /* Opcode: FkIfZero P1 P2 * * *
6058 ** Synopsis: if fkctr[P1]==0 goto P2
6060 ** This opcode tests if a foreign key constraint-counter is currently zero.
6061 ** If so, jump to instruction P2. Otherwise, fall through to the next
6062 ** instruction.
6064 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6065 ** is zero (the one that counts deferred constraint violations). If P1 is
6066 ** zero, the jump is taken if the statement constraint-counter is zero
6067 ** (immediate foreign key constraint violations).
6069 case OP_FkIfZero: { /* jump */
6070 if( pOp->p1 ){
6071 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6072 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6073 }else{
6074 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6075 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6077 break;
6079 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6081 #ifndef SQLITE_OMIT_AUTOINCREMENT
6082 /* Opcode: MemMax P1 P2 * * *
6083 ** Synopsis: r[P1]=max(r[P1],r[P2])
6085 ** P1 is a register in the root frame of this VM (the root frame is
6086 ** different from the current frame if this instruction is being executed
6087 ** within a sub-program). Set the value of register P1 to the maximum of
6088 ** its current value and the value in register P2.
6090 ** This instruction throws an error if the memory cell is not initially
6091 ** an integer.
6093 case OP_MemMax: { /* in2 */
6094 VdbeFrame *pFrame;
6095 if( p->pFrame ){
6096 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
6097 pIn1 = &pFrame->aMem[pOp->p1];
6098 }else{
6099 pIn1 = &aMem[pOp->p1];
6101 assert( memIsValid(pIn1) );
6102 sqlite3VdbeMemIntegerify(pIn1);
6103 pIn2 = &aMem[pOp->p2];
6104 sqlite3VdbeMemIntegerify(pIn2);
6105 if( pIn1->u.i<pIn2->u.i){
6106 pIn1->u.i = pIn2->u.i;
6108 break;
6110 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6112 /* Opcode: IfPos P1 P2 P3 * *
6113 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6115 ** Register P1 must contain an integer.
6116 ** If the value of register P1 is 1 or greater, subtract P3 from the
6117 ** value in P1 and jump to P2.
6119 ** If the initial value of register P1 is less than 1, then the
6120 ** value is unchanged and control passes through to the next instruction.
6122 case OP_IfPos: { /* jump, in1 */
6123 pIn1 = &aMem[pOp->p1];
6124 assert( pIn1->flags&MEM_Int );
6125 VdbeBranchTaken( pIn1->u.i>0, 2);
6126 if( pIn1->u.i>0 ){
6127 pIn1->u.i -= pOp->p3;
6128 goto jump_to_p2;
6130 break;
6133 /* Opcode: OffsetLimit P1 P2 P3 * *
6134 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6136 ** This opcode performs a commonly used computation associated with
6137 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
6138 ** holds the offset counter. The opcode computes the combined value
6139 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
6140 ** value computed is the total number of rows that will need to be
6141 ** visited in order to complete the query.
6143 ** If r[P3] is zero or negative, that means there is no OFFSET
6144 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6146 ** if r[P1] is zero or negative, that means there is no LIMIT
6147 ** and r[P2] is set to -1.
6149 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6151 case OP_OffsetLimit: { /* in1, out2, in3 */
6152 i64 x;
6153 pIn1 = &aMem[pOp->p1];
6154 pIn3 = &aMem[pOp->p3];
6155 pOut = out2Prerelease(p, pOp);
6156 assert( pIn1->flags & MEM_Int );
6157 assert( pIn3->flags & MEM_Int );
6158 x = pIn1->u.i;
6159 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
6160 /* If the LIMIT is less than or equal to zero, loop forever. This
6161 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
6162 ** also loop forever. This is undocumented. In fact, one could argue
6163 ** that the loop should terminate. But assuming 1 billion iterations
6164 ** per second (far exceeding the capabilities of any current hardware)
6165 ** it would take nearly 300 years to actually reach the limit. So
6166 ** looping forever is a reasonable approximation. */
6167 pOut->u.i = -1;
6168 }else{
6169 pOut->u.i = x;
6171 break;
6174 /* Opcode: IfNotZero P1 P2 * * *
6175 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6177 ** Register P1 must contain an integer. If the content of register P1 is
6178 ** initially greater than zero, then decrement the value in register P1.
6179 ** If it is non-zero (negative or positive) and then also jump to P2.
6180 ** If register P1 is initially zero, leave it unchanged and fall through.
6182 case OP_IfNotZero: { /* jump, in1 */
6183 pIn1 = &aMem[pOp->p1];
6184 assert( pIn1->flags&MEM_Int );
6185 VdbeBranchTaken(pIn1->u.i<0, 2);
6186 if( pIn1->u.i ){
6187 if( pIn1->u.i>0 ) pIn1->u.i--;
6188 goto jump_to_p2;
6190 break;
6193 /* Opcode: DecrJumpZero P1 P2 * * *
6194 ** Synopsis: if (--r[P1])==0 goto P2
6196 ** Register P1 must hold an integer. Decrement the value in P1
6197 ** and jump to P2 if the new value is exactly zero.
6199 case OP_DecrJumpZero: { /* jump, in1 */
6200 pIn1 = &aMem[pOp->p1];
6201 assert( pIn1->flags&MEM_Int );
6202 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
6203 VdbeBranchTaken(pIn1->u.i==0, 2);
6204 if( pIn1->u.i==0 ) goto jump_to_p2;
6205 break;
6209 /* Opcode: AggStep0 * P2 P3 P4 P5
6210 ** Synopsis: accum=r[P3] step(r[P2@P5])
6212 ** Execute the step function for an aggregate. The
6213 ** function has P5 arguments. P4 is a pointer to the FuncDef
6214 ** structure that specifies the function. Register P3 is the
6215 ** accumulator.
6217 ** The P5 arguments are taken from register P2 and its
6218 ** successors.
6220 /* Opcode: AggStep * P2 P3 P4 P5
6221 ** Synopsis: accum=r[P3] step(r[P2@P5])
6223 ** Execute the step function for an aggregate. The
6224 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
6225 ** object that is used to run the function. Register P3 is
6226 ** as the accumulator.
6228 ** The P5 arguments are taken from register P2 and its
6229 ** successors.
6231 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6232 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6233 ** the opcode is changed. In this way, the initialization of the
6234 ** sqlite3_context only happens once, instead of on each call to the
6235 ** step function.
6237 case OP_AggStep0: {
6238 int n;
6239 sqlite3_context *pCtx;
6241 assert( pOp->p4type==P4_FUNCDEF );
6242 n = pOp->p5;
6243 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6244 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
6245 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
6246 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
6247 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
6248 if( pCtx==0 ) goto no_mem;
6249 pCtx->pMem = 0;
6250 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
6251 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
6252 pCtx->pFunc = pOp->p4.pFunc;
6253 pCtx->iOp = (int)(pOp - aOp);
6254 pCtx->pVdbe = p;
6255 pCtx->skipFlag = 0;
6256 pCtx->isError = 0;
6257 pCtx->argc = n;
6258 pOp->p4type = P4_FUNCCTX;
6259 pOp->p4.pCtx = pCtx;
6260 pOp->opcode = OP_AggStep;
6261 /* Fall through into OP_AggStep */
6263 case OP_AggStep: {
6264 int i;
6265 sqlite3_context *pCtx;
6266 Mem *pMem;
6268 assert( pOp->p4type==P4_FUNCCTX );
6269 pCtx = pOp->p4.pCtx;
6270 pMem = &aMem[pOp->p3];
6272 /* If this function is inside of a trigger, the register array in aMem[]
6273 ** might change from one evaluation to the next. The next block of code
6274 ** checks to see if the register array has changed, and if so it
6275 ** reinitializes the relavant parts of the sqlite3_context object */
6276 if( pCtx->pMem != pMem ){
6277 pCtx->pMem = pMem;
6278 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
6281 #ifdef SQLITE_DEBUG
6282 for(i=0; i<pCtx->argc; i++){
6283 assert( memIsValid(pCtx->argv[i]) );
6284 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
6286 #endif
6288 pMem->n++;
6289 assert( pCtx->pOut->flags==MEM_Null );
6290 assert( pCtx->isError==0 );
6291 assert( pCtx->skipFlag==0 );
6292 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
6293 if( pCtx->isError ){
6294 if( pCtx->isError>0 ){
6295 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
6296 rc = pCtx->isError;
6298 if( pCtx->skipFlag ){
6299 assert( pOp[-1].opcode==OP_CollSeq );
6300 i = pOp[-1].p1;
6301 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
6302 pCtx->skipFlag = 0;
6304 sqlite3VdbeMemRelease(pCtx->pOut);
6305 pCtx->pOut->flags = MEM_Null;
6306 pCtx->isError = 0;
6307 if( rc ) goto abort_due_to_error;
6309 assert( pCtx->pOut->flags==MEM_Null );
6310 assert( pCtx->skipFlag==0 );
6311 break;
6314 /* Opcode: AggFinal P1 P2 * P4 *
6315 ** Synopsis: accum=r[P1] N=P2
6317 ** Execute the finalizer function for an aggregate. P1 is
6318 ** the memory location that is the accumulator for the aggregate.
6320 ** P2 is the number of arguments that the step function takes and
6321 ** P4 is a pointer to the FuncDef for this function. The P2
6322 ** argument is not used by this opcode. It is only there to disambiguate
6323 ** functions that can take varying numbers of arguments. The
6324 ** P4 argument is only needed for the degenerate case where
6325 ** the step function was not previously called.
6327 case OP_AggFinal: {
6328 Mem *pMem;
6329 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
6330 pMem = &aMem[pOp->p1];
6331 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
6332 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
6333 if( rc ){
6334 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
6335 goto abort_due_to_error;
6337 sqlite3VdbeChangeEncoding(pMem, encoding);
6338 UPDATE_MAX_BLOBSIZE(pMem);
6339 if( sqlite3VdbeMemTooBig(pMem) ){
6340 goto too_big;
6342 break;
6345 #ifndef SQLITE_OMIT_WAL
6346 /* Opcode: Checkpoint P1 P2 P3 * *
6348 ** Checkpoint database P1. This is a no-op if P1 is not currently in
6349 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
6350 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
6351 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
6352 ** WAL after the checkpoint into mem[P3+1] and the number of pages
6353 ** in the WAL that have been checkpointed after the checkpoint
6354 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
6355 ** mem[P3+2] are initialized to -1.
6357 case OP_Checkpoint: {
6358 int i; /* Loop counter */
6359 int aRes[3]; /* Results */
6360 Mem *pMem; /* Write results here */
6362 assert( p->readOnly==0 );
6363 aRes[0] = 0;
6364 aRes[1] = aRes[2] = -1;
6365 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
6366 || pOp->p2==SQLITE_CHECKPOINT_FULL
6367 || pOp->p2==SQLITE_CHECKPOINT_RESTART
6368 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
6370 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
6371 if( rc ){
6372 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
6373 rc = SQLITE_OK;
6374 aRes[0] = 1;
6376 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
6377 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
6379 break;
6381 #endif
6383 #ifndef SQLITE_OMIT_PRAGMA
6384 /* Opcode: JournalMode P1 P2 P3 * *
6386 ** Change the journal mode of database P1 to P3. P3 must be one of the
6387 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
6388 ** modes (delete, truncate, persist, off and memory), this is a simple
6389 ** operation. No IO is required.
6391 ** If changing into or out of WAL mode the procedure is more complicated.
6393 ** Write a string containing the final journal-mode to register P2.
6395 case OP_JournalMode: { /* out2 */
6396 Btree *pBt; /* Btree to change journal mode of */
6397 Pager *pPager; /* Pager associated with pBt */
6398 int eNew; /* New journal mode */
6399 int eOld; /* The old journal mode */
6400 #ifndef SQLITE_OMIT_WAL
6401 const char *zFilename; /* Name of database file for pPager */
6402 #endif
6404 pOut = out2Prerelease(p, pOp);
6405 eNew = pOp->p3;
6406 assert( eNew==PAGER_JOURNALMODE_DELETE
6407 || eNew==PAGER_JOURNALMODE_TRUNCATE
6408 || eNew==PAGER_JOURNALMODE_PERSIST
6409 || eNew==PAGER_JOURNALMODE_OFF
6410 || eNew==PAGER_JOURNALMODE_MEMORY
6411 || eNew==PAGER_JOURNALMODE_WAL
6412 || eNew==PAGER_JOURNALMODE_QUERY
6414 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6415 assert( p->readOnly==0 );
6417 pBt = db->aDb[pOp->p1].pBt;
6418 pPager = sqlite3BtreePager(pBt);
6419 eOld = sqlite3PagerGetJournalMode(pPager);
6420 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
6421 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
6423 #ifndef SQLITE_OMIT_WAL
6424 zFilename = sqlite3PagerFilename(pPager, 1);
6426 /* Do not allow a transition to journal_mode=WAL for a database
6427 ** in temporary storage or if the VFS does not support shared memory
6429 if( eNew==PAGER_JOURNALMODE_WAL
6430 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
6431 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
6433 eNew = eOld;
6436 if( (eNew!=eOld)
6437 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
6439 if( !db->autoCommit || db->nVdbeRead>1 ){
6440 rc = SQLITE_ERROR;
6441 sqlite3VdbeError(p,
6442 "cannot change %s wal mode from within a transaction",
6443 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
6445 goto abort_due_to_error;
6446 }else{
6448 if( eOld==PAGER_JOURNALMODE_WAL ){
6449 /* If leaving WAL mode, close the log file. If successful, the call
6450 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
6451 ** file. An EXCLUSIVE lock may still be held on the database file
6452 ** after a successful return.
6454 rc = sqlite3PagerCloseWal(pPager, db);
6455 if( rc==SQLITE_OK ){
6456 sqlite3PagerSetJournalMode(pPager, eNew);
6458 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
6459 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
6460 ** as an intermediate */
6461 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
6464 /* Open a transaction on the database file. Regardless of the journal
6465 ** mode, this transaction always uses a rollback journal.
6467 assert( sqlite3BtreeIsInTrans(pBt)==0 );
6468 if( rc==SQLITE_OK ){
6469 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
6473 #endif /* ifndef SQLITE_OMIT_WAL */
6475 if( rc ) eNew = eOld;
6476 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
6478 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
6479 pOut->z = (char *)sqlite3JournalModename(eNew);
6480 pOut->n = sqlite3Strlen30(pOut->z);
6481 pOut->enc = SQLITE_UTF8;
6482 sqlite3VdbeChangeEncoding(pOut, encoding);
6483 if( rc ) goto abort_due_to_error;
6484 break;
6486 #endif /* SQLITE_OMIT_PRAGMA */
6488 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
6489 /* Opcode: Vacuum P1 * * * *
6491 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
6492 ** for an attached database. The "temp" database may not be vacuumed.
6494 case OP_Vacuum: {
6495 assert( p->readOnly==0 );
6496 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
6497 if( rc ) goto abort_due_to_error;
6498 break;
6500 #endif
6502 #if !defined(SQLITE_OMIT_AUTOVACUUM)
6503 /* Opcode: IncrVacuum P1 P2 * * *
6505 ** Perform a single step of the incremental vacuum procedure on
6506 ** the P1 database. If the vacuum has finished, jump to instruction
6507 ** P2. Otherwise, fall through to the next instruction.
6509 case OP_IncrVacuum: { /* jump */
6510 Btree *pBt;
6512 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6513 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6514 assert( p->readOnly==0 );
6515 pBt = db->aDb[pOp->p1].pBt;
6516 rc = sqlite3BtreeIncrVacuum(pBt);
6517 VdbeBranchTaken(rc==SQLITE_DONE,2);
6518 if( rc ){
6519 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6520 rc = SQLITE_OK;
6521 goto jump_to_p2;
6523 break;
6525 #endif
6527 /* Opcode: Expire P1 * * * *
6529 ** Cause precompiled statements to expire. When an expired statement
6530 ** is executed using sqlite3_step() it will either automatically
6531 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
6532 ** or it will fail with SQLITE_SCHEMA.
6534 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
6535 ** then only the currently executing statement is expired.
6537 case OP_Expire: {
6538 if( !pOp->p1 ){
6539 sqlite3ExpirePreparedStatements(db);
6540 }else{
6541 p->expired = 1;
6543 break;
6546 #ifndef SQLITE_OMIT_SHARED_CACHE
6547 /* Opcode: TableLock P1 P2 P3 P4 *
6548 ** Synopsis: iDb=P1 root=P2 write=P3
6550 ** Obtain a lock on a particular table. This instruction is only used when
6551 ** the shared-cache feature is enabled.
6553 ** P1 is the index of the database in sqlite3.aDb[] of the database
6554 ** on which the lock is acquired. A readlock is obtained if P3==0 or
6555 ** a write lock if P3==1.
6557 ** P2 contains the root-page of the table to lock.
6559 ** P4 contains a pointer to the name of the table being locked. This is only
6560 ** used to generate an error message if the lock cannot be obtained.
6562 case OP_TableLock: {
6563 u8 isWriteLock = (u8)pOp->p3;
6564 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
6565 int p1 = pOp->p1;
6566 assert( p1>=0 && p1<db->nDb );
6567 assert( DbMaskTest(p->btreeMask, p1) );
6568 assert( isWriteLock==0 || isWriteLock==1 );
6569 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
6570 if( rc ){
6571 if( (rc&0xFF)==SQLITE_LOCKED ){
6572 const char *z = pOp->p4.z;
6573 sqlite3VdbeError(p, "database table is locked: %s", z);
6575 goto abort_due_to_error;
6578 break;
6580 #endif /* SQLITE_OMIT_SHARED_CACHE */
6582 #ifndef SQLITE_OMIT_VIRTUALTABLE
6583 /* Opcode: VBegin * * * P4 *
6585 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
6586 ** xBegin method for that table.
6588 ** Also, whether or not P4 is set, check that this is not being called from
6589 ** within a callback to a virtual table xSync() method. If it is, the error
6590 ** code will be set to SQLITE_LOCKED.
6592 case OP_VBegin: {
6593 VTable *pVTab;
6594 pVTab = pOp->p4.pVtab;
6595 rc = sqlite3VtabBegin(db, pVTab);
6596 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
6597 if( rc ) goto abort_due_to_error;
6598 break;
6600 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6602 #ifndef SQLITE_OMIT_VIRTUALTABLE
6603 /* Opcode: VCreate P1 P2 * * *
6605 ** P2 is a register that holds the name of a virtual table in database
6606 ** P1. Call the xCreate method for that table.
6608 case OP_VCreate: {
6609 Mem sMem; /* For storing the record being decoded */
6610 const char *zTab; /* Name of the virtual table */
6612 memset(&sMem, 0, sizeof(sMem));
6613 sMem.db = db;
6614 /* Because P2 is always a static string, it is impossible for the
6615 ** sqlite3VdbeMemCopy() to fail */
6616 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
6617 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
6618 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
6619 assert( rc==SQLITE_OK );
6620 zTab = (const char*)sqlite3_value_text(&sMem);
6621 assert( zTab || db->mallocFailed );
6622 if( zTab ){
6623 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
6625 sqlite3VdbeMemRelease(&sMem);
6626 if( rc ) goto abort_due_to_error;
6627 break;
6629 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6631 #ifndef SQLITE_OMIT_VIRTUALTABLE
6632 /* Opcode: VDestroy P1 * * P4 *
6634 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
6635 ** of that table.
6637 case OP_VDestroy: {
6638 db->nVDestroy++;
6639 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
6640 db->nVDestroy--;
6641 if( rc ) goto abort_due_to_error;
6642 break;
6644 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6646 #ifndef SQLITE_OMIT_VIRTUALTABLE
6647 /* Opcode: VOpen P1 * * P4 *
6649 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6650 ** P1 is a cursor number. This opcode opens a cursor to the virtual
6651 ** table and stores that cursor in P1.
6653 case OP_VOpen: {
6654 VdbeCursor *pCur;
6655 sqlite3_vtab_cursor *pVCur;
6656 sqlite3_vtab *pVtab;
6657 const sqlite3_module *pModule;
6659 assert( p->bIsReader );
6660 pCur = 0;
6661 pVCur = 0;
6662 pVtab = pOp->p4.pVtab->pVtab;
6663 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6664 rc = SQLITE_LOCKED;
6665 goto abort_due_to_error;
6667 pModule = pVtab->pModule;
6668 rc = pModule->xOpen(pVtab, &pVCur);
6669 sqlite3VtabImportErrmsg(p, pVtab);
6670 if( rc ) goto abort_due_to_error;
6672 /* Initialize sqlite3_vtab_cursor base class */
6673 pVCur->pVtab = pVtab;
6675 /* Initialize vdbe cursor object */
6676 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
6677 if( pCur ){
6678 pCur->uc.pVCur = pVCur;
6679 pVtab->nRef++;
6680 }else{
6681 assert( db->mallocFailed );
6682 pModule->xClose(pVCur);
6683 goto no_mem;
6685 break;
6687 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6689 #ifndef SQLITE_OMIT_VIRTUALTABLE
6690 /* Opcode: VFilter P1 P2 P3 P4 *
6691 ** Synopsis: iplan=r[P3] zplan='P4'
6693 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
6694 ** the filtered result set is empty.
6696 ** P4 is either NULL or a string that was generated by the xBestIndex
6697 ** method of the module. The interpretation of the P4 string is left
6698 ** to the module implementation.
6700 ** This opcode invokes the xFilter method on the virtual table specified
6701 ** by P1. The integer query plan parameter to xFilter is stored in register
6702 ** P3. Register P3+1 stores the argc parameter to be passed to the
6703 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6704 ** additional parameters which are passed to
6705 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6707 ** A jump is made to P2 if the result set after filtering would be empty.
6709 case OP_VFilter: { /* jump */
6710 int nArg;
6711 int iQuery;
6712 const sqlite3_module *pModule;
6713 Mem *pQuery;
6714 Mem *pArgc;
6715 sqlite3_vtab_cursor *pVCur;
6716 sqlite3_vtab *pVtab;
6717 VdbeCursor *pCur;
6718 int res;
6719 int i;
6720 Mem **apArg;
6722 pQuery = &aMem[pOp->p3];
6723 pArgc = &pQuery[1];
6724 pCur = p->apCsr[pOp->p1];
6725 assert( memIsValid(pQuery) );
6726 REGISTER_TRACE(pOp->p3, pQuery);
6727 assert( pCur->eCurType==CURTYPE_VTAB );
6728 pVCur = pCur->uc.pVCur;
6729 pVtab = pVCur->pVtab;
6730 pModule = pVtab->pModule;
6732 /* Grab the index number and argc parameters */
6733 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
6734 nArg = (int)pArgc->u.i;
6735 iQuery = (int)pQuery->u.i;
6737 /* Invoke the xFilter method */
6738 res = 0;
6739 apArg = p->apArg;
6740 for(i = 0; i<nArg; i++){
6741 apArg[i] = &pArgc[i+1];
6743 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
6744 sqlite3VtabImportErrmsg(p, pVtab);
6745 if( rc ) goto abort_due_to_error;
6746 res = pModule->xEof(pVCur);
6747 pCur->nullRow = 0;
6748 VdbeBranchTaken(res!=0,2);
6749 if( res ) goto jump_to_p2;
6750 break;
6752 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6754 #ifndef SQLITE_OMIT_VIRTUALTABLE
6755 /* Opcode: VColumn P1 P2 P3 * P5
6756 ** Synopsis: r[P3]=vcolumn(P2)
6758 ** Store in register P3 the value of the P2-th column of
6759 ** the current row of the virtual-table of cursor P1.
6761 ** If the VColumn opcode is being used to fetch the value of
6762 ** an unchanging column during an UPDATE operation, then the P5
6763 ** value is 1. Otherwise, P5 is 0. The P5 value is returned
6764 ** by sqlite3_vtab_nochange() routine and can be used
6765 ** by virtual table implementations to return special "no-change"
6766 ** marks which can be more efficient, depending on the virtual table.
6768 case OP_VColumn: {
6769 sqlite3_vtab *pVtab;
6770 const sqlite3_module *pModule;
6771 Mem *pDest;
6772 sqlite3_context sContext;
6774 VdbeCursor *pCur = p->apCsr[pOp->p1];
6775 assert( pCur->eCurType==CURTYPE_VTAB );
6776 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6777 pDest = &aMem[pOp->p3];
6778 memAboutToChange(p, pDest);
6779 if( pCur->nullRow ){
6780 sqlite3VdbeMemSetNull(pDest);
6781 break;
6783 pVtab = pCur->uc.pVCur->pVtab;
6784 pModule = pVtab->pModule;
6785 assert( pModule->xColumn );
6786 memset(&sContext, 0, sizeof(sContext));
6787 sContext.pOut = pDest;
6788 if( pOp->p5 ){
6789 sqlite3VdbeMemSetNull(pDest);
6790 pDest->flags = MEM_Null|MEM_Zero;
6791 pDest->u.nZero = 0;
6792 }else{
6793 MemSetTypeFlag(pDest, MEM_Null);
6795 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
6796 sqlite3VtabImportErrmsg(p, pVtab);
6797 if( sContext.isError>0 ){
6798 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
6799 rc = sContext.isError;
6801 sqlite3VdbeChangeEncoding(pDest, encoding);
6802 REGISTER_TRACE(pOp->p3, pDest);
6803 UPDATE_MAX_BLOBSIZE(pDest);
6805 if( sqlite3VdbeMemTooBig(pDest) ){
6806 goto too_big;
6808 if( rc ) goto abort_due_to_error;
6809 break;
6811 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6813 #ifndef SQLITE_OMIT_VIRTUALTABLE
6814 /* Opcode: VNext P1 P2 * * *
6816 ** Advance virtual table P1 to the next row in its result set and
6817 ** jump to instruction P2. Or, if the virtual table has reached
6818 ** the end of its result set, then fall through to the next instruction.
6820 case OP_VNext: { /* jump */
6821 sqlite3_vtab *pVtab;
6822 const sqlite3_module *pModule;
6823 int res;
6824 VdbeCursor *pCur;
6826 res = 0;
6827 pCur = p->apCsr[pOp->p1];
6828 assert( pCur->eCurType==CURTYPE_VTAB );
6829 if( pCur->nullRow ){
6830 break;
6832 pVtab = pCur->uc.pVCur->pVtab;
6833 pModule = pVtab->pModule;
6834 assert( pModule->xNext );
6836 /* Invoke the xNext() method of the module. There is no way for the
6837 ** underlying implementation to return an error if one occurs during
6838 ** xNext(). Instead, if an error occurs, true is returned (indicating that
6839 ** data is available) and the error code returned when xColumn or
6840 ** some other method is next invoked on the save virtual table cursor.
6842 rc = pModule->xNext(pCur->uc.pVCur);
6843 sqlite3VtabImportErrmsg(p, pVtab);
6844 if( rc ) goto abort_due_to_error;
6845 res = pModule->xEof(pCur->uc.pVCur);
6846 VdbeBranchTaken(!res,2);
6847 if( !res ){
6848 /* If there is data, jump to P2 */
6849 goto jump_to_p2_and_check_for_interrupt;
6851 goto check_for_interrupt;
6853 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6855 #ifndef SQLITE_OMIT_VIRTUALTABLE
6856 /* Opcode: VRename P1 * * P4 *
6858 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6859 ** This opcode invokes the corresponding xRename method. The value
6860 ** in register P1 is passed as the zName argument to the xRename method.
6862 case OP_VRename: {
6863 sqlite3_vtab *pVtab;
6864 Mem *pName;
6866 pVtab = pOp->p4.pVtab->pVtab;
6867 pName = &aMem[pOp->p1];
6868 assert( pVtab->pModule->xRename );
6869 assert( memIsValid(pName) );
6870 assert( p->readOnly==0 );
6871 REGISTER_TRACE(pOp->p1, pName);
6872 assert( pName->flags & MEM_Str );
6873 testcase( pName->enc==SQLITE_UTF8 );
6874 testcase( pName->enc==SQLITE_UTF16BE );
6875 testcase( pName->enc==SQLITE_UTF16LE );
6876 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
6877 if( rc ) goto abort_due_to_error;
6878 rc = pVtab->pModule->xRename(pVtab, pName->z);
6879 sqlite3VtabImportErrmsg(p, pVtab);
6880 p->expired = 0;
6881 if( rc ) goto abort_due_to_error;
6882 break;
6884 #endif
6886 #ifndef SQLITE_OMIT_VIRTUALTABLE
6887 /* Opcode: VUpdate P1 P2 P3 P4 P5
6888 ** Synopsis: data=r[P3@P2]
6890 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6891 ** This opcode invokes the corresponding xUpdate method. P2 values
6892 ** are contiguous memory cells starting at P3 to pass to the xUpdate
6893 ** invocation. The value in register (P3+P2-1) corresponds to the
6894 ** p2th element of the argv array passed to xUpdate.
6896 ** The xUpdate method will do a DELETE or an INSERT or both.
6897 ** The argv[0] element (which corresponds to memory cell P3)
6898 ** is the rowid of a row to delete. If argv[0] is NULL then no
6899 ** deletion occurs. The argv[1] element is the rowid of the new
6900 ** row. This can be NULL to have the virtual table select the new
6901 ** rowid for itself. The subsequent elements in the array are
6902 ** the values of columns in the new row.
6904 ** If P2==1 then no insert is performed. argv[0] is the rowid of
6905 ** a row to delete.
6907 ** P1 is a boolean flag. If it is set to true and the xUpdate call
6908 ** is successful, then the value returned by sqlite3_last_insert_rowid()
6909 ** is set to the value of the rowid for the row just inserted.
6911 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
6912 ** apply in the case of a constraint failure on an insert or update.
6914 case OP_VUpdate: {
6915 sqlite3_vtab *pVtab;
6916 const sqlite3_module *pModule;
6917 int nArg;
6918 int i;
6919 sqlite_int64 rowid;
6920 Mem **apArg;
6921 Mem *pX;
6923 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
6924 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
6926 assert( p->readOnly==0 );
6927 sqlite3VdbeIncrWriteCounter(p, 0);
6928 pVtab = pOp->p4.pVtab->pVtab;
6929 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6930 rc = SQLITE_LOCKED;
6931 goto abort_due_to_error;
6933 pModule = pVtab->pModule;
6934 nArg = pOp->p2;
6935 assert( pOp->p4type==P4_VTAB );
6936 if( ALWAYS(pModule->xUpdate) ){
6937 u8 vtabOnConflict = db->vtabOnConflict;
6938 apArg = p->apArg;
6939 pX = &aMem[pOp->p3];
6940 for(i=0; i<nArg; i++){
6941 assert( memIsValid(pX) );
6942 memAboutToChange(p, pX);
6943 apArg[i] = pX;
6944 pX++;
6946 db->vtabOnConflict = pOp->p5;
6947 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
6948 db->vtabOnConflict = vtabOnConflict;
6949 sqlite3VtabImportErrmsg(p, pVtab);
6950 if( rc==SQLITE_OK && pOp->p1 ){
6951 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
6952 db->lastRowid = rowid;
6954 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
6955 if( pOp->p5==OE_Ignore ){
6956 rc = SQLITE_OK;
6957 }else{
6958 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
6960 }else{
6961 p->nChange++;
6963 if( rc ) goto abort_due_to_error;
6965 break;
6967 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6969 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6970 /* Opcode: Pagecount P1 P2 * * *
6972 ** Write the current number of pages in database P1 to memory cell P2.
6974 case OP_Pagecount: { /* out2 */
6975 pOut = out2Prerelease(p, pOp);
6976 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
6977 break;
6979 #endif
6982 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6983 /* Opcode: MaxPgcnt P1 P2 P3 * *
6985 ** Try to set the maximum page count for database P1 to the value in P3.
6986 ** Do not let the maximum page count fall below the current page count and
6987 ** do not change the maximum page count value if P3==0.
6989 ** Store the maximum page count after the change in register P2.
6991 case OP_MaxPgcnt: { /* out2 */
6992 unsigned int newMax;
6993 Btree *pBt;
6995 pOut = out2Prerelease(p, pOp);
6996 pBt = db->aDb[pOp->p1].pBt;
6997 newMax = 0;
6998 if( pOp->p3 ){
6999 newMax = sqlite3BtreeLastPage(pBt);
7000 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
7002 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
7003 break;
7005 #endif
7007 /* Opcode: Function0 P1 P2 P3 P4 P5
7008 ** Synopsis: r[P3]=func(r[P2@P5])
7010 ** Invoke a user function (P4 is a pointer to a FuncDef object that
7011 ** defines the function) with P5 arguments taken from register P2 and
7012 ** successors. The result of the function is stored in register P3.
7013 ** 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 ** See also: Function, AggStep, AggFinal
7024 /* Opcode: Function P1 P2 P3 P4 P5
7025 ** Synopsis: r[P3]=func(r[P2@P5])
7027 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7028 ** contains a pointer to the function to be run) with P5 arguments taken
7029 ** from register P2 and successors. The result of the function is stored
7030 ** in register P3. Register P3 must not be one of the function inputs.
7032 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7033 ** function was determined to be constant at compile time. If the first
7034 ** argument was constant then bit 0 of P1 is set. This is used to determine
7035 ** whether meta data associated with a user function argument using the
7036 ** sqlite3_set_auxdata() API may be safely retained until the next
7037 ** invocation of this opcode.
7039 ** SQL functions are initially coded as OP_Function0 with P4 pointing
7040 ** to a FuncDef object. But on first evaluation, the P4 operand is
7041 ** automatically converted into an sqlite3_context object and the operation
7042 ** changed to this OP_Function opcode. In this way, the initialization of
7043 ** the sqlite3_context object occurs only once, rather than once for each
7044 ** evaluation of the function.
7046 ** See also: Function0, AggStep, AggFinal
7048 case OP_PureFunc0:
7049 case OP_Function0: {
7050 int n;
7051 sqlite3_context *pCtx;
7053 assert( pOp->p4type==P4_FUNCDEF );
7054 n = pOp->p5;
7055 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7056 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7057 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7058 pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
7059 if( pCtx==0 ) goto no_mem;
7060 pCtx->pOut = 0;
7061 pCtx->pFunc = pOp->p4.pFunc;
7062 pCtx->iOp = (int)(pOp - aOp);
7063 pCtx->pVdbe = p;
7064 pCtx->isError = 0;
7065 pCtx->argc = n;
7066 pOp->p4type = P4_FUNCCTX;
7067 pOp->p4.pCtx = pCtx;
7068 assert( OP_PureFunc == OP_PureFunc0+2 );
7069 assert( OP_Function == OP_Function0+2 );
7070 pOp->opcode += 2;
7071 /* Fall through into OP_Function */
7073 case OP_PureFunc:
7074 case OP_Function: {
7075 int i;
7076 sqlite3_context *pCtx;
7078 assert( pOp->p4type==P4_FUNCCTX );
7079 pCtx = pOp->p4.pCtx;
7081 /* If this function is inside of a trigger, the register array in aMem[]
7082 ** might change from one evaluation to the next. The next block of code
7083 ** checks to see if the register array has changed, and if so it
7084 ** reinitializes the relavant parts of the sqlite3_context object */
7085 pOut = &aMem[pOp->p3];
7086 if( pCtx->pOut != pOut ){
7087 pCtx->pOut = pOut;
7088 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7091 memAboutToChange(p, pOut);
7092 #ifdef SQLITE_DEBUG
7093 for(i=0; i<pCtx->argc; i++){
7094 assert( memIsValid(pCtx->argv[i]) );
7095 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7097 #endif
7098 MemSetTypeFlag(pOut, MEM_Null);
7099 assert( pCtx->isError==0 );
7100 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
7102 /* If the function returned an error, throw an exception */
7103 if( pCtx->isError ){
7104 if( pCtx->isError>0 ){
7105 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
7106 rc = pCtx->isError;
7108 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
7109 pCtx->isError = 0;
7110 if( rc ) goto abort_due_to_error;
7113 /* Copy the result of the function into register P3 */
7114 if( pOut->flags & (MEM_Str|MEM_Blob) ){
7115 sqlite3VdbeChangeEncoding(pOut, encoding);
7116 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
7119 REGISTER_TRACE(pOp->p3, pOut);
7120 UPDATE_MAX_BLOBSIZE(pOut);
7121 break;
7124 /* Opcode: Trace P1 P2 * P4 *
7126 ** Write P4 on the statement trace output if statement tracing is
7127 ** enabled.
7129 ** Operand P1 must be 0x7fffffff and P2 must positive.
7131 /* Opcode: Init P1 P2 P3 P4 *
7132 ** Synopsis: Start at P2
7134 ** Programs contain a single instance of this opcode as the very first
7135 ** opcode.
7137 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7138 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7139 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7141 ** If P2 is not zero, jump to instruction P2.
7143 ** Increment the value of P1 so that OP_Once opcodes will jump the
7144 ** first time they are evaluated for this run.
7146 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7147 ** error is encountered.
7149 case OP_Trace:
7150 case OP_Init: { /* jump */
7151 int i;
7152 #ifndef SQLITE_OMIT_TRACE
7153 char *zTrace;
7154 #endif
7156 /* If the P4 argument is not NULL, then it must be an SQL comment string.
7157 ** The "--" string is broken up to prevent false-positives with srcck1.c.
7159 ** This assert() provides evidence for:
7160 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7161 ** would have been returned by the legacy sqlite3_trace() interface by
7162 ** using the X argument when X begins with "--" and invoking
7163 ** sqlite3_expanded_sql(P) otherwise.
7165 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
7167 /* OP_Init is always instruction 0 */
7168 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
7170 #ifndef SQLITE_OMIT_TRACE
7171 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
7172 && !p->doingRerun
7173 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7175 #ifndef SQLITE_OMIT_DEPRECATED
7176 if( db->mTrace & SQLITE_TRACE_LEGACY ){
7177 void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
7178 char *z = sqlite3VdbeExpandSql(p, zTrace);
7179 x(db->pTraceArg, z);
7180 sqlite3_free(z);
7181 }else
7182 #endif
7183 if( db->nVdbeExec>1 ){
7184 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
7185 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
7186 sqlite3DbFree(db, z);
7187 }else{
7188 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
7191 #ifdef SQLITE_USE_FCNTL_TRACE
7192 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
7193 if( zTrace ){
7194 int j;
7195 for(j=0; j<db->nDb; j++){
7196 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
7197 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
7200 #endif /* SQLITE_USE_FCNTL_TRACE */
7201 #ifdef SQLITE_DEBUG
7202 if( (db->flags & SQLITE_SqlTrace)!=0
7203 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7205 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
7207 #endif /* SQLITE_DEBUG */
7208 #endif /* SQLITE_OMIT_TRACE */
7209 assert( pOp->p2>0 );
7210 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
7211 if( pOp->opcode==OP_Trace ) break;
7212 for(i=1; i<p->nOp; i++){
7213 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
7215 pOp->p1 = 0;
7217 pOp->p1++;
7218 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
7219 goto jump_to_p2;
7222 #ifdef SQLITE_ENABLE_CURSOR_HINTS
7223 /* Opcode: CursorHint P1 * * P4 *
7225 ** Provide a hint to cursor P1 that it only needs to return rows that
7226 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
7227 ** to values currently held in registers. TK_COLUMN terms in the P4
7228 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
7230 case OP_CursorHint: {
7231 VdbeCursor *pC;
7233 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7234 assert( pOp->p4type==P4_EXPR );
7235 pC = p->apCsr[pOp->p1];
7236 if( pC ){
7237 assert( pC->eCurType==CURTYPE_BTREE );
7238 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
7239 pOp->p4.pExpr, aMem);
7241 break;
7243 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
7245 #ifdef SQLITE_DEBUG
7246 /* Opcode: Abortable * * * * *
7248 ** Verify that an Abort can happen. Assert if an Abort at this point
7249 ** might cause database corruption. This opcode only appears in debugging
7250 ** builds.
7252 ** An Abort is safe if either there have been no writes, or if there is
7253 ** an active statement journal.
7255 case OP_Abortable: {
7256 sqlite3VdbeAssertAbortable(p);
7257 break;
7259 #endif
7261 /* Opcode: Noop * * * * *
7263 ** Do nothing. This instruction is often useful as a jump
7264 ** destination.
7267 ** The magic Explain opcode are only inserted when explain==2 (which
7268 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
7269 ** This opcode records information from the optimizer. It is the
7270 ** the same as a no-op. This opcodesnever appears in a real VM program.
7272 default: { /* This is really OP_Noop, OP_Explain */
7273 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
7275 break;
7278 /*****************************************************************************
7279 ** The cases of the switch statement above this line should all be indented
7280 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
7281 ** readability. From this point on down, the normal indentation rules are
7282 ** restored.
7283 *****************************************************************************/
7286 #ifdef VDBE_PROFILE
7288 u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
7289 if( endTime>start ) pOrigOp->cycles += endTime - start;
7290 pOrigOp->cnt++;
7292 #endif
7294 /* The following code adds nothing to the actual functionality
7295 ** of the program. It is only here for testing and debugging.
7296 ** On the other hand, it does burn CPU cycles every time through
7297 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
7299 #ifndef NDEBUG
7300 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
7302 #ifdef SQLITE_DEBUG
7303 if( db->flags & SQLITE_VdbeTrace ){
7304 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
7305 if( rc!=0 ) printf("rc=%d\n",rc);
7306 if( opProperty & (OPFLG_OUT2) ){
7307 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
7309 if( opProperty & OPFLG_OUT3 ){
7310 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
7313 #endif /* SQLITE_DEBUG */
7314 #endif /* NDEBUG */
7315 } /* The end of the for(;;) loop the loops through opcodes */
7317 /* If we reach this point, it means that execution is finished with
7318 ** an error of some kind.
7320 abort_due_to_error:
7321 if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
7322 assert( rc );
7323 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
7324 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7326 p->rc = rc;
7327 sqlite3SystemError(db, rc);
7328 testcase( sqlite3GlobalConfig.xLog!=0 );
7329 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
7330 (int)(pOp - aOp), p->zSql, p->zErrMsg);
7331 sqlite3VdbeHalt(p);
7332 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
7333 rc = SQLITE_ERROR;
7334 if( resetSchemaOnFault>0 ){
7335 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
7338 /* This is the only way out of this procedure. We have to
7339 ** release the mutexes on btrees that were acquired at the
7340 ** top. */
7341 vdbe_return:
7342 testcase( nVmStep>0 );
7343 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
7344 sqlite3VdbeLeave(p);
7345 assert( rc!=SQLITE_OK || nExtraDelete==0
7346 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
7348 return rc;
7350 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
7351 ** is encountered.
7353 too_big:
7354 sqlite3VdbeError(p, "string or blob too big");
7355 rc = SQLITE_TOOBIG;
7356 goto abort_due_to_error;
7358 /* Jump to here if a malloc() fails.
7360 no_mem:
7361 sqlite3OomFault(db);
7362 sqlite3VdbeError(p, "out of memory");
7363 rc = SQLITE_NOMEM_BKPT;
7364 goto abort_due_to_error;
7366 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
7367 ** flag.
7369 abort_due_to_interrupt:
7370 assert( db->u1.isInterrupted );
7371 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
7372 p->rc = rc;
7373 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7374 goto abort_due_to_error;