Prevent a harmless unused variable warning when compiling with
[sqlite.git] / src / vdbe.c
blob81a2361a55b612c0c831d166b67f5430bfcf3198
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);
270 ** Processing is determine by the affinity parameter:
272 ** SQLITE_AFF_INTEGER:
273 ** SQLITE_AFF_REAL:
274 ** SQLITE_AFF_NUMERIC:
275 ** Try to convert pRec to an integer representation or a
276 ** floating-point representation if an integer representation
277 ** is not possible. Note that the integer representation is
278 ** always preferred, even if the affinity is REAL, because
279 ** an integer representation is more space efficient on disk.
281 ** SQLITE_AFF_TEXT:
282 ** Convert pRec to a text representation.
284 ** SQLITE_AFF_BLOB:
285 ** No-op. pRec is unchanged.
287 static void applyAffinity(
288 Mem *pRec, /* The value to apply affinity to */
289 char affinity, /* The affinity to be applied */
290 u8 enc /* Use this text encoding */
292 if( affinity>=SQLITE_AFF_NUMERIC ){
293 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
294 || affinity==SQLITE_AFF_NUMERIC );
295 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
296 if( (pRec->flags & MEM_Real)==0 ){
297 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
298 }else{
299 sqlite3VdbeIntegerAffinity(pRec);
302 }else if( affinity==SQLITE_AFF_TEXT ){
303 /* Only attempt the conversion to TEXT if there is an integer or real
304 ** representation (blob and NULL do not get converted) but no string
305 ** representation. It would be harmless to repeat the conversion if
306 ** there is already a string rep, but it is pointless to waste those
307 ** CPU cycles. */
308 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
309 if( (pRec->flags&(MEM_Real|MEM_Int)) ){
310 sqlite3VdbeMemStringify(pRec, enc, 1);
313 pRec->flags &= ~(MEM_Real|MEM_Int);
318 ** Try to convert the type of a function argument or a result column
319 ** into a numeric representation. Use either INTEGER or REAL whichever
320 ** is appropriate. But only do the conversion if it is possible without
321 ** loss of information and return the revised type of the argument.
323 int sqlite3_value_numeric_type(sqlite3_value *pVal){
324 int eType = sqlite3_value_type(pVal);
325 if( eType==SQLITE_TEXT ){
326 Mem *pMem = (Mem*)pVal;
327 applyNumericAffinity(pMem, 0);
328 eType = sqlite3_value_type(pVal);
330 return eType;
334 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
335 ** not the internal Mem* type.
337 void sqlite3ValueApplyAffinity(
338 sqlite3_value *pVal,
339 u8 affinity,
340 u8 enc
342 applyAffinity((Mem *)pVal, affinity, enc);
346 ** pMem currently only holds a string type (or maybe a BLOB that we can
347 ** interpret as a string if we want to). Compute its corresponding
348 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
349 ** accordingly.
351 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
352 assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
353 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
354 if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
355 return 0;
357 if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
358 return MEM_Int;
360 return MEM_Real;
364 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
365 ** none.
367 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
368 ** But it does set pMem->u.r and pMem->u.i appropriately.
370 static u16 numericType(Mem *pMem){
371 if( pMem->flags & (MEM_Int|MEM_Real) ){
372 return pMem->flags & (MEM_Int|MEM_Real);
374 if( pMem->flags & (MEM_Str|MEM_Blob) ){
375 return computeNumericType(pMem);
377 return 0;
380 #ifdef SQLITE_DEBUG
382 ** Write a nice string representation of the contents of cell pMem
383 ** into buffer zBuf, length nBuf.
385 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
386 char *zCsr = zBuf;
387 int f = pMem->flags;
389 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
391 if( f&MEM_Blob ){
392 int i;
393 char c;
394 if( f & MEM_Dyn ){
395 c = 'z';
396 assert( (f & (MEM_Static|MEM_Ephem))==0 );
397 }else if( f & MEM_Static ){
398 c = 't';
399 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
400 }else if( f & MEM_Ephem ){
401 c = 'e';
402 assert( (f & (MEM_Static|MEM_Dyn))==0 );
403 }else{
404 c = 's';
406 *(zCsr++) = c;
407 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
408 zCsr += sqlite3Strlen30(zCsr);
409 for(i=0; i<16 && i<pMem->n; i++){
410 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
411 zCsr += sqlite3Strlen30(zCsr);
413 for(i=0; i<16 && i<pMem->n; i++){
414 char z = pMem->z[i];
415 if( z<32 || z>126 ) *zCsr++ = '.';
416 else *zCsr++ = z;
418 *(zCsr++) = ']';
419 if( f & MEM_Zero ){
420 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
421 zCsr += sqlite3Strlen30(zCsr);
423 *zCsr = '\0';
424 }else if( f & MEM_Str ){
425 int j, k;
426 zBuf[0] = ' ';
427 if( f & MEM_Dyn ){
428 zBuf[1] = 'z';
429 assert( (f & (MEM_Static|MEM_Ephem))==0 );
430 }else if( f & MEM_Static ){
431 zBuf[1] = 't';
432 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
433 }else if( f & MEM_Ephem ){
434 zBuf[1] = 'e';
435 assert( (f & (MEM_Static|MEM_Dyn))==0 );
436 }else{
437 zBuf[1] = 's';
439 k = 2;
440 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
441 k += sqlite3Strlen30(&zBuf[k]);
442 zBuf[k++] = '[';
443 for(j=0; j<15 && j<pMem->n; j++){
444 u8 c = pMem->z[j];
445 if( c>=0x20 && c<0x7f ){
446 zBuf[k++] = c;
447 }else{
448 zBuf[k++] = '.';
451 zBuf[k++] = ']';
452 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
453 k += sqlite3Strlen30(&zBuf[k]);
454 zBuf[k++] = 0;
457 #endif
459 #ifdef SQLITE_DEBUG
461 ** Print the value of a register for tracing purposes:
463 static void memTracePrint(Mem *p){
464 if( p->flags & MEM_Undefined ){
465 printf(" undefined");
466 }else if( p->flags & MEM_Null ){
467 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
468 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
469 printf(" si:%lld", p->u.i);
470 }else if( p->flags & MEM_Int ){
471 printf(" i:%lld", p->u.i);
472 #ifndef SQLITE_OMIT_FLOATING_POINT
473 }else if( p->flags & MEM_Real ){
474 printf(" r:%g", p->u.r);
475 #endif
476 }else if( p->flags & MEM_RowSet ){
477 printf(" (rowset)");
478 }else{
479 char zBuf[200];
480 sqlite3VdbeMemPrettyPrint(p, zBuf);
481 printf(" %s", zBuf);
483 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
485 static void registerTrace(int iReg, Mem *p){
486 printf("REG[%d] = ", iReg);
487 memTracePrint(p);
488 printf("\n");
489 sqlite3VdbeCheckMemInvariants(p);
491 #endif
493 #ifdef SQLITE_DEBUG
494 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
495 #else
496 # define REGISTER_TRACE(R,M)
497 #endif
500 #ifdef VDBE_PROFILE
503 ** hwtime.h contains inline assembler code for implementing
504 ** high-performance timing routines.
506 #include "hwtime.h"
508 #endif
510 #ifndef NDEBUG
512 ** This function is only called from within an assert() expression. It
513 ** checks that the sqlite3.nTransaction variable is correctly set to
514 ** the number of non-transaction savepoints currently in the
515 ** linked list starting at sqlite3.pSavepoint.
517 ** Usage:
519 ** assert( checkSavepointCount(db) );
521 static int checkSavepointCount(sqlite3 *db){
522 int n = 0;
523 Savepoint *p;
524 for(p=db->pSavepoint; p; p=p->pNext) n++;
525 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
526 return 1;
528 #endif
531 ** Return the register of pOp->p2 after first preparing it to be
532 ** overwritten with an integer value.
534 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
535 sqlite3VdbeMemSetNull(pOut);
536 pOut->flags = MEM_Int;
537 return pOut;
539 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
540 Mem *pOut;
541 assert( pOp->p2>0 );
542 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
543 pOut = &p->aMem[pOp->p2];
544 memAboutToChange(p, pOut);
545 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
546 return out2PrereleaseWithClear(pOut);
547 }else{
548 pOut->flags = MEM_Int;
549 return pOut;
555 ** Execute as much of a VDBE program as we can.
556 ** This is the core of sqlite3_step().
558 int sqlite3VdbeExec(
559 Vdbe *p /* The VDBE */
561 Op *aOp = p->aOp; /* Copy of p->aOp */
562 Op *pOp = aOp; /* Current operation */
563 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
564 Op *pOrigOp; /* Value of pOp at the top of the loop */
565 #endif
566 #ifdef SQLITE_DEBUG
567 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
568 #endif
569 int rc = SQLITE_OK; /* Value to return */
570 sqlite3 *db = p->db; /* The database */
571 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
572 u8 encoding = ENC(db); /* The database encoding */
573 int iCompare = 0; /* Result of last comparison */
574 unsigned nVmStep = 0; /* Number of virtual machine steps */
575 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
576 unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
577 #endif
578 Mem *aMem = p->aMem; /* Copy of p->aMem */
579 Mem *pIn1 = 0; /* 1st input operand */
580 Mem *pIn2 = 0; /* 2nd input operand */
581 Mem *pIn3 = 0; /* 3rd input operand */
582 Mem *pOut = 0; /* Output operand */
583 #ifdef VDBE_PROFILE
584 u64 start; /* CPU clock count at start of opcode */
585 #endif
586 /*** INSERT STACK UNION HERE ***/
588 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
589 sqlite3VdbeEnter(p);
590 if( p->rc==SQLITE_NOMEM ){
591 /* This happens if a malloc() inside a call to sqlite3_column_text() or
592 ** sqlite3_column_text16() failed. */
593 goto no_mem;
595 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
596 assert( p->bIsReader || p->readOnly!=0 );
597 p->iCurrentTime = 0;
598 assert( p->explain==0 );
599 p->pResultSet = 0;
600 db->busyHandler.nBusy = 0;
601 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
602 sqlite3VdbeIOTraceSql(p);
603 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
604 if( db->xProgress ){
605 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
606 assert( 0 < db->nProgressOps );
607 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
608 }else{
609 nProgressLimit = 0xffffffff;
611 #endif
612 #ifdef SQLITE_DEBUG
613 sqlite3BeginBenignMalloc();
614 if( p->pc==0
615 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
617 int i;
618 int once = 1;
619 sqlite3VdbePrintSql(p);
620 if( p->db->flags & SQLITE_VdbeListing ){
621 printf("VDBE Program Listing:\n");
622 for(i=0; i<p->nOp; i++){
623 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
626 if( p->db->flags & SQLITE_VdbeEQP ){
627 for(i=0; i<p->nOp; i++){
628 if( aOp[i].opcode==OP_Explain ){
629 if( once ) printf("VDBE Query Plan:\n");
630 printf("%s\n", aOp[i].p4.z);
631 once = 0;
635 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
637 sqlite3EndBenignMalloc();
638 #endif
639 for(pOp=&aOp[p->pc]; 1; pOp++){
640 /* Errors are detected by individual opcodes, with an immediate
641 ** jumps to abort_due_to_error. */
642 assert( rc==SQLITE_OK );
644 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
645 #ifdef VDBE_PROFILE
646 start = sqlite3Hwtime();
647 #endif
648 nVmStep++;
649 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
650 if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
651 #endif
653 /* Only allow tracing if SQLITE_DEBUG is defined.
655 #ifdef SQLITE_DEBUG
656 if( db->flags & SQLITE_VdbeTrace ){
657 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
659 #endif
662 /* Check to see if we need to simulate an interrupt. This only happens
663 ** if we have a special test build.
665 #ifdef SQLITE_TEST
666 if( sqlite3_interrupt_count>0 ){
667 sqlite3_interrupt_count--;
668 if( sqlite3_interrupt_count==0 ){
669 sqlite3_interrupt(db);
672 #endif
674 /* Sanity checking on other operands */
675 #ifdef SQLITE_DEBUG
677 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
678 if( (opProperty & OPFLG_IN1)!=0 ){
679 assert( pOp->p1>0 );
680 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
681 assert( memIsValid(&aMem[pOp->p1]) );
682 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
683 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
685 if( (opProperty & OPFLG_IN2)!=0 ){
686 assert( pOp->p2>0 );
687 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
688 assert( memIsValid(&aMem[pOp->p2]) );
689 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
690 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
692 if( (opProperty & OPFLG_IN3)!=0 ){
693 assert( pOp->p3>0 );
694 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
695 assert( memIsValid(&aMem[pOp->p3]) );
696 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
697 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
699 if( (opProperty & OPFLG_OUT2)!=0 ){
700 assert( pOp->p2>0 );
701 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
702 memAboutToChange(p, &aMem[pOp->p2]);
704 if( (opProperty & OPFLG_OUT3)!=0 ){
705 assert( pOp->p3>0 );
706 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
707 memAboutToChange(p, &aMem[pOp->p3]);
710 #endif
711 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
712 pOrigOp = pOp;
713 #endif
715 switch( pOp->opcode ){
717 /*****************************************************************************
718 ** What follows is a massive switch statement where each case implements a
719 ** separate instruction in the virtual machine. If we follow the usual
720 ** indentation conventions, each case should be indented by 6 spaces. But
721 ** that is a lot of wasted space on the left margin. So the code within
722 ** the switch statement will break with convention and be flush-left. Another
723 ** big comment (similar to this one) will mark the point in the code where
724 ** we transition back to normal indentation.
726 ** The formatting of each case is important. The makefile for SQLite
727 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
728 ** file looking for lines that begin with "case OP_". The opcodes.h files
729 ** will be filled with #defines that give unique integer values to each
730 ** opcode and the opcodes.c file is filled with an array of strings where
731 ** each string is the symbolic name for the corresponding opcode. If the
732 ** case statement is followed by a comment of the form "/# same as ... #/"
733 ** that comment is used to determine the particular value of the opcode.
735 ** Other keywords in the comment that follows each case are used to
736 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
737 ** Keywords include: in1, in2, in3, out2, out3. See
738 ** the mkopcodeh.awk script for additional information.
740 ** Documentation about VDBE opcodes is generated by scanning this file
741 ** for lines of that contain "Opcode:". That line and all subsequent
742 ** comment lines are used in the generation of the opcode.html documentation
743 ** file.
745 ** SUMMARY:
747 ** Formatting is important to scripts that scan this file.
748 ** Do not deviate from the formatting style currently in use.
750 *****************************************************************************/
752 /* Opcode: Goto * P2 * * *
754 ** An unconditional jump to address P2.
755 ** The next instruction executed will be
756 ** the one at index P2 from the beginning of
757 ** the program.
759 ** The P1 parameter is not actually used by this opcode. However, it
760 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
761 ** that this Goto is the bottom of a loop and that the lines from P2 down
762 ** to the current line should be indented for EXPLAIN output.
764 case OP_Goto: { /* jump */
765 jump_to_p2_and_check_for_interrupt:
766 pOp = &aOp[pOp->p2 - 1];
768 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
769 ** OP_VNext, or OP_SorterNext) all jump here upon
770 ** completion. Check to see if sqlite3_interrupt() has been called
771 ** or if the progress callback needs to be invoked.
773 ** This code uses unstructured "goto" statements and does not look clean.
774 ** But that is not due to sloppy coding habits. The code is written this
775 ** way for performance, to avoid having to run the interrupt and progress
776 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
777 ** faster according to "valgrind --tool=cachegrind" */
778 check_for_interrupt:
779 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
780 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
781 /* Call the progress callback if it is configured and the required number
782 ** of VDBE ops have been executed (either since this invocation of
783 ** sqlite3VdbeExec() or since last time the progress callback was called).
784 ** If the progress callback returns non-zero, exit the virtual machine with
785 ** a return code SQLITE_ABORT.
787 if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
788 assert( db->nProgressOps!=0 );
789 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
790 if( db->xProgress(db->pProgressArg) ){
791 rc = SQLITE_INTERRUPT;
792 goto abort_due_to_error;
795 #endif
797 break;
800 /* Opcode: Gosub P1 P2 * * *
802 ** Write the current address onto register P1
803 ** and then jump to address P2.
805 case OP_Gosub: { /* jump */
806 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
807 pIn1 = &aMem[pOp->p1];
808 assert( VdbeMemDynamic(pIn1)==0 );
809 memAboutToChange(p, pIn1);
810 pIn1->flags = MEM_Int;
811 pIn1->u.i = (int)(pOp-aOp);
812 REGISTER_TRACE(pOp->p1, pIn1);
814 /* Most jump operations do a goto to this spot in order to update
815 ** the pOp pointer. */
816 jump_to_p2:
817 pOp = &aOp[pOp->p2 - 1];
818 break;
821 /* Opcode: Return P1 * * * *
823 ** Jump to the next instruction after the address in register P1. After
824 ** the jump, register P1 becomes undefined.
826 case OP_Return: { /* in1 */
827 pIn1 = &aMem[pOp->p1];
828 assert( pIn1->flags==MEM_Int );
829 pOp = &aOp[pIn1->u.i];
830 pIn1->flags = MEM_Undefined;
831 break;
834 /* Opcode: InitCoroutine P1 P2 P3 * *
836 ** Set up register P1 so that it will Yield to the coroutine
837 ** located at address P3.
839 ** If P2!=0 then the coroutine implementation immediately follows
840 ** this opcode. So jump over the coroutine implementation to
841 ** address P2.
843 ** See also: EndCoroutine
845 case OP_InitCoroutine: { /* jump */
846 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
847 assert( pOp->p2>=0 && pOp->p2<p->nOp );
848 assert( pOp->p3>=0 && pOp->p3<p->nOp );
849 pOut = &aMem[pOp->p1];
850 assert( !VdbeMemDynamic(pOut) );
851 pOut->u.i = pOp->p3 - 1;
852 pOut->flags = MEM_Int;
853 if( pOp->p2 ) goto jump_to_p2;
854 break;
857 /* Opcode: EndCoroutine P1 * * * *
859 ** The instruction at the address in register P1 is a Yield.
860 ** Jump to the P2 parameter of that Yield.
861 ** After the jump, register P1 becomes undefined.
863 ** See also: InitCoroutine
865 case OP_EndCoroutine: { /* in1 */
866 VdbeOp *pCaller;
867 pIn1 = &aMem[pOp->p1];
868 assert( pIn1->flags==MEM_Int );
869 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
870 pCaller = &aOp[pIn1->u.i];
871 assert( pCaller->opcode==OP_Yield );
872 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
873 pOp = &aOp[pCaller->p2 - 1];
874 pIn1->flags = MEM_Undefined;
875 break;
878 /* Opcode: Yield P1 P2 * * *
880 ** Swap the program counter with the value in register P1. This
881 ** has the effect of yielding to a coroutine.
883 ** If the coroutine that is launched by this instruction ends with
884 ** Yield or Return then continue to the next instruction. But if
885 ** the coroutine launched by this instruction ends with
886 ** EndCoroutine, then jump to P2 rather than continuing with the
887 ** next instruction.
889 ** See also: InitCoroutine
891 case OP_Yield: { /* in1, jump */
892 int pcDest;
893 pIn1 = &aMem[pOp->p1];
894 assert( VdbeMemDynamic(pIn1)==0 );
895 pIn1->flags = MEM_Int;
896 pcDest = (int)pIn1->u.i;
897 pIn1->u.i = (int)(pOp - aOp);
898 REGISTER_TRACE(pOp->p1, pIn1);
899 pOp = &aOp[pcDest];
900 break;
903 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
904 ** Synopsis: if r[P3]=null halt
906 ** Check the value in register P3. If it is NULL then Halt using
907 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
908 ** value in register P3 is not NULL, then this routine is a no-op.
909 ** The P5 parameter should be 1.
911 case OP_HaltIfNull: { /* in3 */
912 pIn3 = &aMem[pOp->p3];
913 if( (pIn3->flags & MEM_Null)==0 ) break;
914 /* Fall through into OP_Halt */
917 /* Opcode: Halt P1 P2 * P4 P5
919 ** Exit immediately. All open cursors, etc are closed
920 ** automatically.
922 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
923 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
924 ** For errors, it can be some other value. If P1!=0 then P2 will determine
925 ** whether or not to rollback the current transaction. Do not rollback
926 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
927 ** then back out all changes that have occurred during this execution of the
928 ** VDBE, but do not rollback the transaction.
930 ** If P4 is not null then it is an error message string.
932 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
934 ** 0: (no change)
935 ** 1: NOT NULL contraint failed: P4
936 ** 2: UNIQUE constraint failed: P4
937 ** 3: CHECK constraint failed: P4
938 ** 4: FOREIGN KEY constraint failed: P4
940 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
941 ** omitted.
943 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
944 ** every program. So a jump past the last instruction of the program
945 ** is the same as executing Halt.
947 case OP_Halt: {
948 VdbeFrame *pFrame;
949 int pcx;
951 pcx = (int)(pOp - aOp);
952 if( pOp->p1==SQLITE_OK && p->pFrame ){
953 /* Halt the sub-program. Return control to the parent frame. */
954 pFrame = p->pFrame;
955 p->pFrame = pFrame->pParent;
956 p->nFrame--;
957 sqlite3VdbeSetChanges(db, p->nChange);
958 pcx = sqlite3VdbeFrameRestore(pFrame);
959 if( pOp->p2==OE_Ignore ){
960 /* Instruction pcx is the OP_Program that invoked the sub-program
961 ** currently being halted. If the p2 instruction of this OP_Halt
962 ** instruction is set to OE_Ignore, then the sub-program is throwing
963 ** an IGNORE exception. In this case jump to the address specified
964 ** as the p2 of the calling OP_Program. */
965 pcx = p->aOp[pcx].p2-1;
967 aOp = p->aOp;
968 aMem = p->aMem;
969 pOp = &aOp[pcx];
970 break;
972 p->rc = pOp->p1;
973 p->errorAction = (u8)pOp->p2;
974 p->pc = pcx;
975 assert( pOp->p5<=4 );
976 if( p->rc ){
977 if( pOp->p5 ){
978 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
979 "FOREIGN KEY" };
980 testcase( pOp->p5==1 );
981 testcase( pOp->p5==2 );
982 testcase( pOp->p5==3 );
983 testcase( pOp->p5==4 );
984 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
985 if( pOp->p4.z ){
986 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
988 }else{
989 sqlite3VdbeError(p, "%s", pOp->p4.z);
991 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
993 rc = sqlite3VdbeHalt(p);
994 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
995 if( rc==SQLITE_BUSY ){
996 p->rc = SQLITE_BUSY;
997 }else{
998 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
999 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1000 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1002 goto vdbe_return;
1005 /* Opcode: Integer P1 P2 * * *
1006 ** Synopsis: r[P2]=P1
1008 ** The 32-bit integer value P1 is written into register P2.
1010 case OP_Integer: { /* out2 */
1011 pOut = out2Prerelease(p, pOp);
1012 pOut->u.i = pOp->p1;
1013 break;
1016 /* Opcode: Int64 * P2 * P4 *
1017 ** Synopsis: r[P2]=P4
1019 ** P4 is a pointer to a 64-bit integer value.
1020 ** Write that value into register P2.
1022 case OP_Int64: { /* out2 */
1023 pOut = out2Prerelease(p, pOp);
1024 assert( pOp->p4.pI64!=0 );
1025 pOut->u.i = *pOp->p4.pI64;
1026 break;
1029 #ifndef SQLITE_OMIT_FLOATING_POINT
1030 /* Opcode: Real * P2 * P4 *
1031 ** Synopsis: r[P2]=P4
1033 ** P4 is a pointer to a 64-bit floating point value.
1034 ** Write that value into register P2.
1036 case OP_Real: { /* same as TK_FLOAT, out2 */
1037 pOut = out2Prerelease(p, pOp);
1038 pOut->flags = MEM_Real;
1039 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1040 pOut->u.r = *pOp->p4.pReal;
1041 break;
1043 #endif
1045 /* Opcode: String8 * P2 * P4 *
1046 ** Synopsis: r[P2]='P4'
1048 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1049 ** into a String opcode before it is executed for the first time. During
1050 ** this transformation, the length of string P4 is computed and stored
1051 ** as the P1 parameter.
1053 case OP_String8: { /* same as TK_STRING, out2 */
1054 assert( pOp->p4.z!=0 );
1055 pOut = out2Prerelease(p, pOp);
1056 pOp->opcode = OP_String;
1057 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1059 #ifndef SQLITE_OMIT_UTF16
1060 if( encoding!=SQLITE_UTF8 ){
1061 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1062 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1063 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1064 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1065 assert( VdbeMemDynamic(pOut)==0 );
1066 pOut->szMalloc = 0;
1067 pOut->flags |= MEM_Static;
1068 if( pOp->p4type==P4_DYNAMIC ){
1069 sqlite3DbFree(db, pOp->p4.z);
1071 pOp->p4type = P4_DYNAMIC;
1072 pOp->p4.z = pOut->z;
1073 pOp->p1 = pOut->n;
1075 testcase( rc==SQLITE_TOOBIG );
1076 #endif
1077 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1078 goto too_big;
1080 assert( rc==SQLITE_OK );
1081 /* Fall through to the next case, OP_String */
1084 /* Opcode: String P1 P2 P3 P4 P5
1085 ** Synopsis: r[P2]='P4' (len=P1)
1087 ** The string value P4 of length P1 (bytes) is stored in register P2.
1089 ** If P3 is not zero and the content of register P3 is equal to P5, then
1090 ** the datatype of the register P2 is converted to BLOB. The content is
1091 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1092 ** of a string, as if it had been CAST. In other words:
1094 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1096 case OP_String: { /* out2 */
1097 assert( pOp->p4.z!=0 );
1098 pOut = out2Prerelease(p, pOp);
1099 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1100 pOut->z = pOp->p4.z;
1101 pOut->n = pOp->p1;
1102 pOut->enc = encoding;
1103 UPDATE_MAX_BLOBSIZE(pOut);
1104 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1105 if( pOp->p3>0 ){
1106 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1107 pIn3 = &aMem[pOp->p3];
1108 assert( pIn3->flags & MEM_Int );
1109 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1111 #endif
1112 break;
1115 /* Opcode: Null P1 P2 P3 * *
1116 ** Synopsis: r[P2..P3]=NULL
1118 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1119 ** NULL into register P3 and every register in between P2 and P3. If P3
1120 ** is less than P2 (typically P3 is zero) then only register P2 is
1121 ** set to NULL.
1123 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1124 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1125 ** OP_Ne or OP_Eq.
1127 case OP_Null: { /* out2 */
1128 int cnt;
1129 u16 nullFlag;
1130 pOut = out2Prerelease(p, pOp);
1131 cnt = pOp->p3-pOp->p2;
1132 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1133 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1134 pOut->n = 0;
1135 while( cnt>0 ){
1136 pOut++;
1137 memAboutToChange(p, pOut);
1138 sqlite3VdbeMemSetNull(pOut);
1139 pOut->flags = nullFlag;
1140 pOut->n = 0;
1141 cnt--;
1143 break;
1146 /* Opcode: SoftNull P1 * * * *
1147 ** Synopsis: r[P1]=NULL
1149 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1150 ** instruction, but do not free any string or blob memory associated with
1151 ** the register, so that if the value was a string or blob that was
1152 ** previously copied using OP_SCopy, the copies will continue to be valid.
1154 case OP_SoftNull: {
1155 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1156 pOut = &aMem[pOp->p1];
1157 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1158 break;
1161 /* Opcode: Blob P1 P2 * P4 *
1162 ** Synopsis: r[P2]=P4 (len=P1)
1164 ** P4 points to a blob of data P1 bytes long. Store this
1165 ** blob in register P2.
1167 case OP_Blob: { /* out2 */
1168 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1169 pOut = out2Prerelease(p, pOp);
1170 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1171 pOut->enc = encoding;
1172 UPDATE_MAX_BLOBSIZE(pOut);
1173 break;
1176 /* Opcode: Variable P1 P2 * P4 *
1177 ** Synopsis: r[P2]=parameter(P1,P4)
1179 ** Transfer the values of bound parameter P1 into register P2
1181 ** If the parameter is named, then its name appears in P4.
1182 ** The P4 value is used by sqlite3_bind_parameter_name().
1184 case OP_Variable: { /* out2 */
1185 Mem *pVar; /* Value being transferred */
1187 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1188 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1189 pVar = &p->aVar[pOp->p1 - 1];
1190 if( sqlite3VdbeMemTooBig(pVar) ){
1191 goto too_big;
1193 pOut = &aMem[pOp->p2];
1194 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
1195 UPDATE_MAX_BLOBSIZE(pOut);
1196 break;
1199 /* Opcode: Move P1 P2 P3 * *
1200 ** Synopsis: r[P2@P3]=r[P1@P3]
1202 ** Move the P3 values in register P1..P1+P3-1 over into
1203 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1204 ** left holding a NULL. It is an error for register ranges
1205 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1206 ** for P3 to be less than 1.
1208 case OP_Move: {
1209 int n; /* Number of registers left to copy */
1210 int p1; /* Register to copy from */
1211 int p2; /* Register to copy to */
1213 n = pOp->p3;
1214 p1 = pOp->p1;
1215 p2 = pOp->p2;
1216 assert( n>0 && p1>0 && p2>0 );
1217 assert( p1+n<=p2 || p2+n<=p1 );
1219 pIn1 = &aMem[p1];
1220 pOut = &aMem[p2];
1222 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1223 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1224 assert( memIsValid(pIn1) );
1225 memAboutToChange(p, pOut);
1226 sqlite3VdbeMemMove(pOut, pIn1);
1227 #ifdef SQLITE_DEBUG
1228 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
1229 pOut->pScopyFrom += pOp->p2 - p1;
1231 #endif
1232 Deephemeralize(pOut);
1233 REGISTER_TRACE(p2++, pOut);
1234 pIn1++;
1235 pOut++;
1236 }while( --n );
1237 break;
1240 /* Opcode: Copy P1 P2 P3 * *
1241 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1243 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1245 ** This instruction makes a deep copy of the value. A duplicate
1246 ** is made of any string or blob constant. See also OP_SCopy.
1248 case OP_Copy: {
1249 int n;
1251 n = pOp->p3;
1252 pIn1 = &aMem[pOp->p1];
1253 pOut = &aMem[pOp->p2];
1254 assert( pOut!=pIn1 );
1255 while( 1 ){
1256 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1257 Deephemeralize(pOut);
1258 #ifdef SQLITE_DEBUG
1259 pOut->pScopyFrom = 0;
1260 #endif
1261 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1262 if( (n--)==0 ) break;
1263 pOut++;
1264 pIn1++;
1266 break;
1269 /* Opcode: SCopy P1 P2 * * *
1270 ** Synopsis: r[P2]=r[P1]
1272 ** Make a shallow copy of register P1 into register P2.
1274 ** This instruction makes a shallow copy of the value. If the value
1275 ** is a string or blob, then the copy is only a pointer to the
1276 ** original and hence if the original changes so will the copy.
1277 ** Worse, if the original is deallocated, the copy becomes invalid.
1278 ** Thus the program must guarantee that the original will not change
1279 ** during the lifetime of the copy. Use OP_Copy to make a complete
1280 ** copy.
1282 case OP_SCopy: { /* out2 */
1283 pIn1 = &aMem[pOp->p1];
1284 pOut = &aMem[pOp->p2];
1285 assert( pOut!=pIn1 );
1286 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1287 #ifdef SQLITE_DEBUG
1288 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
1289 #endif
1290 break;
1293 /* Opcode: IntCopy P1 P2 * * *
1294 ** Synopsis: r[P2]=r[P1]
1296 ** Transfer the integer value held in register P1 into register P2.
1298 ** This is an optimized version of SCopy that works only for integer
1299 ** values.
1301 case OP_IntCopy: { /* out2 */
1302 pIn1 = &aMem[pOp->p1];
1303 assert( (pIn1->flags & MEM_Int)!=0 );
1304 pOut = &aMem[pOp->p2];
1305 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1306 break;
1309 /* Opcode: ResultRow P1 P2 * * *
1310 ** Synopsis: output=r[P1@P2]
1312 ** The registers P1 through P1+P2-1 contain a single row of
1313 ** results. This opcode causes the sqlite3_step() call to terminate
1314 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1315 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1316 ** the result row.
1318 case OP_ResultRow: {
1319 Mem *pMem;
1320 int i;
1321 assert( p->nResColumn==pOp->p2 );
1322 assert( pOp->p1>0 );
1323 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1325 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1326 /* Run the progress counter just before returning.
1328 if( db->xProgress!=0
1329 && nVmStep>=nProgressLimit
1330 && db->xProgress(db->pProgressArg)!=0
1332 rc = SQLITE_INTERRUPT;
1333 goto abort_due_to_error;
1335 #endif
1337 /* If this statement has violated immediate foreign key constraints, do
1338 ** not return the number of rows modified. And do not RELEASE the statement
1339 ** transaction. It needs to be rolled back. */
1340 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
1341 assert( db->flags&SQLITE_CountRows );
1342 assert( p->usesStmtJournal );
1343 goto abort_due_to_error;
1346 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1347 ** DML statements invoke this opcode to return the number of rows
1348 ** modified to the user. This is the only way that a VM that
1349 ** opens a statement transaction may invoke this opcode.
1351 ** In case this is such a statement, close any statement transaction
1352 ** opened by this VM before returning control to the user. This is to
1353 ** ensure that statement-transactions are always nested, not overlapping.
1354 ** If the open statement-transaction is not closed here, then the user
1355 ** may step another VM that opens its own statement transaction. This
1356 ** may lead to overlapping statement transactions.
1358 ** The statement transaction is never a top-level transaction. Hence
1359 ** the RELEASE call below can never fail.
1361 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
1362 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
1363 assert( rc==SQLITE_OK );
1365 /* Invalidate all ephemeral cursor row caches */
1366 p->cacheCtr = (p->cacheCtr + 2)|1;
1368 /* Make sure the results of the current row are \000 terminated
1369 ** and have an assigned type. The results are de-ephemeralized as
1370 ** a side effect.
1372 pMem = p->pResultSet = &aMem[pOp->p1];
1373 for(i=0; i<pOp->p2; i++){
1374 assert( memIsValid(&pMem[i]) );
1375 Deephemeralize(&pMem[i]);
1376 assert( (pMem[i].flags & MEM_Ephem)==0
1377 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1378 sqlite3VdbeMemNulTerminate(&pMem[i]);
1379 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1381 if( db->mallocFailed ) goto no_mem;
1383 if( db->mTrace & SQLITE_TRACE_ROW ){
1384 db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1387 /* Return SQLITE_ROW
1389 p->pc = (int)(pOp - aOp) + 1;
1390 rc = SQLITE_ROW;
1391 goto vdbe_return;
1394 /* Opcode: Concat P1 P2 P3 * *
1395 ** Synopsis: r[P3]=r[P2]+r[P1]
1397 ** Add the text in register P1 onto the end of the text in
1398 ** register P2 and store the result in register P3.
1399 ** If either the P1 or P2 text are NULL then store NULL in P3.
1401 ** P3 = P2 || P1
1403 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1404 ** if P3 is the same register as P2, the implementation is able
1405 ** to avoid a memcpy().
1407 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1408 i64 nByte;
1410 pIn1 = &aMem[pOp->p1];
1411 pIn2 = &aMem[pOp->p2];
1412 pOut = &aMem[pOp->p3];
1413 assert( pIn1!=pOut );
1414 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1415 sqlite3VdbeMemSetNull(pOut);
1416 break;
1418 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
1419 Stringify(pIn1, encoding);
1420 Stringify(pIn2, encoding);
1421 nByte = pIn1->n + pIn2->n;
1422 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1423 goto too_big;
1425 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1426 goto no_mem;
1428 MemSetTypeFlag(pOut, MEM_Str);
1429 if( pOut!=pIn2 ){
1430 memcpy(pOut->z, pIn2->z, pIn2->n);
1432 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1433 pOut->z[nByte]=0;
1434 pOut->z[nByte+1] = 0;
1435 pOut->flags |= MEM_Term;
1436 pOut->n = (int)nByte;
1437 pOut->enc = encoding;
1438 UPDATE_MAX_BLOBSIZE(pOut);
1439 break;
1442 /* Opcode: Add P1 P2 P3 * *
1443 ** Synopsis: r[P3]=r[P1]+r[P2]
1445 ** Add the value in register P1 to the value in register P2
1446 ** and store the result in register P3.
1447 ** If either input is NULL, the result is NULL.
1449 /* Opcode: Multiply P1 P2 P3 * *
1450 ** Synopsis: r[P3]=r[P1]*r[P2]
1453 ** Multiply the value in register P1 by the value in register P2
1454 ** and store the result in register P3.
1455 ** If either input is NULL, the result is NULL.
1457 /* Opcode: Subtract P1 P2 P3 * *
1458 ** Synopsis: r[P3]=r[P2]-r[P1]
1460 ** Subtract the value in register P1 from the value in register P2
1461 ** and store the result in register P3.
1462 ** If either input is NULL, the result is NULL.
1464 /* Opcode: Divide P1 P2 P3 * *
1465 ** Synopsis: r[P3]=r[P2]/r[P1]
1467 ** Divide the value in register P1 by the value in register P2
1468 ** and store the result in register P3 (P3=P2/P1). If the value in
1469 ** register P1 is zero, then the result is NULL. If either input is
1470 ** NULL, the result is NULL.
1472 /* Opcode: Remainder P1 P2 P3 * *
1473 ** Synopsis: r[P3]=r[P2]%r[P1]
1475 ** Compute the remainder after integer register P2 is divided by
1476 ** register P1 and store the result in register P3.
1477 ** If the value in register P1 is zero the result is NULL.
1478 ** If either operand is NULL, the result is NULL.
1480 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1481 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1482 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1483 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1484 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1485 char bIntint; /* Started out as two integer operands */
1486 u16 flags; /* Combined MEM_* flags from both inputs */
1487 u16 type1; /* Numeric type of left operand */
1488 u16 type2; /* Numeric type of right operand */
1489 i64 iA; /* Integer value of left operand */
1490 i64 iB; /* Integer value of right operand */
1491 double rA; /* Real value of left operand */
1492 double rB; /* Real value of right operand */
1494 pIn1 = &aMem[pOp->p1];
1495 type1 = numericType(pIn1);
1496 pIn2 = &aMem[pOp->p2];
1497 type2 = numericType(pIn2);
1498 pOut = &aMem[pOp->p3];
1499 flags = pIn1->flags | pIn2->flags;
1500 if( (type1 & type2 & MEM_Int)!=0 ){
1501 iA = pIn1->u.i;
1502 iB = pIn2->u.i;
1503 bIntint = 1;
1504 switch( pOp->opcode ){
1505 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1506 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1507 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1508 case OP_Divide: {
1509 if( iA==0 ) goto arithmetic_result_is_null;
1510 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1511 iB /= iA;
1512 break;
1514 default: {
1515 if( iA==0 ) goto arithmetic_result_is_null;
1516 if( iA==-1 ) iA = 1;
1517 iB %= iA;
1518 break;
1521 pOut->u.i = iB;
1522 MemSetTypeFlag(pOut, MEM_Int);
1523 }else if( (flags & MEM_Null)!=0 ){
1524 goto arithmetic_result_is_null;
1525 }else{
1526 bIntint = 0;
1527 fp_math:
1528 rA = sqlite3VdbeRealValue(pIn1);
1529 rB = sqlite3VdbeRealValue(pIn2);
1530 switch( pOp->opcode ){
1531 case OP_Add: rB += rA; break;
1532 case OP_Subtract: rB -= rA; break;
1533 case OP_Multiply: rB *= rA; break;
1534 case OP_Divide: {
1535 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1536 if( rA==(double)0 ) goto arithmetic_result_is_null;
1537 rB /= rA;
1538 break;
1540 default: {
1541 iA = (i64)rA;
1542 iB = (i64)rB;
1543 if( iA==0 ) goto arithmetic_result_is_null;
1544 if( iA==-1 ) iA = 1;
1545 rB = (double)(iB % iA);
1546 break;
1549 #ifdef SQLITE_OMIT_FLOATING_POINT
1550 pOut->u.i = rB;
1551 MemSetTypeFlag(pOut, MEM_Int);
1552 #else
1553 if( sqlite3IsNaN(rB) ){
1554 goto arithmetic_result_is_null;
1556 pOut->u.r = rB;
1557 MemSetTypeFlag(pOut, MEM_Real);
1558 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
1559 sqlite3VdbeIntegerAffinity(pOut);
1561 #endif
1563 break;
1565 arithmetic_result_is_null:
1566 sqlite3VdbeMemSetNull(pOut);
1567 break;
1570 /* Opcode: CollSeq P1 * * P4
1572 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1573 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1574 ** be returned. This is used by the built-in min(), max() and nullif()
1575 ** functions.
1577 ** If P1 is not zero, then it is a register that a subsequent min() or
1578 ** max() aggregate will set to 1 if the current row is not the minimum or
1579 ** maximum. The P1 register is initialized to 0 by this instruction.
1581 ** The interface used by the implementation of the aforementioned functions
1582 ** to retrieve the collation sequence set by this opcode is not available
1583 ** publicly. Only built-in functions have access to this feature.
1585 case OP_CollSeq: {
1586 assert( pOp->p4type==P4_COLLSEQ );
1587 if( pOp->p1 ){
1588 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1590 break;
1593 /* Opcode: BitAnd P1 P2 P3 * *
1594 ** Synopsis: r[P3]=r[P1]&r[P2]
1596 ** Take the bit-wise AND of the values in register P1 and P2 and
1597 ** store the result in register P3.
1598 ** If either input is NULL, the result is NULL.
1600 /* Opcode: BitOr P1 P2 P3 * *
1601 ** Synopsis: r[P3]=r[P1]|r[P2]
1603 ** Take the bit-wise OR of the values in register P1 and P2 and
1604 ** store the result in register P3.
1605 ** If either input is NULL, the result is NULL.
1607 /* Opcode: ShiftLeft P1 P2 P3 * *
1608 ** Synopsis: r[P3]=r[P2]<<r[P1]
1610 ** Shift the integer value in register P2 to the left by the
1611 ** number of bits specified by the integer in register P1.
1612 ** Store the result in register P3.
1613 ** If either input is NULL, the result is NULL.
1615 /* Opcode: ShiftRight P1 P2 P3 * *
1616 ** Synopsis: r[P3]=r[P2]>>r[P1]
1618 ** Shift the integer value in register P2 to the right by the
1619 ** number of bits specified by the integer in register P1.
1620 ** Store the result in register P3.
1621 ** If either input is NULL, the result is NULL.
1623 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1624 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1625 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1626 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1627 i64 iA;
1628 u64 uA;
1629 i64 iB;
1630 u8 op;
1632 pIn1 = &aMem[pOp->p1];
1633 pIn2 = &aMem[pOp->p2];
1634 pOut = &aMem[pOp->p3];
1635 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1636 sqlite3VdbeMemSetNull(pOut);
1637 break;
1639 iA = sqlite3VdbeIntValue(pIn2);
1640 iB = sqlite3VdbeIntValue(pIn1);
1641 op = pOp->opcode;
1642 if( op==OP_BitAnd ){
1643 iA &= iB;
1644 }else if( op==OP_BitOr ){
1645 iA |= iB;
1646 }else if( iB!=0 ){
1647 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1649 /* If shifting by a negative amount, shift in the other direction */
1650 if( iB<0 ){
1651 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1652 op = 2*OP_ShiftLeft + 1 - op;
1653 iB = iB>(-64) ? -iB : 64;
1656 if( iB>=64 ){
1657 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1658 }else{
1659 memcpy(&uA, &iA, sizeof(uA));
1660 if( op==OP_ShiftLeft ){
1661 uA <<= iB;
1662 }else{
1663 uA >>= iB;
1664 /* Sign-extend on a right shift of a negative number */
1665 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1667 memcpy(&iA, &uA, sizeof(iA));
1670 pOut->u.i = iA;
1671 MemSetTypeFlag(pOut, MEM_Int);
1672 break;
1675 /* Opcode: AddImm P1 P2 * * *
1676 ** Synopsis: r[P1]=r[P1]+P2
1678 ** Add the constant P2 to the value in register P1.
1679 ** The result is always an integer.
1681 ** To force any register to be an integer, just add 0.
1683 case OP_AddImm: { /* in1 */
1684 pIn1 = &aMem[pOp->p1];
1685 memAboutToChange(p, pIn1);
1686 sqlite3VdbeMemIntegerify(pIn1);
1687 pIn1->u.i += pOp->p2;
1688 break;
1691 /* Opcode: MustBeInt P1 P2 * * *
1693 ** Force the value in register P1 to be an integer. If the value
1694 ** in P1 is not an integer and cannot be converted into an integer
1695 ** without data loss, then jump immediately to P2, or if P2==0
1696 ** raise an SQLITE_MISMATCH exception.
1698 case OP_MustBeInt: { /* jump, in1 */
1699 pIn1 = &aMem[pOp->p1];
1700 if( (pIn1->flags & MEM_Int)==0 ){
1701 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1702 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
1703 if( (pIn1->flags & MEM_Int)==0 ){
1704 if( pOp->p2==0 ){
1705 rc = SQLITE_MISMATCH;
1706 goto abort_due_to_error;
1707 }else{
1708 goto jump_to_p2;
1712 MemSetTypeFlag(pIn1, MEM_Int);
1713 break;
1716 #ifndef SQLITE_OMIT_FLOATING_POINT
1717 /* Opcode: RealAffinity P1 * * * *
1719 ** If register P1 holds an integer convert it to a real value.
1721 ** This opcode is used when extracting information from a column that
1722 ** has REAL affinity. Such column values may still be stored as
1723 ** integers, for space efficiency, but after extraction we want them
1724 ** to have only a real value.
1726 case OP_RealAffinity: { /* in1 */
1727 pIn1 = &aMem[pOp->p1];
1728 if( pIn1->flags & MEM_Int ){
1729 sqlite3VdbeMemRealify(pIn1);
1731 break;
1733 #endif
1735 #ifndef SQLITE_OMIT_CAST
1736 /* Opcode: Cast P1 P2 * * *
1737 ** Synopsis: affinity(r[P1])
1739 ** Force the value in register P1 to be the type defined by P2.
1741 ** <ul>
1742 ** <li> P2=='A' &rarr; BLOB
1743 ** <li> P2=='B' &rarr; TEXT
1744 ** <li> P2=='C' &rarr; NUMERIC
1745 ** <li> P2=='D' &rarr; INTEGER
1746 ** <li> P2=='E' &rarr; REAL
1747 ** </ul>
1749 ** A NULL value is not changed by this routine. It remains NULL.
1751 case OP_Cast: { /* in1 */
1752 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
1753 testcase( pOp->p2==SQLITE_AFF_TEXT );
1754 testcase( pOp->p2==SQLITE_AFF_BLOB );
1755 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
1756 testcase( pOp->p2==SQLITE_AFF_INTEGER );
1757 testcase( pOp->p2==SQLITE_AFF_REAL );
1758 pIn1 = &aMem[pOp->p1];
1759 memAboutToChange(p, pIn1);
1760 rc = ExpandBlob(pIn1);
1761 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
1762 UPDATE_MAX_BLOBSIZE(pIn1);
1763 if( rc ) goto abort_due_to_error;
1764 break;
1766 #endif /* SQLITE_OMIT_CAST */
1768 /* Opcode: Eq P1 P2 P3 P4 P5
1769 ** Synopsis: IF r[P3]==r[P1]
1771 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
1772 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
1773 ** store the result of comparison in register P2.
1775 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1776 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1777 ** to coerce both inputs according to this affinity before the
1778 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1779 ** affinity is used. Note that the affinity conversions are stored
1780 ** back into the input registers P1 and P3. So this opcode can cause
1781 ** persistent changes to registers P1 and P3.
1783 ** Once any conversions have taken place, and neither value is NULL,
1784 ** the values are compared. If both values are blobs then memcmp() is
1785 ** used to determine the results of the comparison. If both values
1786 ** are text, then the appropriate collating function specified in
1787 ** P4 is used to do the comparison. If P4 is not specified then
1788 ** memcmp() is used to compare text string. If both values are
1789 ** numeric, then a numeric comparison is used. If the two values
1790 ** are of different types, then numbers are considered less than
1791 ** strings and strings are considered less than blobs.
1793 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1794 ** true or false and is never NULL. If both operands are NULL then the result
1795 ** of comparison is true. If either operand is NULL then the result is false.
1796 ** If neither operand is NULL the result is the same as it would be if
1797 ** the SQLITE_NULLEQ flag were omitted from P5.
1799 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1800 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
1801 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
1803 /* Opcode: Ne P1 P2 P3 P4 P5
1804 ** Synopsis: IF r[P3]!=r[P1]
1806 ** This works just like the Eq opcode except that the jump is taken if
1807 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
1808 ** additional information.
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 1 (true).
1812 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
1814 /* Opcode: Lt P1 P2 P3 P4 P5
1815 ** Synopsis: IF r[P3]<r[P1]
1817 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1818 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
1819 ** the result of comparison (0 or 1 or NULL) into register P2.
1821 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1822 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
1823 ** bit is clear then fall through if either operand is NULL.
1825 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1826 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1827 ** to coerce both inputs according to this affinity before the
1828 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1829 ** affinity is used. Note that the affinity conversions are stored
1830 ** back into the input registers P1 and P3. So this opcode can cause
1831 ** persistent changes to registers P1 and P3.
1833 ** Once any conversions have taken place, and neither value is NULL,
1834 ** the values are compared. If both values are blobs then memcmp() is
1835 ** used to determine the results of the comparison. If both values
1836 ** are text, then the appropriate collating function specified in
1837 ** P4 is used to do the comparison. If P4 is not specified then
1838 ** memcmp() is used to compare text string. If both values are
1839 ** numeric, then a numeric comparison is used. If the two values
1840 ** are of different types, then numbers are considered less than
1841 ** strings and strings are considered less than blobs.
1843 /* Opcode: Le P1 P2 P3 P4 P5
1844 ** Synopsis: IF r[P3]<=r[P1]
1846 ** This works just like the Lt opcode except that the jump is taken if
1847 ** the content of register P3 is less than or equal to the content of
1848 ** register P1. See the Lt opcode for additional information.
1850 /* Opcode: Gt P1 P2 P3 P4 P5
1851 ** Synopsis: IF r[P3]>r[P1]
1853 ** This works just like the Lt opcode except that the jump is taken if
1854 ** the content of register P3 is greater than the content of
1855 ** register P1. See the Lt opcode for additional information.
1857 /* Opcode: Ge P1 P2 P3 P4 P5
1858 ** Synopsis: IF r[P3]>=r[P1]
1860 ** This works just like the Lt opcode except that the jump is taken if
1861 ** the content of register P3 is greater than or equal to the content of
1862 ** register P1. See the Lt opcode for additional information.
1864 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
1865 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
1866 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
1867 case OP_Le: /* same as TK_LE, jump, in1, in3 */
1868 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
1869 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
1870 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
1871 char affinity; /* Affinity to use for comparison */
1872 u16 flags1; /* Copy of initial value of pIn1->flags */
1873 u16 flags3; /* Copy of initial value of pIn3->flags */
1875 pIn1 = &aMem[pOp->p1];
1876 pIn3 = &aMem[pOp->p3];
1877 flags1 = pIn1->flags;
1878 flags3 = pIn3->flags;
1879 if( (flags1 | flags3)&MEM_Null ){
1880 /* One or both operands are NULL */
1881 if( pOp->p5 & SQLITE_NULLEQ ){
1882 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1883 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1884 ** or not both operands are null.
1886 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
1887 assert( (flags1 & MEM_Cleared)==0 );
1888 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
1889 if( (flags1&flags3&MEM_Null)!=0
1890 && (flags3&MEM_Cleared)==0
1892 res = 0; /* Operands are equal */
1893 }else{
1894 res = 1; /* Operands are not equal */
1896 }else{
1897 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1898 ** then the result is always NULL.
1899 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1901 if( pOp->p5 & SQLITE_STOREP2 ){
1902 pOut = &aMem[pOp->p2];
1903 iCompare = 1; /* Operands are not equal */
1904 memAboutToChange(p, pOut);
1905 MemSetTypeFlag(pOut, MEM_Null);
1906 REGISTER_TRACE(pOp->p2, pOut);
1907 }else{
1908 VdbeBranchTaken(2,3);
1909 if( pOp->p5 & SQLITE_JUMPIFNULL ){
1910 goto jump_to_p2;
1913 break;
1915 }else{
1916 /* Neither operand is NULL. Do a comparison. */
1917 affinity = pOp->p5 & SQLITE_AFF_MASK;
1918 if( affinity>=SQLITE_AFF_NUMERIC ){
1919 if( (flags1 | flags3)&MEM_Str ){
1920 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1921 applyNumericAffinity(pIn1,0);
1922 testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
1923 flags3 = pIn3->flags;
1925 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1926 applyNumericAffinity(pIn3,0);
1929 /* Handle the common case of integer comparison here, as an
1930 ** optimization, to avoid a call to sqlite3MemCompare() */
1931 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
1932 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
1933 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
1934 res = 0;
1935 goto compare_op;
1937 }else if( affinity==SQLITE_AFF_TEXT ){
1938 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
1939 testcase( pIn1->flags & MEM_Int );
1940 testcase( pIn1->flags & MEM_Real );
1941 sqlite3VdbeMemStringify(pIn1, encoding, 1);
1942 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
1943 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
1944 assert( pIn1!=pIn3 );
1946 if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
1947 testcase( pIn3->flags & MEM_Int );
1948 testcase( pIn3->flags & MEM_Real );
1949 sqlite3VdbeMemStringify(pIn3, encoding, 1);
1950 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
1951 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
1954 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1955 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1957 compare_op:
1958 /* At this point, res is negative, zero, or positive if reg[P1] is
1959 ** less than, equal to, or greater than reg[P3], respectively. Compute
1960 ** the answer to this operator in res2, depending on what the comparison
1961 ** operator actually is. The next block of code depends on the fact
1962 ** that the 6 comparison operators are consecutive integers in this
1963 ** order: NE, EQ, GT, LE, LT, GE */
1964 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
1965 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
1966 if( res<0 ){ /* ne, eq, gt, le, lt, ge */
1967 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
1968 res2 = aLTb[pOp->opcode - OP_Ne];
1969 }else if( res==0 ){
1970 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
1971 res2 = aEQb[pOp->opcode - OP_Ne];
1972 }else{
1973 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
1974 res2 = aGTb[pOp->opcode - OP_Ne];
1977 /* Undo any changes made by applyAffinity() to the input registers. */
1978 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1979 pIn1->flags = flags1;
1980 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
1981 pIn3->flags = flags3;
1983 if( pOp->p5 & SQLITE_STOREP2 ){
1984 pOut = &aMem[pOp->p2];
1985 iCompare = res;
1986 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
1987 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
1988 ** and prevents OP_Ne from overwriting NULL with 0. This flag
1989 ** is only used in contexts where either:
1990 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
1991 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
1992 ** Therefore it is not necessary to check the content of r[P2] for
1993 ** NULL. */
1994 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
1995 assert( res2==0 || res2==1 );
1996 testcase( res2==0 && pOp->opcode==OP_Eq );
1997 testcase( res2==1 && pOp->opcode==OP_Eq );
1998 testcase( res2==0 && pOp->opcode==OP_Ne );
1999 testcase( res2==1 && pOp->opcode==OP_Ne );
2000 if( (pOp->opcode==OP_Eq)==res2 ) break;
2002 memAboutToChange(p, pOut);
2003 MemSetTypeFlag(pOut, MEM_Int);
2004 pOut->u.i = res2;
2005 REGISTER_TRACE(pOp->p2, pOut);
2006 }else{
2007 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2008 if( res2 ){
2009 goto jump_to_p2;
2012 break;
2015 /* Opcode: ElseNotEq * P2 * * *
2017 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
2018 ** If result of an OP_Eq comparison on the same two operands
2019 ** would have be NULL or false (0), then then jump to P2.
2020 ** If the result of an OP_Eq comparison on the two previous operands
2021 ** would have been true (1), then fall through.
2023 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
2024 assert( pOp>aOp );
2025 assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
2026 assert( pOp[-1].p5 & SQLITE_STOREP2 );
2027 VdbeBranchTaken(iCompare!=0, 2);
2028 if( iCompare!=0 ) goto jump_to_p2;
2029 break;
2033 /* Opcode: Permutation * * * P4 *
2035 ** Set the permutation used by the OP_Compare operator in the next
2036 ** instruction. The permutation is stored in the P4 operand.
2038 ** The permutation is only valid until the next OP_Compare that has
2039 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2040 ** occur immediately prior to the OP_Compare.
2042 ** The first integer in the P4 integer array is the length of the array
2043 ** and does not become part of the permutation.
2045 case OP_Permutation: {
2046 assert( pOp->p4type==P4_INTARRAY );
2047 assert( pOp->p4.ai );
2048 assert( pOp[1].opcode==OP_Compare );
2049 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2050 break;
2053 /* Opcode: Compare P1 P2 P3 P4 P5
2054 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2056 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2057 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2058 ** the comparison for use by the next OP_Jump instruct.
2060 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2061 ** determined by the most recent OP_Permutation operator. If the
2062 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2063 ** order.
2065 ** P4 is a KeyInfo structure that defines collating sequences and sort
2066 ** orders for the comparison. The permutation applies to registers
2067 ** only. The KeyInfo elements are used sequentially.
2069 ** The comparison is a sort comparison, so NULLs compare equal,
2070 ** NULLs are less than numbers, numbers are less than strings,
2071 ** and strings are less than blobs.
2073 case OP_Compare: {
2074 int n;
2075 int i;
2076 int p1;
2077 int p2;
2078 const KeyInfo *pKeyInfo;
2079 int idx;
2080 CollSeq *pColl; /* Collating sequence to use on this term */
2081 int bRev; /* True for DESCENDING sort order */
2082 int *aPermute; /* The permutation */
2084 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2085 aPermute = 0;
2086 }else{
2087 assert( pOp>aOp );
2088 assert( pOp[-1].opcode==OP_Permutation );
2089 assert( pOp[-1].p4type==P4_INTARRAY );
2090 aPermute = pOp[-1].p4.ai + 1;
2091 assert( aPermute!=0 );
2093 n = pOp->p3;
2094 pKeyInfo = pOp->p4.pKeyInfo;
2095 assert( n>0 );
2096 assert( pKeyInfo!=0 );
2097 p1 = pOp->p1;
2098 p2 = pOp->p2;
2099 #ifdef SQLITE_DEBUG
2100 if( aPermute ){
2101 int k, mx = 0;
2102 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
2103 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2104 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2105 }else{
2106 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2107 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2109 #endif /* SQLITE_DEBUG */
2110 for(i=0; i<n; i++){
2111 idx = aPermute ? aPermute[i] : i;
2112 assert( memIsValid(&aMem[p1+idx]) );
2113 assert( memIsValid(&aMem[p2+idx]) );
2114 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2115 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2116 assert( i<pKeyInfo->nKeyField );
2117 pColl = pKeyInfo->aColl[i];
2118 bRev = pKeyInfo->aSortOrder[i];
2119 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2120 if( iCompare ){
2121 if( bRev ) iCompare = -iCompare;
2122 break;
2125 break;
2128 /* Opcode: Jump P1 P2 P3 * *
2130 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2131 ** in the most recent OP_Compare instruction the P1 vector was less than
2132 ** equal to, or greater than the P2 vector, respectively.
2134 case OP_Jump: { /* jump */
2135 if( iCompare<0 ){
2136 VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
2137 }else if( iCompare==0 ){
2138 VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
2139 }else{
2140 VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
2142 break;
2145 /* Opcode: And P1 P2 P3 * *
2146 ** Synopsis: r[P3]=(r[P1] && r[P2])
2148 ** Take the logical AND of the values in registers P1 and P2 and
2149 ** write the result into register P3.
2151 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2152 ** the other input is NULL. A NULL and true or two NULLs give
2153 ** a NULL output.
2155 /* Opcode: Or P1 P2 P3 * *
2156 ** Synopsis: r[P3]=(r[P1] || r[P2])
2158 ** Take the logical OR of the values in register P1 and P2 and
2159 ** store the answer in register P3.
2161 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2162 ** even if the other input is NULL. A NULL and false or two NULLs
2163 ** give a NULL output.
2165 case OP_And: /* same as TK_AND, in1, in2, out3 */
2166 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2167 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2168 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2170 pIn1 = &aMem[pOp->p1];
2171 if( pIn1->flags & MEM_Null ){
2172 v1 = 2;
2173 }else{
2174 v1 = sqlite3VdbeIntValue(pIn1)!=0;
2176 pIn2 = &aMem[pOp->p2];
2177 if( pIn2->flags & MEM_Null ){
2178 v2 = 2;
2179 }else{
2180 v2 = sqlite3VdbeIntValue(pIn2)!=0;
2182 if( pOp->opcode==OP_And ){
2183 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2184 v1 = and_logic[v1*3+v2];
2185 }else{
2186 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2187 v1 = or_logic[v1*3+v2];
2189 pOut = &aMem[pOp->p3];
2190 if( v1==2 ){
2191 MemSetTypeFlag(pOut, MEM_Null);
2192 }else{
2193 pOut->u.i = v1;
2194 MemSetTypeFlag(pOut, MEM_Int);
2196 break;
2199 /* Opcode: Not P1 P2 * * *
2200 ** Synopsis: r[P2]= !r[P1]
2202 ** Interpret the value in register P1 as a boolean value. Store the
2203 ** boolean complement in register P2. If the value in register P1 is
2204 ** NULL, then a NULL is stored in P2.
2206 case OP_Not: { /* same as TK_NOT, in1, out2 */
2207 pIn1 = &aMem[pOp->p1];
2208 pOut = &aMem[pOp->p2];
2209 sqlite3VdbeMemSetNull(pOut);
2210 if( (pIn1->flags & MEM_Null)==0 ){
2211 pOut->flags = MEM_Int;
2212 pOut->u.i = !sqlite3VdbeIntValue(pIn1);
2214 break;
2217 /* Opcode: BitNot P1 P2 * * *
2218 ** Synopsis: r[P1]= ~r[P1]
2220 ** Interpret the content of register P1 as an integer. Store the
2221 ** ones-complement of the P1 value into register P2. If P1 holds
2222 ** a NULL then store a NULL in P2.
2224 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2225 pIn1 = &aMem[pOp->p1];
2226 pOut = &aMem[pOp->p2];
2227 sqlite3VdbeMemSetNull(pOut);
2228 if( (pIn1->flags & MEM_Null)==0 ){
2229 pOut->flags = MEM_Int;
2230 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2232 break;
2235 /* Opcode: Once P1 P2 * * *
2237 ** Fall through to the next instruction the first time this opcode is
2238 ** encountered on each invocation of the byte-code program. Jump to P2
2239 ** on the second and all subsequent encounters during the same invocation.
2241 ** Top-level programs determine first invocation by comparing the P1
2242 ** operand against the P1 operand on the OP_Init opcode at the beginning
2243 ** of the program. If the P1 values differ, then fall through and make
2244 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2245 ** the same then take the jump.
2247 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2248 ** whether or not the jump should be taken. The bitmask is necessary
2249 ** because the self-altering code trick does not work for recursive
2250 ** triggers.
2252 case OP_Once: { /* jump */
2253 u32 iAddr; /* Address of this instruction */
2254 assert( p->aOp[0].opcode==OP_Init );
2255 if( p->pFrame ){
2256 iAddr = (int)(pOp - p->aOp);
2257 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2258 VdbeBranchTaken(1, 2);
2259 goto jump_to_p2;
2261 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2262 }else{
2263 if( p->aOp[0].p1==pOp->p1 ){
2264 VdbeBranchTaken(1, 2);
2265 goto jump_to_p2;
2268 VdbeBranchTaken(0, 2);
2269 pOp->p1 = p->aOp[0].p1;
2270 break;
2273 /* Opcode: If P1 P2 P3 * *
2275 ** Jump to P2 if the value in register P1 is true. The value
2276 ** is considered true if it is numeric and non-zero. If the value
2277 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2279 /* Opcode: IfNot P1 P2 P3 * *
2281 ** Jump to P2 if the value in register P1 is False. The value
2282 ** is considered false if it has a numeric value of zero. If the value
2283 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2285 case OP_If: /* jump, in1 */
2286 case OP_IfNot: { /* jump, in1 */
2287 int c;
2288 pIn1 = &aMem[pOp->p1];
2289 if( pIn1->flags & MEM_Null ){
2290 c = pOp->p3;
2291 }else{
2292 #ifdef SQLITE_OMIT_FLOATING_POINT
2293 c = sqlite3VdbeIntValue(pIn1)!=0;
2294 #else
2295 c = sqlite3VdbeRealValue(pIn1)!=0.0;
2296 #endif
2297 if( pOp->opcode==OP_IfNot ) c = !c;
2299 VdbeBranchTaken(c!=0, 2);
2300 if( c ){
2301 goto jump_to_p2;
2303 break;
2306 /* Opcode: IsNull P1 P2 * * *
2307 ** Synopsis: if r[P1]==NULL goto P2
2309 ** Jump to P2 if the value in register P1 is NULL.
2311 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2312 pIn1 = &aMem[pOp->p1];
2313 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2314 if( (pIn1->flags & MEM_Null)!=0 ){
2315 goto jump_to_p2;
2317 break;
2320 /* Opcode: NotNull P1 P2 * * *
2321 ** Synopsis: if r[P1]!=NULL goto P2
2323 ** Jump to P2 if the value in register P1 is not NULL.
2325 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2326 pIn1 = &aMem[pOp->p1];
2327 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2328 if( (pIn1->flags & MEM_Null)==0 ){
2329 goto jump_to_p2;
2331 break;
2334 /* Opcode: IfNullRow P1 P2 P3 * *
2335 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2337 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2338 ** If it is, then set register P3 to NULL and jump immediately to P2.
2339 ** If P1 is not on a NULL row, then fall through without making any
2340 ** changes.
2342 case OP_IfNullRow: { /* jump */
2343 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2344 assert( p->apCsr[pOp->p1]!=0 );
2345 if( p->apCsr[pOp->p1]->nullRow ){
2346 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2347 goto jump_to_p2;
2349 break;
2352 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2353 /* Opcode: Offset P1 P2 P3 * *
2354 ** Synopsis: r[P3] = sqlite_offset(P1)
2356 ** Store in register r[P3] the byte offset into the database file that is the
2357 ** start of the payload for the record at which that cursor P1 is currently
2358 ** pointing.
2360 ** P2 is the column number for the argument to the sqlite_offset() function.
2361 ** This opcode does not use P2 itself, but the P2 value is used by the
2362 ** code generator. The P1, P2, and P3 operands to this opcode are the
2363 ** as as for OP_Column.
2365 ** This opcode is only available if SQLite is compiled with the
2366 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2368 case OP_Offset: { /* out3 */
2369 VdbeCursor *pC; /* The VDBE cursor */
2370 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2371 pC = p->apCsr[pOp->p1];
2372 pOut = &p->aMem[pOp->p3];
2373 if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
2374 sqlite3VdbeMemSetNull(pOut);
2375 }else{
2376 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2378 break;
2380 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2382 /* Opcode: Column P1 P2 P3 P4 P5
2383 ** Synopsis: r[P3]=PX
2385 ** Interpret the data that cursor P1 points to as a structure built using
2386 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2387 ** information about the format of the data.) Extract the P2-th column
2388 ** from this record. If there are less that (P2+1)
2389 ** values in the record, extract a NULL.
2391 ** The value extracted is stored in register P3.
2393 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2394 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2395 ** the result.
2397 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2398 ** then the cache of the cursor is reset prior to extracting the column.
2399 ** The first OP_Column against a pseudo-table after the value of the content
2400 ** register has changed should have this bit set.
2402 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2403 ** the result is guaranteed to only be used as the argument of a length()
2404 ** or typeof() function, respectively. The loading of large blobs can be
2405 ** skipped for length() and all content loading can be skipped for typeof().
2407 case OP_Column: {
2408 int p2; /* column number to retrieve */
2409 VdbeCursor *pC; /* The VDBE cursor */
2410 BtCursor *pCrsr; /* The BTree cursor */
2411 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2412 int len; /* The length of the serialized data for the column */
2413 int i; /* Loop counter */
2414 Mem *pDest; /* Where to write the extracted value */
2415 Mem sMem; /* For storing the record being decoded */
2416 const u8 *zData; /* Part of the record being decoded */
2417 const u8 *zHdr; /* Next unparsed byte of the header */
2418 const u8 *zEndHdr; /* Pointer to first byte after the header */
2419 u64 offset64; /* 64-bit offset */
2420 u32 t; /* A type code from the record header */
2421 Mem *pReg; /* PseudoTable input register */
2423 pC = p->apCsr[pOp->p1];
2424 p2 = pOp->p2;
2426 /* If the cursor cache is stale (meaning it is not currently point at
2427 ** the correct row) then bring it up-to-date by doing the necessary
2428 ** B-Tree seek. */
2429 rc = sqlite3VdbeCursorMoveto(&pC, &p2);
2430 if( rc ) goto abort_due_to_error;
2432 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2433 pDest = &aMem[pOp->p3];
2434 memAboutToChange(p, pDest);
2435 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2436 assert( pC!=0 );
2437 assert( p2<pC->nField );
2438 aOffset = pC->aOffset;
2439 assert( pC->eCurType!=CURTYPE_VTAB );
2440 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2441 assert( pC->eCurType!=CURTYPE_SORTER );
2443 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2444 if( pC->nullRow ){
2445 if( pC->eCurType==CURTYPE_PSEUDO ){
2446 /* For the special case of as pseudo-cursor, the seekResult field
2447 ** identifies the register that holds the record */
2448 assert( pC->seekResult>0 );
2449 pReg = &aMem[pC->seekResult];
2450 assert( pReg->flags & MEM_Blob );
2451 assert( memIsValid(pReg) );
2452 pC->payloadSize = pC->szRow = pReg->n;
2453 pC->aRow = (u8*)pReg->z;
2454 }else{
2455 sqlite3VdbeMemSetNull(pDest);
2456 goto op_column_out;
2458 }else{
2459 pCrsr = pC->uc.pCursor;
2460 assert( pC->eCurType==CURTYPE_BTREE );
2461 assert( pCrsr );
2462 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2463 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2464 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2465 assert( pC->szRow<=pC->payloadSize );
2466 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2467 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2468 goto too_big;
2471 pC->cacheStatus = p->cacheCtr;
2472 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
2473 pC->nHdrParsed = 0;
2476 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2477 /* pC->aRow does not have to hold the entire row, but it does at least
2478 ** need to cover the header of the record. If pC->aRow does not contain
2479 ** the complete header, then set it to zero, forcing the header to be
2480 ** dynamically allocated. */
2481 pC->aRow = 0;
2482 pC->szRow = 0;
2484 /* Make sure a corrupt database has not given us an oversize header.
2485 ** Do this now to avoid an oversize memory allocation.
2487 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2488 ** types use so much data space that there can only be 4096 and 32 of
2489 ** them, respectively. So the maximum header length results from a
2490 ** 3-byte type for each of the maximum of 32768 columns plus three
2491 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2493 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2494 goto op_column_corrupt;
2496 }else{
2497 /* This is an optimization. By skipping over the first few tests
2498 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2499 ** measurable performance gain.
2501 ** This branch is taken even if aOffset[0]==0. Such a record is never
2502 ** generated by SQLite, and could be considered corruption, but we
2503 ** accept it for historical reasons. When aOffset[0]==0, the code this
2504 ** branch jumps to reads past the end of the record, but never more
2505 ** than a few bytes. Even if the record occurs at the end of the page
2506 ** content area, the "page header" comes after the page content and so
2507 ** this overread is harmless. Similar overreads can occur for a corrupt
2508 ** database file.
2510 zData = pC->aRow;
2511 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2512 testcase( aOffset[0]==0 );
2513 goto op_column_read_header;
2517 /* Make sure at least the first p2+1 entries of the header have been
2518 ** parsed and valid information is in aOffset[] and pC->aType[].
2520 if( pC->nHdrParsed<=p2 ){
2521 /* If there is more header available for parsing in the record, try
2522 ** to extract additional fields up through the p2+1-th field
2524 if( pC->iHdrOffset<aOffset[0] ){
2525 /* Make sure zData points to enough of the record to cover the header. */
2526 if( pC->aRow==0 ){
2527 memset(&sMem, 0, sizeof(sMem));
2528 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
2529 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2530 zData = (u8*)sMem.z;
2531 }else{
2532 zData = pC->aRow;
2535 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2536 op_column_read_header:
2537 i = pC->nHdrParsed;
2538 offset64 = aOffset[i];
2539 zHdr = zData + pC->iHdrOffset;
2540 zEndHdr = zData + aOffset[0];
2541 testcase( zHdr>=zEndHdr );
2543 if( (t = zHdr[0])<0x80 ){
2544 zHdr++;
2545 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2546 }else{
2547 zHdr += sqlite3GetVarint32(zHdr, &t);
2548 offset64 += sqlite3VdbeSerialTypeLen(t);
2550 pC->aType[i++] = t;
2551 aOffset[i] = (u32)(offset64 & 0xffffffff);
2552 }while( i<=p2 && zHdr<zEndHdr );
2554 /* The record is corrupt if any of the following are true:
2555 ** (1) the bytes of the header extend past the declared header size
2556 ** (2) the entire header was used but not all data was used
2557 ** (3) the end of the data extends beyond the end of the record.
2559 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2560 || (offset64 > pC->payloadSize)
2562 if( aOffset[0]==0 ){
2563 i = 0;
2564 zHdr = zEndHdr;
2565 }else{
2566 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2567 goto op_column_corrupt;
2571 pC->nHdrParsed = i;
2572 pC->iHdrOffset = (u32)(zHdr - zData);
2573 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2574 }else{
2575 t = 0;
2578 /* If after trying to extract new entries from the header, nHdrParsed is
2579 ** still not up to p2, that means that the record has fewer than p2
2580 ** columns. So the result will be either the default value or a NULL.
2582 if( pC->nHdrParsed<=p2 ){
2583 if( pOp->p4type==P4_MEM ){
2584 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2585 }else{
2586 sqlite3VdbeMemSetNull(pDest);
2588 goto op_column_out;
2590 }else{
2591 t = pC->aType[p2];
2594 /* Extract the content for the p2+1-th column. Control can only
2595 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2596 ** all valid.
2598 assert( p2<pC->nHdrParsed );
2599 assert( rc==SQLITE_OK );
2600 assert( sqlite3VdbeCheckMemInvariants(pDest) );
2601 if( VdbeMemDynamic(pDest) ){
2602 sqlite3VdbeMemSetNull(pDest);
2604 assert( t==pC->aType[p2] );
2605 if( pC->szRow>=aOffset[p2+1] ){
2606 /* This is the common case where the desired content fits on the original
2607 ** page - where the content is not on an overflow page */
2608 zData = pC->aRow + aOffset[p2];
2609 if( t<12 ){
2610 sqlite3VdbeSerialGet(zData, t, pDest);
2611 }else{
2612 /* If the column value is a string, we need a persistent value, not
2613 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2614 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2616 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
2617 pDest->n = len = (t-12)/2;
2618 pDest->enc = encoding;
2619 if( pDest->szMalloc < len+2 ){
2620 pDest->flags = MEM_Null;
2621 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
2622 }else{
2623 pDest->z = pDest->zMalloc;
2625 memcpy(pDest->z, zData, len);
2626 pDest->z[len] = 0;
2627 pDest->z[len+1] = 0;
2628 pDest->flags = aFlag[t&1];
2630 }else{
2631 pDest->enc = encoding;
2632 /* This branch happens only when content is on overflow pages */
2633 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2634 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2635 || (len = sqlite3VdbeSerialTypeLen(t))==0
2637 /* Content is irrelevant for
2638 ** 1. the typeof() function,
2639 ** 2. the length(X) function if X is a blob, and
2640 ** 3. if the content length is zero.
2641 ** So we might as well use bogus content rather than reading
2642 ** content from disk.
2644 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2645 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2646 ** read up to 16. So 16 bytes of bogus content is supplied.
2648 static u8 aZero[16]; /* This is the bogus content */
2649 sqlite3VdbeSerialGet(aZero, t, pDest);
2650 }else{
2651 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
2652 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2653 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2654 pDest->flags &= ~MEM_Ephem;
2658 op_column_out:
2659 UPDATE_MAX_BLOBSIZE(pDest);
2660 REGISTER_TRACE(pOp->p3, pDest);
2661 break;
2663 op_column_corrupt:
2664 if( aOp[0].p3>0 ){
2665 pOp = &aOp[aOp[0].p3-1];
2666 break;
2667 }else{
2668 rc = SQLITE_CORRUPT_BKPT;
2669 goto abort_due_to_error;
2673 /* Opcode: Affinity P1 P2 * P4 *
2674 ** Synopsis: affinity(r[P1@P2])
2676 ** Apply affinities to a range of P2 registers starting with P1.
2678 ** P4 is a string that is P2 characters long. The N-th character of the
2679 ** string indicates the column affinity that should be used for the N-th
2680 ** memory cell in the range.
2682 case OP_Affinity: {
2683 const char *zAffinity; /* The affinity to be applied */
2685 zAffinity = pOp->p4.z;
2686 assert( zAffinity!=0 );
2687 assert( pOp->p2>0 );
2688 assert( zAffinity[pOp->p2]==0 );
2689 pIn1 = &aMem[pOp->p1];
2691 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
2692 assert( memIsValid(pIn1) );
2693 applyAffinity(pIn1, *(zAffinity++), encoding);
2694 pIn1++;
2695 }while( zAffinity[0] );
2696 break;
2699 /* Opcode: MakeRecord P1 P2 P3 P4 *
2700 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2702 ** Convert P2 registers beginning with P1 into the [record format]
2703 ** use as a data record in a database table or as a key
2704 ** in an index. The OP_Column opcode can decode the record later.
2706 ** P4 may be a string that is P2 characters long. The N-th character of the
2707 ** string indicates the column affinity that should be used for the N-th
2708 ** field of the index key.
2710 ** The mapping from character to affinity is given by the SQLITE_AFF_
2711 ** macros defined in sqliteInt.h.
2713 ** If P4 is NULL then all index fields have the affinity BLOB.
2715 case OP_MakeRecord: {
2716 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2717 Mem *pRec; /* The new record */
2718 u64 nData; /* Number of bytes of data space */
2719 int nHdr; /* Number of bytes of header space */
2720 i64 nByte; /* Data space required for this record */
2721 i64 nZero; /* Number of zero bytes at the end of the record */
2722 int nVarint; /* Number of bytes in a varint */
2723 u32 serial_type; /* Type field */
2724 Mem *pData0; /* First field to be combined into the record */
2725 Mem *pLast; /* Last field of the record */
2726 int nField; /* Number of fields in the record */
2727 char *zAffinity; /* The affinity string for the record */
2728 int file_format; /* File format to use for encoding */
2729 int i; /* Space used in zNewRecord[] header */
2730 int j; /* Space used in zNewRecord[] content */
2731 u32 len; /* Length of a field */
2733 /* Assuming the record contains N fields, the record format looks
2734 ** like this:
2736 ** ------------------------------------------------------------------------
2737 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2738 ** ------------------------------------------------------------------------
2740 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2741 ** and so forth.
2743 ** Each type field is a varint representing the serial type of the
2744 ** corresponding data element (see sqlite3VdbeSerialType()). The
2745 ** hdr-size field is also a varint which is the offset from the beginning
2746 ** of the record to data0.
2748 nData = 0; /* Number of bytes of data space */
2749 nHdr = 0; /* Number of bytes of header space */
2750 nZero = 0; /* Number of zero bytes at the end of the record */
2751 nField = pOp->p1;
2752 zAffinity = pOp->p4.z;
2753 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
2754 pData0 = &aMem[nField];
2755 nField = pOp->p2;
2756 pLast = &pData0[nField-1];
2757 file_format = p->minWriteFileFormat;
2759 /* Identify the output register */
2760 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2761 pOut = &aMem[pOp->p3];
2762 memAboutToChange(p, pOut);
2764 /* Apply the requested affinity to all inputs
2766 assert( pData0<=pLast );
2767 if( zAffinity ){
2768 pRec = pData0;
2770 applyAffinity(pRec++, *(zAffinity++), encoding);
2771 assert( zAffinity[0]==0 || pRec<=pLast );
2772 }while( zAffinity[0] );
2775 #ifdef SQLITE_ENABLE_NULL_TRIM
2776 /* NULLs can be safely trimmed from the end of the record, as long as
2777 ** as the schema format is 2 or more and none of the omitted columns
2778 ** have a non-NULL default value. Also, the record must be left with
2779 ** at least one field. If P5>0 then it will be one more than the
2780 ** index of the right-most column with a non-NULL default value */
2781 if( pOp->p5 ){
2782 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
2783 pLast--;
2784 nField--;
2787 #endif
2789 /* Loop through the elements that will make up the record to figure
2790 ** out how much space is required for the new record.
2792 pRec = pLast;
2794 assert( memIsValid(pRec) );
2795 serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
2796 if( pRec->flags & MEM_Zero ){
2797 if( serial_type==0 ){
2798 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
2799 ** table methods that never invoke sqlite3_result_xxxxx() while
2800 ** computing an unchanging column value in an UPDATE statement.
2801 ** Give such values a special internal-use-only serial-type of 10
2802 ** so that they can be passed through to xUpdate and have
2803 ** a true sqlite3_value_nochange(). */
2804 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
2805 serial_type = 10;
2806 }else if( nData ){
2807 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
2808 }else{
2809 nZero += pRec->u.nZero;
2810 len -= pRec->u.nZero;
2813 nData += len;
2814 testcase( serial_type==127 );
2815 testcase( serial_type==128 );
2816 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
2817 pRec->uTemp = serial_type;
2818 if( pRec==pData0 ) break;
2819 pRec--;
2820 }while(1);
2822 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
2823 ** which determines the total number of bytes in the header. The varint
2824 ** value is the size of the header in bytes including the size varint
2825 ** itself. */
2826 testcase( nHdr==126 );
2827 testcase( nHdr==127 );
2828 if( nHdr<=126 ){
2829 /* The common case */
2830 nHdr += 1;
2831 }else{
2832 /* Rare case of a really large header */
2833 nVarint = sqlite3VarintLen(nHdr);
2834 nHdr += nVarint;
2835 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
2837 nByte = nHdr+nData;
2838 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2839 goto too_big;
2842 /* Make sure the output register has a buffer large enough to store
2843 ** the new record. The output register (pOp->p3) is not allowed to
2844 ** be one of the input registers (because the following call to
2845 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2847 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
2848 goto no_mem;
2850 zNewRecord = (u8 *)pOut->z;
2852 /* Write the record */
2853 i = putVarint32(zNewRecord, nHdr);
2854 j = nHdr;
2855 assert( pData0<=pLast );
2856 pRec = pData0;
2858 serial_type = pRec->uTemp;
2859 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
2860 ** additional varints, one per column. */
2861 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
2862 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
2863 ** immediately follow the header. */
2864 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
2865 }while( (++pRec)<=pLast );
2866 assert( i==nHdr );
2867 assert( j==nByte );
2869 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2870 pOut->n = (int)nByte;
2871 pOut->flags = MEM_Blob;
2872 if( nZero ){
2873 pOut->u.nZero = nZero;
2874 pOut->flags |= MEM_Zero;
2876 REGISTER_TRACE(pOp->p3, pOut);
2877 UPDATE_MAX_BLOBSIZE(pOut);
2878 break;
2881 /* Opcode: Count P1 P2 * * *
2882 ** Synopsis: r[P2]=count()
2884 ** Store the number of entries (an integer value) in the table or index
2885 ** opened by cursor P1 in register P2
2887 #ifndef SQLITE_OMIT_BTREECOUNT
2888 case OP_Count: { /* out2 */
2889 i64 nEntry;
2890 BtCursor *pCrsr;
2892 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
2893 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
2894 assert( pCrsr );
2895 nEntry = 0; /* Not needed. Only used to silence a warning. */
2896 rc = sqlite3BtreeCount(pCrsr, &nEntry);
2897 if( rc ) goto abort_due_to_error;
2898 pOut = out2Prerelease(p, pOp);
2899 pOut->u.i = nEntry;
2900 break;
2902 #endif
2904 /* Opcode: Savepoint P1 * * P4 *
2906 ** Open, release or rollback the savepoint named by parameter P4, depending
2907 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2908 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2910 case OP_Savepoint: {
2911 int p1; /* Value of P1 operand */
2912 char *zName; /* Name of savepoint */
2913 int nName;
2914 Savepoint *pNew;
2915 Savepoint *pSavepoint;
2916 Savepoint *pTmp;
2917 int iSavepoint;
2918 int ii;
2920 p1 = pOp->p1;
2921 zName = pOp->p4.z;
2923 /* Assert that the p1 parameter is valid. Also that if there is no open
2924 ** transaction, then there cannot be any savepoints.
2926 assert( db->pSavepoint==0 || db->autoCommit==0 );
2927 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
2928 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
2929 assert( checkSavepointCount(db) );
2930 assert( p->bIsReader );
2932 if( p1==SAVEPOINT_BEGIN ){
2933 if( db->nVdbeWrite>0 ){
2934 /* A new savepoint cannot be created if there are active write
2935 ** statements (i.e. open read/write incremental blob handles).
2937 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
2938 rc = SQLITE_BUSY;
2939 }else{
2940 nName = sqlite3Strlen30(zName);
2942 #ifndef SQLITE_OMIT_VIRTUALTABLE
2943 /* This call is Ok even if this savepoint is actually a transaction
2944 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2945 ** If this is a transaction savepoint being opened, it is guaranteed
2946 ** that the db->aVTrans[] array is empty. */
2947 assert( db->autoCommit==0 || db->nVTrans==0 );
2948 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
2949 db->nStatement+db->nSavepoint);
2950 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2951 #endif
2953 /* Create a new savepoint structure. */
2954 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
2955 if( pNew ){
2956 pNew->zName = (char *)&pNew[1];
2957 memcpy(pNew->zName, zName, nName+1);
2959 /* If there is no open transaction, then mark this as a special
2960 ** "transaction savepoint". */
2961 if( db->autoCommit ){
2962 db->autoCommit = 0;
2963 db->isTransactionSavepoint = 1;
2964 }else{
2965 db->nSavepoint++;
2968 /* Link the new savepoint into the database handle's list. */
2969 pNew->pNext = db->pSavepoint;
2970 db->pSavepoint = pNew;
2971 pNew->nDeferredCons = db->nDeferredCons;
2972 pNew->nDeferredImmCons = db->nDeferredImmCons;
2975 }else{
2976 iSavepoint = 0;
2978 /* Find the named savepoint. If there is no such savepoint, then an
2979 ** an error is returned to the user. */
2980 for(
2981 pSavepoint = db->pSavepoint;
2982 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
2983 pSavepoint = pSavepoint->pNext
2985 iSavepoint++;
2987 if( !pSavepoint ){
2988 sqlite3VdbeError(p, "no such savepoint: %s", zName);
2989 rc = SQLITE_ERROR;
2990 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
2991 /* It is not possible to release (commit) a savepoint if there are
2992 ** active write statements.
2994 sqlite3VdbeError(p, "cannot release savepoint - "
2995 "SQL statements in progress");
2996 rc = SQLITE_BUSY;
2997 }else{
2999 /* Determine whether or not this is a transaction savepoint. If so,
3000 ** and this is a RELEASE command, then the current transaction
3001 ** is committed.
3003 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3004 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3005 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3006 goto vdbe_return;
3008 db->autoCommit = 1;
3009 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3010 p->pc = (int)(pOp - aOp);
3011 db->autoCommit = 0;
3012 p->rc = rc = SQLITE_BUSY;
3013 goto vdbe_return;
3015 db->isTransactionSavepoint = 0;
3016 rc = p->rc;
3017 }else{
3018 int isSchemaChange;
3019 iSavepoint = db->nSavepoint - iSavepoint - 1;
3020 if( p1==SAVEPOINT_ROLLBACK ){
3021 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3022 for(ii=0; ii<db->nDb; ii++){
3023 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3024 SQLITE_ABORT_ROLLBACK,
3025 isSchemaChange==0);
3026 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3028 }else{
3029 isSchemaChange = 0;
3031 for(ii=0; ii<db->nDb; ii++){
3032 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3033 if( rc!=SQLITE_OK ){
3034 goto abort_due_to_error;
3037 if( isSchemaChange ){
3038 sqlite3ExpirePreparedStatements(db);
3039 sqlite3ResetAllSchemasOfConnection(db);
3040 db->mDbFlags |= DBFLAG_SchemaChange;
3044 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3045 ** savepoints nested inside of the savepoint being operated on. */
3046 while( db->pSavepoint!=pSavepoint ){
3047 pTmp = db->pSavepoint;
3048 db->pSavepoint = pTmp->pNext;
3049 sqlite3DbFree(db, pTmp);
3050 db->nSavepoint--;
3053 /* If it is a RELEASE, then destroy the savepoint being operated on
3054 ** too. If it is a ROLLBACK TO, then set the number of deferred
3055 ** constraint violations present in the database to the value stored
3056 ** when the savepoint was created. */
3057 if( p1==SAVEPOINT_RELEASE ){
3058 assert( pSavepoint==db->pSavepoint );
3059 db->pSavepoint = pSavepoint->pNext;
3060 sqlite3DbFree(db, pSavepoint);
3061 if( !isTransaction ){
3062 db->nSavepoint--;
3064 }else{
3065 db->nDeferredCons = pSavepoint->nDeferredCons;
3066 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3069 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3070 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3071 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3075 if( rc ) goto abort_due_to_error;
3077 break;
3080 /* Opcode: AutoCommit P1 P2 * * *
3082 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3083 ** back any currently active btree transactions. If there are any active
3084 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3085 ** there are active writing VMs or active VMs that use shared cache.
3087 ** This instruction causes the VM to halt.
3089 case OP_AutoCommit: {
3090 int desiredAutoCommit;
3091 int iRollback;
3093 desiredAutoCommit = pOp->p1;
3094 iRollback = pOp->p2;
3095 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3096 assert( desiredAutoCommit==1 || iRollback==0 );
3097 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3098 assert( p->bIsReader );
3100 if( desiredAutoCommit!=db->autoCommit ){
3101 if( iRollback ){
3102 assert( desiredAutoCommit==1 );
3103 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3104 db->autoCommit = 1;
3105 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3106 /* If this instruction implements a COMMIT and other VMs are writing
3107 ** return an error indicating that the other VMs must complete first.
3109 sqlite3VdbeError(p, "cannot commit transaction - "
3110 "SQL statements in progress");
3111 rc = SQLITE_BUSY;
3112 goto abort_due_to_error;
3113 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3114 goto vdbe_return;
3115 }else{
3116 db->autoCommit = (u8)desiredAutoCommit;
3118 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3119 p->pc = (int)(pOp - aOp);
3120 db->autoCommit = (u8)(1-desiredAutoCommit);
3121 p->rc = rc = SQLITE_BUSY;
3122 goto vdbe_return;
3124 assert( db->nStatement==0 );
3125 sqlite3CloseSavepoints(db);
3126 if( p->rc==SQLITE_OK ){
3127 rc = SQLITE_DONE;
3128 }else{
3129 rc = SQLITE_ERROR;
3131 goto vdbe_return;
3132 }else{
3133 sqlite3VdbeError(p,
3134 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3135 (iRollback)?"cannot rollback - no transaction is active":
3136 "cannot commit - no transaction is active"));
3138 rc = SQLITE_ERROR;
3139 goto abort_due_to_error;
3141 break;
3144 /* Opcode: Transaction P1 P2 P3 P4 P5
3146 ** Begin a transaction on database P1 if a transaction is not already
3147 ** active.
3148 ** If P2 is non-zero, then a write-transaction is started, or if a
3149 ** read-transaction is already active, it is upgraded to a write-transaction.
3150 ** If P2 is zero, then a read-transaction is started.
3152 ** P1 is the index of the database file on which the transaction is
3153 ** started. Index 0 is the main database file and index 1 is the
3154 ** file used for temporary tables. Indices of 2 or more are used for
3155 ** attached databases.
3157 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3158 ** true (this flag is set if the Vdbe may modify more than one row and may
3159 ** throw an ABORT exception), a statement transaction may also be opened.
3160 ** More specifically, a statement transaction is opened iff the database
3161 ** connection is currently not in autocommit mode, or if there are other
3162 ** active statements. A statement transaction allows the changes made by this
3163 ** VDBE to be rolled back after an error without having to roll back the
3164 ** entire transaction. If no error is encountered, the statement transaction
3165 ** will automatically commit when the VDBE halts.
3167 ** If P5!=0 then this opcode also checks the schema cookie against P3
3168 ** and the schema generation counter against P4.
3169 ** The cookie changes its value whenever the database schema changes.
3170 ** This operation is used to detect when that the cookie has changed
3171 ** and that the current process needs to reread the schema. If the schema
3172 ** cookie in P3 differs from the schema cookie in the database header or
3173 ** if the schema generation counter in P4 differs from the current
3174 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3175 ** halts. The sqlite3_step() wrapper function might then reprepare the
3176 ** statement and rerun it from the beginning.
3178 case OP_Transaction: {
3179 Btree *pBt;
3180 int iMeta;
3181 int iGen;
3183 assert( p->bIsReader );
3184 assert( p->readOnly==0 || pOp->p2==0 );
3185 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3186 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3187 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3188 rc = SQLITE_READONLY;
3189 goto abort_due_to_error;
3191 pBt = db->aDb[pOp->p1].pBt;
3193 if( pBt ){
3194 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
3195 testcase( rc==SQLITE_BUSY_SNAPSHOT );
3196 testcase( rc==SQLITE_BUSY_RECOVERY );
3197 if( rc!=SQLITE_OK ){
3198 if( (rc&0xff)==SQLITE_BUSY ){
3199 p->pc = (int)(pOp - aOp);
3200 p->rc = rc;
3201 goto vdbe_return;
3203 goto abort_due_to_error;
3206 if( pOp->p2 && p->usesStmtJournal
3207 && (db->autoCommit==0 || db->nVdbeRead>1)
3209 assert( sqlite3BtreeIsInTrans(pBt) );
3210 if( p->iStatement==0 ){
3211 assert( db->nStatement>=0 && db->nSavepoint>=0 );
3212 db->nStatement++;
3213 p->iStatement = db->nSavepoint + db->nStatement;
3216 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3217 if( rc==SQLITE_OK ){
3218 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3221 /* Store the current value of the database handles deferred constraint
3222 ** counter. If the statement transaction needs to be rolled back,
3223 ** the value of this counter needs to be restored too. */
3224 p->nStmtDefCons = db->nDeferredCons;
3225 p->nStmtDefImmCons = db->nDeferredImmCons;
3228 /* Gather the schema version number for checking:
3229 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3230 ** version is checked to ensure that the schema has not changed since the
3231 ** SQL statement was prepared.
3233 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
3234 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
3235 }else{
3236 iGen = iMeta = 0;
3238 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3239 if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
3240 sqlite3DbFree(db, p->zErrMsg);
3241 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3242 /* If the schema-cookie from the database file matches the cookie
3243 ** stored with the in-memory representation of the schema, do
3244 ** not reload the schema from the database file.
3246 ** If virtual-tables are in use, this is not just an optimization.
3247 ** Often, v-tables store their data in other SQLite tables, which
3248 ** are queried from within xNext() and other v-table methods using
3249 ** prepared queries. If such a query is out-of-date, we do not want to
3250 ** discard the database schema, as the user code implementing the
3251 ** v-table would have to be ready for the sqlite3_vtab structure itself
3252 ** to be invalidated whenever sqlite3_step() is called from within
3253 ** a v-table method.
3255 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3256 sqlite3ResetOneSchema(db, pOp->p1);
3258 p->expired = 1;
3259 rc = SQLITE_SCHEMA;
3261 if( rc ) goto abort_due_to_error;
3262 break;
3265 /* Opcode: ReadCookie P1 P2 P3 * *
3267 ** Read cookie number P3 from database P1 and write it into register P2.
3268 ** P3==1 is the schema version. P3==2 is the database format.
3269 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3270 ** the main database file and P1==1 is the database file used to store
3271 ** temporary tables.
3273 ** There must be a read-lock on the database (either a transaction
3274 ** must be started or there must be an open cursor) before
3275 ** executing this instruction.
3277 case OP_ReadCookie: { /* out2 */
3278 int iMeta;
3279 int iDb;
3280 int iCookie;
3282 assert( p->bIsReader );
3283 iDb = pOp->p1;
3284 iCookie = pOp->p3;
3285 assert( pOp->p3<SQLITE_N_BTREE_META );
3286 assert( iDb>=0 && iDb<db->nDb );
3287 assert( db->aDb[iDb].pBt!=0 );
3288 assert( DbMaskTest(p->btreeMask, iDb) );
3290 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3291 pOut = out2Prerelease(p, pOp);
3292 pOut->u.i = iMeta;
3293 break;
3296 /* Opcode: SetCookie P1 P2 P3 * *
3298 ** Write the integer value P3 into cookie number P2 of database P1.
3299 ** P2==1 is the schema version. P2==2 is the database format.
3300 ** P2==3 is the recommended pager cache
3301 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3302 ** database file used to store temporary tables.
3304 ** A transaction must be started before executing this opcode.
3306 case OP_SetCookie: {
3307 Db *pDb;
3308 assert( pOp->p2<SQLITE_N_BTREE_META );
3309 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3310 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3311 assert( p->readOnly==0 );
3312 pDb = &db->aDb[pOp->p1];
3313 assert( pDb->pBt!=0 );
3314 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3315 /* See note about index shifting on OP_ReadCookie */
3316 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3317 if( pOp->p2==BTREE_SCHEMA_VERSION ){
3318 /* When the schema cookie changes, record the new cookie internally */
3319 pDb->pSchema->schema_cookie = pOp->p3;
3320 db->mDbFlags |= DBFLAG_SchemaChange;
3321 }else if( pOp->p2==BTREE_FILE_FORMAT ){
3322 /* Record changes in the file format */
3323 pDb->pSchema->file_format = pOp->p3;
3325 if( pOp->p1==1 ){
3326 /* Invalidate all prepared statements whenever the TEMP database
3327 ** schema is changed. Ticket #1644 */
3328 sqlite3ExpirePreparedStatements(db);
3329 p->expired = 0;
3331 if( rc ) goto abort_due_to_error;
3332 break;
3335 /* Opcode: OpenRead P1 P2 P3 P4 P5
3336 ** Synopsis: root=P2 iDb=P3
3338 ** Open a read-only cursor for the database table whose root page is
3339 ** P2 in a database file. The database file is determined by P3.
3340 ** P3==0 means the main database, P3==1 means the database used for
3341 ** temporary tables, and P3>1 means used the corresponding attached
3342 ** database. Give the new cursor an identifier of P1. The P1
3343 ** values need not be contiguous but all P1 values should be small integers.
3344 ** It is an error for P1 to be negative.
3346 ** If P5!=0 then use the content of register P2 as the root page, not
3347 ** the value of P2 itself.
3349 ** There will be a read lock on the database whenever there is an
3350 ** open cursor. If the database was unlocked prior to this instruction
3351 ** then a read lock is acquired as part of this instruction. A read
3352 ** lock allows other processes to read the database but prohibits
3353 ** any other process from modifying the database. The read lock is
3354 ** released when all cursors are closed. If this instruction attempts
3355 ** to get a read lock but fails, the script terminates with an
3356 ** SQLITE_BUSY error code.
3358 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3359 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3360 ** structure, then said structure defines the content and collating
3361 ** sequence of the index being opened. Otherwise, if P4 is an integer
3362 ** value, it is set to the number of columns in the table.
3364 ** See also: OpenWrite, ReopenIdx
3366 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3367 ** Synopsis: root=P2 iDb=P3
3369 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
3370 ** checks to see if the cursor on P1 is already open with a root page
3371 ** number of P2 and if it is this opcode becomes a no-op. In other words,
3372 ** if the cursor is already open, do not reopen it.
3374 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
3375 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
3376 ** every other ReopenIdx or OpenRead for the same cursor number.
3378 ** See the OpenRead opcode documentation for additional information.
3380 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3381 ** Synopsis: root=P2 iDb=P3
3383 ** Open a read/write cursor named P1 on the table or index whose root
3384 ** page is P2. Or if P5!=0 use the content of register P2 to find the
3385 ** root page.
3387 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3388 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3389 ** structure, then said structure defines the content and collating
3390 ** sequence of the index being opened. Otherwise, if P4 is an integer
3391 ** value, it is set to the number of columns in the table, or to the
3392 ** largest index of any column of the table that is actually used.
3394 ** This instruction works just like OpenRead except that it opens the cursor
3395 ** in read/write mode. For a given table, there can be one or more read-only
3396 ** cursors or a single read/write cursor but not both.
3398 ** See also OpenRead.
3400 case OP_ReopenIdx: {
3401 int nField;
3402 KeyInfo *pKeyInfo;
3403 int p2;
3404 int iDb;
3405 int wrFlag;
3406 Btree *pX;
3407 VdbeCursor *pCur;
3408 Db *pDb;
3410 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3411 assert( pOp->p4type==P4_KEYINFO );
3412 pCur = p->apCsr[pOp->p1];
3413 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3414 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
3415 goto open_cursor_set_hints;
3417 /* If the cursor is not currently open or is open on a different
3418 ** index, then fall through into OP_OpenRead to force a reopen */
3419 case OP_OpenRead:
3420 case OP_OpenWrite:
3422 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3423 assert( p->bIsReader );
3424 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3425 || p->readOnly==0 );
3427 if( p->expired ){
3428 rc = SQLITE_ABORT_ROLLBACK;
3429 goto abort_due_to_error;
3432 nField = 0;
3433 pKeyInfo = 0;
3434 p2 = pOp->p2;
3435 iDb = pOp->p3;
3436 assert( iDb>=0 && iDb<db->nDb );
3437 assert( DbMaskTest(p->btreeMask, iDb) );
3438 pDb = &db->aDb[iDb];
3439 pX = pDb->pBt;
3440 assert( pX!=0 );
3441 if( pOp->opcode==OP_OpenWrite ){
3442 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
3443 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
3444 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3445 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3446 p->minWriteFileFormat = pDb->pSchema->file_format;
3448 }else{
3449 wrFlag = 0;
3451 if( pOp->p5 & OPFLAG_P2ISREG ){
3452 assert( p2>0 );
3453 assert( p2<=(p->nMem+1 - p->nCursor) );
3454 pIn2 = &aMem[p2];
3455 assert( memIsValid(pIn2) );
3456 assert( (pIn2->flags & MEM_Int)!=0 );
3457 sqlite3VdbeMemIntegerify(pIn2);
3458 p2 = (int)pIn2->u.i;
3459 /* The p2 value always comes from a prior OP_CreateBtree opcode and
3460 ** that opcode will always set the p2 value to 2 or more or else fail.
3461 ** If there were a failure, the prepared statement would have halted
3462 ** before reaching this instruction. */
3463 assert( p2>=2 );
3465 if( pOp->p4type==P4_KEYINFO ){
3466 pKeyInfo = pOp->p4.pKeyInfo;
3467 assert( pKeyInfo->enc==ENC(db) );
3468 assert( pKeyInfo->db==db );
3469 nField = pKeyInfo->nAllField;
3470 }else if( pOp->p4type==P4_INT32 ){
3471 nField = pOp->p4.i;
3473 assert( pOp->p1>=0 );
3474 assert( nField>=0 );
3475 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3476 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
3477 if( pCur==0 ) goto no_mem;
3478 pCur->nullRow = 1;
3479 pCur->isOrdered = 1;
3480 pCur->pgnoRoot = p2;
3481 #ifdef SQLITE_DEBUG
3482 pCur->wrFlag = wrFlag;
3483 #endif
3484 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
3485 pCur->pKeyInfo = pKeyInfo;
3486 /* Set the VdbeCursor.isTable variable. Previous versions of
3487 ** SQLite used to check if the root-page flags were sane at this point
3488 ** and report database corruption if they were not, but this check has
3489 ** since moved into the btree layer. */
3490 pCur->isTable = pOp->p4type!=P4_KEYINFO;
3492 open_cursor_set_hints:
3493 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3494 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
3495 testcase( pOp->p5 & OPFLAG_BULKCSR );
3496 #ifdef SQLITE_ENABLE_CURSOR_HINTS
3497 testcase( pOp->p2 & OPFLAG_SEEKEQ );
3498 #endif
3499 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
3500 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
3501 if( rc ) goto abort_due_to_error;
3502 break;
3505 /* Opcode: OpenDup P1 P2 * * *
3507 ** Open a new cursor P1 that points to the same ephemeral table as
3508 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
3509 ** opcode. Only ephemeral cursors may be duplicated.
3511 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
3513 case OP_OpenDup: {
3514 VdbeCursor *pOrig; /* The original cursor to be duplicated */
3515 VdbeCursor *pCx; /* The new cursor */
3517 pOrig = p->apCsr[pOp->p2];
3518 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
3520 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
3521 if( pCx==0 ) goto no_mem;
3522 pCx->nullRow = 1;
3523 pCx->isEphemeral = 1;
3524 pCx->pKeyInfo = pOrig->pKeyInfo;
3525 pCx->isTable = pOrig->isTable;
3526 rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
3527 pCx->pKeyInfo, pCx->uc.pCursor);
3528 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
3529 ** opened for a database. Since there is already an open cursor when this
3530 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
3531 assert( rc==SQLITE_OK );
3532 break;
3536 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3537 ** Synopsis: nColumn=P2
3539 ** Open a new cursor P1 to a transient table.
3540 ** The cursor is always opened read/write even if
3541 ** the main database is read-only. The ephemeral
3542 ** table is deleted automatically when the cursor is closed.
3544 ** P2 is the number of columns in the ephemeral table.
3545 ** The cursor points to a BTree table if P4==0 and to a BTree index
3546 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3547 ** that defines the format of keys in the index.
3549 ** The P5 parameter can be a mask of the BTREE_* flags defined
3550 ** in btree.h. These flags control aspects of the operation of
3551 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3552 ** added automatically.
3554 /* Opcode: OpenAutoindex P1 P2 * P4 *
3555 ** Synopsis: nColumn=P2
3557 ** This opcode works the same as OP_OpenEphemeral. It has a
3558 ** different name to distinguish its use. Tables created using
3559 ** by this opcode will be used for automatically created transient
3560 ** indices in joins.
3562 case OP_OpenAutoindex:
3563 case OP_OpenEphemeral: {
3564 VdbeCursor *pCx;
3565 KeyInfo *pKeyInfo;
3567 static const int vfsFlags =
3568 SQLITE_OPEN_READWRITE |
3569 SQLITE_OPEN_CREATE |
3570 SQLITE_OPEN_EXCLUSIVE |
3571 SQLITE_OPEN_DELETEONCLOSE |
3572 SQLITE_OPEN_TRANSIENT_DB;
3573 assert( pOp->p1>=0 );
3574 assert( pOp->p2>=0 );
3575 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
3576 if( pCx==0 ) goto no_mem;
3577 pCx->nullRow = 1;
3578 pCx->isEphemeral = 1;
3579 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
3580 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
3581 if( rc==SQLITE_OK ){
3582 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
3584 if( rc==SQLITE_OK ){
3585 /* If a transient index is required, create it by calling
3586 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3587 ** opening it. If a transient table is required, just use the
3588 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3590 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3591 int pgno;
3592 assert( pOp->p4type==P4_KEYINFO );
3593 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
3594 if( rc==SQLITE_OK ){
3595 assert( pgno==MASTER_ROOT+1 );
3596 assert( pKeyInfo->db==db );
3597 assert( pKeyInfo->enc==ENC(db) );
3598 rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
3599 pKeyInfo, pCx->uc.pCursor);
3601 pCx->isTable = 0;
3602 }else{
3603 rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
3604 0, pCx->uc.pCursor);
3605 pCx->isTable = 1;
3608 if( rc ) goto abort_due_to_error;
3609 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3610 break;
3613 /* Opcode: SorterOpen P1 P2 P3 P4 *
3615 ** This opcode works like OP_OpenEphemeral except that it opens
3616 ** a transient index that is specifically designed to sort large
3617 ** tables using an external merge-sort algorithm.
3619 ** If argument P3 is non-zero, then it indicates that the sorter may
3620 ** assume that a stable sort considering the first P3 fields of each
3621 ** key is sufficient to produce the required results.
3623 case OP_SorterOpen: {
3624 VdbeCursor *pCx;
3626 assert( pOp->p1>=0 );
3627 assert( pOp->p2>=0 );
3628 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
3629 if( pCx==0 ) goto no_mem;
3630 pCx->pKeyInfo = pOp->p4.pKeyInfo;
3631 assert( pCx->pKeyInfo->db==db );
3632 assert( pCx->pKeyInfo->enc==ENC(db) );
3633 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
3634 if( rc ) goto abort_due_to_error;
3635 break;
3638 /* Opcode: SequenceTest P1 P2 * * *
3639 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3641 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3642 ** to P2. Regardless of whether or not the jump is taken, increment the
3643 ** the sequence value.
3645 case OP_SequenceTest: {
3646 VdbeCursor *pC;
3647 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3648 pC = p->apCsr[pOp->p1];
3649 assert( isSorter(pC) );
3650 if( (pC->seqCount++)==0 ){
3651 goto jump_to_p2;
3653 break;
3656 /* Opcode: OpenPseudo P1 P2 P3 * *
3657 ** Synopsis: P3 columns in r[P2]
3659 ** Open a new cursor that points to a fake table that contains a single
3660 ** row of data. The content of that one row is the content of memory
3661 ** register P2. In other words, cursor P1 becomes an alias for the
3662 ** MEM_Blob content contained in register P2.
3664 ** A pseudo-table created by this opcode is used to hold a single
3665 ** row output from the sorter so that the row can be decomposed into
3666 ** individual columns using the OP_Column opcode. The OP_Column opcode
3667 ** is the only cursor opcode that works with a pseudo-table.
3669 ** P3 is the number of fields in the records that will be stored by
3670 ** the pseudo-table.
3672 case OP_OpenPseudo: {
3673 VdbeCursor *pCx;
3675 assert( pOp->p1>=0 );
3676 assert( pOp->p3>=0 );
3677 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
3678 if( pCx==0 ) goto no_mem;
3679 pCx->nullRow = 1;
3680 pCx->seekResult = pOp->p2;
3681 pCx->isTable = 1;
3682 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
3683 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
3684 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
3685 ** which is a performance optimization */
3686 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
3687 assert( pOp->p5==0 );
3688 break;
3691 /* Opcode: Close P1 * * * *
3693 ** Close a cursor previously opened as P1. If P1 is not
3694 ** currently open, this instruction is a no-op.
3696 case OP_Close: {
3697 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3698 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
3699 p->apCsr[pOp->p1] = 0;
3700 break;
3703 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3704 /* Opcode: ColumnsUsed P1 * * P4 *
3706 ** This opcode (which only exists if SQLite was compiled with
3707 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
3708 ** table or index for cursor P1 are used. P4 is a 64-bit integer
3709 ** (P4_INT64) in which the first 63 bits are one for each of the
3710 ** first 63 columns of the table or index that are actually used
3711 ** by the cursor. The high-order bit is set if any column after
3712 ** the 64th is used.
3714 case OP_ColumnsUsed: {
3715 VdbeCursor *pC;
3716 pC = p->apCsr[pOp->p1];
3717 assert( pC->eCurType==CURTYPE_BTREE );
3718 pC->maskUsed = *(u64*)pOp->p4.pI64;
3719 break;
3721 #endif
3723 /* Opcode: SeekGE P1 P2 P3 P4 *
3724 ** Synopsis: key=r[P3@P4]
3726 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3727 ** use the value in register P3 as the key. If cursor P1 refers
3728 ** to an SQL index, then P3 is the first in an array of P4 registers
3729 ** that are used as an unpacked index key.
3731 ** Reposition cursor P1 so that it points to the smallest entry that
3732 ** is greater than or equal to the key value. If there are no records
3733 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3735 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3736 ** opcode will always land on a record that equally equals the key, or
3737 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3738 ** opcode must be followed by an IdxLE opcode with the same arguments.
3739 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
3740 ** IdxLE opcode will be used on subsequent loop iterations.
3742 ** This opcode leaves the cursor configured to move in forward order,
3743 ** from the beginning toward the end. In other words, the cursor is
3744 ** configured to use Next, not Prev.
3746 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3748 /* Opcode: SeekGT P1 P2 P3 P4 *
3749 ** Synopsis: key=r[P3@P4]
3751 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3752 ** use the value in register P3 as a key. If cursor P1 refers
3753 ** to an SQL index, then P3 is the first in an array of P4 registers
3754 ** that are used as an unpacked index key.
3756 ** Reposition cursor P1 so that it points to the smallest entry that
3757 ** is greater than the key value. If there are no records greater than
3758 ** the key and P2 is not zero, then jump to P2.
3760 ** This opcode leaves the cursor configured to move in forward order,
3761 ** from the beginning toward the end. In other words, the cursor is
3762 ** configured to use Next, not Prev.
3764 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3766 /* Opcode: SeekLT P1 P2 P3 P4 *
3767 ** Synopsis: key=r[P3@P4]
3769 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3770 ** use the value in register P3 as a key. If cursor P1 refers
3771 ** to an SQL index, then P3 is the first in an array of P4 registers
3772 ** that are used as an unpacked index key.
3774 ** Reposition cursor P1 so that it points to the largest entry that
3775 ** is less than the key value. If there are no records less than
3776 ** the key and P2 is not zero, then jump to P2.
3778 ** This opcode leaves the cursor configured to move in reverse order,
3779 ** from the end toward the beginning. In other words, the cursor is
3780 ** configured to use Prev, not Next.
3782 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3784 /* Opcode: SeekLE P1 P2 P3 P4 *
3785 ** Synopsis: key=r[P3@P4]
3787 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3788 ** use the value in register P3 as a key. If cursor P1 refers
3789 ** to an SQL index, then P3 is the first in an array of P4 registers
3790 ** that are used as an unpacked index key.
3792 ** Reposition cursor P1 so that it points to the largest entry that
3793 ** is less than or equal to the key value. If there are no records
3794 ** less than or equal to the key and P2 is not zero, then jump to P2.
3796 ** This opcode leaves the cursor configured to move in reverse order,
3797 ** from the end toward the beginning. In other words, the cursor is
3798 ** configured to use Prev, not Next.
3800 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3801 ** opcode will always land on a record that equally equals the key, or
3802 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3803 ** opcode must be followed by an IdxGE opcode with the same arguments.
3804 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
3805 ** IdxGE opcode will be used on subsequent loop iterations.
3807 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3809 case OP_SeekLT: /* jump, in3 */
3810 case OP_SeekLE: /* jump, in3 */
3811 case OP_SeekGE: /* jump, in3 */
3812 case OP_SeekGT: { /* jump, in3 */
3813 int res; /* Comparison result */
3814 int oc; /* Opcode */
3815 VdbeCursor *pC; /* The cursor to seek */
3816 UnpackedRecord r; /* The key to seek for */
3817 int nField; /* Number of columns or fields in the key */
3818 i64 iKey; /* The rowid we are to seek to */
3819 int eqOnly; /* Only interested in == results */
3821 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3822 assert( pOp->p2!=0 );
3823 pC = p->apCsr[pOp->p1];
3824 assert( pC!=0 );
3825 assert( pC->eCurType==CURTYPE_BTREE );
3826 assert( OP_SeekLE == OP_SeekLT+1 );
3827 assert( OP_SeekGE == OP_SeekLT+2 );
3828 assert( OP_SeekGT == OP_SeekLT+3 );
3829 assert( pC->isOrdered );
3830 assert( pC->uc.pCursor!=0 );
3831 oc = pOp->opcode;
3832 eqOnly = 0;
3833 pC->nullRow = 0;
3834 #ifdef SQLITE_DEBUG
3835 pC->seekOp = pOp->opcode;
3836 #endif
3838 if( pC->isTable ){
3839 /* The BTREE_SEEK_EQ flag is only set on index cursors */
3840 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
3841 || CORRUPT_DB );
3843 /* The input value in P3 might be of any type: integer, real, string,
3844 ** blob, or NULL. But it needs to be an integer before we can do
3845 ** the seek, so convert it. */
3846 pIn3 = &aMem[pOp->p3];
3847 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
3848 applyNumericAffinity(pIn3, 0);
3850 iKey = sqlite3VdbeIntValue(pIn3);
3852 /* If the P3 value could not be converted into an integer without
3853 ** loss of information, then special processing is required... */
3854 if( (pIn3->flags & MEM_Int)==0 ){
3855 if( (pIn3->flags & MEM_Real)==0 ){
3856 /* If the P3 value cannot be converted into any kind of a number,
3857 ** then the seek is not possible, so jump to P2 */
3858 VdbeBranchTaken(1,2); goto jump_to_p2;
3859 break;
3862 /* If the approximation iKey is larger than the actual real search
3863 ** term, substitute >= for > and < for <=. e.g. if the search term
3864 ** is 4.9 and the integer approximation 5:
3866 ** (x > 4.9) -> (x >= 5)
3867 ** (x <= 4.9) -> (x < 5)
3869 if( pIn3->u.r<(double)iKey ){
3870 assert( OP_SeekGE==(OP_SeekGT-1) );
3871 assert( OP_SeekLT==(OP_SeekLE-1) );
3872 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
3873 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
3876 /* If the approximation iKey is smaller than the actual real search
3877 ** term, substitute <= for < and > for >=. */
3878 else if( pIn3->u.r>(double)iKey ){
3879 assert( OP_SeekLE==(OP_SeekLT+1) );
3880 assert( OP_SeekGT==(OP_SeekGE+1) );
3881 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
3882 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
3885 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
3886 pC->movetoTarget = iKey; /* Used by OP_Delete */
3887 if( rc!=SQLITE_OK ){
3888 goto abort_due_to_error;
3890 }else{
3891 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
3892 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
3893 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
3895 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
3896 eqOnly = 1;
3897 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
3898 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
3899 assert( pOp[1].p1==pOp[0].p1 );
3900 assert( pOp[1].p2==pOp[0].p2 );
3901 assert( pOp[1].p3==pOp[0].p3 );
3902 assert( pOp[1].p4.i==pOp[0].p4.i );
3905 nField = pOp->p4.i;
3906 assert( pOp->p4type==P4_INT32 );
3907 assert( nField>0 );
3908 r.pKeyInfo = pC->pKeyInfo;
3909 r.nField = (u16)nField;
3911 /* The next line of code computes as follows, only faster:
3912 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3913 ** r.default_rc = -1;
3914 ** }else{
3915 ** r.default_rc = +1;
3916 ** }
3918 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
3919 assert( oc!=OP_SeekGT || r.default_rc==-1 );
3920 assert( oc!=OP_SeekLE || r.default_rc==-1 );
3921 assert( oc!=OP_SeekGE || r.default_rc==+1 );
3922 assert( oc!=OP_SeekLT || r.default_rc==+1 );
3924 r.aMem = &aMem[pOp->p3];
3925 #ifdef SQLITE_DEBUG
3926 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3927 #endif
3928 r.eqSeen = 0;
3929 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
3930 if( rc!=SQLITE_OK ){
3931 goto abort_due_to_error;
3933 if( eqOnly && r.eqSeen==0 ){
3934 assert( res!=0 );
3935 goto seek_not_found;
3938 pC->deferredMoveto = 0;
3939 pC->cacheStatus = CACHE_STALE;
3940 #ifdef SQLITE_TEST
3941 sqlite3_search_count++;
3942 #endif
3943 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
3944 if( res<0 || (res==0 && oc==OP_SeekGT) ){
3945 res = 0;
3946 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
3947 if( rc!=SQLITE_OK ){
3948 if( rc==SQLITE_DONE ){
3949 rc = SQLITE_OK;
3950 res = 1;
3951 }else{
3952 goto abort_due_to_error;
3955 }else{
3956 res = 0;
3958 }else{
3959 assert( oc==OP_SeekLT || oc==OP_SeekLE );
3960 if( res>0 || (res==0 && oc==OP_SeekLT) ){
3961 res = 0;
3962 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
3963 if( rc!=SQLITE_OK ){
3964 if( rc==SQLITE_DONE ){
3965 rc = SQLITE_OK;
3966 res = 1;
3967 }else{
3968 goto abort_due_to_error;
3971 }else{
3972 /* res might be negative because the table is empty. Check to
3973 ** see if this is the case.
3975 res = sqlite3BtreeEof(pC->uc.pCursor);
3978 seek_not_found:
3979 assert( pOp->p2>0 );
3980 VdbeBranchTaken(res!=0,2);
3981 if( res ){
3982 goto jump_to_p2;
3983 }else if( eqOnly ){
3984 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
3985 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
3987 break;
3990 /* Opcode: Found P1 P2 P3 P4 *
3991 ** Synopsis: key=r[P3@P4]
3993 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
3994 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3995 ** record.
3997 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
3998 ** is a prefix of any entry in P1 then a jump is made to P2 and
3999 ** P1 is left pointing at the matching entry.
4001 ** This operation leaves the cursor in a state where it can be
4002 ** advanced in the forward direction. The Next instruction will work,
4003 ** but not the Prev instruction.
4005 ** See also: NotFound, NoConflict, NotExists. SeekGe
4007 /* Opcode: NotFound P1 P2 P3 P4 *
4008 ** Synopsis: key=r[P3@P4]
4010 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4011 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4012 ** record.
4014 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4015 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
4016 ** does contain an entry whose prefix matches the P3/P4 record then control
4017 ** falls through to the next instruction and P1 is left pointing at the
4018 ** matching entry.
4020 ** This operation leaves the cursor in a state where it cannot be
4021 ** advanced in either direction. In other words, the Next and Prev
4022 ** opcodes do not work after this operation.
4024 ** See also: Found, NotExists, NoConflict
4026 /* Opcode: NoConflict P1 P2 P3 P4 *
4027 ** Synopsis: key=r[P3@P4]
4029 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4030 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4031 ** record.
4033 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4034 ** contains any NULL value, jump immediately to P2. If all terms of the
4035 ** record are not-NULL then a check is done to determine if any row in the
4036 ** P1 index btree has a matching key prefix. If there are no matches, jump
4037 ** immediately to P2. If there is a match, fall through and leave the P1
4038 ** cursor pointing to the matching row.
4040 ** This opcode is similar to OP_NotFound with the exceptions that the
4041 ** branch is always taken if any part of the search key input is NULL.
4043 ** This operation leaves the cursor in a state where it cannot be
4044 ** advanced in either direction. In other words, the Next and Prev
4045 ** opcodes do not work after this operation.
4047 ** See also: NotFound, Found, NotExists
4049 case OP_NoConflict: /* jump, in3 */
4050 case OP_NotFound: /* jump, in3 */
4051 case OP_Found: { /* jump, in3 */
4052 int alreadyExists;
4053 int takeJump;
4054 int ii;
4055 VdbeCursor *pC;
4056 int res;
4057 UnpackedRecord *pFree;
4058 UnpackedRecord *pIdxKey;
4059 UnpackedRecord r;
4061 #ifdef SQLITE_TEST
4062 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4063 #endif
4065 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4066 assert( pOp->p4type==P4_INT32 );
4067 pC = p->apCsr[pOp->p1];
4068 assert( pC!=0 );
4069 #ifdef SQLITE_DEBUG
4070 pC->seekOp = pOp->opcode;
4071 #endif
4072 pIn3 = &aMem[pOp->p3];
4073 assert( pC->eCurType==CURTYPE_BTREE );
4074 assert( pC->uc.pCursor!=0 );
4075 assert( pC->isTable==0 );
4076 if( pOp->p4.i>0 ){
4077 r.pKeyInfo = pC->pKeyInfo;
4078 r.nField = (u16)pOp->p4.i;
4079 r.aMem = pIn3;
4080 #ifdef SQLITE_DEBUG
4081 for(ii=0; ii<r.nField; ii++){
4082 assert( memIsValid(&r.aMem[ii]) );
4083 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4084 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4086 #endif
4087 pIdxKey = &r;
4088 pFree = 0;
4089 }else{
4090 assert( pIn3->flags & MEM_Blob );
4091 rc = ExpandBlob(pIn3);
4092 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4093 if( rc ) goto no_mem;
4094 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4095 if( pIdxKey==0 ) goto no_mem;
4096 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4098 pIdxKey->default_rc = 0;
4099 takeJump = 0;
4100 if( pOp->opcode==OP_NoConflict ){
4101 /* For the OP_NoConflict opcode, take the jump if any of the
4102 ** input fields are NULL, since any key with a NULL will not
4103 ** conflict */
4104 for(ii=0; ii<pIdxKey->nField; ii++){
4105 if( pIdxKey->aMem[ii].flags & MEM_Null ){
4106 takeJump = 1;
4107 break;
4111 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
4112 if( pFree ) sqlite3DbFreeNN(db, pFree);
4113 if( rc!=SQLITE_OK ){
4114 goto abort_due_to_error;
4116 pC->seekResult = res;
4117 alreadyExists = (res==0);
4118 pC->nullRow = 1-alreadyExists;
4119 pC->deferredMoveto = 0;
4120 pC->cacheStatus = CACHE_STALE;
4121 if( pOp->opcode==OP_Found ){
4122 VdbeBranchTaken(alreadyExists!=0,2);
4123 if( alreadyExists ) goto jump_to_p2;
4124 }else{
4125 VdbeBranchTaken(takeJump||alreadyExists==0,2);
4126 if( takeJump || !alreadyExists ) goto jump_to_p2;
4128 break;
4131 /* Opcode: SeekRowid P1 P2 P3 * *
4132 ** Synopsis: intkey=r[P3]
4134 ** P1 is the index of a cursor open on an SQL table btree (with integer
4135 ** keys). If register P3 does not contain an integer or if P1 does not
4136 ** contain a record with rowid P3 then jump immediately to P2.
4137 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4138 ** a record with rowid P3 then
4139 ** leave the cursor pointing at that record and fall through to the next
4140 ** instruction.
4142 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4143 ** the P3 register must be guaranteed to contain an integer value. With this
4144 ** opcode, register P3 might not contain an integer.
4146 ** The OP_NotFound opcode performs the same operation on index btrees
4147 ** (with arbitrary multi-value keys).
4149 ** This opcode leaves the cursor in a state where it cannot be advanced
4150 ** in either direction. In other words, the Next and Prev opcodes will
4151 ** not work following this opcode.
4153 ** See also: Found, NotFound, NoConflict, SeekRowid
4155 /* Opcode: NotExists P1 P2 P3 * *
4156 ** Synopsis: intkey=r[P3]
4158 ** P1 is the index of a cursor open on an SQL table btree (with integer
4159 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4160 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4161 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4162 ** leave the cursor pointing at that record and fall through to the next
4163 ** instruction.
4165 ** The OP_SeekRowid opcode performs the same operation but also allows the
4166 ** P3 register to contain a non-integer value, in which case the jump is
4167 ** always taken. This opcode requires that P3 always contain an integer.
4169 ** The OP_NotFound opcode performs the same operation on index btrees
4170 ** (with arbitrary multi-value keys).
4172 ** This opcode leaves the cursor in a state where it cannot be advanced
4173 ** in either direction. In other words, the Next and Prev opcodes will
4174 ** not work following this opcode.
4176 ** See also: Found, NotFound, NoConflict, SeekRowid
4178 case OP_SeekRowid: { /* jump, in3 */
4179 VdbeCursor *pC;
4180 BtCursor *pCrsr;
4181 int res;
4182 u64 iKey;
4184 pIn3 = &aMem[pOp->p3];
4185 if( (pIn3->flags & MEM_Int)==0 ){
4186 applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
4187 if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
4189 /* Fall through into OP_NotExists */
4190 case OP_NotExists: /* jump, in3 */
4191 pIn3 = &aMem[pOp->p3];
4192 assert( pIn3->flags & MEM_Int );
4193 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4194 pC = p->apCsr[pOp->p1];
4195 assert( pC!=0 );
4196 #ifdef SQLITE_DEBUG
4197 pC->seekOp = 0;
4198 #endif
4199 assert( pC->isTable );
4200 assert( pC->eCurType==CURTYPE_BTREE );
4201 pCrsr = pC->uc.pCursor;
4202 assert( pCrsr!=0 );
4203 res = 0;
4204 iKey = pIn3->u.i;
4205 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
4206 assert( rc==SQLITE_OK || res==0 );
4207 pC->movetoTarget = iKey; /* Used by OP_Delete */
4208 pC->nullRow = 0;
4209 pC->cacheStatus = CACHE_STALE;
4210 pC->deferredMoveto = 0;
4211 VdbeBranchTaken(res!=0,2);
4212 pC->seekResult = res;
4213 if( res!=0 ){
4214 assert( rc==SQLITE_OK );
4215 if( pOp->p2==0 ){
4216 rc = SQLITE_CORRUPT_BKPT;
4217 }else{
4218 goto jump_to_p2;
4221 if( rc ) goto abort_due_to_error;
4222 break;
4225 /* Opcode: Sequence P1 P2 * * *
4226 ** Synopsis: r[P2]=cursor[P1].ctr++
4228 ** Find the next available sequence number for cursor P1.
4229 ** Write the sequence number into register P2.
4230 ** The sequence number on the cursor is incremented after this
4231 ** instruction.
4233 case OP_Sequence: { /* out2 */
4234 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4235 assert( p->apCsr[pOp->p1]!=0 );
4236 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
4237 pOut = out2Prerelease(p, pOp);
4238 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
4239 break;
4243 /* Opcode: NewRowid P1 P2 P3 * *
4244 ** Synopsis: r[P2]=rowid
4246 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4247 ** The record number is not previously used as a key in the database
4248 ** table that cursor P1 points to. The new record number is written
4249 ** written to register P2.
4251 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4252 ** the largest previously generated record number. No new record numbers are
4253 ** allowed to be less than this value. When this value reaches its maximum,
4254 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4255 ** generated record number. This P3 mechanism is used to help implement the
4256 ** AUTOINCREMENT feature.
4258 case OP_NewRowid: { /* out2 */
4259 i64 v; /* The new rowid */
4260 VdbeCursor *pC; /* Cursor of table to get the new rowid */
4261 int res; /* Result of an sqlite3BtreeLast() */
4262 int cnt; /* Counter to limit the number of searches */
4263 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
4264 VdbeFrame *pFrame; /* Root frame of VDBE */
4266 v = 0;
4267 res = 0;
4268 pOut = out2Prerelease(p, pOp);
4269 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4270 pC = p->apCsr[pOp->p1];
4271 assert( pC!=0 );
4272 assert( pC->eCurType==CURTYPE_BTREE );
4273 assert( pC->uc.pCursor!=0 );
4275 /* The next rowid or record number (different terms for the same
4276 ** thing) is obtained in a two-step algorithm.
4278 ** First we attempt to find the largest existing rowid and add one
4279 ** to that. But if the largest existing rowid is already the maximum
4280 ** positive integer, we have to fall through to the second
4281 ** probabilistic algorithm
4283 ** The second algorithm is to select a rowid at random and see if
4284 ** it already exists in the table. If it does not exist, we have
4285 ** succeeded. If the random rowid does exist, we select a new one
4286 ** and try again, up to 100 times.
4288 assert( pC->isTable );
4290 #ifdef SQLITE_32BIT_ROWID
4291 # define MAX_ROWID 0x7fffffff
4292 #else
4293 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4294 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4295 ** to provide the constant while making all compilers happy.
4297 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4298 #endif
4300 if( !pC->useRandomRowid ){
4301 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4302 if( rc!=SQLITE_OK ){
4303 goto abort_due_to_error;
4305 if( res ){
4306 v = 1; /* IMP: R-61914-48074 */
4307 }else{
4308 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
4309 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4310 if( v>=MAX_ROWID ){
4311 pC->useRandomRowid = 1;
4312 }else{
4313 v++; /* IMP: R-29538-34987 */
4318 #ifndef SQLITE_OMIT_AUTOINCREMENT
4319 if( pOp->p3 ){
4320 /* Assert that P3 is a valid memory cell. */
4321 assert( pOp->p3>0 );
4322 if( p->pFrame ){
4323 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4324 /* Assert that P3 is a valid memory cell. */
4325 assert( pOp->p3<=pFrame->nMem );
4326 pMem = &pFrame->aMem[pOp->p3];
4327 }else{
4328 /* Assert that P3 is a valid memory cell. */
4329 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
4330 pMem = &aMem[pOp->p3];
4331 memAboutToChange(p, pMem);
4333 assert( memIsValid(pMem) );
4335 REGISTER_TRACE(pOp->p3, pMem);
4336 sqlite3VdbeMemIntegerify(pMem);
4337 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
4338 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4339 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
4340 goto abort_due_to_error;
4342 if( v<pMem->u.i+1 ){
4343 v = pMem->u.i + 1;
4345 pMem->u.i = v;
4347 #endif
4348 if( pC->useRandomRowid ){
4349 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4350 ** largest possible integer (9223372036854775807) then the database
4351 ** engine starts picking positive candidate ROWIDs at random until
4352 ** it finds one that is not previously used. */
4353 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
4354 ** an AUTOINCREMENT table. */
4355 cnt = 0;
4357 sqlite3_randomness(sizeof(v), &v);
4358 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
4359 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
4360 0, &res))==SQLITE_OK)
4361 && (res==0)
4362 && (++cnt<100));
4363 if( rc ) goto abort_due_to_error;
4364 if( res==0 ){
4365 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
4366 goto abort_due_to_error;
4368 assert( v>0 ); /* EV: R-40812-03570 */
4370 pC->deferredMoveto = 0;
4371 pC->cacheStatus = CACHE_STALE;
4373 pOut->u.i = v;
4374 break;
4377 /* Opcode: Insert P1 P2 P3 P4 P5
4378 ** Synopsis: intkey=r[P3] data=r[P2]
4380 ** Write an entry into the table of cursor P1. A new entry is
4381 ** created if it doesn't already exist or the data for an existing
4382 ** entry is overwritten. The data is the value MEM_Blob stored in register
4383 ** number P2. The key is stored in register P3. The key must
4384 ** be a MEM_Int.
4386 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4387 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
4388 ** then rowid is stored for subsequent return by the
4389 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4391 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
4392 ** run faster by avoiding an unnecessary seek on cursor P1. However,
4393 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
4394 ** seeks on the cursor or if the most recent seek used a key equal to P3.
4396 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4397 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
4398 ** is part of an INSERT operation. The difference is only important to
4399 ** the update hook.
4401 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
4402 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
4403 ** following a successful insert.
4405 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4406 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4407 ** and register P2 becomes ephemeral. If the cursor is changed, the
4408 ** value of register P2 will then change. Make sure this does not
4409 ** cause any problems.)
4411 ** This instruction only works on tables. The equivalent instruction
4412 ** for indices is OP_IdxInsert.
4414 /* Opcode: InsertInt P1 P2 P3 P4 P5
4415 ** Synopsis: intkey=P3 data=r[P2]
4417 ** This works exactly like OP_Insert except that the key is the
4418 ** integer value P3, not the value of the integer stored in register P3.
4420 case OP_Insert:
4421 case OP_InsertInt: {
4422 Mem *pData; /* MEM cell holding data for the record to be inserted */
4423 Mem *pKey; /* MEM cell holding key for the record */
4424 VdbeCursor *pC; /* Cursor to table into which insert is written */
4425 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
4426 const char *zDb; /* database name - used by the update hook */
4427 Table *pTab; /* Table structure - used by update and pre-update hooks */
4428 BtreePayload x; /* Payload to be inserted */
4430 pData = &aMem[pOp->p2];
4431 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4432 assert( memIsValid(pData) );
4433 pC = p->apCsr[pOp->p1];
4434 assert( pC!=0 );
4435 assert( pC->eCurType==CURTYPE_BTREE );
4436 assert( pC->uc.pCursor!=0 );
4437 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
4438 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
4439 REGISTER_TRACE(pOp->p2, pData);
4441 if( pOp->opcode==OP_Insert ){
4442 pKey = &aMem[pOp->p3];
4443 assert( pKey->flags & MEM_Int );
4444 assert( memIsValid(pKey) );
4445 REGISTER_TRACE(pOp->p3, pKey);
4446 x.nKey = pKey->u.i;
4447 }else{
4448 assert( pOp->opcode==OP_InsertInt );
4449 x.nKey = pOp->p3;
4452 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4453 assert( pC->iDb>=0 );
4454 zDb = db->aDb[pC->iDb].zDbSName;
4455 pTab = pOp->p4.pTab;
4456 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
4457 }else{
4458 pTab = 0;
4459 zDb = 0; /* Not needed. Silence a compiler warning. */
4462 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4463 /* Invoke the pre-update hook, if any */
4464 if( pTab ){
4465 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
4466 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
4468 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
4469 /* Prevent post-update hook from running in cases when it should not */
4470 pTab = 0;
4473 if( pOp->p5 & OPFLAG_ISNOOP ) break;
4474 #endif
4476 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4477 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
4478 assert( pData->flags & (MEM_Blob|MEM_Str) );
4479 x.pData = pData->z;
4480 x.nData = pData->n;
4481 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
4482 if( pData->flags & MEM_Zero ){
4483 x.nZero = pData->u.nZero;
4484 }else{
4485 x.nZero = 0;
4487 x.pKey = 0;
4488 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
4489 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
4491 pC->deferredMoveto = 0;
4492 pC->cacheStatus = CACHE_STALE;
4494 /* Invoke the update-hook if required. */
4495 if( rc ) goto abort_due_to_error;
4496 if( pTab ){
4497 assert( db->xUpdateCallback!=0 );
4498 assert( pTab->aCol!=0 );
4499 db->xUpdateCallback(db->pUpdateArg,
4500 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
4501 zDb, pTab->zName, x.nKey);
4503 break;
4506 /* Opcode: Delete P1 P2 P3 P4 P5
4508 ** Delete the record at which the P1 cursor is currently pointing.
4510 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
4511 ** the cursor will be left pointing at either the next or the previous
4512 ** record in the table. If it is left pointing at the next record, then
4513 ** the next Next instruction will be a no-op. As a result, in this case
4514 ** it is ok to delete a record from within a Next loop. If
4515 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
4516 ** left in an undefined state.
4518 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
4519 ** delete one of several associated with deleting a table row and all its
4520 ** associated index entries. Exactly one of those deletes is the "primary"
4521 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
4522 ** marked with the AUXDELETE flag.
4524 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
4525 ** change count is incremented (otherwise not).
4527 ** P1 must not be pseudo-table. It has to be a real table with
4528 ** multiple rows.
4530 ** If P4 is not NULL then it points to a Table object. In this case either
4531 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
4532 ** have been positioned using OP_NotFound prior to invoking this opcode in
4533 ** this case. Specifically, if one is configured, the pre-update hook is
4534 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
4535 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
4537 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
4538 ** of the memory cell that contains the value that the rowid of the row will
4539 ** be set to by the update.
4541 case OP_Delete: {
4542 VdbeCursor *pC;
4543 const char *zDb;
4544 Table *pTab;
4545 int opflags;
4547 opflags = pOp->p2;
4548 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4549 pC = p->apCsr[pOp->p1];
4550 assert( pC!=0 );
4551 assert( pC->eCurType==CURTYPE_BTREE );
4552 assert( pC->uc.pCursor!=0 );
4553 assert( pC->deferredMoveto==0 );
4555 #ifdef SQLITE_DEBUG
4556 if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
4557 /* If p5 is zero, the seek operation that positioned the cursor prior to
4558 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
4559 ** the row that is being deleted */
4560 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4561 assert( pC->movetoTarget==iKey );
4563 #endif
4565 /* If the update-hook or pre-update-hook will be invoked, set zDb to
4566 ** the name of the db to pass as to it. Also set local pTab to a copy
4567 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
4568 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
4569 ** VdbeCursor.movetoTarget to the current rowid. */
4570 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
4571 assert( pC->iDb>=0 );
4572 assert( pOp->p4.pTab!=0 );
4573 zDb = db->aDb[pC->iDb].zDbSName;
4574 pTab = pOp->p4.pTab;
4575 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
4576 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4578 }else{
4579 zDb = 0; /* Not needed. Silence a compiler warning. */
4580 pTab = 0; /* Not needed. Silence a compiler warning. */
4583 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4584 /* Invoke the pre-update-hook if required. */
4585 if( db->xPreUpdateCallback && pOp->p4.pTab ){
4586 assert( !(opflags & OPFLAG_ISUPDATE)
4587 || HasRowid(pTab)==0
4588 || (aMem[pOp->p3].flags & MEM_Int)
4590 sqlite3VdbePreUpdateHook(p, pC,
4591 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
4592 zDb, pTab, pC->movetoTarget,
4593 pOp->p3
4596 if( opflags & OPFLAG_ISNOOP ) break;
4597 #endif
4599 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
4600 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
4601 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
4602 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
4604 #ifdef SQLITE_DEBUG
4605 if( p->pFrame==0 ){
4606 if( pC->isEphemeral==0
4607 && (pOp->p5 & OPFLAG_AUXDELETE)==0
4608 && (pC->wrFlag & OPFLAG_FORDELETE)==0
4610 nExtraDelete++;
4612 if( pOp->p2 & OPFLAG_NCHANGE ){
4613 nExtraDelete--;
4616 #endif
4618 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
4619 pC->cacheStatus = CACHE_STALE;
4620 pC->seekResult = 0;
4621 if( rc ) goto abort_due_to_error;
4623 /* Invoke the update-hook if required. */
4624 if( opflags & OPFLAG_NCHANGE ){
4625 p->nChange++;
4626 if( db->xUpdateCallback && HasRowid(pTab) ){
4627 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
4628 pC->movetoTarget);
4629 assert( pC->iDb>=0 );
4633 break;
4635 /* Opcode: ResetCount * * * * *
4637 ** The value of the change counter is copied to the database handle
4638 ** change counter (returned by subsequent calls to sqlite3_changes()).
4639 ** Then the VMs internal change counter resets to 0.
4640 ** This is used by trigger programs.
4642 case OP_ResetCount: {
4643 sqlite3VdbeSetChanges(db, p->nChange);
4644 p->nChange = 0;
4645 break;
4648 /* Opcode: SorterCompare P1 P2 P3 P4
4649 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4651 ** P1 is a sorter cursor. This instruction compares a prefix of the
4652 ** record blob in register P3 against a prefix of the entry that
4653 ** the sorter cursor currently points to. Only the first P4 fields
4654 ** of r[P3] and the sorter record are compared.
4656 ** If either P3 or the sorter contains a NULL in one of their significant
4657 ** fields (not counting the P4 fields at the end which are ignored) then
4658 ** the comparison is assumed to be equal.
4660 ** Fall through to next instruction if the two records compare equal to
4661 ** each other. Jump to P2 if they are different.
4663 case OP_SorterCompare: {
4664 VdbeCursor *pC;
4665 int res;
4666 int nKeyCol;
4668 pC = p->apCsr[pOp->p1];
4669 assert( isSorter(pC) );
4670 assert( pOp->p4type==P4_INT32 );
4671 pIn3 = &aMem[pOp->p3];
4672 nKeyCol = pOp->p4.i;
4673 res = 0;
4674 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
4675 VdbeBranchTaken(res!=0,2);
4676 if( rc ) goto abort_due_to_error;
4677 if( res ) goto jump_to_p2;
4678 break;
4681 /* Opcode: SorterData P1 P2 P3 * *
4682 ** Synopsis: r[P2]=data
4684 ** Write into register P2 the current sorter data for sorter cursor P1.
4685 ** Then clear the column header cache on cursor P3.
4687 ** This opcode is normally use to move a record out of the sorter and into
4688 ** a register that is the source for a pseudo-table cursor created using
4689 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4690 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4691 ** us from having to issue a separate NullRow instruction to clear that cache.
4693 case OP_SorterData: {
4694 VdbeCursor *pC;
4696 pOut = &aMem[pOp->p2];
4697 pC = p->apCsr[pOp->p1];
4698 assert( isSorter(pC) );
4699 rc = sqlite3VdbeSorterRowkey(pC, pOut);
4700 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
4701 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4702 if( rc ) goto abort_due_to_error;
4703 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
4704 break;
4707 /* Opcode: RowData P1 P2 P3 * *
4708 ** Synopsis: r[P2]=data
4710 ** Write into register P2 the complete row content for the row at
4711 ** which cursor P1 is currently pointing.
4712 ** There is no interpretation of the data.
4713 ** It is just copied onto the P2 register exactly as
4714 ** it is found in the database file.
4716 ** If cursor P1 is an index, then the content is the key of the row.
4717 ** If cursor P2 is a table, then the content extracted is the data.
4719 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4720 ** of a real table, not a pseudo-table.
4722 ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
4723 ** into the database page. That means that the content of the output
4724 ** register will be invalidated as soon as the cursor moves - including
4725 ** moves caused by other cursors that "save" the the current cursors
4726 ** position in order that they can write to the same table. If P3==0
4727 ** then a copy of the data is made into memory. P3!=0 is faster, but
4728 ** P3==0 is safer.
4730 ** If P3!=0 then the content of the P2 register is unsuitable for use
4731 ** in OP_Result and any OP_Result will invalidate the P2 register content.
4732 ** The P2 register content is invalidated by opcodes like OP_Function or
4733 ** by any use of another cursor pointing to the same table.
4735 case OP_RowData: {
4736 VdbeCursor *pC;
4737 BtCursor *pCrsr;
4738 u32 n;
4740 pOut = out2Prerelease(p, pOp);
4742 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4743 pC = p->apCsr[pOp->p1];
4744 assert( pC!=0 );
4745 assert( pC->eCurType==CURTYPE_BTREE );
4746 assert( isSorter(pC)==0 );
4747 assert( pC->nullRow==0 );
4748 assert( pC->uc.pCursor!=0 );
4749 pCrsr = pC->uc.pCursor;
4751 /* The OP_RowData opcodes always follow OP_NotExists or
4752 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
4753 ** that might invalidate the cursor.
4754 ** If this where not the case, on of the following assert()s
4755 ** would fail. Should this ever change (because of changes in the code
4756 ** generator) then the fix would be to insert a call to
4757 ** sqlite3VdbeCursorMoveto().
4759 assert( pC->deferredMoveto==0 );
4760 assert( sqlite3BtreeCursorIsValid(pCrsr) );
4761 #if 0 /* Not required due to the previous to assert() statements */
4762 rc = sqlite3VdbeCursorMoveto(pC);
4763 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4764 #endif
4766 n = sqlite3BtreePayloadSize(pCrsr);
4767 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
4768 goto too_big;
4770 testcase( n==0 );
4771 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
4772 if( rc ) goto abort_due_to_error;
4773 if( !pOp->p3 ) Deephemeralize(pOut);
4774 UPDATE_MAX_BLOBSIZE(pOut);
4775 REGISTER_TRACE(pOp->p2, pOut);
4776 break;
4779 /* Opcode: Rowid P1 P2 * * *
4780 ** Synopsis: r[P2]=rowid
4782 ** Store in register P2 an integer which is the key of the table entry that
4783 ** P1 is currently point to.
4785 ** P1 can be either an ordinary table or a virtual table. There used to
4786 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4787 ** one opcode now works for both table types.
4789 case OP_Rowid: { /* out2 */
4790 VdbeCursor *pC;
4791 i64 v;
4792 sqlite3_vtab *pVtab;
4793 const sqlite3_module *pModule;
4795 pOut = out2Prerelease(p, pOp);
4796 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4797 pC = p->apCsr[pOp->p1];
4798 assert( pC!=0 );
4799 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
4800 if( pC->nullRow ){
4801 pOut->flags = MEM_Null;
4802 break;
4803 }else if( pC->deferredMoveto ){
4804 v = pC->movetoTarget;
4805 #ifndef SQLITE_OMIT_VIRTUALTABLE
4806 }else if( pC->eCurType==CURTYPE_VTAB ){
4807 assert( pC->uc.pVCur!=0 );
4808 pVtab = pC->uc.pVCur->pVtab;
4809 pModule = pVtab->pModule;
4810 assert( pModule->xRowid );
4811 rc = pModule->xRowid(pC->uc.pVCur, &v);
4812 sqlite3VtabImportErrmsg(p, pVtab);
4813 if( rc ) goto abort_due_to_error;
4814 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4815 }else{
4816 assert( pC->eCurType==CURTYPE_BTREE );
4817 assert( pC->uc.pCursor!=0 );
4818 rc = sqlite3VdbeCursorRestore(pC);
4819 if( rc ) goto abort_due_to_error;
4820 if( pC->nullRow ){
4821 pOut->flags = MEM_Null;
4822 break;
4824 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4826 pOut->u.i = v;
4827 break;
4830 /* Opcode: NullRow P1 * * * *
4832 ** Move the cursor P1 to a null row. Any OP_Column operations
4833 ** that occur while the cursor is on the null row will always
4834 ** write a NULL.
4836 case OP_NullRow: {
4837 VdbeCursor *pC;
4839 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4840 pC = p->apCsr[pOp->p1];
4841 assert( pC!=0 );
4842 pC->nullRow = 1;
4843 pC->cacheStatus = CACHE_STALE;
4844 if( pC->eCurType==CURTYPE_BTREE ){
4845 assert( pC->uc.pCursor!=0 );
4846 sqlite3BtreeClearCursor(pC->uc.pCursor);
4848 break;
4851 /* Opcode: SeekEnd P1 * * * *
4853 ** Position cursor P1 at the end of the btree for the purpose of
4854 ** appending a new entry onto the btree.
4856 ** It is assumed that the cursor is used only for appending and so
4857 ** if the cursor is valid, then the cursor must already be pointing
4858 ** at the end of the btree and so no changes are made to
4859 ** the cursor.
4861 /* Opcode: Last P1 P2 * * *
4863 ** The next use of the Rowid or Column or Prev instruction for P1
4864 ** will refer to the last entry in the database table or index.
4865 ** If the table or index is empty and P2>0, then jump immediately to P2.
4866 ** If P2 is 0 or if the table or index is not empty, fall through
4867 ** to the following instruction.
4869 ** This opcode leaves the cursor configured to move in reverse order,
4870 ** from the end toward the beginning. In other words, the cursor is
4871 ** configured to use Prev, not Next.
4873 case OP_SeekEnd:
4874 case OP_Last: { /* jump */
4875 VdbeCursor *pC;
4876 BtCursor *pCrsr;
4877 int res;
4879 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4880 pC = p->apCsr[pOp->p1];
4881 assert( pC!=0 );
4882 assert( pC->eCurType==CURTYPE_BTREE );
4883 pCrsr = pC->uc.pCursor;
4884 res = 0;
4885 assert( pCrsr!=0 );
4886 #ifdef SQLITE_DEBUG
4887 pC->seekOp = pOp->opcode;
4888 #endif
4889 if( pOp->opcode==OP_SeekEnd ){
4890 assert( pOp->p2==0 );
4891 pC->seekResult = -1;
4892 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
4893 break;
4896 rc = sqlite3BtreeLast(pCrsr, &res);
4897 pC->nullRow = (u8)res;
4898 pC->deferredMoveto = 0;
4899 pC->cacheStatus = CACHE_STALE;
4900 if( rc ) goto abort_due_to_error;
4901 if( pOp->p2>0 ){
4902 VdbeBranchTaken(res!=0,2);
4903 if( res ) goto jump_to_p2;
4905 break;
4908 /* Opcode: IfSmaller P1 P2 P3 * *
4910 ** Estimate the number of rows in the table P1. Jump to P2 if that
4911 ** estimate is less than approximately 2**(0.1*P3).
4913 case OP_IfSmaller: { /* jump */
4914 VdbeCursor *pC;
4915 BtCursor *pCrsr;
4916 int res;
4917 i64 sz;
4919 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4920 pC = p->apCsr[pOp->p1];
4921 assert( pC!=0 );
4922 pCrsr = pC->uc.pCursor;
4923 assert( pCrsr );
4924 rc = sqlite3BtreeFirst(pCrsr, &res);
4925 if( rc ) goto abort_due_to_error;
4926 if( res==0 ){
4927 sz = sqlite3BtreeRowCountEst(pCrsr);
4928 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
4930 VdbeBranchTaken(res!=0,2);
4931 if( res ) goto jump_to_p2;
4932 break;
4936 /* Opcode: SorterSort P1 P2 * * *
4938 ** After all records have been inserted into the Sorter object
4939 ** identified by P1, invoke this opcode to actually do the sorting.
4940 ** Jump to P2 if there are no records to be sorted.
4942 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
4943 ** for Sorter objects.
4945 /* Opcode: Sort P1 P2 * * *
4947 ** This opcode does exactly the same thing as OP_Rewind except that
4948 ** it increments an undocumented global variable used for testing.
4950 ** Sorting is accomplished by writing records into a sorting index,
4951 ** then rewinding that index and playing it back from beginning to
4952 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
4953 ** rewinding so that the global variable will be incremented and
4954 ** regression tests can determine whether or not the optimizer is
4955 ** correctly optimizing out sorts.
4957 case OP_SorterSort: /* jump */
4958 case OP_Sort: { /* jump */
4959 #ifdef SQLITE_TEST
4960 sqlite3_sort_count++;
4961 sqlite3_search_count--;
4962 #endif
4963 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
4964 /* Fall through into OP_Rewind */
4966 /* Opcode: Rewind P1 P2 * * *
4968 ** The next use of the Rowid or Column or Next instruction for P1
4969 ** will refer to the first entry in the database table or index.
4970 ** If the table or index is empty, jump immediately to P2.
4971 ** If the table or index is not empty, fall through to the following
4972 ** instruction.
4974 ** This opcode leaves the cursor configured to move in forward order,
4975 ** from the beginning toward the end. In other words, the cursor is
4976 ** configured to use Next, not Prev.
4978 case OP_Rewind: { /* jump */
4979 VdbeCursor *pC;
4980 BtCursor *pCrsr;
4981 int res;
4983 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4984 pC = p->apCsr[pOp->p1];
4985 assert( pC!=0 );
4986 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
4987 res = 1;
4988 #ifdef SQLITE_DEBUG
4989 pC->seekOp = OP_Rewind;
4990 #endif
4991 if( isSorter(pC) ){
4992 rc = sqlite3VdbeSorterRewind(pC, &res);
4993 }else{
4994 assert( pC->eCurType==CURTYPE_BTREE );
4995 pCrsr = pC->uc.pCursor;
4996 assert( pCrsr );
4997 rc = sqlite3BtreeFirst(pCrsr, &res);
4998 pC->deferredMoveto = 0;
4999 pC->cacheStatus = CACHE_STALE;
5001 if( rc ) goto abort_due_to_error;
5002 pC->nullRow = (u8)res;
5003 assert( pOp->p2>0 && pOp->p2<p->nOp );
5004 VdbeBranchTaken(res!=0,2);
5005 if( res ) goto jump_to_p2;
5006 break;
5009 /* Opcode: Next P1 P2 P3 P4 P5
5011 ** Advance cursor P1 so that it points to the next key/data pair in its
5012 ** table or index. If there are no more key/value pairs then fall through
5013 ** to the following instruction. But if the cursor advance was successful,
5014 ** jump immediately to P2.
5016 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5017 ** OP_Rewind opcode used to position the cursor. Next is not allowed
5018 ** to follow SeekLT, SeekLE, or OP_Last.
5020 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
5021 ** been opened prior to this opcode or the program will segfault.
5023 ** The P3 value is a hint to the btree implementation. If P3==1, that
5024 ** means P1 is an SQL index and that this instruction could have been
5025 ** omitted if that index had been unique. P3 is usually 0. P3 is
5026 ** always either 0 or 1.
5028 ** P4 is always of type P4_ADVANCE. The function pointer points to
5029 ** sqlite3BtreeNext().
5031 ** If P5 is positive and the jump is taken, then event counter
5032 ** number P5-1 in the prepared statement is incremented.
5034 ** See also: Prev, NextIfOpen
5036 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
5038 ** This opcode works just like Next except that if cursor P1 is not
5039 ** open it behaves a no-op.
5041 /* Opcode: Prev P1 P2 P3 P4 P5
5043 ** Back up cursor P1 so that it points to the previous key/data pair in its
5044 ** table or index. If there is no previous key/value pairs then fall through
5045 ** to the following instruction. But if the cursor backup was successful,
5046 ** jump immediately to P2.
5049 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5050 ** OP_Last opcode used to position the cursor. Prev is not allowed
5051 ** to follow SeekGT, SeekGE, or OP_Rewind.
5053 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
5054 ** not open then the behavior is undefined.
5056 ** The P3 value is a hint to the btree implementation. If P3==1, that
5057 ** means P1 is an SQL index and that this instruction could have been
5058 ** omitted if that index had been unique. P3 is usually 0. P3 is
5059 ** always either 0 or 1.
5061 ** P4 is always of type P4_ADVANCE. The function pointer points to
5062 ** sqlite3BtreePrevious().
5064 ** If P5 is positive and the jump is taken, then event counter
5065 ** number P5-1 in the prepared statement is incremented.
5067 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
5069 ** This opcode works just like Prev except that if cursor P1 is not
5070 ** open it behaves a no-op.
5072 /* Opcode: SorterNext P1 P2 * * P5
5074 ** This opcode works just like OP_Next except that P1 must be a
5075 ** sorter object for which the OP_SorterSort opcode has been
5076 ** invoked. This opcode advances the cursor to the next sorted
5077 ** record, or jumps to P2 if there are no more sorted records.
5079 case OP_SorterNext: { /* jump */
5080 VdbeCursor *pC;
5082 pC = p->apCsr[pOp->p1];
5083 assert( isSorter(pC) );
5084 rc = sqlite3VdbeSorterNext(db, pC);
5085 goto next_tail;
5086 case OP_PrevIfOpen: /* jump */
5087 case OP_NextIfOpen: /* jump */
5088 if( p->apCsr[pOp->p1]==0 ) break;
5089 /* Fall through */
5090 case OP_Prev: /* jump */
5091 case OP_Next: /* jump */
5092 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5093 assert( pOp->p5<ArraySize(p->aCounter) );
5094 pC = p->apCsr[pOp->p1];
5095 assert( pC!=0 );
5096 assert( pC->deferredMoveto==0 );
5097 assert( pC->eCurType==CURTYPE_BTREE );
5098 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5099 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5100 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
5101 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
5103 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
5104 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5105 assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
5106 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5107 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
5108 assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
5109 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5110 || pC->seekOp==OP_Last );
5112 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5113 next_tail:
5114 pC->cacheStatus = CACHE_STALE;
5115 VdbeBranchTaken(rc==SQLITE_OK,2);
5116 if( rc==SQLITE_OK ){
5117 pC->nullRow = 0;
5118 p->aCounter[pOp->p5]++;
5119 #ifdef SQLITE_TEST
5120 sqlite3_search_count++;
5121 #endif
5122 goto jump_to_p2_and_check_for_interrupt;
5124 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5125 rc = SQLITE_OK;
5126 pC->nullRow = 1;
5127 goto check_for_interrupt;
5130 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5131 ** Synopsis: key=r[P2]
5133 ** Register P2 holds an SQL index key made using the
5134 ** MakeRecord instructions. This opcode writes that key
5135 ** into the index P1. Data for the entry is nil.
5137 ** If P4 is not zero, then it is the number of values in the unpacked
5138 ** key of reg(P2). In that case, P3 is the index of the first register
5139 ** for the unpacked key. The availability of the unpacked key can sometimes
5140 ** be an optimization.
5142 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5143 ** that this insert is likely to be an append.
5145 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5146 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
5147 ** then the change counter is unchanged.
5149 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5150 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5151 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5152 ** seeks on the cursor or if the most recent seek used a key equivalent
5153 ** to P2.
5155 ** This instruction only works for indices. The equivalent instruction
5156 ** for tables is OP_Insert.
5158 /* Opcode: SorterInsert P1 P2 * * *
5159 ** Synopsis: key=r[P2]
5161 ** Register P2 holds an SQL index key made using the
5162 ** MakeRecord instructions. This opcode writes that key
5163 ** into the sorter P1. Data for the entry is nil.
5165 case OP_SorterInsert: /* in2 */
5166 case OP_IdxInsert: { /* in2 */
5167 VdbeCursor *pC;
5168 BtreePayload x;
5170 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5171 pC = p->apCsr[pOp->p1];
5172 assert( pC!=0 );
5173 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
5174 pIn2 = &aMem[pOp->p2];
5175 assert( pIn2->flags & MEM_Blob );
5176 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5177 assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
5178 assert( pC->isTable==0 );
5179 rc = ExpandBlob(pIn2);
5180 if( rc ) goto abort_due_to_error;
5181 if( pOp->opcode==OP_SorterInsert ){
5182 rc = sqlite3VdbeSorterWrite(pC, pIn2);
5183 }else{
5184 x.nKey = pIn2->n;
5185 x.pKey = pIn2->z;
5186 x.aMem = aMem + pOp->p3;
5187 x.nMem = (u16)pOp->p4.i;
5188 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5189 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
5190 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
5192 assert( pC->deferredMoveto==0 );
5193 pC->cacheStatus = CACHE_STALE;
5195 if( rc) goto abort_due_to_error;
5196 break;
5199 /* Opcode: IdxDelete P1 P2 P3 * *
5200 ** Synopsis: key=r[P2@P3]
5202 ** The content of P3 registers starting at register P2 form
5203 ** an unpacked index key. This opcode removes that entry from the
5204 ** index opened by cursor P1.
5206 case OP_IdxDelete: {
5207 VdbeCursor *pC;
5208 BtCursor *pCrsr;
5209 int res;
5210 UnpackedRecord r;
5212 assert( pOp->p3>0 );
5213 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
5214 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5215 pC = p->apCsr[pOp->p1];
5216 assert( pC!=0 );
5217 assert( pC->eCurType==CURTYPE_BTREE );
5218 pCrsr = pC->uc.pCursor;
5219 assert( pCrsr!=0 );
5220 assert( pOp->p5==0 );
5221 r.pKeyInfo = pC->pKeyInfo;
5222 r.nField = (u16)pOp->p3;
5223 r.default_rc = 0;
5224 r.aMem = &aMem[pOp->p2];
5225 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
5226 if( rc ) goto abort_due_to_error;
5227 if( res==0 ){
5228 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
5229 if( rc ) goto abort_due_to_error;
5231 assert( pC->deferredMoveto==0 );
5232 pC->cacheStatus = CACHE_STALE;
5233 pC->seekResult = 0;
5234 break;
5237 /* Opcode: DeferredSeek P1 * P3 P4 *
5238 ** Synopsis: Move P3 to P1.rowid if needed
5240 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5241 ** table. This opcode does a deferred seek of the P3 table cursor
5242 ** to the row that corresponds to the current row of P1.
5244 ** This is a deferred seek. Nothing actually happens until
5245 ** the cursor is used to read a record. That way, if no reads
5246 ** occur, no unnecessary I/O happens.
5248 ** P4 may be an array of integers (type P4_INTARRAY) containing
5249 ** one entry for each column in the P3 table. If array entry a(i)
5250 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5251 ** equivalent to performing the deferred seek and then reading column i
5252 ** from P1. This information is stored in P3 and used to redirect
5253 ** reads against P3 over to P1, thus possibly avoiding the need to
5254 ** seek and read cursor P3.
5256 /* Opcode: IdxRowid P1 P2 * * *
5257 ** Synopsis: r[P2]=rowid
5259 ** Write into register P2 an integer which is the last entry in the record at
5260 ** the end of the index key pointed to by cursor P1. This integer should be
5261 ** the rowid of the table entry to which this index entry points.
5263 ** See also: Rowid, MakeRecord.
5265 case OP_DeferredSeek:
5266 case OP_IdxRowid: { /* out2 */
5267 VdbeCursor *pC; /* The P1 index cursor */
5268 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
5269 i64 rowid; /* Rowid that P1 current points to */
5271 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5272 pC = p->apCsr[pOp->p1];
5273 assert( pC!=0 );
5274 assert( pC->eCurType==CURTYPE_BTREE );
5275 assert( pC->uc.pCursor!=0 );
5276 assert( pC->isTable==0 );
5277 assert( pC->deferredMoveto==0 );
5278 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
5280 /* The IdxRowid and Seek opcodes are combined because of the commonality
5281 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5282 rc = sqlite3VdbeCursorRestore(pC);
5284 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5285 ** out from under the cursor. That will never happens for an IdxRowid
5286 ** or Seek opcode */
5287 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
5289 if( !pC->nullRow ){
5290 rowid = 0; /* Not needed. Only used to silence a warning. */
5291 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
5292 if( rc!=SQLITE_OK ){
5293 goto abort_due_to_error;
5295 if( pOp->opcode==OP_DeferredSeek ){
5296 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
5297 pTabCur = p->apCsr[pOp->p3];
5298 assert( pTabCur!=0 );
5299 assert( pTabCur->eCurType==CURTYPE_BTREE );
5300 assert( pTabCur->uc.pCursor!=0 );
5301 assert( pTabCur->isTable );
5302 pTabCur->nullRow = 0;
5303 pTabCur->movetoTarget = rowid;
5304 pTabCur->deferredMoveto = 1;
5305 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
5306 pTabCur->aAltMap = pOp->p4.ai;
5307 pTabCur->pAltCursor = pC;
5308 }else{
5309 pOut = out2Prerelease(p, pOp);
5310 pOut->u.i = rowid;
5312 }else{
5313 assert( pOp->opcode==OP_IdxRowid );
5314 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
5316 break;
5319 /* Opcode: IdxGE P1 P2 P3 P4 P5
5320 ** Synopsis: key=r[P3@P4]
5322 ** The P4 register values beginning with P3 form an unpacked index
5323 ** key that omits the PRIMARY KEY. Compare this key value against the index
5324 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5325 ** fields at the end.
5327 ** If the P1 index entry is greater than or equal to the key value
5328 ** then jump to P2. Otherwise fall through to the next instruction.
5330 /* Opcode: IdxGT P1 P2 P3 P4 P5
5331 ** Synopsis: key=r[P3@P4]
5333 ** The P4 register values beginning with P3 form an unpacked index
5334 ** key that omits the PRIMARY KEY. Compare this key value against the index
5335 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5336 ** fields at the end.
5338 ** If the P1 index entry is greater than the key value
5339 ** then jump to P2. Otherwise fall through to the next instruction.
5341 /* Opcode: IdxLT P1 P2 P3 P4 P5
5342 ** Synopsis: key=r[P3@P4]
5344 ** The P4 register values beginning with P3 form an unpacked index
5345 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5346 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5347 ** ROWID on the P1 index.
5349 ** If the P1 index entry is less than the key value then jump to P2.
5350 ** Otherwise fall through to the next instruction.
5352 /* Opcode: IdxLE P1 P2 P3 P4 P5
5353 ** Synopsis: key=r[P3@P4]
5355 ** The P4 register values beginning with P3 form an unpacked index
5356 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5357 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5358 ** ROWID on the P1 index.
5360 ** If the P1 index entry is less than or equal to the key value then jump
5361 ** to P2. Otherwise fall through to the next instruction.
5363 case OP_IdxLE: /* jump */
5364 case OP_IdxGT: /* jump */
5365 case OP_IdxLT: /* jump */
5366 case OP_IdxGE: { /* jump */
5367 VdbeCursor *pC;
5368 int res;
5369 UnpackedRecord r;
5371 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5372 pC = p->apCsr[pOp->p1];
5373 assert( pC!=0 );
5374 assert( pC->isOrdered );
5375 assert( pC->eCurType==CURTYPE_BTREE );
5376 assert( pC->uc.pCursor!=0);
5377 assert( pC->deferredMoveto==0 );
5378 assert( pOp->p5==0 || pOp->p5==1 );
5379 assert( pOp->p4type==P4_INT32 );
5380 r.pKeyInfo = pC->pKeyInfo;
5381 r.nField = (u16)pOp->p4.i;
5382 if( pOp->opcode<OP_IdxLT ){
5383 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
5384 r.default_rc = -1;
5385 }else{
5386 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
5387 r.default_rc = 0;
5389 r.aMem = &aMem[pOp->p3];
5390 #ifdef SQLITE_DEBUG
5391 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
5392 #endif
5393 res = 0; /* Not needed. Only used to silence a warning. */
5394 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5395 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
5396 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
5397 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
5398 res = -res;
5399 }else{
5400 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
5401 res++;
5403 VdbeBranchTaken(res>0,2);
5404 if( rc ) goto abort_due_to_error;
5405 if( res>0 ) goto jump_to_p2;
5406 break;
5409 /* Opcode: Destroy P1 P2 P3 * *
5411 ** Delete an entire database table or index whose root page in the database
5412 ** file is given by P1.
5414 ** The table being destroyed is in the main database file if P3==0. If
5415 ** P3==1 then the table to be clear is in the auxiliary database file
5416 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5418 ** If AUTOVACUUM is enabled then it is possible that another root page
5419 ** might be moved into the newly deleted root page in order to keep all
5420 ** root pages contiguous at the beginning of the database. The former
5421 ** value of the root page that moved - its value before the move occurred -
5422 ** is stored in register P2. If no page movement was required (because the
5423 ** table being dropped was already the last one in the database) then a
5424 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
5425 ** is stored in register P2.
5427 ** This opcode throws an error if there are any active reader VMs when
5428 ** it is invoked. This is done to avoid the difficulty associated with
5429 ** updating existing cursors when a root page is moved in an AUTOVACUUM
5430 ** database. This error is thrown even if the database is not an AUTOVACUUM
5431 ** db in order to avoid introducing an incompatibility between autovacuum
5432 ** and non-autovacuum modes.
5434 ** See also: Clear
5436 case OP_Destroy: { /* out2 */
5437 int iMoved;
5438 int iDb;
5440 assert( p->readOnly==0 );
5441 assert( pOp->p1>1 );
5442 pOut = out2Prerelease(p, pOp);
5443 pOut->flags = MEM_Null;
5444 if( db->nVdbeRead > db->nVDestroy+1 ){
5445 rc = SQLITE_LOCKED;
5446 p->errorAction = OE_Abort;
5447 goto abort_due_to_error;
5448 }else{
5449 iDb = pOp->p3;
5450 assert( DbMaskTest(p->btreeMask, iDb) );
5451 iMoved = 0; /* Not needed. Only to silence a warning. */
5452 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
5453 pOut->flags = MEM_Int;
5454 pOut->u.i = iMoved;
5455 if( rc ) goto abort_due_to_error;
5456 #ifndef SQLITE_OMIT_AUTOVACUUM
5457 if( iMoved!=0 ){
5458 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
5459 /* All OP_Destroy operations occur on the same btree */
5460 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
5461 resetSchemaOnFault = iDb+1;
5463 #endif
5465 break;
5468 /* Opcode: Clear P1 P2 P3
5470 ** Delete all contents of the database table or index whose root page
5471 ** in the database file is given by P1. But, unlike Destroy, do not
5472 ** remove the table or index from the database file.
5474 ** The table being clear is in the main database file if P2==0. If
5475 ** P2==1 then the table to be clear is in the auxiliary database file
5476 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5478 ** If the P3 value is non-zero, then the table referred to must be an
5479 ** intkey table (an SQL table, not an index). In this case the row change
5480 ** count is incremented by the number of rows in the table being cleared.
5481 ** If P3 is greater than zero, then the value stored in register P3 is
5482 ** also incremented by the number of rows in the table being cleared.
5484 ** See also: Destroy
5486 case OP_Clear: {
5487 int nChange;
5489 nChange = 0;
5490 assert( p->readOnly==0 );
5491 assert( DbMaskTest(p->btreeMask, pOp->p2) );
5492 rc = sqlite3BtreeClearTable(
5493 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
5495 if( pOp->p3 ){
5496 p->nChange += nChange;
5497 if( pOp->p3>0 ){
5498 assert( memIsValid(&aMem[pOp->p3]) );
5499 memAboutToChange(p, &aMem[pOp->p3]);
5500 aMem[pOp->p3].u.i += nChange;
5503 if( rc ) goto abort_due_to_error;
5504 break;
5507 /* Opcode: ResetSorter P1 * * * *
5509 ** Delete all contents from the ephemeral table or sorter
5510 ** that is open on cursor P1.
5512 ** This opcode only works for cursors used for sorting and
5513 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5515 case OP_ResetSorter: {
5516 VdbeCursor *pC;
5518 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5519 pC = p->apCsr[pOp->p1];
5520 assert( pC!=0 );
5521 if( isSorter(pC) ){
5522 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
5523 }else{
5524 assert( pC->eCurType==CURTYPE_BTREE );
5525 assert( pC->isEphemeral );
5526 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
5527 if( rc ) goto abort_due_to_error;
5529 break;
5532 /* Opcode: CreateBtree P1 P2 P3 * *
5533 ** Synopsis: r[P2]=root iDb=P1 flags=P3
5535 ** Allocate a new b-tree in the main database file if P1==0 or in the
5536 ** TEMP database file if P1==1 or in an attached database if
5537 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
5538 ** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
5539 ** The root page number of the new b-tree is stored in register P2.
5541 case OP_CreateBtree: { /* out2 */
5542 int pgno;
5543 Db *pDb;
5545 pOut = out2Prerelease(p, pOp);
5546 pgno = 0;
5547 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
5548 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5549 assert( DbMaskTest(p->btreeMask, pOp->p1) );
5550 assert( p->readOnly==0 );
5551 pDb = &db->aDb[pOp->p1];
5552 assert( pDb->pBt!=0 );
5553 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
5554 if( rc ) goto abort_due_to_error;
5555 pOut->u.i = pgno;
5556 break;
5559 /* Opcode: SqlExec * * * P4 *
5561 ** Run the SQL statement or statements specified in the P4 string.
5563 case OP_SqlExec: {
5564 db->nSqlExec++;
5565 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
5566 db->nSqlExec--;
5567 if( rc ) goto abort_due_to_error;
5568 break;
5571 /* Opcode: ParseSchema P1 * * P4 *
5573 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5574 ** that match the WHERE clause P4.
5576 ** This opcode invokes the parser to create a new virtual machine,
5577 ** then runs the new virtual machine. It is thus a re-entrant opcode.
5579 case OP_ParseSchema: {
5580 int iDb;
5581 const char *zMaster;
5582 char *zSql;
5583 InitData initData;
5585 /* Any prepared statement that invokes this opcode will hold mutexes
5586 ** on every btree. This is a prerequisite for invoking
5587 ** sqlite3InitCallback().
5589 #ifdef SQLITE_DEBUG
5590 for(iDb=0; iDb<db->nDb; iDb++){
5591 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
5593 #endif
5595 iDb = pOp->p1;
5596 assert( iDb>=0 && iDb<db->nDb );
5597 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
5598 /* Used to be a conditional */ {
5599 zMaster = MASTER_NAME;
5600 initData.db = db;
5601 initData.iDb = pOp->p1;
5602 initData.pzErrMsg = &p->zErrMsg;
5603 zSql = sqlite3MPrintf(db,
5604 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5605 db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
5606 if( zSql==0 ){
5607 rc = SQLITE_NOMEM_BKPT;
5608 }else{
5609 assert( db->init.busy==0 );
5610 db->init.busy = 1;
5611 initData.rc = SQLITE_OK;
5612 assert( !db->mallocFailed );
5613 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
5614 if( rc==SQLITE_OK ) rc = initData.rc;
5615 sqlite3DbFreeNN(db, zSql);
5616 db->init.busy = 0;
5619 if( rc ){
5620 sqlite3ResetAllSchemasOfConnection(db);
5621 if( rc==SQLITE_NOMEM ){
5622 goto no_mem;
5624 goto abort_due_to_error;
5626 break;
5629 #if !defined(SQLITE_OMIT_ANALYZE)
5630 /* Opcode: LoadAnalysis P1 * * * *
5632 ** Read the sqlite_stat1 table for database P1 and load the content
5633 ** of that table into the internal index hash table. This will cause
5634 ** the analysis to be used when preparing all subsequent queries.
5636 case OP_LoadAnalysis: {
5637 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5638 rc = sqlite3AnalysisLoad(db, pOp->p1);
5639 if( rc ) goto abort_due_to_error;
5640 break;
5642 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5644 /* Opcode: DropTable P1 * * P4 *
5646 ** Remove the internal (in-memory) data structures that describe
5647 ** the table named P4 in database P1. This is called after a table
5648 ** is dropped from disk (using the Destroy opcode) in order to keep
5649 ** the internal representation of the
5650 ** schema consistent with what is on disk.
5652 case OP_DropTable: {
5653 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
5654 break;
5657 /* Opcode: DropIndex P1 * * P4 *
5659 ** Remove the internal (in-memory) data structures that describe
5660 ** the index named P4 in database P1. This is called after an index
5661 ** is dropped from disk (using the Destroy opcode)
5662 ** in order to keep the internal representation of the
5663 ** schema consistent with what is on disk.
5665 case OP_DropIndex: {
5666 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
5667 break;
5670 /* Opcode: DropTrigger P1 * * P4 *
5672 ** Remove the internal (in-memory) data structures that describe
5673 ** the trigger named P4 in database P1. This is called after a trigger
5674 ** is dropped from disk (using the Destroy opcode) in order to keep
5675 ** the internal representation of the
5676 ** schema consistent with what is on disk.
5678 case OP_DropTrigger: {
5679 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
5680 break;
5684 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5685 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
5687 ** Do an analysis of the currently open database. Store in
5688 ** register P1 the text of an error message describing any problems.
5689 ** If no problems are found, store a NULL in register P1.
5691 ** The register P3 contains one less than the maximum number of allowed errors.
5692 ** At most reg(P3) errors will be reported.
5693 ** In other words, the analysis stops as soon as reg(P1) errors are
5694 ** seen. Reg(P1) is updated with the number of errors remaining.
5696 ** The root page numbers of all tables in the database are integers
5697 ** stored in P4_INTARRAY argument.
5699 ** If P5 is not zero, the check is done on the auxiliary database
5700 ** file, not the main database file.
5702 ** This opcode is used to implement the integrity_check pragma.
5704 case OP_IntegrityCk: {
5705 int nRoot; /* Number of tables to check. (Number of root pages.) */
5706 int *aRoot; /* Array of rootpage numbers for tables to be checked */
5707 int nErr; /* Number of errors reported */
5708 char *z; /* Text of the error report */
5709 Mem *pnErr; /* Register keeping track of errors remaining */
5711 assert( p->bIsReader );
5712 nRoot = pOp->p2;
5713 aRoot = pOp->p4.ai;
5714 assert( nRoot>0 );
5715 assert( aRoot[0]==nRoot );
5716 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
5717 pnErr = &aMem[pOp->p3];
5718 assert( (pnErr->flags & MEM_Int)!=0 );
5719 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
5720 pIn1 = &aMem[pOp->p1];
5721 assert( pOp->p5<db->nDb );
5722 assert( DbMaskTest(p->btreeMask, pOp->p5) );
5723 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
5724 (int)pnErr->u.i+1, &nErr);
5725 sqlite3VdbeMemSetNull(pIn1);
5726 if( nErr==0 ){
5727 assert( z==0 );
5728 }else if( z==0 ){
5729 goto no_mem;
5730 }else{
5731 pnErr->u.i -= nErr-1;
5732 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
5734 UPDATE_MAX_BLOBSIZE(pIn1);
5735 sqlite3VdbeChangeEncoding(pIn1, encoding);
5736 break;
5738 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5740 /* Opcode: RowSetAdd P1 P2 * * *
5741 ** Synopsis: rowset(P1)=r[P2]
5743 ** Insert the integer value held by register P2 into a RowSet object
5744 ** held in register P1.
5746 ** An assertion fails if P2 is not an integer.
5748 case OP_RowSetAdd: { /* in1, in2 */
5749 pIn1 = &aMem[pOp->p1];
5750 pIn2 = &aMem[pOp->p2];
5751 assert( (pIn2->flags & MEM_Int)!=0 );
5752 if( (pIn1->flags & MEM_RowSet)==0 ){
5753 sqlite3VdbeMemSetRowSet(pIn1);
5754 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5756 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
5757 break;
5760 /* Opcode: RowSetRead P1 P2 P3 * *
5761 ** Synopsis: r[P3]=rowset(P1)
5763 ** Extract the smallest value from the RowSet object in P1
5764 ** and put that value into register P3.
5765 ** Or, if RowSet object P1 is initially empty, leave P3
5766 ** unchanged and jump to instruction P2.
5768 case OP_RowSetRead: { /* jump, in1, out3 */
5769 i64 val;
5771 pIn1 = &aMem[pOp->p1];
5772 if( (pIn1->flags & MEM_RowSet)==0
5773 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
5775 /* The boolean index is empty */
5776 sqlite3VdbeMemSetNull(pIn1);
5777 VdbeBranchTaken(1,2);
5778 goto jump_to_p2_and_check_for_interrupt;
5779 }else{
5780 /* A value was pulled from the index */
5781 VdbeBranchTaken(0,2);
5782 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
5784 goto check_for_interrupt;
5787 /* Opcode: RowSetTest P1 P2 P3 P4
5788 ** Synopsis: if r[P3] in rowset(P1) goto P2
5790 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5791 ** contains a RowSet object and that RowSet object contains
5792 ** the value held in P3, jump to register P2. Otherwise, insert the
5793 ** integer in P3 into the RowSet and continue on to the
5794 ** next opcode.
5796 ** The RowSet object is optimized for the case where sets of integers
5797 ** are inserted in distinct phases, which each set contains no duplicates.
5798 ** Each set is identified by a unique P4 value. The first set
5799 ** must have P4==0, the final set must have P4==-1, and for all other sets
5800 ** must have P4>0.
5802 ** This allows optimizations: (a) when P4==0 there is no need to test
5803 ** the RowSet object for P3, as it is guaranteed not to contain it,
5804 ** (b) when P4==-1 there is no need to insert the value, as it will
5805 ** never be tested for, and (c) when a value that is part of set X is
5806 ** inserted, there is no need to search to see if the same value was
5807 ** previously inserted as part of set X (only if it was previously
5808 ** inserted as part of some other set).
5810 case OP_RowSetTest: { /* jump, in1, in3 */
5811 int iSet;
5812 int exists;
5814 pIn1 = &aMem[pOp->p1];
5815 pIn3 = &aMem[pOp->p3];
5816 iSet = pOp->p4.i;
5817 assert( pIn3->flags&MEM_Int );
5819 /* If there is anything other than a rowset object in memory cell P1,
5820 ** delete it now and initialize P1 with an empty rowset
5822 if( (pIn1->flags & MEM_RowSet)==0 ){
5823 sqlite3VdbeMemSetRowSet(pIn1);
5824 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5827 assert( pOp->p4type==P4_INT32 );
5828 assert( iSet==-1 || iSet>=0 );
5829 if( iSet ){
5830 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
5831 VdbeBranchTaken(exists!=0,2);
5832 if( exists ) goto jump_to_p2;
5834 if( iSet>=0 ){
5835 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
5837 break;
5841 #ifndef SQLITE_OMIT_TRIGGER
5843 /* Opcode: Program P1 P2 P3 P4 P5
5845 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5847 ** P1 contains the address of the memory cell that contains the first memory
5848 ** cell in an array of values used as arguments to the sub-program. P2
5849 ** contains the address to jump to if the sub-program throws an IGNORE
5850 ** exception using the RAISE() function. Register P3 contains the address
5851 ** of a memory cell in this (the parent) VM that is used to allocate the
5852 ** memory required by the sub-vdbe at runtime.
5854 ** P4 is a pointer to the VM containing the trigger program.
5856 ** If P5 is non-zero, then recursive program invocation is enabled.
5858 case OP_Program: { /* jump */
5859 int nMem; /* Number of memory registers for sub-program */
5860 int nByte; /* Bytes of runtime space required for sub-program */
5861 Mem *pRt; /* Register to allocate runtime space */
5862 Mem *pMem; /* Used to iterate through memory cells */
5863 Mem *pEnd; /* Last memory cell in new array */
5864 VdbeFrame *pFrame; /* New vdbe frame to execute in */
5865 SubProgram *pProgram; /* Sub-program to execute */
5866 void *t; /* Token identifying trigger */
5868 pProgram = pOp->p4.pProgram;
5869 pRt = &aMem[pOp->p3];
5870 assert( pProgram->nOp>0 );
5872 /* If the p5 flag is clear, then recursive invocation of triggers is
5873 ** disabled for backwards compatibility (p5 is set if this sub-program
5874 ** is really a trigger, not a foreign key action, and the flag set
5875 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
5877 ** It is recursive invocation of triggers, at the SQL level, that is
5878 ** disabled. In some cases a single trigger may generate more than one
5879 ** SubProgram (if the trigger may be executed with more than one different
5880 ** ON CONFLICT algorithm). SubProgram structures associated with a
5881 ** single trigger all have the same value for the SubProgram.token
5882 ** variable. */
5883 if( pOp->p5 ){
5884 t = pProgram->token;
5885 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
5886 if( pFrame ) break;
5889 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
5890 rc = SQLITE_ERROR;
5891 sqlite3VdbeError(p, "too many levels of trigger recursion");
5892 goto abort_due_to_error;
5895 /* Register pRt is used to store the memory required to save the state
5896 ** of the current program, and the memory required at runtime to execute
5897 ** the trigger program. If this trigger has been fired before, then pRt
5898 ** is already allocated. Otherwise, it must be initialized. */
5899 if( (pRt->flags&MEM_Frame)==0 ){
5900 /* SubProgram.nMem is set to the number of memory cells used by the
5901 ** program stored in SubProgram.aOp. As well as these, one memory
5902 ** cell is required for each cursor used by the program. Set local
5903 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
5905 nMem = pProgram->nMem + pProgram->nCsr;
5906 assert( nMem>0 );
5907 if( pProgram->nCsr==0 ) nMem++;
5908 nByte = ROUND8(sizeof(VdbeFrame))
5909 + nMem * sizeof(Mem)
5910 + pProgram->nCsr * sizeof(VdbeCursor*)
5911 + (pProgram->nOp + 7)/8;
5912 pFrame = sqlite3DbMallocZero(db, nByte);
5913 if( !pFrame ){
5914 goto no_mem;
5916 sqlite3VdbeMemRelease(pRt);
5917 pRt->flags = MEM_Frame;
5918 pRt->u.pFrame = pFrame;
5920 pFrame->v = p;
5921 pFrame->nChildMem = nMem;
5922 pFrame->nChildCsr = pProgram->nCsr;
5923 pFrame->pc = (int)(pOp - aOp);
5924 pFrame->aMem = p->aMem;
5925 pFrame->nMem = p->nMem;
5926 pFrame->apCsr = p->apCsr;
5927 pFrame->nCursor = p->nCursor;
5928 pFrame->aOp = p->aOp;
5929 pFrame->nOp = p->nOp;
5930 pFrame->token = pProgram->token;
5931 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
5932 pFrame->anExec = p->anExec;
5933 #endif
5935 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
5936 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
5937 pMem->flags = MEM_Undefined;
5938 pMem->db = db;
5940 }else{
5941 pFrame = pRt->u.pFrame;
5942 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
5943 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
5944 assert( pProgram->nCsr==pFrame->nChildCsr );
5945 assert( (int)(pOp - aOp)==pFrame->pc );
5948 p->nFrame++;
5949 pFrame->pParent = p->pFrame;
5950 pFrame->lastRowid = db->lastRowid;
5951 pFrame->nChange = p->nChange;
5952 pFrame->nDbChange = p->db->nChange;
5953 assert( pFrame->pAuxData==0 );
5954 pFrame->pAuxData = p->pAuxData;
5955 p->pAuxData = 0;
5956 p->nChange = 0;
5957 p->pFrame = pFrame;
5958 p->aMem = aMem = VdbeFrameMem(pFrame);
5959 p->nMem = pFrame->nChildMem;
5960 p->nCursor = (u16)pFrame->nChildCsr;
5961 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
5962 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
5963 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
5964 p->aOp = aOp = pProgram->aOp;
5965 p->nOp = pProgram->nOp;
5966 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
5967 p->anExec = 0;
5968 #endif
5969 pOp = &aOp[-1];
5971 break;
5974 /* Opcode: Param P1 P2 * * *
5976 ** This opcode is only ever present in sub-programs called via the
5977 ** OP_Program instruction. Copy a value currently stored in a memory
5978 ** cell of the calling (parent) frame to cell P2 in the current frames
5979 ** address space. This is used by trigger programs to access the new.*
5980 ** and old.* values.
5982 ** The address of the cell in the parent frame is determined by adding
5983 ** the value of the P1 argument to the value of the P1 argument to the
5984 ** calling OP_Program instruction.
5986 case OP_Param: { /* out2 */
5987 VdbeFrame *pFrame;
5988 Mem *pIn;
5989 pOut = out2Prerelease(p, pOp);
5990 pFrame = p->pFrame;
5991 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
5992 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
5993 break;
5996 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
5998 #ifndef SQLITE_OMIT_FOREIGN_KEY
5999 /* Opcode: FkCounter P1 P2 * * *
6000 ** Synopsis: fkctr[P1]+=P2
6002 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6003 ** If P1 is non-zero, the database constraint counter is incremented
6004 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6005 ** statement counter is incremented (immediate foreign key constraints).
6007 case OP_FkCounter: {
6008 if( db->flags & SQLITE_DeferFKs ){
6009 db->nDeferredImmCons += pOp->p2;
6010 }else if( pOp->p1 ){
6011 db->nDeferredCons += pOp->p2;
6012 }else{
6013 p->nFkConstraint += pOp->p2;
6015 break;
6018 /* Opcode: FkIfZero P1 P2 * * *
6019 ** Synopsis: if fkctr[P1]==0 goto P2
6021 ** This opcode tests if a foreign key constraint-counter is currently zero.
6022 ** If so, jump to instruction P2. Otherwise, fall through to the next
6023 ** instruction.
6025 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6026 ** is zero (the one that counts deferred constraint violations). If P1 is
6027 ** zero, the jump is taken if the statement constraint-counter is zero
6028 ** (immediate foreign key constraint violations).
6030 case OP_FkIfZero: { /* jump */
6031 if( pOp->p1 ){
6032 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6033 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6034 }else{
6035 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6036 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6038 break;
6040 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6042 #ifndef SQLITE_OMIT_AUTOINCREMENT
6043 /* Opcode: MemMax P1 P2 * * *
6044 ** Synopsis: r[P1]=max(r[P1],r[P2])
6046 ** P1 is a register in the root frame of this VM (the root frame is
6047 ** different from the current frame if this instruction is being executed
6048 ** within a sub-program). Set the value of register P1 to the maximum of
6049 ** its current value and the value in register P2.
6051 ** This instruction throws an error if the memory cell is not initially
6052 ** an integer.
6054 case OP_MemMax: { /* in2 */
6055 VdbeFrame *pFrame;
6056 if( p->pFrame ){
6057 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
6058 pIn1 = &pFrame->aMem[pOp->p1];
6059 }else{
6060 pIn1 = &aMem[pOp->p1];
6062 assert( memIsValid(pIn1) );
6063 sqlite3VdbeMemIntegerify(pIn1);
6064 pIn2 = &aMem[pOp->p2];
6065 sqlite3VdbeMemIntegerify(pIn2);
6066 if( pIn1->u.i<pIn2->u.i){
6067 pIn1->u.i = pIn2->u.i;
6069 break;
6071 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6073 /* Opcode: IfPos P1 P2 P3 * *
6074 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6076 ** Register P1 must contain an integer.
6077 ** If the value of register P1 is 1 or greater, subtract P3 from the
6078 ** value in P1 and jump to P2.
6080 ** If the initial value of register P1 is less than 1, then the
6081 ** value is unchanged and control passes through to the next instruction.
6083 case OP_IfPos: { /* jump, in1 */
6084 pIn1 = &aMem[pOp->p1];
6085 assert( pIn1->flags&MEM_Int );
6086 VdbeBranchTaken( pIn1->u.i>0, 2);
6087 if( pIn1->u.i>0 ){
6088 pIn1->u.i -= pOp->p3;
6089 goto jump_to_p2;
6091 break;
6094 /* Opcode: OffsetLimit P1 P2 P3 * *
6095 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6097 ** This opcode performs a commonly used computation associated with
6098 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
6099 ** holds the offset counter. The opcode computes the combined value
6100 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
6101 ** value computed is the total number of rows that will need to be
6102 ** visited in order to complete the query.
6104 ** If r[P3] is zero or negative, that means there is no OFFSET
6105 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6107 ** if r[P1] is zero or negative, that means there is no LIMIT
6108 ** and r[P2] is set to -1.
6110 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6112 case OP_OffsetLimit: { /* in1, out2, in3 */
6113 i64 x;
6114 pIn1 = &aMem[pOp->p1];
6115 pIn3 = &aMem[pOp->p3];
6116 pOut = out2Prerelease(p, pOp);
6117 assert( pIn1->flags & MEM_Int );
6118 assert( pIn3->flags & MEM_Int );
6119 x = pIn1->u.i;
6120 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
6121 /* If the LIMIT is less than or equal to zero, loop forever. This
6122 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
6123 ** also loop forever. This is undocumented. In fact, one could argue
6124 ** that the loop should terminate. But assuming 1 billion iterations
6125 ** per second (far exceeding the capabilities of any current hardware)
6126 ** it would take nearly 300 years to actually reach the limit. So
6127 ** looping forever is a reasonable approximation. */
6128 pOut->u.i = -1;
6129 }else{
6130 pOut->u.i = x;
6132 break;
6135 /* Opcode: IfNotZero P1 P2 * * *
6136 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6138 ** Register P1 must contain an integer. If the content of register P1 is
6139 ** initially greater than zero, then decrement the value in register P1.
6140 ** If it is non-zero (negative or positive) and then also jump to P2.
6141 ** If register P1 is initially zero, leave it unchanged and fall through.
6143 case OP_IfNotZero: { /* jump, in1 */
6144 pIn1 = &aMem[pOp->p1];
6145 assert( pIn1->flags&MEM_Int );
6146 VdbeBranchTaken(pIn1->u.i<0, 2);
6147 if( pIn1->u.i ){
6148 if( pIn1->u.i>0 ) pIn1->u.i--;
6149 goto jump_to_p2;
6151 break;
6154 /* Opcode: DecrJumpZero P1 P2 * * *
6155 ** Synopsis: if (--r[P1])==0 goto P2
6157 ** Register P1 must hold an integer. Decrement the value in P1
6158 ** and jump to P2 if the new value is exactly zero.
6160 case OP_DecrJumpZero: { /* jump, in1 */
6161 pIn1 = &aMem[pOp->p1];
6162 assert( pIn1->flags&MEM_Int );
6163 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
6164 VdbeBranchTaken(pIn1->u.i==0, 2);
6165 if( pIn1->u.i==0 ) goto jump_to_p2;
6166 break;
6170 /* Opcode: AggStep0 * P2 P3 P4 P5
6171 ** Synopsis: accum=r[P3] step(r[P2@P5])
6173 ** Execute the step function for an aggregate. The
6174 ** function has P5 arguments. P4 is a pointer to the FuncDef
6175 ** structure that specifies the function. Register P3 is the
6176 ** accumulator.
6178 ** The P5 arguments are taken from register P2 and its
6179 ** successors.
6181 /* Opcode: AggStep * P2 P3 P4 P5
6182 ** Synopsis: accum=r[P3] step(r[P2@P5])
6184 ** Execute the step function for an aggregate. The
6185 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
6186 ** object that is used to run the function. Register P3 is
6187 ** as the accumulator.
6189 ** The P5 arguments are taken from register P2 and its
6190 ** successors.
6192 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6193 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6194 ** the opcode is changed. In this way, the initialization of the
6195 ** sqlite3_context only happens once, instead of on each call to the
6196 ** step function.
6198 case OP_AggStep0: {
6199 int n;
6200 sqlite3_context *pCtx;
6202 assert( pOp->p4type==P4_FUNCDEF );
6203 n = pOp->p5;
6204 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6205 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
6206 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
6207 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
6208 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
6209 if( pCtx==0 ) goto no_mem;
6210 pCtx->pMem = 0;
6211 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
6212 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
6213 pCtx->pFunc = pOp->p4.pFunc;
6214 pCtx->iOp = (int)(pOp - aOp);
6215 pCtx->pVdbe = p;
6216 pCtx->skipFlag = 0;
6217 pCtx->isError = 0;
6218 pCtx->argc = n;
6219 pOp->p4type = P4_FUNCCTX;
6220 pOp->p4.pCtx = pCtx;
6221 pOp->opcode = OP_AggStep;
6222 /* Fall through into OP_AggStep */
6224 case OP_AggStep: {
6225 int i;
6226 sqlite3_context *pCtx;
6227 Mem *pMem;
6229 assert( pOp->p4type==P4_FUNCCTX );
6230 pCtx = pOp->p4.pCtx;
6231 pMem = &aMem[pOp->p3];
6233 /* If this function is inside of a trigger, the register array in aMem[]
6234 ** might change from one evaluation to the next. The next block of code
6235 ** checks to see if the register array has changed, and if so it
6236 ** reinitializes the relavant parts of the sqlite3_context object */
6237 if( pCtx->pMem != pMem ){
6238 pCtx->pMem = pMem;
6239 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
6242 #ifdef SQLITE_DEBUG
6243 for(i=0; i<pCtx->argc; i++){
6244 assert( memIsValid(pCtx->argv[i]) );
6245 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
6247 #endif
6249 pMem->n++;
6250 assert( pCtx->pOut->flags==MEM_Null );
6251 assert( pCtx->isError==0 );
6252 assert( pCtx->skipFlag==0 );
6253 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
6254 if( pCtx->isError ){
6255 if( pCtx->isError>0 ){
6256 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
6257 rc = pCtx->isError;
6259 if( pCtx->skipFlag ){
6260 assert( pOp[-1].opcode==OP_CollSeq );
6261 i = pOp[-1].p1;
6262 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
6263 pCtx->skipFlag = 0;
6265 sqlite3VdbeMemRelease(pCtx->pOut);
6266 pCtx->pOut->flags = MEM_Null;
6267 pCtx->isError = 0;
6268 if( rc ) goto abort_due_to_error;
6270 assert( pCtx->pOut->flags==MEM_Null );
6271 assert( pCtx->skipFlag==0 );
6272 break;
6275 /* Opcode: AggFinal P1 P2 * P4 *
6276 ** Synopsis: accum=r[P1] N=P2
6278 ** Execute the finalizer function for an aggregate. P1 is
6279 ** the memory location that is the accumulator for the aggregate.
6281 ** P2 is the number of arguments that the step function takes and
6282 ** P4 is a pointer to the FuncDef for this function. The P2
6283 ** argument is not used by this opcode. It is only there to disambiguate
6284 ** functions that can take varying numbers of arguments. The
6285 ** P4 argument is only needed for the degenerate case where
6286 ** the step function was not previously called.
6288 case OP_AggFinal: {
6289 Mem *pMem;
6290 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
6291 pMem = &aMem[pOp->p1];
6292 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
6293 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
6294 if( rc ){
6295 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
6296 goto abort_due_to_error;
6298 sqlite3VdbeChangeEncoding(pMem, encoding);
6299 UPDATE_MAX_BLOBSIZE(pMem);
6300 if( sqlite3VdbeMemTooBig(pMem) ){
6301 goto too_big;
6303 break;
6306 #ifndef SQLITE_OMIT_WAL
6307 /* Opcode: Checkpoint P1 P2 P3 * *
6309 ** Checkpoint database P1. This is a no-op if P1 is not currently in
6310 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
6311 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
6312 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
6313 ** WAL after the checkpoint into mem[P3+1] and the number of pages
6314 ** in the WAL that have been checkpointed after the checkpoint
6315 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
6316 ** mem[P3+2] are initialized to -1.
6318 case OP_Checkpoint: {
6319 int i; /* Loop counter */
6320 int aRes[3]; /* Results */
6321 Mem *pMem; /* Write results here */
6323 assert( p->readOnly==0 );
6324 aRes[0] = 0;
6325 aRes[1] = aRes[2] = -1;
6326 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
6327 || pOp->p2==SQLITE_CHECKPOINT_FULL
6328 || pOp->p2==SQLITE_CHECKPOINT_RESTART
6329 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
6331 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
6332 if( rc ){
6333 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
6334 rc = SQLITE_OK;
6335 aRes[0] = 1;
6337 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
6338 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
6340 break;
6342 #endif
6344 #ifndef SQLITE_OMIT_PRAGMA
6345 /* Opcode: JournalMode P1 P2 P3 * *
6347 ** Change the journal mode of database P1 to P3. P3 must be one of the
6348 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
6349 ** modes (delete, truncate, persist, off and memory), this is a simple
6350 ** operation. No IO is required.
6352 ** If changing into or out of WAL mode the procedure is more complicated.
6354 ** Write a string containing the final journal-mode to register P2.
6356 case OP_JournalMode: { /* out2 */
6357 Btree *pBt; /* Btree to change journal mode of */
6358 Pager *pPager; /* Pager associated with pBt */
6359 int eNew; /* New journal mode */
6360 int eOld; /* The old journal mode */
6361 #ifndef SQLITE_OMIT_WAL
6362 const char *zFilename; /* Name of database file for pPager */
6363 #endif
6365 pOut = out2Prerelease(p, pOp);
6366 eNew = pOp->p3;
6367 assert( eNew==PAGER_JOURNALMODE_DELETE
6368 || eNew==PAGER_JOURNALMODE_TRUNCATE
6369 || eNew==PAGER_JOURNALMODE_PERSIST
6370 || eNew==PAGER_JOURNALMODE_OFF
6371 || eNew==PAGER_JOURNALMODE_MEMORY
6372 || eNew==PAGER_JOURNALMODE_WAL
6373 || eNew==PAGER_JOURNALMODE_QUERY
6375 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6376 assert( p->readOnly==0 );
6378 pBt = db->aDb[pOp->p1].pBt;
6379 pPager = sqlite3BtreePager(pBt);
6380 eOld = sqlite3PagerGetJournalMode(pPager);
6381 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
6382 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
6384 #ifndef SQLITE_OMIT_WAL
6385 zFilename = sqlite3PagerFilename(pPager, 1);
6387 /* Do not allow a transition to journal_mode=WAL for a database
6388 ** in temporary storage or if the VFS does not support shared memory
6390 if( eNew==PAGER_JOURNALMODE_WAL
6391 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
6392 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
6394 eNew = eOld;
6397 if( (eNew!=eOld)
6398 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
6400 if( !db->autoCommit || db->nVdbeRead>1 ){
6401 rc = SQLITE_ERROR;
6402 sqlite3VdbeError(p,
6403 "cannot change %s wal mode from within a transaction",
6404 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
6406 goto abort_due_to_error;
6407 }else{
6409 if( eOld==PAGER_JOURNALMODE_WAL ){
6410 /* If leaving WAL mode, close the log file. If successful, the call
6411 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
6412 ** file. An EXCLUSIVE lock may still be held on the database file
6413 ** after a successful return.
6415 rc = sqlite3PagerCloseWal(pPager, db);
6416 if( rc==SQLITE_OK ){
6417 sqlite3PagerSetJournalMode(pPager, eNew);
6419 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
6420 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
6421 ** as an intermediate */
6422 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
6425 /* Open a transaction on the database file. Regardless of the journal
6426 ** mode, this transaction always uses a rollback journal.
6428 assert( sqlite3BtreeIsInTrans(pBt)==0 );
6429 if( rc==SQLITE_OK ){
6430 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
6434 #endif /* ifndef SQLITE_OMIT_WAL */
6436 if( rc ) eNew = eOld;
6437 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
6439 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
6440 pOut->z = (char *)sqlite3JournalModename(eNew);
6441 pOut->n = sqlite3Strlen30(pOut->z);
6442 pOut->enc = SQLITE_UTF8;
6443 sqlite3VdbeChangeEncoding(pOut, encoding);
6444 if( rc ) goto abort_due_to_error;
6445 break;
6447 #endif /* SQLITE_OMIT_PRAGMA */
6449 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
6450 /* Opcode: Vacuum P1 * * * *
6452 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
6453 ** for an attached database. The "temp" database may not be vacuumed.
6455 case OP_Vacuum: {
6456 assert( p->readOnly==0 );
6457 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
6458 if( rc ) goto abort_due_to_error;
6459 break;
6461 #endif
6463 #if !defined(SQLITE_OMIT_AUTOVACUUM)
6464 /* Opcode: IncrVacuum P1 P2 * * *
6466 ** Perform a single step of the incremental vacuum procedure on
6467 ** the P1 database. If the vacuum has finished, jump to instruction
6468 ** P2. Otherwise, fall through to the next instruction.
6470 case OP_IncrVacuum: { /* jump */
6471 Btree *pBt;
6473 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6474 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6475 assert( p->readOnly==0 );
6476 pBt = db->aDb[pOp->p1].pBt;
6477 rc = sqlite3BtreeIncrVacuum(pBt);
6478 VdbeBranchTaken(rc==SQLITE_DONE,2);
6479 if( rc ){
6480 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6481 rc = SQLITE_OK;
6482 goto jump_to_p2;
6484 break;
6486 #endif
6488 /* Opcode: Expire P1 * * * *
6490 ** Cause precompiled statements to expire. When an expired statement
6491 ** is executed using sqlite3_step() it will either automatically
6492 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
6493 ** or it will fail with SQLITE_SCHEMA.
6495 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
6496 ** then only the currently executing statement is expired.
6498 case OP_Expire: {
6499 if( !pOp->p1 ){
6500 sqlite3ExpirePreparedStatements(db);
6501 }else{
6502 p->expired = 1;
6504 break;
6507 #ifndef SQLITE_OMIT_SHARED_CACHE
6508 /* Opcode: TableLock P1 P2 P3 P4 *
6509 ** Synopsis: iDb=P1 root=P2 write=P3
6511 ** Obtain a lock on a particular table. This instruction is only used when
6512 ** the shared-cache feature is enabled.
6514 ** P1 is the index of the database in sqlite3.aDb[] of the database
6515 ** on which the lock is acquired. A readlock is obtained if P3==0 or
6516 ** a write lock if P3==1.
6518 ** P2 contains the root-page of the table to lock.
6520 ** P4 contains a pointer to the name of the table being locked. This is only
6521 ** used to generate an error message if the lock cannot be obtained.
6523 case OP_TableLock: {
6524 u8 isWriteLock = (u8)pOp->p3;
6525 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
6526 int p1 = pOp->p1;
6527 assert( p1>=0 && p1<db->nDb );
6528 assert( DbMaskTest(p->btreeMask, p1) );
6529 assert( isWriteLock==0 || isWriteLock==1 );
6530 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
6531 if( rc ){
6532 if( (rc&0xFF)==SQLITE_LOCKED ){
6533 const char *z = pOp->p4.z;
6534 sqlite3VdbeError(p, "database table is locked: %s", z);
6536 goto abort_due_to_error;
6539 break;
6541 #endif /* SQLITE_OMIT_SHARED_CACHE */
6543 #ifndef SQLITE_OMIT_VIRTUALTABLE
6544 /* Opcode: VBegin * * * P4 *
6546 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
6547 ** xBegin method for that table.
6549 ** Also, whether or not P4 is set, check that this is not being called from
6550 ** within a callback to a virtual table xSync() method. If it is, the error
6551 ** code will be set to SQLITE_LOCKED.
6553 case OP_VBegin: {
6554 VTable *pVTab;
6555 pVTab = pOp->p4.pVtab;
6556 rc = sqlite3VtabBegin(db, pVTab);
6557 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
6558 if( rc ) goto abort_due_to_error;
6559 break;
6561 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6563 #ifndef SQLITE_OMIT_VIRTUALTABLE
6564 /* Opcode: VCreate P1 P2 * * *
6566 ** P2 is a register that holds the name of a virtual table in database
6567 ** P1. Call the xCreate method for that table.
6569 case OP_VCreate: {
6570 Mem sMem; /* For storing the record being decoded */
6571 const char *zTab; /* Name of the virtual table */
6573 memset(&sMem, 0, sizeof(sMem));
6574 sMem.db = db;
6575 /* Because P2 is always a static string, it is impossible for the
6576 ** sqlite3VdbeMemCopy() to fail */
6577 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
6578 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
6579 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
6580 assert( rc==SQLITE_OK );
6581 zTab = (const char*)sqlite3_value_text(&sMem);
6582 assert( zTab || db->mallocFailed );
6583 if( zTab ){
6584 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
6586 sqlite3VdbeMemRelease(&sMem);
6587 if( rc ) goto abort_due_to_error;
6588 break;
6590 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6592 #ifndef SQLITE_OMIT_VIRTUALTABLE
6593 /* Opcode: VDestroy P1 * * P4 *
6595 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
6596 ** of that table.
6598 case OP_VDestroy: {
6599 db->nVDestroy++;
6600 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
6601 db->nVDestroy--;
6602 if( rc ) goto abort_due_to_error;
6603 break;
6605 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6607 #ifndef SQLITE_OMIT_VIRTUALTABLE
6608 /* Opcode: VOpen P1 * * P4 *
6610 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6611 ** P1 is a cursor number. This opcode opens a cursor to the virtual
6612 ** table and stores that cursor in P1.
6614 case OP_VOpen: {
6615 VdbeCursor *pCur;
6616 sqlite3_vtab_cursor *pVCur;
6617 sqlite3_vtab *pVtab;
6618 const sqlite3_module *pModule;
6620 assert( p->bIsReader );
6621 pCur = 0;
6622 pVCur = 0;
6623 pVtab = pOp->p4.pVtab->pVtab;
6624 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6625 rc = SQLITE_LOCKED;
6626 goto abort_due_to_error;
6628 pModule = pVtab->pModule;
6629 rc = pModule->xOpen(pVtab, &pVCur);
6630 sqlite3VtabImportErrmsg(p, pVtab);
6631 if( rc ) goto abort_due_to_error;
6633 /* Initialize sqlite3_vtab_cursor base class */
6634 pVCur->pVtab = pVtab;
6636 /* Initialize vdbe cursor object */
6637 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
6638 if( pCur ){
6639 pCur->uc.pVCur = pVCur;
6640 pVtab->nRef++;
6641 }else{
6642 assert( db->mallocFailed );
6643 pModule->xClose(pVCur);
6644 goto no_mem;
6646 break;
6648 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6650 #ifndef SQLITE_OMIT_VIRTUALTABLE
6651 /* Opcode: VFilter P1 P2 P3 P4 *
6652 ** Synopsis: iplan=r[P3] zplan='P4'
6654 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
6655 ** the filtered result set is empty.
6657 ** P4 is either NULL or a string that was generated by the xBestIndex
6658 ** method of the module. The interpretation of the P4 string is left
6659 ** to the module implementation.
6661 ** This opcode invokes the xFilter method on the virtual table specified
6662 ** by P1. The integer query plan parameter to xFilter is stored in register
6663 ** P3. Register P3+1 stores the argc parameter to be passed to the
6664 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6665 ** additional parameters which are passed to
6666 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6668 ** A jump is made to P2 if the result set after filtering would be empty.
6670 case OP_VFilter: { /* jump */
6671 int nArg;
6672 int iQuery;
6673 const sqlite3_module *pModule;
6674 Mem *pQuery;
6675 Mem *pArgc;
6676 sqlite3_vtab_cursor *pVCur;
6677 sqlite3_vtab *pVtab;
6678 VdbeCursor *pCur;
6679 int res;
6680 int i;
6681 Mem **apArg;
6683 pQuery = &aMem[pOp->p3];
6684 pArgc = &pQuery[1];
6685 pCur = p->apCsr[pOp->p1];
6686 assert( memIsValid(pQuery) );
6687 REGISTER_TRACE(pOp->p3, pQuery);
6688 assert( pCur->eCurType==CURTYPE_VTAB );
6689 pVCur = pCur->uc.pVCur;
6690 pVtab = pVCur->pVtab;
6691 pModule = pVtab->pModule;
6693 /* Grab the index number and argc parameters */
6694 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
6695 nArg = (int)pArgc->u.i;
6696 iQuery = (int)pQuery->u.i;
6698 /* Invoke the xFilter method */
6699 res = 0;
6700 apArg = p->apArg;
6701 for(i = 0; i<nArg; i++){
6702 apArg[i] = &pArgc[i+1];
6704 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
6705 sqlite3VtabImportErrmsg(p, pVtab);
6706 if( rc ) goto abort_due_to_error;
6707 res = pModule->xEof(pVCur);
6708 pCur->nullRow = 0;
6709 VdbeBranchTaken(res!=0,2);
6710 if( res ) goto jump_to_p2;
6711 break;
6713 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6715 #ifndef SQLITE_OMIT_VIRTUALTABLE
6716 /* Opcode: VColumn P1 P2 P3 * P5
6717 ** Synopsis: r[P3]=vcolumn(P2)
6719 ** Store in register P3 the value of the P2-th column of
6720 ** the current row of the virtual-table of cursor P1.
6722 ** If the VColumn opcode is being used to fetch the value of
6723 ** an unchanging column during an UPDATE operation, then the P5
6724 ** value is 1. Otherwise, P5 is 0. The P5 value is returned
6725 ** by sqlite3_vtab_nochange() routine can can be used
6726 ** by virtual table implementations to return special "no-change"
6727 ** marks which can be more efficient, depending on the virtual table.
6729 case OP_VColumn: {
6730 sqlite3_vtab *pVtab;
6731 const sqlite3_module *pModule;
6732 Mem *pDest;
6733 sqlite3_context sContext;
6735 VdbeCursor *pCur = p->apCsr[pOp->p1];
6736 assert( pCur->eCurType==CURTYPE_VTAB );
6737 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6738 pDest = &aMem[pOp->p3];
6739 memAboutToChange(p, pDest);
6740 if( pCur->nullRow ){
6741 sqlite3VdbeMemSetNull(pDest);
6742 break;
6744 pVtab = pCur->uc.pVCur->pVtab;
6745 pModule = pVtab->pModule;
6746 assert( pModule->xColumn );
6747 memset(&sContext, 0, sizeof(sContext));
6748 sContext.pOut = pDest;
6749 if( pOp->p5 ){
6750 sqlite3VdbeMemSetNull(pDest);
6751 pDest->flags = MEM_Null|MEM_Zero;
6752 pDest->u.nZero = 0;
6753 }else{
6754 MemSetTypeFlag(pDest, MEM_Null);
6756 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
6757 sqlite3VtabImportErrmsg(p, pVtab);
6758 if( sContext.isError>0 ){
6759 rc = sContext.isError;
6761 sqlite3VdbeChangeEncoding(pDest, encoding);
6762 REGISTER_TRACE(pOp->p3, pDest);
6763 UPDATE_MAX_BLOBSIZE(pDest);
6765 if( sqlite3VdbeMemTooBig(pDest) ){
6766 goto too_big;
6768 if( rc ) goto abort_due_to_error;
6769 break;
6771 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6773 #ifndef SQLITE_OMIT_VIRTUALTABLE
6774 /* Opcode: VNext P1 P2 * * *
6776 ** Advance virtual table P1 to the next row in its result set and
6777 ** jump to instruction P2. Or, if the virtual table has reached
6778 ** the end of its result set, then fall through to the next instruction.
6780 case OP_VNext: { /* jump */
6781 sqlite3_vtab *pVtab;
6782 const sqlite3_module *pModule;
6783 int res;
6784 VdbeCursor *pCur;
6786 res = 0;
6787 pCur = p->apCsr[pOp->p1];
6788 assert( pCur->eCurType==CURTYPE_VTAB );
6789 if( pCur->nullRow ){
6790 break;
6792 pVtab = pCur->uc.pVCur->pVtab;
6793 pModule = pVtab->pModule;
6794 assert( pModule->xNext );
6796 /* Invoke the xNext() method of the module. There is no way for the
6797 ** underlying implementation to return an error if one occurs during
6798 ** xNext(). Instead, if an error occurs, true is returned (indicating that
6799 ** data is available) and the error code returned when xColumn or
6800 ** some other method is next invoked on the save virtual table cursor.
6802 rc = pModule->xNext(pCur->uc.pVCur);
6803 sqlite3VtabImportErrmsg(p, pVtab);
6804 if( rc ) goto abort_due_to_error;
6805 res = pModule->xEof(pCur->uc.pVCur);
6806 VdbeBranchTaken(!res,2);
6807 if( !res ){
6808 /* If there is data, jump to P2 */
6809 goto jump_to_p2_and_check_for_interrupt;
6811 goto check_for_interrupt;
6813 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6815 #ifndef SQLITE_OMIT_VIRTUALTABLE
6816 /* Opcode: VRename P1 * * P4 *
6818 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6819 ** This opcode invokes the corresponding xRename method. The value
6820 ** in register P1 is passed as the zName argument to the xRename method.
6822 case OP_VRename: {
6823 sqlite3_vtab *pVtab;
6824 Mem *pName;
6826 pVtab = pOp->p4.pVtab->pVtab;
6827 pName = &aMem[pOp->p1];
6828 assert( pVtab->pModule->xRename );
6829 assert( memIsValid(pName) );
6830 assert( p->readOnly==0 );
6831 REGISTER_TRACE(pOp->p1, pName);
6832 assert( pName->flags & MEM_Str );
6833 testcase( pName->enc==SQLITE_UTF8 );
6834 testcase( pName->enc==SQLITE_UTF16BE );
6835 testcase( pName->enc==SQLITE_UTF16LE );
6836 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
6837 if( rc ) goto abort_due_to_error;
6838 rc = pVtab->pModule->xRename(pVtab, pName->z);
6839 sqlite3VtabImportErrmsg(p, pVtab);
6840 p->expired = 0;
6841 if( rc ) goto abort_due_to_error;
6842 break;
6844 #endif
6846 #ifndef SQLITE_OMIT_VIRTUALTABLE
6847 /* Opcode: VUpdate P1 P2 P3 P4 P5
6848 ** Synopsis: data=r[P3@P2]
6850 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6851 ** This opcode invokes the corresponding xUpdate method. P2 values
6852 ** are contiguous memory cells starting at P3 to pass to the xUpdate
6853 ** invocation. The value in register (P3+P2-1) corresponds to the
6854 ** p2th element of the argv array passed to xUpdate.
6856 ** The xUpdate method will do a DELETE or an INSERT or both.
6857 ** The argv[0] element (which corresponds to memory cell P3)
6858 ** is the rowid of a row to delete. If argv[0] is NULL then no
6859 ** deletion occurs. The argv[1] element is the rowid of the new
6860 ** row. This can be NULL to have the virtual table select the new
6861 ** rowid for itself. The subsequent elements in the array are
6862 ** the values of columns in the new row.
6864 ** If P2==1 then no insert is performed. argv[0] is the rowid of
6865 ** a row to delete.
6867 ** P1 is a boolean flag. If it is set to true and the xUpdate call
6868 ** is successful, then the value returned by sqlite3_last_insert_rowid()
6869 ** is set to the value of the rowid for the row just inserted.
6871 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
6872 ** apply in the case of a constraint failure on an insert or update.
6874 case OP_VUpdate: {
6875 sqlite3_vtab *pVtab;
6876 const sqlite3_module *pModule;
6877 int nArg;
6878 int i;
6879 sqlite_int64 rowid;
6880 Mem **apArg;
6881 Mem *pX;
6883 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
6884 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
6886 assert( p->readOnly==0 );
6887 pVtab = pOp->p4.pVtab->pVtab;
6888 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
6889 rc = SQLITE_LOCKED;
6890 goto abort_due_to_error;
6892 pModule = pVtab->pModule;
6893 nArg = pOp->p2;
6894 assert( pOp->p4type==P4_VTAB );
6895 if( ALWAYS(pModule->xUpdate) ){
6896 u8 vtabOnConflict = db->vtabOnConflict;
6897 apArg = p->apArg;
6898 pX = &aMem[pOp->p3];
6899 for(i=0; i<nArg; i++){
6900 assert( memIsValid(pX) );
6901 memAboutToChange(p, pX);
6902 apArg[i] = pX;
6903 pX++;
6905 db->vtabOnConflict = pOp->p5;
6906 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
6907 db->vtabOnConflict = vtabOnConflict;
6908 sqlite3VtabImportErrmsg(p, pVtab);
6909 if( rc==SQLITE_OK && pOp->p1 ){
6910 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
6911 db->lastRowid = rowid;
6913 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
6914 if( pOp->p5==OE_Ignore ){
6915 rc = SQLITE_OK;
6916 }else{
6917 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
6919 }else{
6920 p->nChange++;
6922 if( rc ) goto abort_due_to_error;
6924 break;
6926 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6928 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6929 /* Opcode: Pagecount P1 P2 * * *
6931 ** Write the current number of pages in database P1 to memory cell P2.
6933 case OP_Pagecount: { /* out2 */
6934 pOut = out2Prerelease(p, pOp);
6935 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
6936 break;
6938 #endif
6941 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6942 /* Opcode: MaxPgcnt P1 P2 P3 * *
6944 ** Try to set the maximum page count for database P1 to the value in P3.
6945 ** Do not let the maximum page count fall below the current page count and
6946 ** do not change the maximum page count value if P3==0.
6948 ** Store the maximum page count after the change in register P2.
6950 case OP_MaxPgcnt: { /* out2 */
6951 unsigned int newMax;
6952 Btree *pBt;
6954 pOut = out2Prerelease(p, pOp);
6955 pBt = db->aDb[pOp->p1].pBt;
6956 newMax = 0;
6957 if( pOp->p3 ){
6958 newMax = sqlite3BtreeLastPage(pBt);
6959 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
6961 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
6962 break;
6964 #endif
6966 /* Opcode: Function0 P1 P2 P3 P4 P5
6967 ** Synopsis: r[P3]=func(r[P2@P5])
6969 ** Invoke a user function (P4 is a pointer to a FuncDef object that
6970 ** defines the function) with P5 arguments taken from register P2 and
6971 ** successors. The result of the function is stored in register P3.
6972 ** Register P3 must not be one of the function inputs.
6974 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
6975 ** function was determined to be constant at compile time. If the first
6976 ** argument was constant then bit 0 of P1 is set. This is used to determine
6977 ** whether meta data associated with a user function argument using the
6978 ** sqlite3_set_auxdata() API may be safely retained until the next
6979 ** invocation of this opcode.
6981 ** See also: Function, AggStep, AggFinal
6983 /* Opcode: Function P1 P2 P3 P4 P5
6984 ** Synopsis: r[P3]=func(r[P2@P5])
6986 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
6987 ** contains a pointer to the function to be run) with P5 arguments taken
6988 ** from register P2 and successors. The result of the function is stored
6989 ** in register P3. Register P3 must not be one of the function inputs.
6991 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
6992 ** function was determined to be constant at compile time. If the first
6993 ** argument was constant then bit 0 of P1 is set. This is used to determine
6994 ** whether meta data associated with a user function argument using the
6995 ** sqlite3_set_auxdata() API may be safely retained until the next
6996 ** invocation of this opcode.
6998 ** SQL functions are initially coded as OP_Function0 with P4 pointing
6999 ** to a FuncDef object. But on first evaluation, the P4 operand is
7000 ** automatically converted into an sqlite3_context object and the operation
7001 ** changed to this OP_Function opcode. In this way, the initialization of
7002 ** the sqlite3_context object occurs only once, rather than once for each
7003 ** evaluation of the function.
7005 ** See also: Function0, AggStep, AggFinal
7007 case OP_PureFunc0:
7008 case OP_Function0: {
7009 int n;
7010 sqlite3_context *pCtx;
7012 assert( pOp->p4type==P4_FUNCDEF );
7013 n = pOp->p5;
7014 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7015 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7016 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7017 pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
7018 if( pCtx==0 ) goto no_mem;
7019 pCtx->pOut = 0;
7020 pCtx->pFunc = pOp->p4.pFunc;
7021 pCtx->iOp = (int)(pOp - aOp);
7022 pCtx->pVdbe = p;
7023 pCtx->isError = 0;
7024 pCtx->argc = n;
7025 pOp->p4type = P4_FUNCCTX;
7026 pOp->p4.pCtx = pCtx;
7027 assert( OP_PureFunc == OP_PureFunc0+2 );
7028 assert( OP_Function == OP_Function0+2 );
7029 pOp->opcode += 2;
7030 /* Fall through into OP_Function */
7032 case OP_PureFunc:
7033 case OP_Function: {
7034 int i;
7035 sqlite3_context *pCtx;
7037 assert( pOp->p4type==P4_FUNCCTX );
7038 pCtx = pOp->p4.pCtx;
7040 /* If this function is inside of a trigger, the register array in aMem[]
7041 ** might change from one evaluation to the next. The next block of code
7042 ** checks to see if the register array has changed, and if so it
7043 ** reinitializes the relavant parts of the sqlite3_context object */
7044 pOut = &aMem[pOp->p3];
7045 if( pCtx->pOut != pOut ){
7046 pCtx->pOut = pOut;
7047 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7050 memAboutToChange(p, pOut);
7051 #ifdef SQLITE_DEBUG
7052 for(i=0; i<pCtx->argc; i++){
7053 assert( memIsValid(pCtx->argv[i]) );
7054 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7056 #endif
7057 MemSetTypeFlag(pOut, MEM_Null);
7058 assert( pCtx->isError==0 );
7059 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
7061 /* If the function returned an error, throw an exception */
7062 if( pCtx->isError ){
7063 if( pCtx->isError>0 ){
7064 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
7065 rc = pCtx->isError;
7067 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
7068 pCtx->isError = 0;
7069 if( rc ) goto abort_due_to_error;
7072 /* Copy the result of the function into register P3 */
7073 if( pOut->flags & (MEM_Str|MEM_Blob) ){
7074 sqlite3VdbeChangeEncoding(pOut, encoding);
7075 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
7078 REGISTER_TRACE(pOp->p3, pOut);
7079 UPDATE_MAX_BLOBSIZE(pOut);
7080 break;
7083 /* Opcode: Trace P1 P2 * P4 *
7085 ** Write P4 on the statement trace output if statement tracing is
7086 ** enabled.
7088 ** Operand P1 must be 0x7fffffff and P2 must positive.
7090 /* Opcode: Init P1 P2 P3 P4 *
7091 ** Synopsis: Start at P2
7093 ** Programs contain a single instance of this opcode as the very first
7094 ** opcode.
7096 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7097 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7098 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7100 ** If P2 is not zero, jump to instruction P2.
7102 ** Increment the value of P1 so that OP_Once opcodes will jump the
7103 ** first time they are evaluated for this run.
7105 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7106 ** error is encountered.
7108 case OP_Trace:
7109 case OP_Init: { /* jump */
7110 int i;
7111 #ifndef SQLITE_OMIT_TRACE
7112 char *zTrace;
7113 #endif
7115 /* If the P4 argument is not NULL, then it must be an SQL comment string.
7116 ** The "--" string is broken up to prevent false-positives with srcck1.c.
7118 ** This assert() provides evidence for:
7119 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7120 ** would have been returned by the legacy sqlite3_trace() interface by
7121 ** using the X argument when X begins with "--" and invoking
7122 ** sqlite3_expanded_sql(P) otherwise.
7124 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
7126 /* OP_Init is always instruction 0 */
7127 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
7129 #ifndef SQLITE_OMIT_TRACE
7130 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
7131 && !p->doingRerun
7132 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7134 #ifndef SQLITE_OMIT_DEPRECATED
7135 if( db->mTrace & SQLITE_TRACE_LEGACY ){
7136 void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
7137 char *z = sqlite3VdbeExpandSql(p, zTrace);
7138 x(db->pTraceArg, z);
7139 sqlite3_free(z);
7140 }else
7141 #endif
7142 if( db->nVdbeExec>1 ){
7143 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
7144 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
7145 sqlite3DbFree(db, z);
7146 }else{
7147 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
7150 #ifdef SQLITE_USE_FCNTL_TRACE
7151 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
7152 if( zTrace ){
7153 int j;
7154 for(j=0; j<db->nDb; j++){
7155 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
7156 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
7159 #endif /* SQLITE_USE_FCNTL_TRACE */
7160 #ifdef SQLITE_DEBUG
7161 if( (db->flags & SQLITE_SqlTrace)!=0
7162 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7164 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
7166 #endif /* SQLITE_DEBUG */
7167 #endif /* SQLITE_OMIT_TRACE */
7168 assert( pOp->p2>0 );
7169 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
7170 if( pOp->opcode==OP_Trace ) break;
7171 for(i=1; i<p->nOp; i++){
7172 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
7174 pOp->p1 = 0;
7176 pOp->p1++;
7177 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
7178 goto jump_to_p2;
7181 #ifdef SQLITE_ENABLE_CURSOR_HINTS
7182 /* Opcode: CursorHint P1 * * P4 *
7184 ** Provide a hint to cursor P1 that it only needs to return rows that
7185 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
7186 ** to values currently held in registers. TK_COLUMN terms in the P4
7187 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
7189 case OP_CursorHint: {
7190 VdbeCursor *pC;
7192 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7193 assert( pOp->p4type==P4_EXPR );
7194 pC = p->apCsr[pOp->p1];
7195 if( pC ){
7196 assert( pC->eCurType==CURTYPE_BTREE );
7197 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
7198 pOp->p4.pExpr, aMem);
7200 break;
7202 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
7204 /* Opcode: Noop * * * * *
7206 ** Do nothing. This instruction is often useful as a jump
7207 ** destination.
7210 ** The magic Explain opcode are only inserted when explain==2 (which
7211 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
7212 ** This opcode records information from the optimizer. It is the
7213 ** the same as a no-op. This opcodesnever appears in a real VM program.
7215 default: { /* This is really OP_Noop and OP_Explain */
7216 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
7217 break;
7220 /*****************************************************************************
7221 ** The cases of the switch statement above this line should all be indented
7222 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
7223 ** readability. From this point on down, the normal indentation rules are
7224 ** restored.
7225 *****************************************************************************/
7228 #ifdef VDBE_PROFILE
7230 u64 endTime = sqlite3Hwtime();
7231 if( endTime>start ) pOrigOp->cycles += endTime - start;
7232 pOrigOp->cnt++;
7234 #endif
7236 /* The following code adds nothing to the actual functionality
7237 ** of the program. It is only here for testing and debugging.
7238 ** On the other hand, it does burn CPU cycles every time through
7239 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
7241 #ifndef NDEBUG
7242 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
7244 #ifdef SQLITE_DEBUG
7245 if( db->flags & SQLITE_VdbeTrace ){
7246 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
7247 if( rc!=0 ) printf("rc=%d\n",rc);
7248 if( opProperty & (OPFLG_OUT2) ){
7249 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
7251 if( opProperty & OPFLG_OUT3 ){
7252 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
7255 #endif /* SQLITE_DEBUG */
7256 #endif /* NDEBUG */
7257 } /* The end of the for(;;) loop the loops through opcodes */
7259 /* If we reach this point, it means that execution is finished with
7260 ** an error of some kind.
7262 abort_due_to_error:
7263 if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
7264 assert( rc );
7265 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
7266 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7268 p->rc = rc;
7269 sqlite3SystemError(db, rc);
7270 testcase( sqlite3GlobalConfig.xLog!=0 );
7271 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
7272 (int)(pOp - aOp), p->zSql, p->zErrMsg);
7273 sqlite3VdbeHalt(p);
7274 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
7275 rc = SQLITE_ERROR;
7276 if( resetSchemaOnFault>0 ){
7277 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
7280 /* This is the only way out of this procedure. We have to
7281 ** release the mutexes on btrees that were acquired at the
7282 ** top. */
7283 vdbe_return:
7284 testcase( nVmStep>0 );
7285 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
7286 sqlite3VdbeLeave(p);
7287 assert( rc!=SQLITE_OK || nExtraDelete==0
7288 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
7290 return rc;
7292 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
7293 ** is encountered.
7295 too_big:
7296 sqlite3VdbeError(p, "string or blob too big");
7297 rc = SQLITE_TOOBIG;
7298 goto abort_due_to_error;
7300 /* Jump to here if a malloc() fails.
7302 no_mem:
7303 sqlite3OomFault(db);
7304 sqlite3VdbeError(p, "out of memory");
7305 rc = SQLITE_NOMEM_BKPT;
7306 goto abort_due_to_error;
7308 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
7309 ** flag.
7311 abort_due_to_interrupt:
7312 assert( db->u1.isInterrupted );
7313 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
7314 p->rc = rc;
7315 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
7316 goto abort_due_to_error;