4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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"
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.
34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
36 # define memAboutToChange(P,M)
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.
47 int sqlite3_search_count
= 0;
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.
59 int sqlite3_interrupt_count
= 0;
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
70 int sqlite3_sort_count
= 0;
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.
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
;
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)
96 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
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
107 int sqlite3_found_count
= 0;
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_OMIT_BUILTIN_TEST)
115 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
117 # define UPDATE_MAX_BLOBSIZE(P)
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)
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) ){
143 /* Assert the truth of VdbeCoverageAlwaysTaken() and
144 ** VdbeCoverageNeverTaken() */
145 assert( (M
& I
)==I
);
147 if( sqlite3GlobalConfig
.xVdbeBranch
==0 ) return; /*NO_TEST*/
148 sqlite3GlobalConfig
.xVdbeBranch(sqlite3GlobalConfig
.pVdbeBranchArg
,
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)) \
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
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
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
;
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
]);
222 if( SQLITE_OK
==sqlite3VdbeMemClearAndResize(pMem
, nByte
) ){
223 p
->apCsr
[iCur
] = pCx
= (VdbeCursor
*)pMem
->z
;
224 memset(pCx
, 0, sizeof(VdbeCursor
));
225 pCx
->eCurType
= eCurType
;
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
);
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
){
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
) ){
261 pRec
->flags
|= MEM_Int
;
264 pRec
->flags
|= MEM_Real
;
265 if( bTryForInt
) sqlite3VdbeIntegerAffinity(pRec
);
270 ** Processing is determine by the affinity parameter:
272 ** SQLITE_AFF_INTEGER:
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.
282 ** Convert pRec to a text representation.
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);
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
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
);
334 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
335 ** not the internal Mem* type.
337 void sqlite3ValueApplyAffinity(
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
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 ){
357 if( sqlite3Atoi64(pMem
->z
, &pMem
->u
.i
, pMem
->n
, pMem
->enc
)==SQLITE_OK
){
364 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
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
);
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
){
389 static const char *const encnames
[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
396 assert( (f
& (MEM_Static
|MEM_Ephem
))==0 );
397 }else if( f
& MEM_Static
){
399 assert( (f
& (MEM_Dyn
|MEM_Ephem
))==0 );
400 }else if( f
& MEM_Ephem
){
402 assert( (f
& (MEM_Static
|MEM_Dyn
))==0 );
407 sqlite3_snprintf(100, zCsr
, "%c", c
);
408 zCsr
+= sqlite3Strlen30(zCsr
);
409 sqlite3_snprintf(100, zCsr
, "%d[", pMem
->n
);
410 zCsr
+= sqlite3Strlen30(zCsr
);
411 for(i
=0; i
<16 && i
<pMem
->n
; i
++){
412 sqlite3_snprintf(100, zCsr
, "%02X", ((int)pMem
->z
[i
] & 0xFF));
413 zCsr
+= sqlite3Strlen30(zCsr
);
415 for(i
=0; i
<16 && i
<pMem
->n
; i
++){
417 if( z
<32 || z
>126 ) *zCsr
++ = '.';
421 sqlite3_snprintf(100, zCsr
, "]%s", encnames
[pMem
->enc
]);
422 zCsr
+= sqlite3Strlen30(zCsr
);
424 sqlite3_snprintf(100, zCsr
,"+%dz",pMem
->u
.nZero
);
425 zCsr
+= sqlite3Strlen30(zCsr
);
428 }else if( f
& MEM_Str
){
433 assert( (f
& (MEM_Static
|MEM_Ephem
))==0 );
434 }else if( f
& MEM_Static
){
436 assert( (f
& (MEM_Dyn
|MEM_Ephem
))==0 );
437 }else if( f
& MEM_Ephem
){
439 assert( (f
& (MEM_Static
|MEM_Dyn
))==0 );
444 sqlite3_snprintf(100, &zBuf
[k
], "%d", pMem
->n
);
445 k
+= sqlite3Strlen30(&zBuf
[k
]);
447 for(j
=0; j
<15 && j
<pMem
->n
; j
++){
449 if( c
>=0x20 && c
<0x7f ){
456 sqlite3_snprintf(100,&zBuf
[k
], encnames
[pMem
->enc
]);
457 k
+= sqlite3Strlen30(&zBuf
[k
]);
465 ** Print the value of a register for tracing purposes:
467 static void memTracePrint(Mem
*p
){
468 if( p
->flags
& MEM_Undefined
){
469 printf(" undefined");
470 }else if( p
->flags
& MEM_Null
){
472 }else if( (p
->flags
& (MEM_Int
|MEM_Str
))==(MEM_Int
|MEM_Str
) ){
473 printf(" si:%lld", p
->u
.i
);
474 }else if( p
->flags
& MEM_Int
){
475 printf(" i:%lld", p
->u
.i
);
476 #ifndef SQLITE_OMIT_FLOATING_POINT
477 }else if( p
->flags
& MEM_Real
){
478 printf(" r:%g", p
->u
.r
);
480 }else if( p
->flags
& MEM_RowSet
){
484 sqlite3VdbeMemPrettyPrint(p
, zBuf
);
487 if( p
->flags
& MEM_Subtype
) printf(" subtype=0x%02x", p
->eSubtype
);
489 static void registerTrace(int iReg
, Mem
*p
){
490 printf("REG[%d] = ", iReg
);
497 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
499 # define REGISTER_TRACE(R,M)
506 ** hwtime.h contains inline assembler code for implementing
507 ** high-performance timing routines.
515 ** This function is only called from within an assert() expression. It
516 ** checks that the sqlite3.nTransaction variable is correctly set to
517 ** the number of non-transaction savepoints currently in the
518 ** linked list starting at sqlite3.pSavepoint.
522 ** assert( checkSavepointCount(db) );
524 static int checkSavepointCount(sqlite3
*db
){
527 for(p
=db
->pSavepoint
; p
; p
=p
->pNext
) n
++;
528 assert( n
==(db
->nSavepoint
+ db
->isTransactionSavepoint
) );
534 ** Return the register of pOp->p2 after first preparing it to be
535 ** overwritten with an integer value.
537 static SQLITE_NOINLINE Mem
*out2PrereleaseWithClear(Mem
*pOut
){
538 sqlite3VdbeMemSetNull(pOut
);
539 pOut
->flags
= MEM_Int
;
542 static Mem
*out2Prerelease(Vdbe
*p
, VdbeOp
*pOp
){
545 assert( pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
) );
546 pOut
= &p
->aMem
[pOp
->p2
];
547 memAboutToChange(p
, pOut
);
548 if( VdbeMemDynamic(pOut
) ){ /*OPTIMIZATION-IF-FALSE*/
549 return out2PrereleaseWithClear(pOut
);
551 pOut
->flags
= MEM_Int
;
558 ** Execute as much of a VDBE program as we can.
559 ** This is the core of sqlite3_step().
562 Vdbe
*p
/* The VDBE */
564 Op
*aOp
= p
->aOp
; /* Copy of p->aOp */
565 Op
*pOp
= aOp
; /* Current operation */
566 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
567 Op
*pOrigOp
; /* Value of pOp at the top of the loop */
570 int nExtraDelete
= 0; /* Verifies FORDELETE and AUXDELETE flags */
572 int rc
= SQLITE_OK
; /* Value to return */
573 sqlite3
*db
= p
->db
; /* The database */
574 u8 resetSchemaOnFault
= 0; /* Reset schema after an error if positive */
575 u8 encoding
= ENC(db
); /* The database encoding */
576 int iCompare
= 0; /* Result of last OP_Compare operation */
577 unsigned nVmStep
= 0; /* Number of virtual machine steps */
578 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
579 unsigned nProgressLimit
= 0;/* Invoke xProgress() when nVmStep reaches this */
581 Mem
*aMem
= p
->aMem
; /* Copy of p->aMem */
582 Mem
*pIn1
= 0; /* 1st input operand */
583 Mem
*pIn2
= 0; /* 2nd input operand */
584 Mem
*pIn3
= 0; /* 3rd input operand */
585 Mem
*pOut
= 0; /* Output operand */
586 int *aPermute
= 0; /* Permutation of columns for OP_Compare */
587 i64 lastRowid
= db
->lastRowid
; /* Saved value of the last insert ROWID */
589 u64 start
; /* CPU clock count at start of opcode */
591 /*** INSERT STACK UNION HERE ***/
593 assert( p
->magic
==VDBE_MAGIC_RUN
); /* sqlite3_step() verifies this */
595 if( p
->rc
==SQLITE_NOMEM
){
596 /* This happens if a malloc() inside a call to sqlite3_column_text() or
597 ** sqlite3_column_text16() failed. */
600 assert( p
->rc
==SQLITE_OK
|| (p
->rc
&0xff)==SQLITE_BUSY
);
601 assert( p
->bIsReader
|| p
->readOnly
!=0 );
604 assert( p
->explain
==0 );
606 db
->busyHandler
.nBusy
= 0;
607 if( db
->u1
.isInterrupted
) goto abort_due_to_interrupt
;
608 sqlite3VdbeIOTraceSql(p
);
609 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
611 u32 iPrior
= p
->aCounter
[SQLITE_STMTSTATUS_VM_STEP
];
612 assert( 0 < db
->nProgressOps
);
613 nProgressLimit
= db
->nProgressOps
- (iPrior
% db
->nProgressOps
);
617 sqlite3BeginBenignMalloc();
619 && (p
->db
->flags
& (SQLITE_VdbeListing
|SQLITE_VdbeEQP
|SQLITE_VdbeTrace
))!=0
623 sqlite3VdbePrintSql(p
);
624 if( p
->db
->flags
& SQLITE_VdbeListing
){
625 printf("VDBE Program Listing:\n");
626 for(i
=0; i
<p
->nOp
; i
++){
627 sqlite3VdbePrintOp(stdout
, i
, &aOp
[i
]);
630 if( p
->db
->flags
& SQLITE_VdbeEQP
){
631 for(i
=0; i
<p
->nOp
; i
++){
632 if( aOp
[i
].opcode
==OP_Explain
){
633 if( once
) printf("VDBE Query Plan:\n");
634 printf("%s\n", aOp
[i
].p4
.z
);
639 if( p
->db
->flags
& SQLITE_VdbeTrace
) printf("VDBE Trace:\n");
641 sqlite3EndBenignMalloc();
643 for(pOp
=&aOp
[p
->pc
]; 1; pOp
++){
644 /* Errors are detected by individual opcodes, with an immediate
645 ** jumps to abort_due_to_error. */
646 assert( rc
==SQLITE_OK
);
648 assert( pOp
>=aOp
&& pOp
<&aOp
[p
->nOp
]);
650 start
= sqlite3Hwtime();
653 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
654 if( p
->anExec
) p
->anExec
[(int)(pOp
-aOp
)]++;
657 /* Only allow tracing if SQLITE_DEBUG is defined.
660 if( db
->flags
& SQLITE_VdbeTrace
){
661 sqlite3VdbePrintOp(stdout
, (int)(pOp
- aOp
), pOp
);
666 /* Check to see if we need to simulate an interrupt. This only happens
667 ** if we have a special test build.
670 if( sqlite3_interrupt_count
>0 ){
671 sqlite3_interrupt_count
--;
672 if( sqlite3_interrupt_count
==0 ){
673 sqlite3_interrupt(db
);
678 /* Sanity checking on other operands */
681 u8 opProperty
= sqlite3OpcodeProperty
[pOp
->opcode
];
682 if( (opProperty
& OPFLG_IN1
)!=0 ){
684 assert( pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
685 assert( memIsValid(&aMem
[pOp
->p1
]) );
686 assert( sqlite3VdbeCheckMemInvariants(&aMem
[pOp
->p1
]) );
687 REGISTER_TRACE(pOp
->p1
, &aMem
[pOp
->p1
]);
689 if( (opProperty
& OPFLG_IN2
)!=0 ){
691 assert( pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
) );
692 assert( memIsValid(&aMem
[pOp
->p2
]) );
693 assert( sqlite3VdbeCheckMemInvariants(&aMem
[pOp
->p2
]) );
694 REGISTER_TRACE(pOp
->p2
, &aMem
[pOp
->p2
]);
696 if( (opProperty
& OPFLG_IN3
)!=0 ){
698 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
699 assert( memIsValid(&aMem
[pOp
->p3
]) );
700 assert( sqlite3VdbeCheckMemInvariants(&aMem
[pOp
->p3
]) );
701 REGISTER_TRACE(pOp
->p3
, &aMem
[pOp
->p3
]);
703 if( (opProperty
& OPFLG_OUT2
)!=0 ){
705 assert( pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
) );
706 memAboutToChange(p
, &aMem
[pOp
->p2
]);
708 if( (opProperty
& OPFLG_OUT3
)!=0 ){
710 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
711 memAboutToChange(p
, &aMem
[pOp
->p3
]);
715 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
719 switch( pOp
->opcode
){
721 /*****************************************************************************
722 ** What follows is a massive switch statement where each case implements a
723 ** separate instruction in the virtual machine. If we follow the usual
724 ** indentation conventions, each case should be indented by 6 spaces. But
725 ** that is a lot of wasted space on the left margin. So the code within
726 ** the switch statement will break with convention and be flush-left. Another
727 ** big comment (similar to this one) will mark the point in the code where
728 ** we transition back to normal indentation.
730 ** The formatting of each case is important. The makefile for SQLite
731 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
732 ** file looking for lines that begin with "case OP_". The opcodes.h files
733 ** will be filled with #defines that give unique integer values to each
734 ** opcode and the opcodes.c file is filled with an array of strings where
735 ** each string is the symbolic name for the corresponding opcode. If the
736 ** case statement is followed by a comment of the form "/# same as ... #/"
737 ** that comment is used to determine the particular value of the opcode.
739 ** Other keywords in the comment that follows each case are used to
740 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
741 ** Keywords include: in1, in2, in3, out2, out3. See
742 ** the mkopcodeh.awk script for additional information.
744 ** Documentation about VDBE opcodes is generated by scanning this file
745 ** for lines of that contain "Opcode:". That line and all subsequent
746 ** comment lines are used in the generation of the opcode.html documentation
751 ** Formatting is important to scripts that scan this file.
752 ** Do not deviate from the formatting style currently in use.
754 *****************************************************************************/
756 /* Opcode: Goto * P2 * * *
758 ** An unconditional jump to address P2.
759 ** The next instruction executed will be
760 ** the one at index P2 from the beginning of
763 ** The P1 parameter is not actually used by this opcode. However, it
764 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
765 ** that this Goto is the bottom of a loop and that the lines from P2 down
766 ** to the current line should be indented for EXPLAIN output.
768 case OP_Goto
: { /* jump */
769 jump_to_p2_and_check_for_interrupt
:
770 pOp
= &aOp
[pOp
->p2
- 1];
772 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
773 ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
774 ** completion. Check to see if sqlite3_interrupt() has been called
775 ** or if the progress callback needs to be invoked.
777 ** This code uses unstructured "goto" statements and does not look clean.
778 ** But that is not due to sloppy coding habits. The code is written this
779 ** way for performance, to avoid having to run the interrupt and progress
780 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
781 ** faster according to "valgrind --tool=cachegrind" */
783 if( db
->u1
.isInterrupted
) goto abort_due_to_interrupt
;
784 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
785 /* Call the progress callback if it is configured and the required number
786 ** of VDBE ops have been executed (either since this invocation of
787 ** sqlite3VdbeExec() or since last time the progress callback was called).
788 ** If the progress callback returns non-zero, exit the virtual machine with
789 ** a return code SQLITE_ABORT.
791 if( db
->xProgress
!=0 && nVmStep
>=nProgressLimit
){
792 assert( db
->nProgressOps
!=0 );
793 nProgressLimit
= nVmStep
+ db
->nProgressOps
- (nVmStep
%db
->nProgressOps
);
794 if( db
->xProgress(db
->pProgressArg
) ){
795 rc
= SQLITE_INTERRUPT
;
796 goto abort_due_to_error
;
804 /* Opcode: Gosub P1 P2 * * *
806 ** Write the current address onto register P1
807 ** and then jump to address P2.
809 case OP_Gosub
: { /* jump */
810 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
811 pIn1
= &aMem
[pOp
->p1
];
812 assert( VdbeMemDynamic(pIn1
)==0 );
813 memAboutToChange(p
, pIn1
);
814 pIn1
->flags
= MEM_Int
;
815 pIn1
->u
.i
= (int)(pOp
-aOp
);
816 REGISTER_TRACE(pOp
->p1
, pIn1
);
818 /* Most jump operations do a goto to this spot in order to update
819 ** the pOp pointer. */
821 pOp
= &aOp
[pOp
->p2
- 1];
825 /* Opcode: Return P1 * * * *
827 ** Jump to the next instruction after the address in register P1. After
828 ** the jump, register P1 becomes undefined.
830 case OP_Return
: { /* in1 */
831 pIn1
= &aMem
[pOp
->p1
];
832 assert( pIn1
->flags
==MEM_Int
);
833 pOp
= &aOp
[pIn1
->u
.i
];
834 pIn1
->flags
= MEM_Undefined
;
838 /* Opcode: InitCoroutine P1 P2 P3 * *
840 ** Set up register P1 so that it will Yield to the coroutine
841 ** located at address P3.
843 ** If P2!=0 then the coroutine implementation immediately follows
844 ** this opcode. So jump over the coroutine implementation to
847 ** See also: EndCoroutine
849 case OP_InitCoroutine
: { /* jump */
850 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
851 assert( pOp
->p2
>=0 && pOp
->p2
<p
->nOp
);
852 assert( pOp
->p3
>=0 && pOp
->p3
<p
->nOp
);
853 pOut
= &aMem
[pOp
->p1
];
854 assert( !VdbeMemDynamic(pOut
) );
855 pOut
->u
.i
= pOp
->p3
- 1;
856 pOut
->flags
= MEM_Int
;
857 if( pOp
->p2
) goto jump_to_p2
;
861 /* Opcode: EndCoroutine P1 * * * *
863 ** The instruction at the address in register P1 is a Yield.
864 ** Jump to the P2 parameter of that Yield.
865 ** After the jump, register P1 becomes undefined.
867 ** See also: InitCoroutine
869 case OP_EndCoroutine
: { /* in1 */
871 pIn1
= &aMem
[pOp
->p1
];
872 assert( pIn1
->flags
==MEM_Int
);
873 assert( pIn1
->u
.i
>=0 && pIn1
->u
.i
<p
->nOp
);
874 pCaller
= &aOp
[pIn1
->u
.i
];
875 assert( pCaller
->opcode
==OP_Yield
);
876 assert( pCaller
->p2
>=0 && pCaller
->p2
<p
->nOp
);
877 pOp
= &aOp
[pCaller
->p2
- 1];
878 pIn1
->flags
= MEM_Undefined
;
882 /* Opcode: Yield P1 P2 * * *
884 ** Swap the program counter with the value in register P1. This
885 ** has the effect of yielding to a coroutine.
887 ** If the coroutine that is launched by this instruction ends with
888 ** Yield or Return then continue to the next instruction. But if
889 ** the coroutine launched by this instruction ends with
890 ** EndCoroutine, then jump to P2 rather than continuing with the
893 ** See also: InitCoroutine
895 case OP_Yield
: { /* in1, jump */
897 pIn1
= &aMem
[pOp
->p1
];
898 assert( VdbeMemDynamic(pIn1
)==0 );
899 pIn1
->flags
= MEM_Int
;
900 pcDest
= (int)pIn1
->u
.i
;
901 pIn1
->u
.i
= (int)(pOp
- aOp
);
902 REGISTER_TRACE(pOp
->p1
, pIn1
);
907 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
908 ** Synopsis: if r[P3]=null halt
910 ** Check the value in register P3. If it is NULL then Halt using
911 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
912 ** value in register P3 is not NULL, then this routine is a no-op.
913 ** The P5 parameter should be 1.
915 case OP_HaltIfNull
: { /* in3 */
916 pIn3
= &aMem
[pOp
->p3
];
917 if( (pIn3
->flags
& MEM_Null
)==0 ) break;
918 /* Fall through into OP_Halt */
921 /* Opcode: Halt P1 P2 * P4 P5
923 ** Exit immediately. All open cursors, etc are closed
926 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
927 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
928 ** For errors, it can be some other value. If P1!=0 then P2 will determine
929 ** whether or not to rollback the current transaction. Do not rollback
930 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
931 ** then back out all changes that have occurred during this execution of the
932 ** VDBE, but do not rollback the transaction.
934 ** If P4 is not null then it is an error message string.
936 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
939 ** 1: NOT NULL contraint failed: P4
940 ** 2: UNIQUE constraint failed: P4
941 ** 3: CHECK constraint failed: P4
942 ** 4: FOREIGN KEY constraint failed: P4
944 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
947 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
948 ** every program. So a jump past the last instruction of the program
949 ** is the same as executing Halt.
955 pcx
= (int)(pOp
- aOp
);
956 if( pOp
->p1
==SQLITE_OK
&& p
->pFrame
){
957 /* Halt the sub-program. Return control to the parent frame. */
959 p
->pFrame
= pFrame
->pParent
;
961 sqlite3VdbeSetChanges(db
, p
->nChange
);
962 pcx
= sqlite3VdbeFrameRestore(pFrame
);
963 lastRowid
= db
->lastRowid
;
964 if( pOp
->p2
==OE_Ignore
){
965 /* Instruction pcx is the OP_Program that invoked the sub-program
966 ** currently being halted. If the p2 instruction of this OP_Halt
967 ** instruction is set to OE_Ignore, then the sub-program is throwing
968 ** an IGNORE exception. In this case jump to the address specified
969 ** as the p2 of the calling OP_Program. */
970 pcx
= p
->aOp
[pcx
].p2
-1;
978 p
->errorAction
= (u8
)pOp
->p2
;
980 assert( pOp
->p5
>=0 && pOp
->p5
<=4 );
983 static const char * const azType
[] = { "NOT NULL", "UNIQUE", "CHECK",
985 testcase( pOp
->p5
==1 );
986 testcase( pOp
->p5
==2 );
987 testcase( pOp
->p5
==3 );
988 testcase( pOp
->p5
==4 );
989 sqlite3VdbeError(p
, "%s constraint failed", azType
[pOp
->p5
-1]);
991 p
->zErrMsg
= sqlite3MPrintf(db
, "%z: %s", p
->zErrMsg
, pOp
->p4
.z
);
994 sqlite3VdbeError(p
, "%s", pOp
->p4
.z
);
996 sqlite3_log(pOp
->p1
, "abort at %d in [%s]: %s", pcx
, p
->zSql
, p
->zErrMsg
);
998 rc
= sqlite3VdbeHalt(p
);
999 assert( rc
==SQLITE_BUSY
|| rc
==SQLITE_OK
|| rc
==SQLITE_ERROR
);
1000 if( rc
==SQLITE_BUSY
){
1001 p
->rc
= SQLITE_BUSY
;
1003 assert( rc
==SQLITE_OK
|| (p
->rc
&0xff)==SQLITE_CONSTRAINT
);
1004 assert( rc
==SQLITE_OK
|| db
->nDeferredCons
>0 || db
->nDeferredImmCons
>0 );
1005 rc
= p
->rc
? SQLITE_ERROR
: SQLITE_DONE
;
1010 /* Opcode: Integer P1 P2 * * *
1011 ** Synopsis: r[P2]=P1
1013 ** The 32-bit integer value P1 is written into register P2.
1015 case OP_Integer
: { /* out2 */
1016 pOut
= out2Prerelease(p
, pOp
);
1017 pOut
->u
.i
= pOp
->p1
;
1021 /* Opcode: Int64 * P2 * P4 *
1022 ** Synopsis: r[P2]=P4
1024 ** P4 is a pointer to a 64-bit integer value.
1025 ** Write that value into register P2.
1027 case OP_Int64
: { /* out2 */
1028 pOut
= out2Prerelease(p
, pOp
);
1029 assert( pOp
->p4
.pI64
!=0 );
1030 pOut
->u
.i
= *pOp
->p4
.pI64
;
1034 #ifndef SQLITE_OMIT_FLOATING_POINT
1035 /* Opcode: Real * P2 * P4 *
1036 ** Synopsis: r[P2]=P4
1038 ** P4 is a pointer to a 64-bit floating point value.
1039 ** Write that value into register P2.
1041 case OP_Real
: { /* same as TK_FLOAT, out2 */
1042 pOut
= out2Prerelease(p
, pOp
);
1043 pOut
->flags
= MEM_Real
;
1044 assert( !sqlite3IsNaN(*pOp
->p4
.pReal
) );
1045 pOut
->u
.r
= *pOp
->p4
.pReal
;
1050 /* Opcode: String8 * P2 * P4 *
1051 ** Synopsis: r[P2]='P4'
1053 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1054 ** into a String opcode before it is executed for the first time. During
1055 ** this transformation, the length of string P4 is computed and stored
1056 ** as the P1 parameter.
1058 case OP_String8
: { /* same as TK_STRING, out2 */
1059 assert( pOp
->p4
.z
!=0 );
1060 pOut
= out2Prerelease(p
, pOp
);
1061 pOp
->opcode
= OP_String
;
1062 pOp
->p1
= sqlite3Strlen30(pOp
->p4
.z
);
1064 #ifndef SQLITE_OMIT_UTF16
1065 if( encoding
!=SQLITE_UTF8
){
1066 rc
= sqlite3VdbeMemSetStr(pOut
, pOp
->p4
.z
, -1, SQLITE_UTF8
, SQLITE_STATIC
);
1067 assert( rc
==SQLITE_OK
|| rc
==SQLITE_TOOBIG
);
1068 if( SQLITE_OK
!=sqlite3VdbeChangeEncoding(pOut
, encoding
) ) goto no_mem
;
1069 assert( pOut
->szMalloc
>0 && pOut
->zMalloc
==pOut
->z
);
1070 assert( VdbeMemDynamic(pOut
)==0 );
1072 pOut
->flags
|= MEM_Static
;
1073 if( pOp
->p4type
==P4_DYNAMIC
){
1074 sqlite3DbFree(db
, pOp
->p4
.z
);
1076 pOp
->p4type
= P4_DYNAMIC
;
1077 pOp
->p4
.z
= pOut
->z
;
1080 testcase( rc
==SQLITE_TOOBIG
);
1082 if( pOp
->p1
>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
1085 assert( rc
==SQLITE_OK
);
1086 /* Fall through to the next case, OP_String */
1089 /* Opcode: String P1 P2 P3 P4 P5
1090 ** Synopsis: r[P2]='P4' (len=P1)
1092 ** The string value P4 of length P1 (bytes) is stored in register P2.
1094 ** If P3 is not zero and the content of register P3 is equal to P5, then
1095 ** the datatype of the register P2 is converted to BLOB. The content is
1096 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1097 ** of a string, as if it had been CAST. In other words:
1099 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1101 case OP_String
: { /* out2 */
1102 assert( pOp
->p4
.z
!=0 );
1103 pOut
= out2Prerelease(p
, pOp
);
1104 pOut
->flags
= MEM_Str
|MEM_Static
|MEM_Term
;
1105 pOut
->z
= pOp
->p4
.z
;
1107 pOut
->enc
= encoding
;
1108 UPDATE_MAX_BLOBSIZE(pOut
);
1109 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1111 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
1112 pIn3
= &aMem
[pOp
->p3
];
1113 assert( pIn3
->flags
& MEM_Int
);
1114 if( pIn3
->u
.i
==pOp
->p5
) pOut
->flags
= MEM_Blob
|MEM_Static
|MEM_Term
;
1120 /* Opcode: Null P1 P2 P3 * *
1121 ** Synopsis: r[P2..P3]=NULL
1123 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1124 ** NULL into register P3 and every register in between P2 and P3. If P3
1125 ** is less than P2 (typically P3 is zero) then only register P2 is
1128 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1129 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1132 case OP_Null
: { /* out2 */
1135 pOut
= out2Prerelease(p
, pOp
);
1136 cnt
= pOp
->p3
-pOp
->p2
;
1137 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
1138 pOut
->flags
= nullFlag
= pOp
->p1
? (MEM_Null
|MEM_Cleared
) : MEM_Null
;
1141 memAboutToChange(p
, pOut
);
1142 sqlite3VdbeMemSetNull(pOut
);
1143 pOut
->flags
= nullFlag
;
1149 /* Opcode: SoftNull P1 * * * *
1150 ** Synopsis: r[P1]=NULL
1152 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1153 ** instruction, but do not free any string or blob memory associated with
1154 ** the register, so that if the value was a string or blob that was
1155 ** previously copied using OP_SCopy, the copies will continue to be valid.
1158 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
1159 pOut
= &aMem
[pOp
->p1
];
1160 pOut
->flags
= (pOut
->flags
|MEM_Null
)&~MEM_Undefined
;
1164 /* Opcode: Blob P1 P2 * P4 *
1165 ** Synopsis: r[P2]=P4 (len=P1)
1167 ** P4 points to a blob of data P1 bytes long. Store this
1168 ** blob in register P2.
1170 case OP_Blob
: { /* out2 */
1171 assert( pOp
->p1
<= SQLITE_MAX_LENGTH
);
1172 pOut
= out2Prerelease(p
, pOp
);
1173 sqlite3VdbeMemSetStr(pOut
, pOp
->p4
.z
, pOp
->p1
, 0, 0);
1174 pOut
->enc
= encoding
;
1175 UPDATE_MAX_BLOBSIZE(pOut
);
1179 /* Opcode: Variable P1 P2 * P4 *
1180 ** Synopsis: r[P2]=parameter(P1,P4)
1182 ** Transfer the values of bound parameter P1 into register P2
1184 ** If the parameter is named, then its name appears in P4.
1185 ** The P4 value is used by sqlite3_bind_parameter_name().
1187 case OP_Variable
: { /* out2 */
1188 Mem
*pVar
; /* Value being transferred */
1190 assert( pOp
->p1
>0 && pOp
->p1
<=p
->nVar
);
1191 assert( pOp
->p4
.z
==0 || pOp
->p4
.z
==p
->azVar
[pOp
->p1
-1] );
1192 pVar
= &p
->aVar
[pOp
->p1
- 1];
1193 if( sqlite3VdbeMemTooBig(pVar
) ){
1196 pOut
= out2Prerelease(p
, pOp
);
1197 sqlite3VdbeMemShallowCopy(pOut
, pVar
, MEM_Static
);
1198 UPDATE_MAX_BLOBSIZE(pOut
);
1202 /* Opcode: Move P1 P2 P3 * *
1203 ** Synopsis: r[P2@P3]=r[P1@P3]
1205 ** Move the P3 values in register P1..P1+P3-1 over into
1206 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1207 ** left holding a NULL. It is an error for register ranges
1208 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1209 ** for P3 to be less than 1.
1212 int n
; /* Number of registers left to copy */
1213 int p1
; /* Register to copy from */
1214 int p2
; /* Register to copy to */
1219 assert( n
>0 && p1
>0 && p2
>0 );
1220 assert( p1
+n
<=p2
|| p2
+n
<=p1
);
1225 assert( pOut
<=&aMem
[(p
->nMem
+1 - p
->nCursor
)] );
1226 assert( pIn1
<=&aMem
[(p
->nMem
+1 - p
->nCursor
)] );
1227 assert( memIsValid(pIn1
) );
1228 memAboutToChange(p
, pOut
);
1229 sqlite3VdbeMemMove(pOut
, pIn1
);
1231 if( pOut
->pScopyFrom
>=&aMem
[p1
] && pOut
->pScopyFrom
<pOut
){
1232 pOut
->pScopyFrom
+= pOp
->p2
- p1
;
1235 Deephemeralize(pOut
);
1236 REGISTER_TRACE(p2
++, pOut
);
1243 /* Opcode: Copy P1 P2 P3 * *
1244 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1246 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1248 ** This instruction makes a deep copy of the value. A duplicate
1249 ** is made of any string or blob constant. See also OP_SCopy.
1255 pIn1
= &aMem
[pOp
->p1
];
1256 pOut
= &aMem
[pOp
->p2
];
1257 assert( pOut
!=pIn1
);
1259 sqlite3VdbeMemShallowCopy(pOut
, pIn1
, MEM_Ephem
);
1260 Deephemeralize(pOut
);
1262 pOut
->pScopyFrom
= 0;
1264 REGISTER_TRACE(pOp
->p2
+pOp
->p3
-n
, pOut
);
1265 if( (n
--)==0 ) break;
1272 /* Opcode: SCopy P1 P2 * * *
1273 ** Synopsis: r[P2]=r[P1]
1275 ** Make a shallow copy of register P1 into register P2.
1277 ** This instruction makes a shallow copy of the value. If the value
1278 ** is a string or blob, then the copy is only a pointer to the
1279 ** original and hence if the original changes so will the copy.
1280 ** Worse, if the original is deallocated, the copy becomes invalid.
1281 ** Thus the program must guarantee that the original will not change
1282 ** during the lifetime of the copy. Use OP_Copy to make a complete
1285 case OP_SCopy
: { /* out2 */
1286 pIn1
= &aMem
[pOp
->p1
];
1287 pOut
= &aMem
[pOp
->p2
];
1288 assert( pOut
!=pIn1
);
1289 sqlite3VdbeMemShallowCopy(pOut
, pIn1
, MEM_Ephem
);
1291 if( pOut
->pScopyFrom
==0 ) pOut
->pScopyFrom
= pIn1
;
1296 /* Opcode: IntCopy P1 P2 * * *
1297 ** Synopsis: r[P2]=r[P1]
1299 ** Transfer the integer value held in register P1 into register P2.
1301 ** This is an optimized version of SCopy that works only for integer
1304 case OP_IntCopy
: { /* out2 */
1305 pIn1
= &aMem
[pOp
->p1
];
1306 assert( (pIn1
->flags
& MEM_Int
)!=0 );
1307 pOut
= &aMem
[pOp
->p2
];
1308 sqlite3VdbeMemSetInt64(pOut
, pIn1
->u
.i
);
1312 /* Opcode: ResultRow P1 P2 * * *
1313 ** Synopsis: output=r[P1@P2]
1315 ** The registers P1 through P1+P2-1 contain a single row of
1316 ** results. This opcode causes the sqlite3_step() call to terminate
1317 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1318 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1321 case OP_ResultRow
: {
1324 assert( p
->nResColumn
==pOp
->p2
);
1325 assert( pOp
->p1
>0 );
1326 assert( pOp
->p1
+pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
)+1 );
1328 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1329 /* Run the progress counter just before returning.
1331 if( db
->xProgress
!=0
1332 && nVmStep
>=nProgressLimit
1333 && db
->xProgress(db
->pProgressArg
)!=0
1335 rc
= SQLITE_INTERRUPT
;
1336 goto abort_due_to_error
;
1340 /* If this statement has violated immediate foreign key constraints, do
1341 ** not return the number of rows modified. And do not RELEASE the statement
1342 ** transaction. It needs to be rolled back. */
1343 if( SQLITE_OK
!=(rc
= sqlite3VdbeCheckFk(p
, 0)) ){
1344 assert( db
->flags
&SQLITE_CountRows
);
1345 assert( p
->usesStmtJournal
);
1346 goto abort_due_to_error
;
1349 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1350 ** DML statements invoke this opcode to return the number of rows
1351 ** modified to the user. This is the only way that a VM that
1352 ** opens a statement transaction may invoke this opcode.
1354 ** In case this is such a statement, close any statement transaction
1355 ** opened by this VM before returning control to the user. This is to
1356 ** ensure that statement-transactions are always nested, not overlapping.
1357 ** If the open statement-transaction is not closed here, then the user
1358 ** may step another VM that opens its own statement transaction. This
1359 ** may lead to overlapping statement transactions.
1361 ** The statement transaction is never a top-level transaction. Hence
1362 ** the RELEASE call below can never fail.
1364 assert( p
->iStatement
==0 || db
->flags
&SQLITE_CountRows
);
1365 rc
= sqlite3VdbeCloseStatement(p
, SAVEPOINT_RELEASE
);
1366 assert( rc
==SQLITE_OK
);
1368 /* Invalidate all ephemeral cursor row caches */
1369 p
->cacheCtr
= (p
->cacheCtr
+ 2)|1;
1371 /* Make sure the results of the current row are \000 terminated
1372 ** and have an assigned type. The results are de-ephemeralized as
1375 pMem
= p
->pResultSet
= &aMem
[pOp
->p1
];
1376 for(i
=0; i
<pOp
->p2
; i
++){
1377 assert( memIsValid(&pMem
[i
]) );
1378 Deephemeralize(&pMem
[i
]);
1379 assert( (pMem
[i
].flags
& MEM_Ephem
)==0
1380 || (pMem
[i
].flags
& (MEM_Str
|MEM_Blob
))==0 );
1381 sqlite3VdbeMemNulTerminate(&pMem
[i
]);
1382 REGISTER_TRACE(pOp
->p1
+i
, &pMem
[i
]);
1384 if( db
->mallocFailed
) goto no_mem
;
1386 if( db
->mTrace
& SQLITE_TRACE_ROW
){
1387 db
->xTrace(SQLITE_TRACE_ROW
, db
->pTraceArg
, p
, 0);
1390 /* Return SQLITE_ROW
1392 p
->pc
= (int)(pOp
- aOp
) + 1;
1397 /* Opcode: Concat P1 P2 P3 * *
1398 ** Synopsis: r[P3]=r[P2]+r[P1]
1400 ** Add the text in register P1 onto the end of the text in
1401 ** register P2 and store the result in register P3.
1402 ** If either the P1 or P2 text are NULL then store NULL in P3.
1406 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1407 ** if P3 is the same register as P2, the implementation is able
1408 ** to avoid a memcpy().
1410 case OP_Concat
: { /* same as TK_CONCAT, in1, in2, out3 */
1413 pIn1
= &aMem
[pOp
->p1
];
1414 pIn2
= &aMem
[pOp
->p2
];
1415 pOut
= &aMem
[pOp
->p3
];
1416 assert( pIn1
!=pOut
);
1417 if( (pIn1
->flags
| pIn2
->flags
) & MEM_Null
){
1418 sqlite3VdbeMemSetNull(pOut
);
1421 if( ExpandBlob(pIn1
) || ExpandBlob(pIn2
) ) goto no_mem
;
1422 Stringify(pIn1
, encoding
);
1423 Stringify(pIn2
, encoding
);
1424 nByte
= pIn1
->n
+ pIn2
->n
;
1425 if( nByte
>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
1428 if( sqlite3VdbeMemGrow(pOut
, (int)nByte
+2, pOut
==pIn2
) ){
1431 MemSetTypeFlag(pOut
, MEM_Str
);
1433 memcpy(pOut
->z
, pIn2
->z
, pIn2
->n
);
1435 memcpy(&pOut
->z
[pIn2
->n
], pIn1
->z
, pIn1
->n
);
1437 pOut
->z
[nByte
+1] = 0;
1438 pOut
->flags
|= MEM_Term
;
1439 pOut
->n
= (int)nByte
;
1440 pOut
->enc
= encoding
;
1441 UPDATE_MAX_BLOBSIZE(pOut
);
1445 /* Opcode: Add P1 P2 P3 * *
1446 ** Synopsis: r[P3]=r[P1]+r[P2]
1448 ** Add the value in register P1 to the value in register P2
1449 ** and store the result in register P3.
1450 ** If either input is NULL, the result is NULL.
1452 /* Opcode: Multiply P1 P2 P3 * *
1453 ** Synopsis: r[P3]=r[P1]*r[P2]
1456 ** Multiply the value in register P1 by the value in register P2
1457 ** and store the result in register P3.
1458 ** If either input is NULL, the result is NULL.
1460 /* Opcode: Subtract P1 P2 P3 * *
1461 ** Synopsis: r[P3]=r[P2]-r[P1]
1463 ** Subtract the value in register P1 from the value in register P2
1464 ** and store the result in register P3.
1465 ** If either input is NULL, the result is NULL.
1467 /* Opcode: Divide P1 P2 P3 * *
1468 ** Synopsis: r[P3]=r[P2]/r[P1]
1470 ** Divide the value in register P1 by the value in register P2
1471 ** and store the result in register P3 (P3=P2/P1). If the value in
1472 ** register P1 is zero, then the result is NULL. If either input is
1473 ** NULL, the result is NULL.
1475 /* Opcode: Remainder P1 P2 P3 * *
1476 ** Synopsis: r[P3]=r[P2]%r[P1]
1478 ** Compute the remainder after integer register P2 is divided by
1479 ** register P1 and store the result in register P3.
1480 ** If the value in register P1 is zero the result is NULL.
1481 ** If either operand is NULL, the result is NULL.
1483 case OP_Add
: /* same as TK_PLUS, in1, in2, out3 */
1484 case OP_Subtract
: /* same as TK_MINUS, in1, in2, out3 */
1485 case OP_Multiply
: /* same as TK_STAR, in1, in2, out3 */
1486 case OP_Divide
: /* same as TK_SLASH, in1, in2, out3 */
1487 case OP_Remainder
: { /* same as TK_REM, in1, in2, out3 */
1488 char bIntint
; /* Started out as two integer operands */
1489 u16 flags
; /* Combined MEM_* flags from both inputs */
1490 u16 type1
; /* Numeric type of left operand */
1491 u16 type2
; /* Numeric type of right operand */
1492 i64 iA
; /* Integer value of left operand */
1493 i64 iB
; /* Integer value of right operand */
1494 double rA
; /* Real value of left operand */
1495 double rB
; /* Real value of right operand */
1497 pIn1
= &aMem
[pOp
->p1
];
1498 type1
= numericType(pIn1
);
1499 pIn2
= &aMem
[pOp
->p2
];
1500 type2
= numericType(pIn2
);
1501 pOut
= &aMem
[pOp
->p3
];
1502 flags
= pIn1
->flags
| pIn2
->flags
;
1503 if( (flags
& MEM_Null
)!=0 ) goto arithmetic_result_is_null
;
1504 if( (type1
& type2
& MEM_Int
)!=0 ){
1508 switch( pOp
->opcode
){
1509 case OP_Add
: if( sqlite3AddInt64(&iB
,iA
) ) goto fp_math
; break;
1510 case OP_Subtract
: if( sqlite3SubInt64(&iB
,iA
) ) goto fp_math
; break;
1511 case OP_Multiply
: if( sqlite3MulInt64(&iB
,iA
) ) goto fp_math
; break;
1513 if( iA
==0 ) goto arithmetic_result_is_null
;
1514 if( iA
==-1 && iB
==SMALLEST_INT64
) goto fp_math
;
1519 if( iA
==0 ) goto arithmetic_result_is_null
;
1520 if( iA
==-1 ) iA
= 1;
1526 MemSetTypeFlag(pOut
, MEM_Int
);
1530 rA
= sqlite3VdbeRealValue(pIn1
);
1531 rB
= sqlite3VdbeRealValue(pIn2
);
1532 switch( pOp
->opcode
){
1533 case OP_Add
: rB
+= rA
; break;
1534 case OP_Subtract
: rB
-= rA
; break;
1535 case OP_Multiply
: rB
*= rA
; break;
1537 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1538 if( rA
==(double)0 ) goto arithmetic_result_is_null
;
1545 if( iA
==0 ) goto arithmetic_result_is_null
;
1546 if( iA
==-1 ) iA
= 1;
1547 rB
= (double)(iB
% iA
);
1551 #ifdef SQLITE_OMIT_FLOATING_POINT
1553 MemSetTypeFlag(pOut
, MEM_Int
);
1555 if( sqlite3IsNaN(rB
) ){
1556 goto arithmetic_result_is_null
;
1559 MemSetTypeFlag(pOut
, MEM_Real
);
1560 if( ((type1
|type2
)&MEM_Real
)==0 && !bIntint
){
1561 sqlite3VdbeIntegerAffinity(pOut
);
1567 arithmetic_result_is_null
:
1568 sqlite3VdbeMemSetNull(pOut
);
1572 /* Opcode: CollSeq P1 * * P4
1574 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
1575 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1576 ** be returned. This is used by the built-in min(), max() and nullif()
1579 ** If P1 is not zero, then it is a register that a subsequent min() or
1580 ** max() aggregate will set to 1 if the current row is not the minimum or
1581 ** maximum. The P1 register is initialized to 0 by this instruction.
1583 ** The interface used by the implementation of the aforementioned functions
1584 ** to retrieve the collation sequence set by this opcode is not available
1585 ** publicly. Only built-in functions have access to this feature.
1588 assert( pOp
->p4type
==P4_COLLSEQ
);
1590 sqlite3VdbeMemSetInt64(&aMem
[pOp
->p1
], 0);
1595 /* Opcode: Function0 P1 P2 P3 P4 P5
1596 ** Synopsis: r[P3]=func(r[P2@P5])
1598 ** Invoke a user function (P4 is a pointer to a FuncDef object that
1599 ** defines the function) with P5 arguments taken from register P2 and
1600 ** successors. The result of the function is stored in register P3.
1601 ** Register P3 must not be one of the function inputs.
1603 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
1604 ** function was determined to be constant at compile time. If the first
1605 ** argument was constant then bit 0 of P1 is set. This is used to determine
1606 ** whether meta data associated with a user function argument using the
1607 ** sqlite3_set_auxdata() API may be safely retained until the next
1608 ** invocation of this opcode.
1610 ** See also: Function, AggStep, AggFinal
1612 /* Opcode: Function P1 P2 P3 P4 P5
1613 ** Synopsis: r[P3]=func(r[P2@P5])
1615 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
1616 ** contains a pointer to the function to be run) with P5 arguments taken
1617 ** from register P2 and successors. The result of the function is stored
1618 ** in register P3. Register P3 must not be one of the function inputs.
1620 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
1621 ** function was determined to be constant at compile time. If the first
1622 ** argument was constant then bit 0 of P1 is set. This is used to determine
1623 ** whether meta data associated with a user function argument using the
1624 ** sqlite3_set_auxdata() API may be safely retained until the next
1625 ** invocation of this opcode.
1627 ** SQL functions are initially coded as OP_Function0 with P4 pointing
1628 ** to a FuncDef object. But on first evaluation, the P4 operand is
1629 ** automatically converted into an sqlite3_context object and the operation
1630 ** changed to this OP_Function opcode. In this way, the initialization of
1631 ** the sqlite3_context object occurs only once, rather than once for each
1632 ** evaluation of the function.
1634 ** See also: Function0, AggStep, AggFinal
1636 case OP_Function0
: {
1638 sqlite3_context
*pCtx
;
1640 assert( pOp
->p4type
==P4_FUNCDEF
);
1642 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
1643 assert( n
==0 || (pOp
->p2
>0 && pOp
->p2
+n
<=(p
->nMem
+1 - p
->nCursor
)+1) );
1644 assert( pOp
->p3
<pOp
->p2
|| pOp
->p3
>=pOp
->p2
+n
);
1645 pCtx
= sqlite3DbMallocRawNN(db
, sizeof(*pCtx
) + (n
-1)*sizeof(sqlite3_value
*));
1646 if( pCtx
==0 ) goto no_mem
;
1648 pCtx
->pFunc
= pOp
->p4
.pFunc
;
1649 pCtx
->iOp
= (int)(pOp
- aOp
);
1652 pOp
->p4type
= P4_FUNCCTX
;
1653 pOp
->p4
.pCtx
= pCtx
;
1654 pOp
->opcode
= OP_Function
;
1655 /* Fall through into OP_Function */
1659 sqlite3_context
*pCtx
;
1661 assert( pOp
->p4type
==P4_FUNCCTX
);
1662 pCtx
= pOp
->p4
.pCtx
;
1664 /* If this function is inside of a trigger, the register array in aMem[]
1665 ** might change from one evaluation to the next. The next block of code
1666 ** checks to see if the register array has changed, and if so it
1667 ** reinitializes the relavant parts of the sqlite3_context object */
1668 pOut
= &aMem
[pOp
->p3
];
1669 if( pCtx
->pOut
!= pOut
){
1671 for(i
=pCtx
->argc
-1; i
>=0; i
--) pCtx
->argv
[i
] = &aMem
[pOp
->p2
+i
];
1674 memAboutToChange(p
, pCtx
->pOut
);
1676 for(i
=0; i
<pCtx
->argc
; i
++){
1677 assert( memIsValid(pCtx
->argv
[i
]) );
1678 REGISTER_TRACE(pOp
->p2
+i
, pCtx
->argv
[i
]);
1681 MemSetTypeFlag(pCtx
->pOut
, MEM_Null
);
1682 pCtx
->fErrorOrAux
= 0;
1683 db
->lastRowid
= lastRowid
;
1684 (*pCtx
->pFunc
->xSFunc
)(pCtx
, pCtx
->argc
, pCtx
->argv
);/* IMP: R-24505-23230 */
1685 lastRowid
= db
->lastRowid
; /* Remember rowid changes made by xSFunc */
1687 /* If the function returned an error, throw an exception */
1688 if( pCtx
->fErrorOrAux
){
1689 if( pCtx
->isError
){
1690 sqlite3VdbeError(p
, "%s", sqlite3_value_text(pCtx
->pOut
));
1693 sqlite3VdbeDeleteAuxData(db
, &p
->pAuxData
, pCtx
->iOp
, pOp
->p1
);
1694 if( rc
) goto abort_due_to_error
;
1697 /* Copy the result of the function into register P3 */
1698 if( pOut
->flags
& (MEM_Str
|MEM_Blob
) ){
1699 sqlite3VdbeChangeEncoding(pCtx
->pOut
, encoding
);
1700 if( sqlite3VdbeMemTooBig(pCtx
->pOut
) ) goto too_big
;
1703 REGISTER_TRACE(pOp
->p3
, pCtx
->pOut
);
1704 UPDATE_MAX_BLOBSIZE(pCtx
->pOut
);
1708 /* Opcode: BitAnd P1 P2 P3 * *
1709 ** Synopsis: r[P3]=r[P1]&r[P2]
1711 ** Take the bit-wise AND of the values in register P1 and P2 and
1712 ** store the result in register P3.
1713 ** If either input is NULL, the result is NULL.
1715 /* Opcode: BitOr P1 P2 P3 * *
1716 ** Synopsis: r[P3]=r[P1]|r[P2]
1718 ** Take the bit-wise OR of the values in register P1 and P2 and
1719 ** store the result in register P3.
1720 ** If either input is NULL, the result is NULL.
1722 /* Opcode: ShiftLeft P1 P2 P3 * *
1723 ** Synopsis: r[P3]=r[P2]<<r[P1]
1725 ** Shift the integer value in register P2 to the left by the
1726 ** number of bits specified by the integer in register P1.
1727 ** Store the result in register P3.
1728 ** If either input is NULL, the result is NULL.
1730 /* Opcode: ShiftRight P1 P2 P3 * *
1731 ** Synopsis: r[P3]=r[P2]>>r[P1]
1733 ** Shift the integer value in register P2 to the right by the
1734 ** number of bits specified by the integer in register P1.
1735 ** Store the result in register P3.
1736 ** If either input is NULL, the result is NULL.
1738 case OP_BitAnd
: /* same as TK_BITAND, in1, in2, out3 */
1739 case OP_BitOr
: /* same as TK_BITOR, in1, in2, out3 */
1740 case OP_ShiftLeft
: /* same as TK_LSHIFT, in1, in2, out3 */
1741 case OP_ShiftRight
: { /* same as TK_RSHIFT, in1, in2, out3 */
1747 pIn1
= &aMem
[pOp
->p1
];
1748 pIn2
= &aMem
[pOp
->p2
];
1749 pOut
= &aMem
[pOp
->p3
];
1750 if( (pIn1
->flags
| pIn2
->flags
) & MEM_Null
){
1751 sqlite3VdbeMemSetNull(pOut
);
1754 iA
= sqlite3VdbeIntValue(pIn2
);
1755 iB
= sqlite3VdbeIntValue(pIn1
);
1757 if( op
==OP_BitAnd
){
1759 }else if( op
==OP_BitOr
){
1762 assert( op
==OP_ShiftRight
|| op
==OP_ShiftLeft
);
1764 /* If shifting by a negative amount, shift in the other direction */
1766 assert( OP_ShiftRight
==OP_ShiftLeft
+1 );
1767 op
= 2*OP_ShiftLeft
+ 1 - op
;
1768 iB
= iB
>(-64) ? -iB
: 64;
1772 iA
= (iA
>=0 || op
==OP_ShiftLeft
) ? 0 : -1;
1774 memcpy(&uA
, &iA
, sizeof(uA
));
1775 if( op
==OP_ShiftLeft
){
1779 /* Sign-extend on a right shift of a negative number */
1780 if( iA
<0 ) uA
|= ((((u64
)0xffffffff)<<32)|0xffffffff) << (64-iB
);
1782 memcpy(&iA
, &uA
, sizeof(iA
));
1786 MemSetTypeFlag(pOut
, MEM_Int
);
1790 /* Opcode: AddImm P1 P2 * * *
1791 ** Synopsis: r[P1]=r[P1]+P2
1793 ** Add the constant P2 to the value in register P1.
1794 ** The result is always an integer.
1796 ** To force any register to be an integer, just add 0.
1798 case OP_AddImm
: { /* in1 */
1799 pIn1
= &aMem
[pOp
->p1
];
1800 memAboutToChange(p
, pIn1
);
1801 sqlite3VdbeMemIntegerify(pIn1
);
1802 pIn1
->u
.i
+= pOp
->p2
;
1806 /* Opcode: MustBeInt P1 P2 * * *
1808 ** Force the value in register P1 to be an integer. If the value
1809 ** in P1 is not an integer and cannot be converted into an integer
1810 ** without data loss, then jump immediately to P2, or if P2==0
1811 ** raise an SQLITE_MISMATCH exception.
1813 case OP_MustBeInt
: { /* jump, in1 */
1814 pIn1
= &aMem
[pOp
->p1
];
1815 if( (pIn1
->flags
& MEM_Int
)==0 ){
1816 applyAffinity(pIn1
, SQLITE_AFF_NUMERIC
, encoding
);
1817 VdbeBranchTaken((pIn1
->flags
&MEM_Int
)==0, 2);
1818 if( (pIn1
->flags
& MEM_Int
)==0 ){
1820 rc
= SQLITE_MISMATCH
;
1821 goto abort_due_to_error
;
1827 MemSetTypeFlag(pIn1
, MEM_Int
);
1831 #ifndef SQLITE_OMIT_FLOATING_POINT
1832 /* Opcode: RealAffinity P1 * * * *
1834 ** If register P1 holds an integer convert it to a real value.
1836 ** This opcode is used when extracting information from a column that
1837 ** has REAL affinity. Such column values may still be stored as
1838 ** integers, for space efficiency, but after extraction we want them
1839 ** to have only a real value.
1841 case OP_RealAffinity
: { /* in1 */
1842 pIn1
= &aMem
[pOp
->p1
];
1843 if( pIn1
->flags
& MEM_Int
){
1844 sqlite3VdbeMemRealify(pIn1
);
1850 #ifndef SQLITE_OMIT_CAST
1851 /* Opcode: Cast P1 P2 * * *
1852 ** Synopsis: affinity(r[P1])
1854 ** Force the value in register P1 to be the type defined by P2.
1857 ** <li value="97"> TEXT
1858 ** <li value="98"> BLOB
1859 ** <li value="99"> NUMERIC
1860 ** <li value="100"> INTEGER
1861 ** <li value="101"> REAL
1864 ** A NULL value is not changed by this routine. It remains NULL.
1866 case OP_Cast
: { /* in1 */
1867 assert( pOp
->p2
>=SQLITE_AFF_BLOB
&& pOp
->p2
<=SQLITE_AFF_REAL
);
1868 testcase( pOp
->p2
==SQLITE_AFF_TEXT
);
1869 testcase( pOp
->p2
==SQLITE_AFF_BLOB
);
1870 testcase( pOp
->p2
==SQLITE_AFF_NUMERIC
);
1871 testcase( pOp
->p2
==SQLITE_AFF_INTEGER
);
1872 testcase( pOp
->p2
==SQLITE_AFF_REAL
);
1873 pIn1
= &aMem
[pOp
->p1
];
1874 memAboutToChange(p
, pIn1
);
1875 rc
= ExpandBlob(pIn1
);
1876 sqlite3VdbeMemCast(pIn1
, pOp
->p2
, encoding
);
1877 UPDATE_MAX_BLOBSIZE(pIn1
);
1878 if( rc
) goto abort_due_to_error
;
1881 #endif /* SQLITE_OMIT_CAST */
1883 /* Opcode: Lt P1 P2 P3 P4 P5
1884 ** Synopsis: if r[P1]<r[P3] goto P2
1886 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1887 ** jump to address P2.
1889 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1890 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
1891 ** bit is clear then fall through if either operand is NULL.
1893 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1894 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1895 ** to coerce both inputs according to this affinity before the
1896 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1897 ** affinity is used. Note that the affinity conversions are stored
1898 ** back into the input registers P1 and P3. So this opcode can cause
1899 ** persistent changes to registers P1 and P3.
1901 ** Once any conversions have taken place, and neither value is NULL,
1902 ** the values are compared. If both values are blobs then memcmp() is
1903 ** used to determine the results of the comparison. If both values
1904 ** are text, then the appropriate collating function specified in
1905 ** P4 is used to do the comparison. If P4 is not specified then
1906 ** memcmp() is used to compare text string. If both values are
1907 ** numeric, then a numeric comparison is used. If the two values
1908 ** are of different types, then numbers are considered less than
1909 ** strings and strings are considered less than blobs.
1911 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
1912 ** store a boolean result (either 0, or 1, or NULL) in register P2.
1914 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
1915 ** equal to one another, provided that they do not have their MEM_Cleared
1918 /* Opcode: Ne P1 P2 P3 P4 P5
1919 ** Synopsis: if r[P1]!=r[P3] goto P2
1921 ** This works just like the Lt opcode except that the jump is taken if
1922 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
1923 ** additional information.
1925 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1926 ** true or false and is never NULL. If both operands are NULL then the result
1927 ** of comparison is false. If either operand is NULL then the result is true.
1928 ** If neither operand is NULL the result is the same as it would be if
1929 ** the SQLITE_NULLEQ flag were omitted from P5.
1931 /* Opcode: Eq P1 P2 P3 P4 P5
1932 ** Synopsis: if r[P1]==r[P3] goto P2
1934 ** This works just like the Lt opcode except that the jump is taken if
1935 ** the operands in registers P1 and P3 are equal.
1936 ** See the Lt opcode for additional information.
1938 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1939 ** true or false and is never NULL. If both operands are NULL then the result
1940 ** of comparison is true. If either operand is NULL then the result is false.
1941 ** If neither operand is NULL the result is the same as it would be if
1942 ** the SQLITE_NULLEQ flag were omitted from P5.
1944 /* Opcode: Le P1 P2 P3 P4 P5
1945 ** Synopsis: if r[P1]<=r[P3] goto P2
1947 ** This works just like the Lt opcode except that the jump is taken if
1948 ** the content of register P3 is less than or equal to the content of
1949 ** register P1. See the Lt opcode for additional information.
1951 /* Opcode: Gt P1 P2 P3 P4 P5
1952 ** Synopsis: if r[P1]>r[P3] goto P2
1954 ** This works just like the Lt opcode except that the jump is taken if
1955 ** the content of register P3 is greater than the content of
1956 ** register P1. See the Lt opcode for additional information.
1958 /* Opcode: Ge P1 P2 P3 P4 P5
1959 ** Synopsis: if r[P1]>=r[P3] goto P2
1961 ** This works just like the Lt opcode except that the jump is taken if
1962 ** the content of register P3 is greater than or equal to the content of
1963 ** register P1. See the Lt opcode for additional information.
1965 case OP_Eq
: /* same as TK_EQ, jump, in1, in3 */
1966 case OP_Ne
: /* same as TK_NE, jump, in1, in3 */
1967 case OP_Lt
: /* same as TK_LT, jump, in1, in3 */
1968 case OP_Le
: /* same as TK_LE, jump, in1, in3 */
1969 case OP_Gt
: /* same as TK_GT, jump, in1, in3 */
1970 case OP_Ge
: { /* same as TK_GE, jump, in1, in3 */
1971 int res
; /* Result of the comparison of pIn1 against pIn3 */
1972 char affinity
; /* Affinity to use for comparison */
1973 u16 flags1
; /* Copy of initial value of pIn1->flags */
1974 u16 flags3
; /* Copy of initial value of pIn3->flags */
1976 pIn1
= &aMem
[pOp
->p1
];
1977 pIn3
= &aMem
[pOp
->p3
];
1978 flags1
= pIn1
->flags
;
1979 flags3
= pIn3
->flags
;
1980 if( (flags1
| flags3
)&MEM_Null
){
1981 /* One or both operands are NULL */
1982 if( pOp
->p5
& SQLITE_NULLEQ
){
1983 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1984 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1985 ** or not both operands are null.
1987 assert( pOp
->opcode
==OP_Eq
|| pOp
->opcode
==OP_Ne
);
1988 assert( (flags1
& MEM_Cleared
)==0 );
1989 assert( (pOp
->p5
& SQLITE_JUMPIFNULL
)==0 );
1990 if( (flags1
&MEM_Null
)!=0
1991 && (flags3
&MEM_Null
)!=0
1992 && (flags3
&MEM_Cleared
)==0
1994 res
= 0; /* Results are equal */
1996 res
= 1; /* Results are not equal */
1999 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
2000 ** then the result is always NULL.
2001 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
2003 if( pOp
->p5
& SQLITE_STOREP2
){
2004 pOut
= &aMem
[pOp
->p2
];
2005 memAboutToChange(p
, pOut
);
2006 MemSetTypeFlag(pOut
, MEM_Null
);
2007 REGISTER_TRACE(pOp
->p2
, pOut
);
2009 VdbeBranchTaken(2,3);
2010 if( pOp
->p5
& SQLITE_JUMPIFNULL
){
2017 /* Neither operand is NULL. Do a comparison. */
2018 affinity
= pOp
->p5
& SQLITE_AFF_MASK
;
2019 if( affinity
>=SQLITE_AFF_NUMERIC
){
2020 if( (flags1
| flags3
)&MEM_Str
){
2021 if( (flags1
& (MEM_Int
|MEM_Real
|MEM_Str
))==MEM_Str
){
2022 applyNumericAffinity(pIn1
,0);
2023 flags3
= pIn3
->flags
;
2025 if( (flags3
& (MEM_Int
|MEM_Real
|MEM_Str
))==MEM_Str
){
2026 applyNumericAffinity(pIn3
,0);
2029 }else if( affinity
==SQLITE_AFF_TEXT
){
2030 if( (flags1
& MEM_Str
)==0 && (flags1
& (MEM_Int
|MEM_Real
))!=0 ){
2031 testcase( pIn1
->flags
& MEM_Int
);
2032 testcase( pIn1
->flags
& MEM_Real
);
2033 sqlite3VdbeMemStringify(pIn1
, encoding
, 1);
2034 testcase( (flags1
&MEM_Dyn
) != (pIn1
->flags
&MEM_Dyn
) );
2035 flags1
= (pIn1
->flags
& ~MEM_TypeMask
) | (flags1
& MEM_TypeMask
);
2036 flags3
= pIn3
->flags
;
2038 if( (flags3
& MEM_Str
)==0 && (flags3
& (MEM_Int
|MEM_Real
))!=0 ){
2039 testcase( pIn3
->flags
& MEM_Int
);
2040 testcase( pIn3
->flags
& MEM_Real
);
2041 sqlite3VdbeMemStringify(pIn3
, encoding
, 1);
2042 testcase( (flags3
&MEM_Dyn
) != (pIn3
->flags
&MEM_Dyn
) );
2043 flags3
= (pIn3
->flags
& ~MEM_TypeMask
) | (flags3
& MEM_TypeMask
);
2046 assert( pOp
->p4type
==P4_COLLSEQ
|| pOp
->p4
.pColl
==0 );
2047 if( flags1
& MEM_Zero
){
2048 sqlite3VdbeMemExpandBlob(pIn1
);
2049 flags1
&= ~MEM_Zero
;
2051 if( flags3
& MEM_Zero
){
2052 sqlite3VdbeMemExpandBlob(pIn3
);
2053 flags3
&= ~MEM_Zero
;
2055 res
= sqlite3MemCompare(pIn3
, pIn1
, pOp
->p4
.pColl
);
2057 switch( pOp
->opcode
){
2058 case OP_Eq
: res
= res
==0; break;
2059 case OP_Ne
: res
= res
!=0; break;
2060 case OP_Lt
: res
= res
<0; break;
2061 case OP_Le
: res
= res
<=0; break;
2062 case OP_Gt
: res
= res
>0; break;
2063 default: res
= res
>=0; break;
2066 /* Undo any changes made by applyAffinity() to the input registers. */
2067 assert( (pIn1
->flags
& MEM_Dyn
) == (flags1
& MEM_Dyn
) );
2068 pIn1
->flags
= flags1
;
2069 assert( (pIn3
->flags
& MEM_Dyn
) == (flags3
& MEM_Dyn
) );
2070 pIn3
->flags
= flags3
;
2072 if( pOp
->p5
& SQLITE_STOREP2
){
2073 pOut
= &aMem
[pOp
->p2
];
2074 memAboutToChange(p
, pOut
);
2075 MemSetTypeFlag(pOut
, MEM_Int
);
2077 REGISTER_TRACE(pOp
->p2
, pOut
);
2079 VdbeBranchTaken(res
!=0, (pOp
->p5
& SQLITE_NULLEQ
)?2:3);
2087 /* Opcode: Permutation * * * P4 *
2089 ** Set the permutation used by the OP_Compare operator to be the array
2090 ** of integers in P4.
2092 ** The permutation is only valid until the next OP_Compare that has
2093 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2094 ** occur immediately prior to the OP_Compare.
2096 ** The first integer in the P4 integer array is the length of the array
2097 ** and does not become part of the permutation.
2099 case OP_Permutation
: {
2100 assert( pOp
->p4type
==P4_INTARRAY
);
2101 assert( pOp
->p4
.ai
);
2102 aPermute
= pOp
->p4
.ai
+ 1;
2106 /* Opcode: Compare P1 P2 P3 P4 P5
2107 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2109 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2110 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2111 ** the comparison for use by the next OP_Jump instruct.
2113 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2114 ** determined by the most recent OP_Permutation operator. If the
2115 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2118 ** P4 is a KeyInfo structure that defines collating sequences and sort
2119 ** orders for the comparison. The permutation applies to registers
2120 ** only. The KeyInfo elements are used sequentially.
2122 ** The comparison is a sort comparison, so NULLs compare equal,
2123 ** NULLs are less than numbers, numbers are less than strings,
2124 ** and strings are less than blobs.
2131 const KeyInfo
*pKeyInfo
;
2133 CollSeq
*pColl
; /* Collating sequence to use on this term */
2134 int bRev
; /* True for DESCENDING sort order */
2136 if( (pOp
->p5
& OPFLAG_PERMUTE
)==0 ) aPermute
= 0;
2138 pKeyInfo
= pOp
->p4
.pKeyInfo
;
2140 assert( pKeyInfo
!=0 );
2146 for(k
=0; k
<n
; k
++) if( aPermute
[k
]>mx
) mx
= aPermute
[k
];
2147 assert( p1
>0 && p1
+mx
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2148 assert( p2
>0 && p2
+mx
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2150 assert( p1
>0 && p1
+n
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2151 assert( p2
>0 && p2
+n
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2153 #endif /* SQLITE_DEBUG */
2155 idx
= aPermute
? aPermute
[i
] : i
;
2156 assert( memIsValid(&aMem
[p1
+idx
]) );
2157 assert( memIsValid(&aMem
[p2
+idx
]) );
2158 REGISTER_TRACE(p1
+idx
, &aMem
[p1
+idx
]);
2159 REGISTER_TRACE(p2
+idx
, &aMem
[p2
+idx
]);
2160 assert( i
<pKeyInfo
->nField
);
2161 pColl
= pKeyInfo
->aColl
[i
];
2162 bRev
= pKeyInfo
->aSortOrder
[i
];
2163 iCompare
= sqlite3MemCompare(&aMem
[p1
+idx
], &aMem
[p2
+idx
], pColl
);
2165 if( bRev
) iCompare
= -iCompare
;
2173 /* Opcode: Jump P1 P2 P3 * *
2175 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2176 ** in the most recent OP_Compare instruction the P1 vector was less than
2177 ** equal to, or greater than the P2 vector, respectively.
2179 case OP_Jump
: { /* jump */
2181 VdbeBranchTaken(0,3); pOp
= &aOp
[pOp
->p1
- 1];
2182 }else if( iCompare
==0 ){
2183 VdbeBranchTaken(1,3); pOp
= &aOp
[pOp
->p2
- 1];
2185 VdbeBranchTaken(2,3); pOp
= &aOp
[pOp
->p3
- 1];
2190 /* Opcode: And P1 P2 P3 * *
2191 ** Synopsis: r[P3]=(r[P1] && r[P2])
2193 ** Take the logical AND of the values in registers P1 and P2 and
2194 ** write the result into register P3.
2196 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2197 ** the other input is NULL. A NULL and true or two NULLs give
2200 /* Opcode: Or P1 P2 P3 * *
2201 ** Synopsis: r[P3]=(r[P1] || r[P2])
2203 ** Take the logical OR of the values in register P1 and P2 and
2204 ** store the answer in register P3.
2206 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2207 ** even if the other input is NULL. A NULL and false or two NULLs
2208 ** give a NULL output.
2210 case OP_And
: /* same as TK_AND, in1, in2, out3 */
2211 case OP_Or
: { /* same as TK_OR, in1, in2, out3 */
2212 int v1
; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2213 int v2
; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2215 pIn1
= &aMem
[pOp
->p1
];
2216 if( pIn1
->flags
& MEM_Null
){
2219 v1
= sqlite3VdbeIntValue(pIn1
)!=0;
2221 pIn2
= &aMem
[pOp
->p2
];
2222 if( pIn2
->flags
& MEM_Null
){
2225 v2
= sqlite3VdbeIntValue(pIn2
)!=0;
2227 if( pOp
->opcode
==OP_And
){
2228 static const unsigned char and_logic
[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2229 v1
= and_logic
[v1
*3+v2
];
2231 static const unsigned char or_logic
[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2232 v1
= or_logic
[v1
*3+v2
];
2234 pOut
= &aMem
[pOp
->p3
];
2236 MemSetTypeFlag(pOut
, MEM_Null
);
2239 MemSetTypeFlag(pOut
, MEM_Int
);
2244 /* Opcode: Not P1 P2 * * *
2245 ** Synopsis: r[P2]= !r[P1]
2247 ** Interpret the value in register P1 as a boolean value. Store the
2248 ** boolean complement in register P2. If the value in register P1 is
2249 ** NULL, then a NULL is stored in P2.
2251 case OP_Not
: { /* same as TK_NOT, in1, out2 */
2252 pIn1
= &aMem
[pOp
->p1
];
2253 pOut
= &aMem
[pOp
->p2
];
2254 sqlite3VdbeMemSetNull(pOut
);
2255 if( (pIn1
->flags
& MEM_Null
)==0 ){
2256 pOut
->flags
= MEM_Int
;
2257 pOut
->u
.i
= !sqlite3VdbeIntValue(pIn1
);
2262 /* Opcode: BitNot P1 P2 * * *
2263 ** Synopsis: r[P1]= ~r[P1]
2265 ** Interpret the content of register P1 as an integer. Store the
2266 ** ones-complement of the P1 value into register P2. If P1 holds
2267 ** a NULL then store a NULL in P2.
2269 case OP_BitNot
: { /* same as TK_BITNOT, in1, out2 */
2270 pIn1
= &aMem
[pOp
->p1
];
2271 pOut
= &aMem
[pOp
->p2
];
2272 sqlite3VdbeMemSetNull(pOut
);
2273 if( (pIn1
->flags
& MEM_Null
)==0 ){
2274 pOut
->flags
= MEM_Int
;
2275 pOut
->u
.i
= ~sqlite3VdbeIntValue(pIn1
);
2280 /* Opcode: Once P1 P2 * * *
2282 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
2283 ** Otherwise, set the flag and fall through to the next instruction.
2284 ** In other words, this opcode causes all following opcodes up through P2
2285 ** (but not including P2) to run just once and to be skipped on subsequent
2286 ** times through the loop.
2288 ** All "once" flags are initially cleared whenever a prepared statement
2289 ** first begins to run.
2291 case OP_Once
: { /* jump */
2292 assert( pOp
->p1
<p
->nOnceFlag
);
2293 VdbeBranchTaken(p
->aOnceFlag
[pOp
->p1
]!=0, 2);
2294 if( p
->aOnceFlag
[pOp
->p1
] ){
2297 p
->aOnceFlag
[pOp
->p1
] = 1;
2302 /* Opcode: If P1 P2 P3 * *
2304 ** Jump to P2 if the value in register P1 is true. The value
2305 ** is considered true if it is numeric and non-zero. If the value
2306 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2308 /* Opcode: IfNot P1 P2 P3 * *
2310 ** Jump to P2 if the value in register P1 is False. The value
2311 ** is considered false if it has a numeric value of zero. If the value
2312 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2314 case OP_If
: /* jump, in1 */
2315 case OP_IfNot
: { /* jump, in1 */
2317 pIn1
= &aMem
[pOp
->p1
];
2318 if( pIn1
->flags
& MEM_Null
){
2321 #ifdef SQLITE_OMIT_FLOATING_POINT
2322 c
= sqlite3VdbeIntValue(pIn1
)!=0;
2324 c
= sqlite3VdbeRealValue(pIn1
)!=0.0;
2326 if( pOp
->opcode
==OP_IfNot
) c
= !c
;
2328 VdbeBranchTaken(c
!=0, 2);
2335 /* Opcode: IsNull P1 P2 * * *
2336 ** Synopsis: if r[P1]==NULL goto P2
2338 ** Jump to P2 if the value in register P1 is NULL.
2340 case OP_IsNull
: { /* same as TK_ISNULL, jump, in1 */
2341 pIn1
= &aMem
[pOp
->p1
];
2342 VdbeBranchTaken( (pIn1
->flags
& MEM_Null
)!=0, 2);
2343 if( (pIn1
->flags
& MEM_Null
)!=0 ){
2349 /* Opcode: NotNull P1 P2 * * *
2350 ** Synopsis: if r[P1]!=NULL goto P2
2352 ** Jump to P2 if the value in register P1 is not NULL.
2354 case OP_NotNull
: { /* same as TK_NOTNULL, jump, in1 */
2355 pIn1
= &aMem
[pOp
->p1
];
2356 VdbeBranchTaken( (pIn1
->flags
& MEM_Null
)==0, 2);
2357 if( (pIn1
->flags
& MEM_Null
)==0 ){
2363 /* Opcode: Column P1 P2 P3 P4 P5
2364 ** Synopsis: r[P3]=PX
2366 ** Interpret the data that cursor P1 points to as a structure built using
2367 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2368 ** information about the format of the data.) Extract the P2-th column
2369 ** from this record. If there are less that (P2+1)
2370 ** values in the record, extract a NULL.
2372 ** The value extracted is stored in register P3.
2374 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
2375 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2378 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2379 ** then the cache of the cursor is reset prior to extracting the column.
2380 ** The first OP_Column against a pseudo-table after the value of the content
2381 ** register has changed should have this bit set.
2383 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
2384 ** the result is guaranteed to only be used as the argument of a length()
2385 ** or typeof() function, respectively. The loading of large blobs can be
2386 ** skipped for length() and all content loading can be skipped for typeof().
2389 int p2
; /* column number to retrieve */
2390 VdbeCursor
*pC
; /* The VDBE cursor */
2391 BtCursor
*pCrsr
; /* The BTree cursor */
2392 u32
*aOffset
; /* aOffset[i] is offset to start of data for i-th column */
2393 int len
; /* The length of the serialized data for the column */
2394 int i
; /* Loop counter */
2395 Mem
*pDest
; /* Where to write the extracted value */
2396 Mem sMem
; /* For storing the record being decoded */
2397 const u8
*zData
; /* Part of the record being decoded */
2398 const u8
*zHdr
; /* Next unparsed byte of the header */
2399 const u8
*zEndHdr
; /* Pointer to first byte after the header */
2400 u32 offset
; /* Offset into the data */
2401 u64 offset64
; /* 64-bit offset */
2402 u32 avail
; /* Number of bytes of available data */
2403 u32 t
; /* A type code from the record header */
2404 Mem
*pReg
; /* PseudoTable input register */
2406 pC
= p
->apCsr
[pOp
->p1
];
2409 /* If the cursor cache is stale, bring it up-to-date */
2410 rc
= sqlite3VdbeCursorMoveto(&pC
, &p2
);
2411 if( rc
) goto abort_due_to_error
;
2413 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
2414 pDest
= &aMem
[pOp
->p3
];
2415 memAboutToChange(p
, pDest
);
2416 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
2418 assert( p2
<pC
->nField
);
2419 aOffset
= pC
->aOffset
;
2420 assert( pC
->eCurType
!=CURTYPE_VTAB
);
2421 assert( pC
->eCurType
!=CURTYPE_PSEUDO
|| pC
->nullRow
);
2422 assert( pC
->eCurType
!=CURTYPE_SORTER
);
2423 pCrsr
= pC
->uc
.pCursor
;
2425 if( pC
->cacheStatus
!=p
->cacheCtr
){ /*OPTIMIZATION-IF-FALSE*/
2427 if( pC
->eCurType
==CURTYPE_PSEUDO
){
2428 assert( pC
->uc
.pseudoTableReg
>0 );
2429 pReg
= &aMem
[pC
->uc
.pseudoTableReg
];
2430 assert( pReg
->flags
& MEM_Blob
);
2431 assert( memIsValid(pReg
) );
2432 pC
->payloadSize
= pC
->szRow
= avail
= pReg
->n
;
2433 pC
->aRow
= (u8
*)pReg
->z
;
2435 sqlite3VdbeMemSetNull(pDest
);
2439 assert( pC
->eCurType
==CURTYPE_BTREE
);
2441 assert( sqlite3BtreeCursorIsValid(pCrsr
) );
2442 pC
->payloadSize
= sqlite3BtreePayloadSize(pCrsr
);
2443 pC
->aRow
= sqlite3BtreePayloadFetch(pCrsr
, &avail
);
2444 assert( avail
<=65536 ); /* Maximum page size is 64KiB */
2445 if( pC
->payloadSize
<= (u32
)avail
){
2446 pC
->szRow
= pC
->payloadSize
;
2447 }else if( pC
->payloadSize
> (u32
)db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
2453 pC
->cacheStatus
= p
->cacheCtr
;
2454 pC
->iHdrOffset
= getVarint32(pC
->aRow
, offset
);
2456 aOffset
[0] = offset
;
2459 if( avail
<offset
){ /*OPTIMIZATION-IF-FALSE*/
2460 /* pC->aRow does not have to hold the entire row, but it does at least
2461 ** need to cover the header of the record. If pC->aRow does not contain
2462 ** the complete header, then set it to zero, forcing the header to be
2463 ** dynamically allocated. */
2467 /* Make sure a corrupt database has not given us an oversize header.
2468 ** Do this now to avoid an oversize memory allocation.
2470 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2471 ** types use so much data space that there can only be 4096 and 32 of
2472 ** them, respectively. So the maximum header length results from a
2473 ** 3-byte type for each of the maximum of 32768 columns plus three
2474 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2476 if( offset
> 98307 || offset
> pC
->payloadSize
){
2477 rc
= SQLITE_CORRUPT_BKPT
;
2478 goto abort_due_to_error
;
2480 }else if( offset
>0 ){ /*OPTIMIZATION-IF-TRUE*/
2481 /* The following goto is an optimization. It can be omitted and
2482 ** everything will still work. But OP_Column is measurably faster
2483 ** by skipping the subsequent conditional, which is always true.
2486 assert( pC
->nHdrParsed
<=p2
); /* Conditional skipped */
2487 goto op_column_read_header
;
2491 /* Make sure at least the first p2+1 entries of the header have been
2492 ** parsed and valid information is in aOffset[] and pC->aType[].
2494 if( pC
->nHdrParsed
<=p2
){
2495 /* If there is more header available for parsing in the record, try
2496 ** to extract additional fields up through the p2+1-th field
2498 if( pC
->iHdrOffset
<aOffset
[0] ){
2499 /* Make sure zData points to enough of the record to cover the header. */
2501 memset(&sMem
, 0, sizeof(sMem
));
2502 rc
= sqlite3VdbeMemFromBtree(pCrsr
, 0, aOffset
[0], !pC
->isTable
, &sMem
);
2503 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
2504 zData
= (u8
*)sMem
.z
;
2509 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2510 op_column_read_header
:
2512 offset64
= aOffset
[i
];
2513 zHdr
= zData
+ pC
->iHdrOffset
;
2514 zEndHdr
= zData
+ aOffset
[0];
2516 if( (t
= zHdr
[0])<0x80 ){
2518 offset64
+= sqlite3VdbeOneByteSerialTypeLen(t
);
2520 zHdr
+= sqlite3GetVarint32(zHdr
, &t
);
2521 offset64
+= sqlite3VdbeSerialTypeLen(t
);
2524 aOffset
[i
] = (u32
)(offset64
& 0xffffffff);
2525 }while( i
<=p2
&& zHdr
<zEndHdr
);
2527 /* The record is corrupt if any of the following are true:
2528 ** (1) the bytes of the header extend past the declared header size
2529 ** (2) the entire header was used but not all data was used
2530 ** (3) the end of the data extends beyond the end of the record.
2532 if( (zHdr
>=zEndHdr
&& (zHdr
>zEndHdr
|| offset64
!=pC
->payloadSize
))
2533 || (offset64
> pC
->payloadSize
)
2535 if( pC
->aRow
==0 ) sqlite3VdbeMemRelease(&sMem
);
2536 rc
= SQLITE_CORRUPT_BKPT
;
2537 goto abort_due_to_error
;
2541 pC
->iHdrOffset
= (u32
)(zHdr
- zData
);
2542 if( pC
->aRow
==0 ) sqlite3VdbeMemRelease(&sMem
);
2547 /* If after trying to extract new entries from the header, nHdrParsed is
2548 ** still not up to p2, that means that the record has fewer than p2
2549 ** columns. So the result will be either the default value or a NULL.
2551 if( pC
->nHdrParsed
<=p2
){
2552 if( pOp
->p4type
==P4_MEM
){
2553 sqlite3VdbeMemShallowCopy(pDest
, pOp
->p4
.pMem
, MEM_Static
);
2555 sqlite3VdbeMemSetNull(pDest
);
2563 /* Extract the content for the p2+1-th column. Control can only
2564 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2567 assert( p2
<pC
->nHdrParsed
);
2568 assert( rc
==SQLITE_OK
);
2569 assert( sqlite3VdbeCheckMemInvariants(pDest
) );
2570 if( VdbeMemDynamic(pDest
) ){
2571 sqlite3VdbeMemSetNull(pDest
);
2573 assert( t
==pC
->aType
[p2
] );
2574 if( pC
->szRow
>=aOffset
[p2
+1] ){
2575 /* This is the common case where the desired content fits on the original
2576 ** page - where the content is not on an overflow page */
2577 zData
= pC
->aRow
+ aOffset
[p2
];
2579 sqlite3VdbeSerialGet(zData
, t
, pDest
);
2581 /* If the column value is a string, we need a persistent value, not
2582 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2583 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2585 static const u16 aFlag
[] = { MEM_Blob
, MEM_Str
|MEM_Term
};
2586 pDest
->n
= len
= (t
-12)/2;
2587 pDest
->enc
= encoding
;
2588 if( pDest
->szMalloc
< len
+2 ){
2589 pDest
->flags
= MEM_Null
;
2590 if( sqlite3VdbeMemGrow(pDest
, len
+2, 0) ) goto no_mem
;
2592 pDest
->z
= pDest
->zMalloc
;
2594 memcpy(pDest
->z
, zData
, len
);
2596 pDest
->z
[len
+1] = 0;
2597 pDest
->flags
= aFlag
[t
&1];
2600 pDest
->enc
= encoding
;
2601 /* This branch happens only when content is on overflow pages */
2602 if( ((pOp
->p5
& (OPFLAG_LENGTHARG
|OPFLAG_TYPEOFARG
))!=0
2603 && ((t
>=12 && (t
&1)==0) || (pOp
->p5
& OPFLAG_TYPEOFARG
)!=0))
2604 || (len
= sqlite3VdbeSerialTypeLen(t
))==0
2606 /* Content is irrelevant for
2607 ** 1. the typeof() function,
2608 ** 2. the length(X) function if X is a blob, and
2609 ** 3. if the content length is zero.
2610 ** So we might as well use bogus content rather than reading
2611 ** content from disk. */
2612 static u8 aZero
[8]; /* This is the bogus content */
2613 sqlite3VdbeSerialGet(aZero
, t
, pDest
);
2615 rc
= sqlite3VdbeMemFromBtree(pCrsr
, aOffset
[p2
], len
, !pC
->isTable
,
2617 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
2618 sqlite3VdbeSerialGet((const u8
*)pDest
->z
, t
, pDest
);
2619 pDest
->flags
&= ~MEM_Ephem
;
2624 UPDATE_MAX_BLOBSIZE(pDest
);
2625 REGISTER_TRACE(pOp
->p3
, pDest
);
2629 /* Opcode: Affinity P1 P2 * P4 *
2630 ** Synopsis: affinity(r[P1@P2])
2632 ** Apply affinities to a range of P2 registers starting with P1.
2634 ** P4 is a string that is P2 characters long. The nth character of the
2635 ** string indicates the column affinity that should be used for the nth
2636 ** memory cell in the range.
2639 const char *zAffinity
; /* The affinity to be applied */
2640 char cAff
; /* A single character of affinity */
2642 zAffinity
= pOp
->p4
.z
;
2643 assert( zAffinity
!=0 );
2644 assert( zAffinity
[pOp
->p2
]==0 );
2645 pIn1
= &aMem
[pOp
->p1
];
2646 while( (cAff
= *(zAffinity
++))!=0 ){
2647 assert( pIn1
<= &p
->aMem
[(p
->nMem
+1 - p
->nCursor
)] );
2648 assert( memIsValid(pIn1
) );
2649 applyAffinity(pIn1
, cAff
, encoding
);
2655 /* Opcode: MakeRecord P1 P2 P3 P4 *
2656 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2658 ** Convert P2 registers beginning with P1 into the [record format]
2659 ** use as a data record in a database table or as a key
2660 ** in an index. The OP_Column opcode can decode the record later.
2662 ** P4 may be a string that is P2 characters long. The nth character of the
2663 ** string indicates the column affinity that should be used for the nth
2664 ** field of the index key.
2666 ** The mapping from character to affinity is given by the SQLITE_AFF_
2667 ** macros defined in sqliteInt.h.
2669 ** If P4 is NULL then all index fields have the affinity BLOB.
2671 case OP_MakeRecord
: {
2672 u8
*zNewRecord
; /* A buffer to hold the data for the new record */
2673 Mem
*pRec
; /* The new record */
2674 u64 nData
; /* Number of bytes of data space */
2675 int nHdr
; /* Number of bytes of header space */
2676 i64 nByte
; /* Data space required for this record */
2677 i64 nZero
; /* Number of zero bytes at the end of the record */
2678 int nVarint
; /* Number of bytes in a varint */
2679 u32 serial_type
; /* Type field */
2680 Mem
*pData0
; /* First field to be combined into the record */
2681 Mem
*pLast
; /* Last field of the record */
2682 int nField
; /* Number of fields in the record */
2683 char *zAffinity
; /* The affinity string for the record */
2684 int file_format
; /* File format to use for encoding */
2685 int i
; /* Space used in zNewRecord[] header */
2686 int j
; /* Space used in zNewRecord[] content */
2687 u32 len
; /* Length of a field */
2689 /* Assuming the record contains N fields, the record format looks
2692 ** ------------------------------------------------------------------------
2693 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2694 ** ------------------------------------------------------------------------
2696 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2699 ** Each type field is a varint representing the serial type of the
2700 ** corresponding data element (see sqlite3VdbeSerialType()). The
2701 ** hdr-size field is also a varint which is the offset from the beginning
2702 ** of the record to data0.
2704 nData
= 0; /* Number of bytes of data space */
2705 nHdr
= 0; /* Number of bytes of header space */
2706 nZero
= 0; /* Number of zero bytes at the end of the record */
2708 zAffinity
= pOp
->p4
.z
;
2709 assert( nField
>0 && pOp
->p2
>0 && pOp
->p2
+nField
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2710 pData0
= &aMem
[nField
];
2712 pLast
= &pData0
[nField
-1];
2713 file_format
= p
->minWriteFileFormat
;
2715 /* Identify the output register */
2716 assert( pOp
->p3
<pOp
->p1
|| pOp
->p3
>=pOp
->p1
+pOp
->p2
);
2717 pOut
= &aMem
[pOp
->p3
];
2718 memAboutToChange(p
, pOut
);
2720 /* Apply the requested affinity to all inputs
2722 assert( pData0
<=pLast
);
2726 applyAffinity(pRec
++, *(zAffinity
++), encoding
);
2727 assert( zAffinity
[0]==0 || pRec
<=pLast
);
2728 }while( zAffinity
[0] );
2731 /* Loop through the elements that will make up the record to figure
2732 ** out how much space is required for the new record.
2736 assert( memIsValid(pRec
) );
2737 pRec
->uTemp
= serial_type
= sqlite3VdbeSerialType(pRec
, file_format
, &len
);
2738 if( pRec
->flags
& MEM_Zero
){
2740 if( sqlite3VdbeMemExpandBlob(pRec
) ) goto no_mem
;
2742 nZero
+= pRec
->u
.nZero
;
2743 len
-= pRec
->u
.nZero
;
2747 testcase( serial_type
==127 );
2748 testcase( serial_type
==128 );
2749 nHdr
+= serial_type
<=127 ? 1 : sqlite3VarintLen(serial_type
);
2750 if( pRec
==pData0
) break;
2754 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
2755 ** which determines the total number of bytes in the header. The varint
2756 ** value is the size of the header in bytes including the size varint
2758 testcase( nHdr
==126 );
2759 testcase( nHdr
==127 );
2761 /* The common case */
2764 /* Rare case of a really large header */
2765 nVarint
= sqlite3VarintLen(nHdr
);
2767 if( nVarint
<sqlite3VarintLen(nHdr
) ) nHdr
++;
2770 if( nByte
+nZero
>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
2774 /* Make sure the output register has a buffer large enough to store
2775 ** the new record. The output register (pOp->p3) is not allowed to
2776 ** be one of the input registers (because the following call to
2777 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2779 if( sqlite3VdbeMemClearAndResize(pOut
, (int)nByte
) ){
2782 zNewRecord
= (u8
*)pOut
->z
;
2784 /* Write the record */
2785 i
= putVarint32(zNewRecord
, nHdr
);
2787 assert( pData0
<=pLast
);
2790 serial_type
= pRec
->uTemp
;
2791 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
2792 ** additional varints, one per column. */
2793 i
+= putVarint32(&zNewRecord
[i
], serial_type
); /* serial type */
2794 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
2795 ** immediately follow the header. */
2796 j
+= sqlite3VdbeSerialPut(&zNewRecord
[j
], pRec
, serial_type
); /* content */
2797 }while( (++pRec
)<=pLast
);
2801 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
2802 pOut
->n
= (int)nByte
;
2803 pOut
->flags
= MEM_Blob
;
2805 pOut
->u
.nZero
= nZero
;
2806 pOut
->flags
|= MEM_Zero
;
2808 pOut
->enc
= SQLITE_UTF8
; /* In case the blob is ever converted to text */
2809 REGISTER_TRACE(pOp
->p3
, pOut
);
2810 UPDATE_MAX_BLOBSIZE(pOut
);
2814 /* Opcode: Count P1 P2 * * *
2815 ** Synopsis: r[P2]=count()
2817 ** Store the number of entries (an integer value) in the table or index
2818 ** opened by cursor P1 in register P2
2820 #ifndef SQLITE_OMIT_BTREECOUNT
2821 case OP_Count
: { /* out2 */
2825 assert( p
->apCsr
[pOp
->p1
]->eCurType
==CURTYPE_BTREE
);
2826 pCrsr
= p
->apCsr
[pOp
->p1
]->uc
.pCursor
;
2828 nEntry
= 0; /* Not needed. Only used to silence a warning. */
2829 rc
= sqlite3BtreeCount(pCrsr
, &nEntry
);
2830 if( rc
) goto abort_due_to_error
;
2831 pOut
= out2Prerelease(p
, pOp
);
2837 /* Opcode: Savepoint P1 * * P4 *
2839 ** Open, release or rollback the savepoint named by parameter P4, depending
2840 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2841 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2843 case OP_Savepoint
: {
2844 int p1
; /* Value of P1 operand */
2845 char *zName
; /* Name of savepoint */
2848 Savepoint
*pSavepoint
;
2856 /* Assert that the p1 parameter is valid. Also that if there is no open
2857 ** transaction, then there cannot be any savepoints.
2859 assert( db
->pSavepoint
==0 || db
->autoCommit
==0 );
2860 assert( p1
==SAVEPOINT_BEGIN
||p1
==SAVEPOINT_RELEASE
||p1
==SAVEPOINT_ROLLBACK
);
2861 assert( db
->pSavepoint
|| db
->isTransactionSavepoint
==0 );
2862 assert( checkSavepointCount(db
) );
2863 assert( p
->bIsReader
);
2865 if( p1
==SAVEPOINT_BEGIN
){
2866 if( db
->nVdbeWrite
>0 ){
2867 /* A new savepoint cannot be created if there are active write
2868 ** statements (i.e. open read/write incremental blob handles).
2870 sqlite3VdbeError(p
, "cannot open savepoint - SQL statements in progress");
2873 nName
= sqlite3Strlen30(zName
);
2875 #ifndef SQLITE_OMIT_VIRTUALTABLE
2876 /* This call is Ok even if this savepoint is actually a transaction
2877 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2878 ** If this is a transaction savepoint being opened, it is guaranteed
2879 ** that the db->aVTrans[] array is empty. */
2880 assert( db
->autoCommit
==0 || db
->nVTrans
==0 );
2881 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_BEGIN
,
2882 db
->nStatement
+db
->nSavepoint
);
2883 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
2886 /* Create a new savepoint structure. */
2887 pNew
= sqlite3DbMallocRawNN(db
, sizeof(Savepoint
)+nName
+1);
2889 pNew
->zName
= (char *)&pNew
[1];
2890 memcpy(pNew
->zName
, zName
, nName
+1);
2892 /* If there is no open transaction, then mark this as a special
2893 ** "transaction savepoint". */
2894 if( db
->autoCommit
){
2896 db
->isTransactionSavepoint
= 1;
2901 /* Link the new savepoint into the database handle's list. */
2902 pNew
->pNext
= db
->pSavepoint
;
2903 db
->pSavepoint
= pNew
;
2904 pNew
->nDeferredCons
= db
->nDeferredCons
;
2905 pNew
->nDeferredImmCons
= db
->nDeferredImmCons
;
2911 /* Find the named savepoint. If there is no such savepoint, then an
2912 ** an error is returned to the user. */
2914 pSavepoint
= db
->pSavepoint
;
2915 pSavepoint
&& sqlite3StrICmp(pSavepoint
->zName
, zName
);
2916 pSavepoint
= pSavepoint
->pNext
2921 sqlite3VdbeError(p
, "no such savepoint: %s", zName
);
2923 }else if( db
->nVdbeWrite
>0 && p1
==SAVEPOINT_RELEASE
){
2924 /* It is not possible to release (commit) a savepoint if there are
2925 ** active write statements.
2927 sqlite3VdbeError(p
, "cannot release savepoint - "
2928 "SQL statements in progress");
2932 /* Determine whether or not this is a transaction savepoint. If so,
2933 ** and this is a RELEASE command, then the current transaction
2936 int isTransaction
= pSavepoint
->pNext
==0 && db
->isTransactionSavepoint
;
2937 if( isTransaction
&& p1
==SAVEPOINT_RELEASE
){
2938 if( (rc
= sqlite3VdbeCheckFk(p
, 1))!=SQLITE_OK
){
2942 if( sqlite3VdbeHalt(p
)==SQLITE_BUSY
){
2943 p
->pc
= (int)(pOp
- aOp
);
2945 p
->rc
= rc
= SQLITE_BUSY
;
2948 db
->isTransactionSavepoint
= 0;
2952 iSavepoint
= db
->nSavepoint
- iSavepoint
- 1;
2953 if( p1
==SAVEPOINT_ROLLBACK
){
2954 isSchemaChange
= (db
->flags
& SQLITE_InternChanges
)!=0;
2955 for(ii
=0; ii
<db
->nDb
; ii
++){
2956 rc
= sqlite3BtreeTripAllCursors(db
->aDb
[ii
].pBt
,
2957 SQLITE_ABORT_ROLLBACK
,
2959 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
2964 for(ii
=0; ii
<db
->nDb
; ii
++){
2965 rc
= sqlite3BtreeSavepoint(db
->aDb
[ii
].pBt
, p1
, iSavepoint
);
2966 if( rc
!=SQLITE_OK
){
2967 goto abort_due_to_error
;
2970 if( isSchemaChange
){
2971 sqlite3ExpirePreparedStatements(db
);
2972 sqlite3ResetAllSchemasOfConnection(db
);
2973 db
->flags
= (db
->flags
| SQLITE_InternChanges
);
2977 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
2978 ** savepoints nested inside of the savepoint being operated on. */
2979 while( db
->pSavepoint
!=pSavepoint
){
2980 pTmp
= db
->pSavepoint
;
2981 db
->pSavepoint
= pTmp
->pNext
;
2982 sqlite3DbFree(db
, pTmp
);
2986 /* If it is a RELEASE, then destroy the savepoint being operated on
2987 ** too. If it is a ROLLBACK TO, then set the number of deferred
2988 ** constraint violations present in the database to the value stored
2989 ** when the savepoint was created. */
2990 if( p1
==SAVEPOINT_RELEASE
){
2991 assert( pSavepoint
==db
->pSavepoint
);
2992 db
->pSavepoint
= pSavepoint
->pNext
;
2993 sqlite3DbFree(db
, pSavepoint
);
2994 if( !isTransaction
){
2998 db
->nDeferredCons
= pSavepoint
->nDeferredCons
;
2999 db
->nDeferredImmCons
= pSavepoint
->nDeferredImmCons
;
3002 if( !isTransaction
|| p1
==SAVEPOINT_ROLLBACK
){
3003 rc
= sqlite3VtabSavepoint(db
, p1
, iSavepoint
);
3004 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
3008 if( rc
) goto abort_due_to_error
;
3013 /* Opcode: AutoCommit P1 P2 * * *
3015 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3016 ** back any currently active btree transactions. If there are any active
3017 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3018 ** there are active writing VMs or active VMs that use shared cache.
3020 ** This instruction causes the VM to halt.
3022 case OP_AutoCommit
: {
3023 int desiredAutoCommit
;
3026 desiredAutoCommit
= pOp
->p1
;
3027 iRollback
= pOp
->p2
;
3028 assert( desiredAutoCommit
==1 || desiredAutoCommit
==0 );
3029 assert( desiredAutoCommit
==1 || iRollback
==0 );
3030 assert( db
->nVdbeActive
>0 ); /* At least this one VM is active */
3031 assert( p
->bIsReader
);
3033 if( desiredAutoCommit
!=db
->autoCommit
){
3035 assert( desiredAutoCommit
==1 );
3036 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
3038 }else if( desiredAutoCommit
&& db
->nVdbeWrite
>0 ){
3039 /* If this instruction implements a COMMIT and other VMs are writing
3040 ** return an error indicating that the other VMs must complete first.
3042 sqlite3VdbeError(p
, "cannot commit transaction - "
3043 "SQL statements in progress");
3045 goto abort_due_to_error
;
3046 }else if( (rc
= sqlite3VdbeCheckFk(p
, 1))!=SQLITE_OK
){
3049 db
->autoCommit
= (u8
)desiredAutoCommit
;
3051 if( sqlite3VdbeHalt(p
)==SQLITE_BUSY
){
3052 p
->pc
= (int)(pOp
- aOp
);
3053 db
->autoCommit
= (u8
)(1-desiredAutoCommit
);
3054 p
->rc
= rc
= SQLITE_BUSY
;
3057 assert( db
->nStatement
==0 );
3058 sqlite3CloseSavepoints(db
);
3059 if( p
->rc
==SQLITE_OK
){
3067 (!desiredAutoCommit
)?"cannot start a transaction within a transaction":(
3068 (iRollback
)?"cannot rollback - no transaction is active":
3069 "cannot commit - no transaction is active"));
3072 goto abort_due_to_error
;
3077 /* Opcode: Transaction P1 P2 P3 P4 P5
3079 ** Begin a transaction on database P1 if a transaction is not already
3081 ** If P2 is non-zero, then a write-transaction is started, or if a
3082 ** read-transaction is already active, it is upgraded to a write-transaction.
3083 ** If P2 is zero, then a read-transaction is started.
3085 ** P1 is the index of the database file on which the transaction is
3086 ** started. Index 0 is the main database file and index 1 is the
3087 ** file used for temporary tables. Indices of 2 or more are used for
3088 ** attached databases.
3090 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3091 ** true (this flag is set if the Vdbe may modify more than one row and may
3092 ** throw an ABORT exception), a statement transaction may also be opened.
3093 ** More specifically, a statement transaction is opened iff the database
3094 ** connection is currently not in autocommit mode, or if there are other
3095 ** active statements. A statement transaction allows the changes made by this
3096 ** VDBE to be rolled back after an error without having to roll back the
3097 ** entire transaction. If no error is encountered, the statement transaction
3098 ** will automatically commit when the VDBE halts.
3100 ** If P5!=0 then this opcode also checks the schema cookie against P3
3101 ** and the schema generation counter against P4.
3102 ** The cookie changes its value whenever the database schema changes.
3103 ** This operation is used to detect when that the cookie has changed
3104 ** and that the current process needs to reread the schema. If the schema
3105 ** cookie in P3 differs from the schema cookie in the database header or
3106 ** if the schema generation counter in P4 differs from the current
3107 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3108 ** halts. The sqlite3_step() wrapper function might then reprepare the
3109 ** statement and rerun it from the beginning.
3111 case OP_Transaction
: {
3116 assert( p
->bIsReader
);
3117 assert( p
->readOnly
==0 || pOp
->p2
==0 );
3118 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
3119 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
3120 if( pOp
->p2
&& (db
->flags
& SQLITE_QueryOnly
)!=0 ){
3121 rc
= SQLITE_READONLY
;
3122 goto abort_due_to_error
;
3124 pBt
= db
->aDb
[pOp
->p1
].pBt
;
3127 rc
= sqlite3BtreeBeginTrans(pBt
, pOp
->p2
);
3128 testcase( rc
==SQLITE_BUSY_SNAPSHOT
);
3129 testcase( rc
==SQLITE_BUSY_RECOVERY
);
3130 if( (rc
&0xff)==SQLITE_BUSY
){
3131 p
->pc
= (int)(pOp
- aOp
);
3135 if( rc
!=SQLITE_OK
){
3136 goto abort_due_to_error
;
3139 if( pOp
->p2
&& p
->usesStmtJournal
3140 && (db
->autoCommit
==0 || db
->nVdbeRead
>1)
3142 assert( sqlite3BtreeIsInTrans(pBt
) );
3143 if( p
->iStatement
==0 ){
3144 assert( db
->nStatement
>=0 && db
->nSavepoint
>=0 );
3146 p
->iStatement
= db
->nSavepoint
+ db
->nStatement
;
3149 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_BEGIN
, p
->iStatement
-1);
3150 if( rc
==SQLITE_OK
){
3151 rc
= sqlite3BtreeBeginStmt(pBt
, p
->iStatement
);
3154 /* Store the current value of the database handles deferred constraint
3155 ** counter. If the statement transaction needs to be rolled back,
3156 ** the value of this counter needs to be restored too. */
3157 p
->nStmtDefCons
= db
->nDeferredCons
;
3158 p
->nStmtDefImmCons
= db
->nDeferredImmCons
;
3161 /* Gather the schema version number for checking:
3162 ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
3163 ** each time a query is executed to ensure that the internal cache of the
3164 ** schema used when compiling the SQL query matches the schema of the
3165 ** database against which the compiled query is actually executed.
3167 sqlite3BtreeGetMeta(pBt
, BTREE_SCHEMA_VERSION
, (u32
*)&iMeta
);
3168 iGen
= db
->aDb
[pOp
->p1
].pSchema
->iGeneration
;
3172 assert( pOp
->p5
==0 || pOp
->p4type
==P4_INT32
);
3173 if( pOp
->p5
&& (iMeta
!=pOp
->p3
|| iGen
!=pOp
->p4
.i
) ){
3174 sqlite3DbFree(db
, p
->zErrMsg
);
3175 p
->zErrMsg
= sqlite3DbStrDup(db
, "database schema has changed");
3176 /* If the schema-cookie from the database file matches the cookie
3177 ** stored with the in-memory representation of the schema, do
3178 ** not reload the schema from the database file.
3180 ** If virtual-tables are in use, this is not just an optimization.
3181 ** Often, v-tables store their data in other SQLite tables, which
3182 ** are queried from within xNext() and other v-table methods using
3183 ** prepared queries. If such a query is out-of-date, we do not want to
3184 ** discard the database schema, as the user code implementing the
3185 ** v-table would have to be ready for the sqlite3_vtab structure itself
3186 ** to be invalidated whenever sqlite3_step() is called from within
3187 ** a v-table method.
3189 if( db
->aDb
[pOp
->p1
].pSchema
->schema_cookie
!=iMeta
){
3190 sqlite3ResetOneSchema(db
, pOp
->p1
);
3195 if( rc
) goto abort_due_to_error
;
3199 /* Opcode: ReadCookie P1 P2 P3 * *
3201 ** Read cookie number P3 from database P1 and write it into register P2.
3202 ** P3==1 is the schema version. P3==2 is the database format.
3203 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3204 ** the main database file and P1==1 is the database file used to store
3205 ** temporary tables.
3207 ** There must be a read-lock on the database (either a transaction
3208 ** must be started or there must be an open cursor) before
3209 ** executing this instruction.
3211 case OP_ReadCookie
: { /* out2 */
3216 assert( p
->bIsReader
);
3219 assert( pOp
->p3
<SQLITE_N_BTREE_META
);
3220 assert( iDb
>=0 && iDb
<db
->nDb
);
3221 assert( db
->aDb
[iDb
].pBt
!=0 );
3222 assert( DbMaskTest(p
->btreeMask
, iDb
) );
3224 sqlite3BtreeGetMeta(db
->aDb
[iDb
].pBt
, iCookie
, (u32
*)&iMeta
);
3225 pOut
= out2Prerelease(p
, pOp
);
3230 /* Opcode: SetCookie P1 P2 P3 * *
3232 ** Write the integer value P3 into cookie number P2 of database P1.
3233 ** P2==1 is the schema version. P2==2 is the database format.
3234 ** P2==3 is the recommended pager cache
3235 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3236 ** database file used to store temporary tables.
3238 ** A transaction must be started before executing this opcode.
3240 case OP_SetCookie
: {
3242 assert( pOp
->p2
<SQLITE_N_BTREE_META
);
3243 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
3244 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
3245 assert( p
->readOnly
==0 );
3246 pDb
= &db
->aDb
[pOp
->p1
];
3247 assert( pDb
->pBt
!=0 );
3248 assert( sqlite3SchemaMutexHeld(db
, pOp
->p1
, 0) );
3249 /* See note about index shifting on OP_ReadCookie */
3250 rc
= sqlite3BtreeUpdateMeta(pDb
->pBt
, pOp
->p2
, pOp
->p3
);
3251 if( pOp
->p2
==BTREE_SCHEMA_VERSION
){
3252 /* When the schema cookie changes, record the new cookie internally */
3253 pDb
->pSchema
->schema_cookie
= pOp
->p3
;
3254 db
->flags
|= SQLITE_InternChanges
;
3255 }else if( pOp
->p2
==BTREE_FILE_FORMAT
){
3256 /* Record changes in the file format */
3257 pDb
->pSchema
->file_format
= pOp
->p3
;
3260 /* Invalidate all prepared statements whenever the TEMP database
3261 ** schema is changed. Ticket #1644 */
3262 sqlite3ExpirePreparedStatements(db
);
3265 if( rc
) goto abort_due_to_error
;
3269 /* Opcode: OpenRead P1 P2 P3 P4 P5
3270 ** Synopsis: root=P2 iDb=P3
3272 ** Open a read-only cursor for the database table whose root page is
3273 ** P2 in a database file. The database file is determined by P3.
3274 ** P3==0 means the main database, P3==1 means the database used for
3275 ** temporary tables, and P3>1 means used the corresponding attached
3276 ** database. Give the new cursor an identifier of P1. The P1
3277 ** values need not be contiguous but all P1 values should be small integers.
3278 ** It is an error for P1 to be negative.
3280 ** If P5!=0 then use the content of register P2 as the root page, not
3281 ** the value of P2 itself.
3283 ** There will be a read lock on the database whenever there is an
3284 ** open cursor. If the database was unlocked prior to this instruction
3285 ** then a read lock is acquired as part of this instruction. A read
3286 ** lock allows other processes to read the database but prohibits
3287 ** any other process from modifying the database. The read lock is
3288 ** released when all cursors are closed. If this instruction attempts
3289 ** to get a read lock but fails, the script terminates with an
3290 ** SQLITE_BUSY error code.
3292 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3293 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3294 ** structure, then said structure defines the content and collating
3295 ** sequence of the index being opened. Otherwise, if P4 is an integer
3296 ** value, it is set to the number of columns in the table.
3298 ** See also: OpenWrite, ReopenIdx
3300 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3301 ** Synopsis: root=P2 iDb=P3
3303 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
3304 ** checks to see if the cursor on P1 is already open with a root page
3305 ** number of P2 and if it is this opcode becomes a no-op. In other words,
3306 ** if the cursor is already open, do not reopen it.
3308 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
3309 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
3310 ** every other ReopenIdx or OpenRead for the same cursor number.
3312 ** See the OpenRead opcode documentation for additional information.
3314 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3315 ** Synopsis: root=P2 iDb=P3
3317 ** Open a read/write cursor named P1 on the table or index whose root
3318 ** page is P2. Or if P5!=0 use the content of register P2 to find the
3321 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3322 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3323 ** structure, then said structure defines the content and collating
3324 ** sequence of the index being opened. Otherwise, if P4 is an integer
3325 ** value, it is set to the number of columns in the table, or to the
3326 ** largest index of any column of the table that is actually used.
3328 ** This instruction works just like OpenRead except that it opens the cursor
3329 ** in read/write mode. For a given table, there can be one or more read-only
3330 ** cursors or a single read/write cursor but not both.
3332 ** See also OpenRead.
3334 case OP_ReopenIdx
: {
3344 assert( pOp
->p5
==0 || pOp
->p5
==OPFLAG_SEEKEQ
);
3345 assert( pOp
->p4type
==P4_KEYINFO
);
3346 pCur
= p
->apCsr
[pOp
->p1
];
3347 if( pCur
&& pCur
->pgnoRoot
==(u32
)pOp
->p2
){
3348 assert( pCur
->iDb
==pOp
->p3
); /* Guaranteed by the code generator */
3349 goto open_cursor_set_hints
;
3351 /* If the cursor is not currently open or is open on a different
3352 ** index, then fall through into OP_OpenRead to force a reopen */
3356 assert( pOp
->opcode
==OP_OpenWrite
|| pOp
->p5
==0 || pOp
->p5
==OPFLAG_SEEKEQ
);
3357 assert( p
->bIsReader
);
3358 assert( pOp
->opcode
==OP_OpenRead
|| pOp
->opcode
==OP_ReopenIdx
3359 || p
->readOnly
==0 );
3362 rc
= SQLITE_ABORT_ROLLBACK
;
3363 goto abort_due_to_error
;
3370 assert( iDb
>=0 && iDb
<db
->nDb
);
3371 assert( DbMaskTest(p
->btreeMask
, iDb
) );
3372 pDb
= &db
->aDb
[iDb
];
3375 if( pOp
->opcode
==OP_OpenWrite
){
3376 assert( OPFLAG_FORDELETE
==BTREE_FORDELETE
);
3377 wrFlag
= BTREE_WRCSR
| (pOp
->p5
& OPFLAG_FORDELETE
);
3378 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
3379 if( pDb
->pSchema
->file_format
< p
->minWriteFileFormat
){
3380 p
->minWriteFileFormat
= pDb
->pSchema
->file_format
;
3385 if( pOp
->p5
& OPFLAG_P2ISREG
){
3387 assert( p2
<=(p
->nMem
+1 - p
->nCursor
) );
3389 assert( memIsValid(pIn2
) );
3390 assert( (pIn2
->flags
& MEM_Int
)!=0 );
3391 sqlite3VdbeMemIntegerify(pIn2
);
3392 p2
= (int)pIn2
->u
.i
;
3393 /* The p2 value always comes from a prior OP_CreateTable opcode and
3394 ** that opcode will always set the p2 value to 2 or more or else fail.
3395 ** If there were a failure, the prepared statement would have halted
3396 ** before reaching this instruction. */
3399 if( pOp
->p4type
==P4_KEYINFO
){
3400 pKeyInfo
= pOp
->p4
.pKeyInfo
;
3401 assert( pKeyInfo
->enc
==ENC(db
) );
3402 assert( pKeyInfo
->db
==db
);
3403 nField
= pKeyInfo
->nField
+pKeyInfo
->nXField
;
3404 }else if( pOp
->p4type
==P4_INT32
){
3407 assert( pOp
->p1
>=0 );
3408 assert( nField
>=0 );
3409 testcase( nField
==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3410 pCur
= allocateCursor(p
, pOp
->p1
, nField
, iDb
, CURTYPE_BTREE
);
3411 if( pCur
==0 ) goto no_mem
;
3413 pCur
->isOrdered
= 1;
3414 pCur
->pgnoRoot
= p2
;
3416 pCur
->wrFlag
= wrFlag
;
3418 rc
= sqlite3BtreeCursor(pX
, p2
, wrFlag
, pKeyInfo
, pCur
->uc
.pCursor
);
3419 pCur
->pKeyInfo
= pKeyInfo
;
3420 /* Set the VdbeCursor.isTable variable. Previous versions of
3421 ** SQLite used to check if the root-page flags were sane at this point
3422 ** and report database corruption if they were not, but this check has
3423 ** since moved into the btree layer. */
3424 pCur
->isTable
= pOp
->p4type
!=P4_KEYINFO
;
3426 open_cursor_set_hints
:
3427 assert( OPFLAG_BULKCSR
==BTREE_BULKLOAD
);
3428 assert( OPFLAG_SEEKEQ
==BTREE_SEEK_EQ
);
3429 testcase( pOp
->p5
& OPFLAG_BULKCSR
);
3430 #ifdef SQLITE_ENABLE_CURSOR_HINTS
3431 testcase( pOp
->p2
& OPFLAG_SEEKEQ
);
3433 sqlite3BtreeCursorHintFlags(pCur
->uc
.pCursor
,
3434 (pOp
->p5
& (OPFLAG_BULKCSR
|OPFLAG_SEEKEQ
)));
3435 if( rc
) goto abort_due_to_error
;
3439 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3440 ** Synopsis: nColumn=P2
3442 ** Open a new cursor P1 to a transient table.
3443 ** The cursor is always opened read/write even if
3444 ** the main database is read-only. The ephemeral
3445 ** table is deleted automatically when the cursor is closed.
3447 ** P2 is the number of columns in the ephemeral table.
3448 ** The cursor points to a BTree table if P4==0 and to a BTree index
3449 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3450 ** that defines the format of keys in the index.
3452 ** The P5 parameter can be a mask of the BTREE_* flags defined
3453 ** in btree.h. These flags control aspects of the operation of
3454 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3455 ** added automatically.
3457 /* Opcode: OpenAutoindex P1 P2 * P4 *
3458 ** Synopsis: nColumn=P2
3460 ** This opcode works the same as OP_OpenEphemeral. It has a
3461 ** different name to distinguish its use. Tables created using
3462 ** by this opcode will be used for automatically created transient
3463 ** indices in joins.
3465 case OP_OpenAutoindex
:
3466 case OP_OpenEphemeral
: {
3470 static const int vfsFlags
=
3471 SQLITE_OPEN_READWRITE
|
3472 SQLITE_OPEN_CREATE
|
3473 SQLITE_OPEN_EXCLUSIVE
|
3474 SQLITE_OPEN_DELETEONCLOSE
|
3475 SQLITE_OPEN_TRANSIENT_DB
;
3476 assert( pOp
->p1
>=0 );
3477 assert( pOp
->p2
>=0 );
3478 pCx
= allocateCursor(p
, pOp
->p1
, pOp
->p2
, -1, CURTYPE_BTREE
);
3479 if( pCx
==0 ) goto no_mem
;
3481 pCx
->isEphemeral
= 1;
3482 rc
= sqlite3BtreeOpen(db
->pVfs
, 0, db
, &pCx
->pBt
,
3483 BTREE_OMIT_JOURNAL
| BTREE_SINGLE
| pOp
->p5
, vfsFlags
);
3484 if( rc
==SQLITE_OK
){
3485 rc
= sqlite3BtreeBeginTrans(pCx
->pBt
, 1);
3487 if( rc
==SQLITE_OK
){
3488 /* If a transient index is required, create it by calling
3489 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3490 ** opening it. If a transient table is required, just use the
3491 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3493 if( (pKeyInfo
= pOp
->p4
.pKeyInfo
)!=0 ){
3495 assert( pOp
->p4type
==P4_KEYINFO
);
3496 rc
= sqlite3BtreeCreateTable(pCx
->pBt
, &pgno
, BTREE_BLOBKEY
| pOp
->p5
);
3497 if( rc
==SQLITE_OK
){
3498 assert( pgno
==MASTER_ROOT
+1 );
3499 assert( pKeyInfo
->db
==db
);
3500 assert( pKeyInfo
->enc
==ENC(db
) );
3501 pCx
->pKeyInfo
= pKeyInfo
;
3502 rc
= sqlite3BtreeCursor(pCx
->pBt
, pgno
, BTREE_WRCSR
,
3503 pKeyInfo
, pCx
->uc
.pCursor
);
3507 rc
= sqlite3BtreeCursor(pCx
->pBt
, MASTER_ROOT
, BTREE_WRCSR
,
3508 0, pCx
->uc
.pCursor
);
3512 if( rc
) goto abort_due_to_error
;
3513 pCx
->isOrdered
= (pOp
->p5
!=BTREE_UNORDERED
);
3517 /* Opcode: SorterOpen P1 P2 P3 P4 *
3519 ** This opcode works like OP_OpenEphemeral except that it opens
3520 ** a transient index that is specifically designed to sort large
3521 ** tables using an external merge-sort algorithm.
3523 ** If argument P3 is non-zero, then it indicates that the sorter may
3524 ** assume that a stable sort considering the first P3 fields of each
3525 ** key is sufficient to produce the required results.
3527 case OP_SorterOpen
: {
3530 assert( pOp
->p1
>=0 );
3531 assert( pOp
->p2
>=0 );
3532 pCx
= allocateCursor(p
, pOp
->p1
, pOp
->p2
, -1, CURTYPE_SORTER
);
3533 if( pCx
==0 ) goto no_mem
;
3534 pCx
->pKeyInfo
= pOp
->p4
.pKeyInfo
;
3535 assert( pCx
->pKeyInfo
->db
==db
);
3536 assert( pCx
->pKeyInfo
->enc
==ENC(db
) );
3537 rc
= sqlite3VdbeSorterInit(db
, pOp
->p3
, pCx
);
3538 if( rc
) goto abort_due_to_error
;
3542 /* Opcode: SequenceTest P1 P2 * * *
3543 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3545 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3546 ** to P2. Regardless of whether or not the jump is taken, increment the
3547 ** the sequence value.
3549 case OP_SequenceTest
: {
3551 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
3552 pC
= p
->apCsr
[pOp
->p1
];
3553 assert( isSorter(pC
) );
3554 if( (pC
->seqCount
++)==0 ){
3560 /* Opcode: OpenPseudo P1 P2 P3 * *
3561 ** Synopsis: P3 columns in r[P2]
3563 ** Open a new cursor that points to a fake table that contains a single
3564 ** row of data. The content of that one row is the content of memory
3565 ** register P2. In other words, cursor P1 becomes an alias for the
3566 ** MEM_Blob content contained in register P2.
3568 ** A pseudo-table created by this opcode is used to hold a single
3569 ** row output from the sorter so that the row can be decomposed into
3570 ** individual columns using the OP_Column opcode. The OP_Column opcode
3571 ** is the only cursor opcode that works with a pseudo-table.
3573 ** P3 is the number of fields in the records that will be stored by
3574 ** the pseudo-table.
3576 case OP_OpenPseudo
: {
3579 assert( pOp
->p1
>=0 );
3580 assert( pOp
->p3
>=0 );
3581 pCx
= allocateCursor(p
, pOp
->p1
, pOp
->p3
, -1, CURTYPE_PSEUDO
);
3582 if( pCx
==0 ) goto no_mem
;
3584 pCx
->uc
.pseudoTableReg
= pOp
->p2
;
3586 assert( pOp
->p5
==0 );
3590 /* Opcode: Close P1 * * * *
3592 ** Close a cursor previously opened as P1. If P1 is not
3593 ** currently open, this instruction is a no-op.
3596 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
3597 sqlite3VdbeFreeCursor(p
, p
->apCsr
[pOp
->p1
]);
3598 p
->apCsr
[pOp
->p1
] = 0;
3602 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3603 /* Opcode: ColumnsUsed P1 * * P4 *
3605 ** This opcode (which only exists if SQLite was compiled with
3606 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
3607 ** table or index for cursor P1 are used. P4 is a 64-bit integer
3608 ** (P4_INT64) in which the first 63 bits are one for each of the
3609 ** first 63 columns of the table or index that are actually used
3610 ** by the cursor. The high-order bit is set if any column after
3611 ** the 64th is used.
3613 case OP_ColumnsUsed
: {
3615 pC
= p
->apCsr
[pOp
->p1
];
3616 assert( pC
->eCurType
==CURTYPE_BTREE
);
3617 pC
->maskUsed
= *(u64
*)pOp
->p4
.pI64
;
3622 /* Opcode: SeekGE P1 P2 P3 P4 *
3623 ** Synopsis: key=r[P3@P4]
3625 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3626 ** use the value in register P3 as the key. If cursor P1 refers
3627 ** to an SQL index, then P3 is the first in an array of P4 registers
3628 ** that are used as an unpacked index key.
3630 ** Reposition cursor P1 so that it points to the smallest entry that
3631 ** is greater than or equal to the key value. If there are no records
3632 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3634 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3635 ** opcode will always land on a record that equally equals the key, or
3636 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3637 ** opcode must be followed by an IdxLE opcode with the same arguments.
3638 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
3639 ** IdxLE opcode will be used on subsequent loop iterations.
3641 ** This opcode leaves the cursor configured to move in forward order,
3642 ** from the beginning toward the end. In other words, the cursor is
3643 ** configured to use Next, not Prev.
3645 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3647 /* Opcode: SeekGT P1 P2 P3 P4 *
3648 ** Synopsis: key=r[P3@P4]
3650 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3651 ** use the value in register P3 as a key. If cursor P1 refers
3652 ** to an SQL index, then P3 is the first in an array of P4 registers
3653 ** that are used as an unpacked index key.
3655 ** Reposition cursor P1 so that it points to the smallest entry that
3656 ** is greater than the key value. If there are no records greater than
3657 ** the key and P2 is not zero, then jump to P2.
3659 ** This opcode leaves the cursor configured to move in forward order,
3660 ** from the beginning toward the end. In other words, the cursor is
3661 ** configured to use Next, not Prev.
3663 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3665 /* Opcode: SeekLT P1 P2 P3 P4 *
3666 ** Synopsis: key=r[P3@P4]
3668 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3669 ** use the value in register P3 as a key. If cursor P1 refers
3670 ** to an SQL index, then P3 is the first in an array of P4 registers
3671 ** that are used as an unpacked index key.
3673 ** Reposition cursor P1 so that it points to the largest entry that
3674 ** is less than the key value. If there are no records less than
3675 ** the key and P2 is not zero, then jump to P2.
3677 ** This opcode leaves the cursor configured to move in reverse order,
3678 ** from the end toward the beginning. In other words, the cursor is
3679 ** configured to use Prev, not Next.
3681 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3683 /* Opcode: SeekLE P1 P2 P3 P4 *
3684 ** Synopsis: key=r[P3@P4]
3686 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3687 ** use the value in register P3 as a key. If cursor P1 refers
3688 ** to an SQL index, then P3 is the first in an array of P4 registers
3689 ** that are used as an unpacked index key.
3691 ** Reposition cursor P1 so that it points to the largest entry that
3692 ** is less than or equal to the key value. If there are no records
3693 ** less than or equal to the key and P2 is not zero, then jump to P2.
3695 ** This opcode leaves the cursor configured to move in reverse order,
3696 ** from the end toward the beginning. In other words, the cursor is
3697 ** configured to use Prev, not Next.
3699 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3700 ** opcode will always land on a record that equally equals the key, or
3701 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3702 ** opcode must be followed by an IdxGE opcode with the same arguments.
3703 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
3704 ** IdxGE opcode will be used on subsequent loop iterations.
3706 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3708 case OP_SeekLT
: /* jump, in3 */
3709 case OP_SeekLE
: /* jump, in3 */
3710 case OP_SeekGE
: /* jump, in3 */
3711 case OP_SeekGT
: { /* jump, in3 */
3712 int res
; /* Comparison result */
3713 int oc
; /* Opcode */
3714 VdbeCursor
*pC
; /* The cursor to seek */
3715 UnpackedRecord r
; /* The key to seek for */
3716 int nField
; /* Number of columns or fields in the key */
3717 i64 iKey
; /* The rowid we are to seek to */
3718 int eqOnly
; /* Only interested in == results */
3720 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
3721 assert( pOp
->p2
!=0 );
3722 pC
= p
->apCsr
[pOp
->p1
];
3724 assert( pC
->eCurType
==CURTYPE_BTREE
);
3725 assert( OP_SeekLE
== OP_SeekLT
+1 );
3726 assert( OP_SeekGE
== OP_SeekLT
+2 );
3727 assert( OP_SeekGT
== OP_SeekLT
+3 );
3728 assert( pC
->isOrdered
);
3729 assert( pC
->uc
.pCursor
!=0 );
3734 pC
->seekOp
= pOp
->opcode
;
3738 /* The BTREE_SEEK_EQ flag is only set on index cursors */
3739 assert( sqlite3BtreeCursorHasHint(pC
->uc
.pCursor
, BTREE_SEEK_EQ
)==0 );
3741 /* The input value in P3 might be of any type: integer, real, string,
3742 ** blob, or NULL. But it needs to be an integer before we can do
3743 ** the seek, so convert it. */
3744 pIn3
= &aMem
[pOp
->p3
];
3745 if( (pIn3
->flags
& (MEM_Int
|MEM_Real
|MEM_Str
))==MEM_Str
){
3746 applyNumericAffinity(pIn3
, 0);
3748 iKey
= sqlite3VdbeIntValue(pIn3
);
3750 /* If the P3 value could not be converted into an integer without
3751 ** loss of information, then special processing is required... */
3752 if( (pIn3
->flags
& MEM_Int
)==0 ){
3753 if( (pIn3
->flags
& MEM_Real
)==0 ){
3754 /* If the P3 value cannot be converted into any kind of a number,
3755 ** then the seek is not possible, so jump to P2 */
3756 VdbeBranchTaken(1,2); goto jump_to_p2
;
3760 /* If the approximation iKey is larger than the actual real search
3761 ** term, substitute >= for > and < for <=. e.g. if the search term
3762 ** is 4.9 and the integer approximation 5:
3764 ** (x > 4.9) -> (x >= 5)
3765 ** (x <= 4.9) -> (x < 5)
3767 if( pIn3
->u
.r
<(double)iKey
){
3768 assert( OP_SeekGE
==(OP_SeekGT
-1) );
3769 assert( OP_SeekLT
==(OP_SeekLE
-1) );
3770 assert( (OP_SeekLE
& 0x0001)==(OP_SeekGT
& 0x0001) );
3771 if( (oc
& 0x0001)==(OP_SeekGT
& 0x0001) ) oc
--;
3774 /* If the approximation iKey is smaller than the actual real search
3775 ** term, substitute <= for < and > for >=. */
3776 else if( pIn3
->u
.r
>(double)iKey
){
3777 assert( OP_SeekLE
==(OP_SeekLT
+1) );
3778 assert( OP_SeekGT
==(OP_SeekGE
+1) );
3779 assert( (OP_SeekLT
& 0x0001)==(OP_SeekGE
& 0x0001) );
3780 if( (oc
& 0x0001)==(OP_SeekLT
& 0x0001) ) oc
++;
3783 rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, 0, (u64
)iKey
, 0, &res
);
3784 pC
->movetoTarget
= iKey
; /* Used by OP_Delete */
3785 if( rc
!=SQLITE_OK
){
3786 goto abort_due_to_error
;
3789 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
3790 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
3791 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
3793 if( sqlite3BtreeCursorHasHint(pC
->uc
.pCursor
, BTREE_SEEK_EQ
) ){
3795 assert( pOp
->opcode
==OP_SeekGE
|| pOp
->opcode
==OP_SeekLE
);
3796 assert( pOp
[1].opcode
==OP_IdxLT
|| pOp
[1].opcode
==OP_IdxGT
);
3797 assert( pOp
[1].p1
==pOp
[0].p1
);
3798 assert( pOp
[1].p2
==pOp
[0].p2
);
3799 assert( pOp
[1].p3
==pOp
[0].p3
);
3800 assert( pOp
[1].p4
.i
==pOp
[0].p4
.i
);
3804 assert( pOp
->p4type
==P4_INT32
);
3806 r
.pKeyInfo
= pC
->pKeyInfo
;
3807 r
.nField
= (u16
)nField
;
3809 /* The next line of code computes as follows, only faster:
3810 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3811 ** r.default_rc = -1;
3813 ** r.default_rc = +1;
3816 r
.default_rc
= ((1 & (oc
- OP_SeekLT
)) ? -1 : +1);
3817 assert( oc
!=OP_SeekGT
|| r
.default_rc
==-1 );
3818 assert( oc
!=OP_SeekLE
|| r
.default_rc
==-1 );
3819 assert( oc
!=OP_SeekGE
|| r
.default_rc
==+1 );
3820 assert( oc
!=OP_SeekLT
|| r
.default_rc
==+1 );
3822 r
.aMem
= &aMem
[pOp
->p3
];
3824 { int i
; for(i
=0; i
<r
.nField
; i
++) assert( memIsValid(&r
.aMem
[i
]) ); }
3828 rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, &r
, 0, 0, &res
);
3829 if( rc
!=SQLITE_OK
){
3830 goto abort_due_to_error
;
3832 if( eqOnly
&& r
.eqSeen
==0 ){
3834 goto seek_not_found
;
3837 pC
->deferredMoveto
= 0;
3838 pC
->cacheStatus
= CACHE_STALE
;
3840 sqlite3_search_count
++;
3842 if( oc
>=OP_SeekGE
){ assert( oc
==OP_SeekGE
|| oc
==OP_SeekGT
);
3843 if( res
<0 || (res
==0 && oc
==OP_SeekGT
) ){
3845 rc
= sqlite3BtreeNext(pC
->uc
.pCursor
, &res
);
3846 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
3851 assert( oc
==OP_SeekLT
|| oc
==OP_SeekLE
);
3852 if( res
>0 || (res
==0 && oc
==OP_SeekLT
) ){
3854 rc
= sqlite3BtreePrevious(pC
->uc
.pCursor
, &res
);
3855 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
3857 /* res might be negative because the table is empty. Check to
3858 ** see if this is the case.
3860 res
= sqlite3BtreeEof(pC
->uc
.pCursor
);
3864 assert( pOp
->p2
>0 );
3865 VdbeBranchTaken(res
!=0,2);
3869 assert( pOp
[1].opcode
==OP_IdxLT
|| pOp
[1].opcode
==OP_IdxGT
);
3870 pOp
++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
3876 /* Opcode: Found P1 P2 P3 P4 *
3877 ** Synopsis: key=r[P3@P4]
3879 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
3880 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3883 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
3884 ** is a prefix of any entry in P1 then a jump is made to P2 and
3885 ** P1 is left pointing at the matching entry.
3887 ** This operation leaves the cursor in a state where it can be
3888 ** advanced in the forward direction. The Next instruction will work,
3889 ** but not the Prev instruction.
3891 ** See also: NotFound, NoConflict, NotExists. SeekGe
3893 /* Opcode: NotFound P1 P2 P3 P4 *
3894 ** Synopsis: key=r[P3@P4]
3896 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
3897 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3900 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
3901 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
3902 ** does contain an entry whose prefix matches the P3/P4 record then control
3903 ** falls through to the next instruction and P1 is left pointing at the
3906 ** This operation leaves the cursor in a state where it cannot be
3907 ** advanced in either direction. In other words, the Next and Prev
3908 ** opcodes do not work after this operation.
3910 ** See also: Found, NotExists, NoConflict
3912 /* Opcode: NoConflict P1 P2 P3 P4 *
3913 ** Synopsis: key=r[P3@P4]
3915 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
3916 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3919 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
3920 ** contains any NULL value, jump immediately to P2. If all terms of the
3921 ** record are not-NULL then a check is done to determine if any row in the
3922 ** P1 index btree has a matching key prefix. If there are no matches, jump
3923 ** immediately to P2. If there is a match, fall through and leave the P1
3924 ** cursor pointing to the matching row.
3926 ** This opcode is similar to OP_NotFound with the exceptions that the
3927 ** branch is always taken if any part of the search key input is NULL.
3929 ** This operation leaves the cursor in a state where it cannot be
3930 ** advanced in either direction. In other words, the Next and Prev
3931 ** opcodes do not work after this operation.
3933 ** See also: NotFound, Found, NotExists
3935 case OP_NoConflict
: /* jump, in3 */
3936 case OP_NotFound
: /* jump, in3 */
3937 case OP_Found
: { /* jump, in3 */
3944 UnpackedRecord
*pIdxKey
;
3946 char aTempRec
[ROUND8(sizeof(UnpackedRecord
)) + sizeof(Mem
)*4 + 7];
3949 if( pOp
->opcode
!=OP_NoConflict
) sqlite3_found_count
++;
3952 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
3953 assert( pOp
->p4type
==P4_INT32
);
3954 pC
= p
->apCsr
[pOp
->p1
];
3957 pC
->seekOp
= pOp
->opcode
;
3959 pIn3
= &aMem
[pOp
->p3
];
3960 assert( pC
->eCurType
==CURTYPE_BTREE
);
3961 assert( pC
->uc
.pCursor
!=0 );
3962 assert( pC
->isTable
==0 );
3965 r
.pKeyInfo
= pC
->pKeyInfo
;
3966 r
.nField
= (u16
)pOp
->p4
.i
;
3968 for(ii
=0; ii
<r
.nField
; ii
++){
3969 assert( memIsValid(&r
.aMem
[ii
]) );
3970 ExpandBlob(&r
.aMem
[ii
]);
3972 if( ii
) REGISTER_TRACE(pOp
->p3
+ii
, &r
.aMem
[ii
]);
3977 pIdxKey
= sqlite3VdbeAllocUnpackedRecord(
3978 pC
->pKeyInfo
, aTempRec
, sizeof(aTempRec
), &pFree
3980 if( pIdxKey
==0 ) goto no_mem
;
3981 assert( pIn3
->flags
& MEM_Blob
);
3983 sqlite3VdbeRecordUnpack(pC
->pKeyInfo
, pIn3
->n
, pIn3
->z
, pIdxKey
);
3985 pIdxKey
->default_rc
= 0;
3987 if( pOp
->opcode
==OP_NoConflict
){
3988 /* For the OP_NoConflict opcode, take the jump if any of the
3989 ** input fields are NULL, since any key with a NULL will not
3991 for(ii
=0; ii
<pIdxKey
->nField
; ii
++){
3992 if( pIdxKey
->aMem
[ii
].flags
& MEM_Null
){
3998 rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, pIdxKey
, 0, 0, &res
);
3999 sqlite3DbFree(db
, pFree
);
4000 if( rc
!=SQLITE_OK
){
4001 goto abort_due_to_error
;
4003 pC
->seekResult
= res
;
4004 alreadyExists
= (res
==0);
4005 pC
->nullRow
= 1-alreadyExists
;
4006 pC
->deferredMoveto
= 0;
4007 pC
->cacheStatus
= CACHE_STALE
;
4008 if( pOp
->opcode
==OP_Found
){
4009 VdbeBranchTaken(alreadyExists
!=0,2);
4010 if( alreadyExists
) goto jump_to_p2
;
4012 VdbeBranchTaken(takeJump
||alreadyExists
==0,2);
4013 if( takeJump
|| !alreadyExists
) goto jump_to_p2
;
4018 /* Opcode: SeekRowid P1 P2 P3 * *
4019 ** Synopsis: intkey=r[P3]
4021 ** P1 is the index of a cursor open on an SQL table btree (with integer
4022 ** keys). If register P3 does not contain an integer or if P1 does not
4023 ** contain a record with rowid P3 then jump immediately to P2.
4024 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4025 ** a record with rowid P3 then
4026 ** leave the cursor pointing at that record and fall through to the next
4029 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4030 ** the P3 register must be guaranteed to contain an integer value. With this
4031 ** opcode, register P3 might not contain an integer.
4033 ** The OP_NotFound opcode performs the same operation on index btrees
4034 ** (with arbitrary multi-value keys).
4036 ** This opcode leaves the cursor in a state where it cannot be advanced
4037 ** in either direction. In other words, the Next and Prev opcodes will
4038 ** not work following this opcode.
4040 ** See also: Found, NotFound, NoConflict, SeekRowid
4042 /* Opcode: NotExists P1 P2 P3 * *
4043 ** Synopsis: intkey=r[P3]
4045 ** P1 is the index of a cursor open on an SQL table btree (with integer
4046 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4047 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4048 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4049 ** leave the cursor pointing at that record and fall through to the next
4052 ** The OP_SeekRowid opcode performs the same operation but also allows the
4053 ** P3 register to contain a non-integer value, in which case the jump is
4054 ** always taken. This opcode requires that P3 always contain an integer.
4056 ** The OP_NotFound opcode performs the same operation on index btrees
4057 ** (with arbitrary multi-value keys).
4059 ** This opcode leaves the cursor in a state where it cannot be advanced
4060 ** in either direction. In other words, the Next and Prev opcodes will
4061 ** not work following this opcode.
4063 ** See also: Found, NotFound, NoConflict, SeekRowid
4065 case OP_SeekRowid
: { /* jump, in3 */
4071 pIn3
= &aMem
[pOp
->p3
];
4072 if( (pIn3
->flags
& MEM_Int
)==0 ){
4073 applyAffinity(pIn3
, SQLITE_AFF_NUMERIC
, encoding
);
4074 if( (pIn3
->flags
& MEM_Int
)==0 ) goto jump_to_p2
;
4076 /* Fall through into OP_NotExists */
4077 case OP_NotExists
: /* jump, in3 */
4078 pIn3
= &aMem
[pOp
->p3
];
4079 assert( pIn3
->flags
& MEM_Int
);
4080 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4081 pC
= p
->apCsr
[pOp
->p1
];
4086 assert( pC
->isTable
);
4087 assert( pC
->eCurType
==CURTYPE_BTREE
);
4088 pCrsr
= pC
->uc
.pCursor
;
4092 rc
= sqlite3BtreeMovetoUnpacked(pCrsr
, 0, iKey
, 0, &res
);
4093 assert( rc
==SQLITE_OK
|| res
==0 );
4094 pC
->movetoTarget
= iKey
; /* Used by OP_Delete */
4096 pC
->cacheStatus
= CACHE_STALE
;
4097 pC
->deferredMoveto
= 0;
4098 VdbeBranchTaken(res
!=0,2);
4099 pC
->seekResult
= res
;
4101 assert( rc
==SQLITE_OK
);
4103 rc
= SQLITE_CORRUPT_BKPT
;
4108 if( rc
) goto abort_due_to_error
;
4112 /* Opcode: Sequence P1 P2 * * *
4113 ** Synopsis: r[P2]=cursor[P1].ctr++
4115 ** Find the next available sequence number for cursor P1.
4116 ** Write the sequence number into register P2.
4117 ** The sequence number on the cursor is incremented after this
4120 case OP_Sequence
: { /* out2 */
4121 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4122 assert( p
->apCsr
[pOp
->p1
]!=0 );
4123 assert( p
->apCsr
[pOp
->p1
]->eCurType
!=CURTYPE_VTAB
);
4124 pOut
= out2Prerelease(p
, pOp
);
4125 pOut
->u
.i
= p
->apCsr
[pOp
->p1
]->seqCount
++;
4130 /* Opcode: NewRowid P1 P2 P3 * *
4131 ** Synopsis: r[P2]=rowid
4133 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4134 ** The record number is not previously used as a key in the database
4135 ** table that cursor P1 points to. The new record number is written
4136 ** written to register P2.
4138 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4139 ** the largest previously generated record number. No new record numbers are
4140 ** allowed to be less than this value. When this value reaches its maximum,
4141 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4142 ** generated record number. This P3 mechanism is used to help implement the
4143 ** AUTOINCREMENT feature.
4145 case OP_NewRowid
: { /* out2 */
4146 i64 v
; /* The new rowid */
4147 VdbeCursor
*pC
; /* Cursor of table to get the new rowid */
4148 int res
; /* Result of an sqlite3BtreeLast() */
4149 int cnt
; /* Counter to limit the number of searches */
4150 Mem
*pMem
; /* Register holding largest rowid for AUTOINCREMENT */
4151 VdbeFrame
*pFrame
; /* Root frame of VDBE */
4155 pOut
= out2Prerelease(p
, pOp
);
4156 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4157 pC
= p
->apCsr
[pOp
->p1
];
4159 assert( pC
->eCurType
==CURTYPE_BTREE
);
4160 assert( pC
->uc
.pCursor
!=0 );
4162 /* The next rowid or record number (different terms for the same
4163 ** thing) is obtained in a two-step algorithm.
4165 ** First we attempt to find the largest existing rowid and add one
4166 ** to that. But if the largest existing rowid is already the maximum
4167 ** positive integer, we have to fall through to the second
4168 ** probabilistic algorithm
4170 ** The second algorithm is to select a rowid at random and see if
4171 ** it already exists in the table. If it does not exist, we have
4172 ** succeeded. If the random rowid does exist, we select a new one
4173 ** and try again, up to 100 times.
4175 assert( pC
->isTable
);
4177 #ifdef SQLITE_32BIT_ROWID
4178 # define MAX_ROWID 0x7fffffff
4180 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4181 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4182 ** to provide the constant while making all compilers happy.
4184 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4187 if( !pC
->useRandomRowid
){
4188 rc
= sqlite3BtreeLast(pC
->uc
.pCursor
, &res
);
4189 if( rc
!=SQLITE_OK
){
4190 goto abort_due_to_error
;
4193 v
= 1; /* IMP: R-61914-48074 */
4195 assert( sqlite3BtreeCursorIsValid(pC
->uc
.pCursor
) );
4196 v
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4198 pC
->useRandomRowid
= 1;
4200 v
++; /* IMP: R-29538-34987 */
4205 #ifndef SQLITE_OMIT_AUTOINCREMENT
4207 /* Assert that P3 is a valid memory cell. */
4208 assert( pOp
->p3
>0 );
4210 for(pFrame
=p
->pFrame
; pFrame
->pParent
; pFrame
=pFrame
->pParent
);
4211 /* Assert that P3 is a valid memory cell. */
4212 assert( pOp
->p3
<=pFrame
->nMem
);
4213 pMem
= &pFrame
->aMem
[pOp
->p3
];
4215 /* Assert that P3 is a valid memory cell. */
4216 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
4217 pMem
= &aMem
[pOp
->p3
];
4218 memAboutToChange(p
, pMem
);
4220 assert( memIsValid(pMem
) );
4222 REGISTER_TRACE(pOp
->p3
, pMem
);
4223 sqlite3VdbeMemIntegerify(pMem
);
4224 assert( (pMem
->flags
& MEM_Int
)!=0 ); /* mem(P3) holds an integer */
4225 if( pMem
->u
.i
==MAX_ROWID
|| pC
->useRandomRowid
){
4226 rc
= SQLITE_FULL
; /* IMP: R-12275-61338 */
4227 goto abort_due_to_error
;
4229 if( v
<pMem
->u
.i
+1 ){
4235 if( pC
->useRandomRowid
){
4236 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4237 ** largest possible integer (9223372036854775807) then the database
4238 ** engine starts picking positive candidate ROWIDs at random until
4239 ** it finds one that is not previously used. */
4240 assert( pOp
->p3
==0 ); /* We cannot be in random rowid mode if this is
4241 ** an AUTOINCREMENT table. */
4244 sqlite3_randomness(sizeof(v
), &v
);
4245 v
&= (MAX_ROWID
>>1); v
++; /* Ensure that v is greater than zero */
4246 }while( ((rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, 0, (u64
)v
,
4247 0, &res
))==SQLITE_OK
)
4250 if( rc
) goto abort_due_to_error
;
4252 rc
= SQLITE_FULL
; /* IMP: R-38219-53002 */
4253 goto abort_due_to_error
;
4255 assert( v
>0 ); /* EV: R-40812-03570 */
4257 pC
->deferredMoveto
= 0;
4258 pC
->cacheStatus
= CACHE_STALE
;
4264 /* Opcode: Insert P1 P2 P3 P4 P5
4265 ** Synopsis: intkey=r[P3] data=r[P2]
4267 ** Write an entry into the table of cursor P1. A new entry is
4268 ** created if it doesn't already exist or the data for an existing
4269 ** entry is overwritten. The data is the value MEM_Blob stored in register
4270 ** number P2. The key is stored in register P3. The key must
4273 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4274 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
4275 ** then rowid is stored for subsequent return by the
4276 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4278 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
4279 ** the last seek operation (OP_NotExists or OP_SeekRowid) was a success,
4281 ** operation will not attempt to find the appropriate row before doing
4282 ** the insert but will instead overwrite the row that the cursor is
4283 ** currently pointing to. Presumably, the prior OP_NotExists or
4284 ** OP_SeekRowid opcode
4285 ** has already positioned the cursor correctly. This is an optimization
4286 ** that boosts performance by avoiding redundant seeks.
4288 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4289 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
4290 ** is part of an INSERT operation. The difference is only important to
4293 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
4294 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
4295 ** following a successful insert.
4297 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4298 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4299 ** and register P2 becomes ephemeral. If the cursor is changed, the
4300 ** value of register P2 will then change. Make sure this does not
4301 ** cause any problems.)
4303 ** This instruction only works on tables. The equivalent instruction
4304 ** for indices is OP_IdxInsert.
4306 /* Opcode: InsertInt P1 P2 P3 P4 P5
4307 ** Synopsis: intkey=P3 data=r[P2]
4309 ** This works exactly like OP_Insert except that the key is the
4310 ** integer value P3, not the value of the integer stored in register P3.
4313 case OP_InsertInt
: {
4314 Mem
*pData
; /* MEM cell holding data for the record to be inserted */
4315 Mem
*pKey
; /* MEM cell holding key for the record */
4316 VdbeCursor
*pC
; /* Cursor to table into which insert is written */
4317 int seekResult
; /* Result of prior seek or 0 if no USESEEKRESULT flag */
4318 const char *zDb
; /* database name - used by the update hook */
4319 Table
*pTab
; /* Table structure - used by update and pre-update hooks */
4320 int op
; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
4321 BtreePayload x
; /* Payload to be inserted */
4324 pData
= &aMem
[pOp
->p2
];
4325 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4326 assert( memIsValid(pData
) );
4327 pC
= p
->apCsr
[pOp
->p1
];
4329 assert( pC
->eCurType
==CURTYPE_BTREE
);
4330 assert( pC
->uc
.pCursor
!=0 );
4331 assert( pC
->isTable
);
4332 assert( pOp
->p4type
==P4_TABLE
|| pOp
->p4type
>=P4_STATIC
);
4333 REGISTER_TRACE(pOp
->p2
, pData
);
4335 if( pOp
->opcode
==OP_Insert
){
4336 pKey
= &aMem
[pOp
->p3
];
4337 assert( pKey
->flags
& MEM_Int
);
4338 assert( memIsValid(pKey
) );
4339 REGISTER_TRACE(pOp
->p3
, pKey
);
4342 assert( pOp
->opcode
==OP_InsertInt
);
4346 if( pOp
->p4type
==P4_TABLE
&& HAS_UPDATE_HOOK(db
) ){
4347 assert( pC
->isTable
);
4348 assert( pC
->iDb
>=0 );
4349 zDb
= db
->aDb
[pC
->iDb
].zName
;
4350 pTab
= pOp
->p4
.pTab
;
4351 assert( HasRowid(pTab
) );
4352 op
= ((pOp
->p5
& OPFLAG_ISUPDATE
) ? SQLITE_UPDATE
: SQLITE_INSERT
);
4354 pTab
= 0; /* Not needed. Silence a comiler warning. */
4355 zDb
= 0; /* Not needed. Silence a compiler warning. */
4358 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4359 /* Invoke the pre-update hook, if any */
4360 if( db
->xPreUpdateCallback
4361 && pOp
->p4type
==P4_TABLE
4362 && !(pOp
->p5
& OPFLAG_ISUPDATE
)
4364 sqlite3VdbePreUpdateHook(p
, pC
, SQLITE_INSERT
, zDb
, pTab
, x
.nKey
, pOp
->p2
);
4368 if( pOp
->p5
& OPFLAG_NCHANGE
) p
->nChange
++;
4369 if( pOp
->p5
& OPFLAG_LASTROWID
) db
->lastRowid
= lastRowid
= x
.nKey
;
4370 if( pData
->flags
& MEM_Null
){
4374 assert( pData
->flags
& (MEM_Blob
|MEM_Str
) );
4378 seekResult
= ((pOp
->p5
& OPFLAG_USESEEKRESULT
) ? pC
->seekResult
: 0);
4379 if( pData
->flags
& MEM_Zero
){
4380 x
.nZero
= pData
->u
.nZero
;
4385 rc
= sqlite3BtreeInsert(pC
->uc
.pCursor
, &x
,
4386 (pOp
->p5
& OPFLAG_APPEND
)!=0, seekResult
4388 pC
->deferredMoveto
= 0;
4389 pC
->cacheStatus
= CACHE_STALE
;
4391 /* Invoke the update-hook if required. */
4392 if( rc
) goto abort_due_to_error
;
4393 if( db
->xUpdateCallback
&& op
){
4394 db
->xUpdateCallback(db
->pUpdateArg
, op
, zDb
, pTab
->zName
, x
.nKey
);
4399 /* Opcode: Delete P1 P2 P3 P4 P5
4401 ** Delete the record at which the P1 cursor is currently pointing.
4403 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
4404 ** the cursor will be left pointing at either the next or the previous
4405 ** record in the table. If it is left pointing at the next record, then
4406 ** the next Next instruction will be a no-op. As a result, in this case
4407 ** it is ok to delete a record from within a Next loop. If
4408 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
4409 ** left in an undefined state.
4411 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
4412 ** delete one of several associated with deleting a table row and all its
4413 ** associated index entries. Exactly one of those deletes is the "primary"
4414 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
4415 ** marked with the AUXDELETE flag.
4417 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
4418 ** change count is incremented (otherwise not).
4420 ** P1 must not be pseudo-table. It has to be a real table with
4423 ** If P4 is not NULL then it points to a Table struture. In this case either
4424 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
4425 ** have been positioned using OP_NotFound prior to invoking this opcode in
4426 ** this case. Specifically, if one is configured, the pre-update hook is
4427 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
4428 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
4430 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
4431 ** of the memory cell that contains the value that the rowid of the row will
4432 ** be set to by the update.
4441 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4442 pC
= p
->apCsr
[pOp
->p1
];
4444 assert( pC
->eCurType
==CURTYPE_BTREE
);
4445 assert( pC
->uc
.pCursor
!=0 );
4446 assert( pC
->deferredMoveto
==0 );
4449 if( pOp
->p4type
==P4_TABLE
&& HasRowid(pOp
->p4
.pTab
) && pOp
->p5
==0 ){
4450 /* If p5 is zero, the seek operation that positioned the cursor prior to
4451 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
4452 ** the row that is being deleted */
4453 i64 iKey
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4454 assert( pC
->movetoTarget
==iKey
);
4458 /* If the update-hook or pre-update-hook will be invoked, set zDb to
4459 ** the name of the db to pass as to it. Also set local pTab to a copy
4460 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
4461 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
4462 ** VdbeCursor.movetoTarget to the current rowid. */
4463 if( pOp
->p4type
==P4_TABLE
&& HAS_UPDATE_HOOK(db
) ){
4464 assert( pC
->iDb
>=0 );
4465 assert( pOp
->p4
.pTab
!=0 );
4466 zDb
= db
->aDb
[pC
->iDb
].zName
;
4467 pTab
= pOp
->p4
.pTab
;
4468 if( (pOp
->p5
& OPFLAG_SAVEPOSITION
)!=0 && pC
->isTable
){
4469 pC
->movetoTarget
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4472 zDb
= 0; /* Not needed. Silence a compiler warning. */
4473 pTab
= 0; /* Not needed. Silence a compiler warning. */
4476 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4477 /* Invoke the pre-update-hook if required. */
4478 if( db
->xPreUpdateCallback
&& pOp
->p4
.pTab
&& HasRowid(pTab
) ){
4479 assert( !(opflags
& OPFLAG_ISUPDATE
) || (aMem
[pOp
->p3
].flags
& MEM_Int
) );
4480 sqlite3VdbePreUpdateHook(p
, pC
,
4481 (opflags
& OPFLAG_ISUPDATE
) ? SQLITE_UPDATE
: SQLITE_DELETE
,
4482 zDb
, pTab
, pC
->movetoTarget
,
4486 if( opflags
& OPFLAG_ISNOOP
) break;
4489 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
4490 assert( (pOp
->p5
& ~(OPFLAG_SAVEPOSITION
|OPFLAG_AUXDELETE
))==0 );
4491 assert( OPFLAG_SAVEPOSITION
==BTREE_SAVEPOSITION
);
4492 assert( OPFLAG_AUXDELETE
==BTREE_AUXDELETE
);
4496 if( pC
->isEphemeral
==0
4497 && (pOp
->p5
& OPFLAG_AUXDELETE
)==0
4498 && (pC
->wrFlag
& OPFLAG_FORDELETE
)==0
4502 if( pOp
->p2
& OPFLAG_NCHANGE
){
4508 rc
= sqlite3BtreeDelete(pC
->uc
.pCursor
, pOp
->p5
);
4509 pC
->cacheStatus
= CACHE_STALE
;
4510 if( rc
) goto abort_due_to_error
;
4512 /* Invoke the update-hook if required. */
4513 if( opflags
& OPFLAG_NCHANGE
){
4515 if( db
->xUpdateCallback
&& HasRowid(pTab
) ){
4516 db
->xUpdateCallback(db
->pUpdateArg
, SQLITE_DELETE
, zDb
, pTab
->zName
,
4518 assert( pC
->iDb
>=0 );
4524 /* Opcode: ResetCount * * * * *
4526 ** The value of the change counter is copied to the database handle
4527 ** change counter (returned by subsequent calls to sqlite3_changes()).
4528 ** Then the VMs internal change counter resets to 0.
4529 ** This is used by trigger programs.
4531 case OP_ResetCount
: {
4532 sqlite3VdbeSetChanges(db
, p
->nChange
);
4537 /* Opcode: SorterCompare P1 P2 P3 P4
4538 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4540 ** P1 is a sorter cursor. This instruction compares a prefix of the
4541 ** record blob in register P3 against a prefix of the entry that
4542 ** the sorter cursor currently points to. Only the first P4 fields
4543 ** of r[P3] and the sorter record are compared.
4545 ** If either P3 or the sorter contains a NULL in one of their significant
4546 ** fields (not counting the P4 fields at the end which are ignored) then
4547 ** the comparison is assumed to be equal.
4549 ** Fall through to next instruction if the two records compare equal to
4550 ** each other. Jump to P2 if they are different.
4552 case OP_SorterCompare
: {
4557 pC
= p
->apCsr
[pOp
->p1
];
4558 assert( isSorter(pC
) );
4559 assert( pOp
->p4type
==P4_INT32
);
4560 pIn3
= &aMem
[pOp
->p3
];
4561 nKeyCol
= pOp
->p4
.i
;
4563 rc
= sqlite3VdbeSorterCompare(pC
, pIn3
, nKeyCol
, &res
);
4564 VdbeBranchTaken(res
!=0,2);
4565 if( rc
) goto abort_due_to_error
;
4566 if( res
) goto jump_to_p2
;
4570 /* Opcode: SorterData P1 P2 P3 * *
4571 ** Synopsis: r[P2]=data
4573 ** Write into register P2 the current sorter data for sorter cursor P1.
4574 ** Then clear the column header cache on cursor P3.
4576 ** This opcode is normally use to move a record out of the sorter and into
4577 ** a register that is the source for a pseudo-table cursor created using
4578 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4579 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4580 ** us from having to issue a separate NullRow instruction to clear that cache.
4582 case OP_SorterData
: {
4585 pOut
= &aMem
[pOp
->p2
];
4586 pC
= p
->apCsr
[pOp
->p1
];
4587 assert( isSorter(pC
) );
4588 rc
= sqlite3VdbeSorterRowkey(pC
, pOut
);
4589 assert( rc
!=SQLITE_OK
|| (pOut
->flags
& MEM_Blob
) );
4590 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4591 if( rc
) goto abort_due_to_error
;
4592 p
->apCsr
[pOp
->p3
]->cacheStatus
= CACHE_STALE
;
4596 /* Opcode: RowData P1 P2 * * *
4597 ** Synopsis: r[P2]=data
4599 ** Write into register P2 the complete row data for cursor P1.
4600 ** There is no interpretation of the data.
4601 ** It is just copied onto the P2 register exactly as
4602 ** it is found in the database file.
4604 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4605 ** of a real table, not a pseudo-table.
4607 /* Opcode: RowKey P1 P2 * * *
4608 ** Synopsis: r[P2]=key
4610 ** Write into register P2 the complete row key for cursor P1.
4611 ** There is no interpretation of the data.
4612 ** The key is copied onto the P2 register exactly as
4613 ** it is found in the database file.
4615 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4616 ** of a real table, not a pseudo-table.
4624 pOut
= &aMem
[pOp
->p2
];
4625 memAboutToChange(p
, pOut
);
4627 /* Note that RowKey and RowData are really exactly the same instruction */
4628 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4629 pC
= p
->apCsr
[pOp
->p1
];
4631 assert( pC
->eCurType
==CURTYPE_BTREE
);
4632 assert( isSorter(pC
)==0 );
4633 assert( pC
->isTable
|| pOp
->opcode
!=OP_RowData
);
4634 assert( pC
->isTable
==0 || pOp
->opcode
==OP_RowData
);
4635 assert( pC
->nullRow
==0 );
4636 assert( pC
->uc
.pCursor
!=0 );
4637 pCrsr
= pC
->uc
.pCursor
;
4639 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
4640 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
4641 ** that might invalidate the cursor.
4642 ** If this where not the case, on of the following assert()s
4643 ** would fail. Should this ever change (because of changes in the code
4644 ** generator) then the fix would be to insert a call to
4645 ** sqlite3VdbeCursorMoveto().
4647 assert( pC
->deferredMoveto
==0 );
4648 assert( sqlite3BtreeCursorIsValid(pCrsr
) );
4649 #if 0 /* Not required due to the previous to assert() statements */
4650 rc
= sqlite3VdbeCursorMoveto(pC
);
4651 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
4654 n
= sqlite3BtreePayloadSize(pCrsr
);
4655 if( n
>(u32
)db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
4659 if( sqlite3VdbeMemClearAndResize(pOut
, MAX(n
,32)) ){
4663 MemSetTypeFlag(pOut
, MEM_Blob
);
4664 if( pC
->isTable
==0 ){
4665 rc
= sqlite3BtreeKey(pCrsr
, 0, n
, pOut
->z
);
4667 rc
= sqlite3BtreeData(pCrsr
, 0, n
, pOut
->z
);
4669 if( rc
) goto abort_due_to_error
;
4670 pOut
->enc
= SQLITE_UTF8
; /* In case the blob is ever cast to text */
4671 UPDATE_MAX_BLOBSIZE(pOut
);
4672 REGISTER_TRACE(pOp
->p2
, pOut
);
4676 /* Opcode: Rowid P1 P2 * * *
4677 ** Synopsis: r[P2]=rowid
4679 ** Store in register P2 an integer which is the key of the table entry that
4680 ** P1 is currently point to.
4682 ** P1 can be either an ordinary table or a virtual table. There used to
4683 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4684 ** one opcode now works for both table types.
4686 case OP_Rowid
: { /* out2 */
4689 sqlite3_vtab
*pVtab
;
4690 const sqlite3_module
*pModule
;
4692 pOut
= out2Prerelease(p
, pOp
);
4693 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4694 pC
= p
->apCsr
[pOp
->p1
];
4696 assert( pC
->eCurType
!=CURTYPE_PSEUDO
|| pC
->nullRow
);
4698 pOut
->flags
= MEM_Null
;
4700 }else if( pC
->deferredMoveto
){
4701 v
= pC
->movetoTarget
;
4702 #ifndef SQLITE_OMIT_VIRTUALTABLE
4703 }else if( pC
->eCurType
==CURTYPE_VTAB
){
4704 assert( pC
->uc
.pVCur
!=0 );
4705 pVtab
= pC
->uc
.pVCur
->pVtab
;
4706 pModule
= pVtab
->pModule
;
4707 assert( pModule
->xRowid
);
4708 rc
= pModule
->xRowid(pC
->uc
.pVCur
, &v
);
4709 sqlite3VtabImportErrmsg(p
, pVtab
);
4710 if( rc
) goto abort_due_to_error
;
4711 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4713 assert( pC
->eCurType
==CURTYPE_BTREE
);
4714 assert( pC
->uc
.pCursor
!=0 );
4715 rc
= sqlite3VdbeCursorRestore(pC
);
4716 if( rc
) goto abort_due_to_error
;
4718 pOut
->flags
= MEM_Null
;
4721 v
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4727 /* Opcode: NullRow P1 * * * *
4729 ** Move the cursor P1 to a null row. Any OP_Column operations
4730 ** that occur while the cursor is on the null row will always
4736 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4737 pC
= p
->apCsr
[pOp
->p1
];
4740 pC
->cacheStatus
= CACHE_STALE
;
4741 if( pC
->eCurType
==CURTYPE_BTREE
){
4742 assert( pC
->uc
.pCursor
!=0 );
4743 sqlite3BtreeClearCursor(pC
->uc
.pCursor
);
4748 /* Opcode: Last P1 P2 P3 * *
4750 ** The next use of the Rowid or Column or Prev instruction for P1
4751 ** will refer to the last entry in the database table or index.
4752 ** If the table or index is empty and P2>0, then jump immediately to P2.
4753 ** If P2 is 0 or if the table or index is not empty, fall through
4754 ** to the following instruction.
4756 ** This opcode leaves the cursor configured to move in reverse order,
4757 ** from the end toward the beginning. In other words, the cursor is
4758 ** configured to use Prev, not Next.
4760 case OP_Last
: { /* jump */
4765 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4766 pC
= p
->apCsr
[pOp
->p1
];
4768 assert( pC
->eCurType
==CURTYPE_BTREE
);
4769 pCrsr
= pC
->uc
.pCursor
;
4772 rc
= sqlite3BtreeLast(pCrsr
, &res
);
4773 pC
->nullRow
= (u8
)res
;
4774 pC
->deferredMoveto
= 0;
4775 pC
->cacheStatus
= CACHE_STALE
;
4776 pC
->seekResult
= pOp
->p3
;
4778 pC
->seekOp
= OP_Last
;
4780 if( rc
) goto abort_due_to_error
;
4782 VdbeBranchTaken(res
!=0,2);
4783 if( res
) goto jump_to_p2
;
4789 /* Opcode: Sort P1 P2 * * *
4791 ** This opcode does exactly the same thing as OP_Rewind except that
4792 ** it increments an undocumented global variable used for testing.
4794 ** Sorting is accomplished by writing records into a sorting index,
4795 ** then rewinding that index and playing it back from beginning to
4796 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
4797 ** rewinding so that the global variable will be incremented and
4798 ** regression tests can determine whether or not the optimizer is
4799 ** correctly optimizing out sorts.
4801 case OP_SorterSort
: /* jump */
4802 case OP_Sort
: { /* jump */
4804 sqlite3_sort_count
++;
4805 sqlite3_search_count
--;
4807 p
->aCounter
[SQLITE_STMTSTATUS_SORT
]++;
4808 /* Fall through into OP_Rewind */
4810 /* Opcode: Rewind P1 P2 * * *
4812 ** The next use of the Rowid or Column or Next instruction for P1
4813 ** will refer to the first entry in the database table or index.
4814 ** If the table or index is empty, jump immediately to P2.
4815 ** If the table or index is not empty, fall through to the following
4818 ** This opcode leaves the cursor configured to move in forward order,
4819 ** from the beginning toward the end. In other words, the cursor is
4820 ** configured to use Next, not Prev.
4822 case OP_Rewind
: { /* jump */
4827 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4828 pC
= p
->apCsr
[pOp
->p1
];
4830 assert( isSorter(pC
)==(pOp
->opcode
==OP_SorterSort
) );
4833 pC
->seekOp
= OP_Rewind
;
4836 rc
= sqlite3VdbeSorterRewind(pC
, &res
);
4838 assert( pC
->eCurType
==CURTYPE_BTREE
);
4839 pCrsr
= pC
->uc
.pCursor
;
4841 rc
= sqlite3BtreeFirst(pCrsr
, &res
);
4842 pC
->deferredMoveto
= 0;
4843 pC
->cacheStatus
= CACHE_STALE
;
4845 if( rc
) goto abort_due_to_error
;
4846 pC
->nullRow
= (u8
)res
;
4847 assert( pOp
->p2
>0 && pOp
->p2
<p
->nOp
);
4848 VdbeBranchTaken(res
!=0,2);
4849 if( res
) goto jump_to_p2
;
4853 /* Opcode: Next P1 P2 P3 P4 P5
4855 ** Advance cursor P1 so that it points to the next key/data pair in its
4856 ** table or index. If there are no more key/value pairs then fall through
4857 ** to the following instruction. But if the cursor advance was successful,
4858 ** jump immediately to P2.
4860 ** The Next opcode is only valid following an SeekGT, SeekGE, or
4861 ** OP_Rewind opcode used to position the cursor. Next is not allowed
4862 ** to follow SeekLT, SeekLE, or OP_Last.
4864 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
4865 ** been opened prior to this opcode or the program will segfault.
4867 ** The P3 value is a hint to the btree implementation. If P3==1, that
4868 ** means P1 is an SQL index and that this instruction could have been
4869 ** omitted if that index had been unique. P3 is usually 0. P3 is
4870 ** always either 0 or 1.
4872 ** P4 is always of type P4_ADVANCE. The function pointer points to
4873 ** sqlite3BtreeNext().
4875 ** If P5 is positive and the jump is taken, then event counter
4876 ** number P5-1 in the prepared statement is incremented.
4878 ** See also: Prev, NextIfOpen
4880 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
4882 ** This opcode works just like Next except that if cursor P1 is not
4883 ** open it behaves a no-op.
4885 /* Opcode: Prev P1 P2 P3 P4 P5
4887 ** Back up cursor P1 so that it points to the previous key/data pair in its
4888 ** table or index. If there is no previous key/value pairs then fall through
4889 ** to the following instruction. But if the cursor backup was successful,
4890 ** jump immediately to P2.
4893 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
4894 ** OP_Last opcode used to position the cursor. Prev is not allowed
4895 ** to follow SeekGT, SeekGE, or OP_Rewind.
4897 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
4898 ** not open then the behavior is undefined.
4900 ** The P3 value is a hint to the btree implementation. If P3==1, that
4901 ** means P1 is an SQL index and that this instruction could have been
4902 ** omitted if that index had been unique. P3 is usually 0. P3 is
4903 ** always either 0 or 1.
4905 ** P4 is always of type P4_ADVANCE. The function pointer points to
4906 ** sqlite3BtreePrevious().
4908 ** If P5 is positive and the jump is taken, then event counter
4909 ** number P5-1 in the prepared statement is incremented.
4911 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
4913 ** This opcode works just like Prev except that if cursor P1 is not
4914 ** open it behaves a no-op.
4916 case OP_SorterNext
: { /* jump */
4920 pC
= p
->apCsr
[pOp
->p1
];
4921 assert( isSorter(pC
) );
4923 rc
= sqlite3VdbeSorterNext(db
, pC
, &res
);
4925 case OP_PrevIfOpen
: /* jump */
4926 case OP_NextIfOpen
: /* jump */
4927 if( p
->apCsr
[pOp
->p1
]==0 ) break;
4929 case OP_Prev
: /* jump */
4930 case OP_Next
: /* jump */
4931 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4932 assert( pOp
->p5
<ArraySize(p
->aCounter
) );
4933 pC
= p
->apCsr
[pOp
->p1
];
4936 assert( pC
->deferredMoveto
==0 );
4937 assert( pC
->eCurType
==CURTYPE_BTREE
);
4938 assert( res
==0 || (res
==1 && pC
->isTable
==0) );
4940 assert( pOp
->opcode
!=OP_Next
|| pOp
->p4
.xAdvance
==sqlite3BtreeNext
);
4941 assert( pOp
->opcode
!=OP_Prev
|| pOp
->p4
.xAdvance
==sqlite3BtreePrevious
);
4942 assert( pOp
->opcode
!=OP_NextIfOpen
|| pOp
->p4
.xAdvance
==sqlite3BtreeNext
);
4943 assert( pOp
->opcode
!=OP_PrevIfOpen
|| pOp
->p4
.xAdvance
==sqlite3BtreePrevious
);
4945 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
4946 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
4947 assert( pOp
->opcode
!=OP_Next
|| pOp
->opcode
!=OP_NextIfOpen
4948 || pC
->seekOp
==OP_SeekGT
|| pC
->seekOp
==OP_SeekGE
4949 || pC
->seekOp
==OP_Rewind
|| pC
->seekOp
==OP_Found
);
4950 assert( pOp
->opcode
!=OP_Prev
|| pOp
->opcode
!=OP_PrevIfOpen
4951 || pC
->seekOp
==OP_SeekLT
|| pC
->seekOp
==OP_SeekLE
4952 || pC
->seekOp
==OP_Last
);
4954 rc
= pOp
->p4
.xAdvance(pC
->uc
.pCursor
, &res
);
4956 pC
->cacheStatus
= CACHE_STALE
;
4957 VdbeBranchTaken(res
==0,2);
4958 if( rc
) goto abort_due_to_error
;
4961 p
->aCounter
[pOp
->p5
]++;
4963 sqlite3_search_count
++;
4965 goto jump_to_p2_and_check_for_interrupt
;
4969 goto check_for_interrupt
;
4972 /* Opcode: IdxInsert P1 P2 P3 * P5
4973 ** Synopsis: key=r[P2]
4975 ** Register P2 holds an SQL index key made using the
4976 ** MakeRecord instructions. This opcode writes that key
4977 ** into the index P1. Data for the entry is nil.
4979 ** P3 is a flag that provides a hint to the b-tree layer that this
4980 ** insert is likely to be an append.
4982 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
4983 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
4984 ** then the change counter is unchanged.
4986 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
4987 ** just done a seek to the spot where the new entry is to be inserted.
4988 ** This flag avoids doing an extra seek.
4990 ** This instruction only works for indices. The equivalent instruction
4991 ** for tables is OP_Insert.
4993 case OP_SorterInsert
: /* in2 */
4994 case OP_IdxInsert
: { /* in2 */
4998 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4999 pC
= p
->apCsr
[pOp
->p1
];
5001 assert( isSorter(pC
)==(pOp
->opcode
==OP_SorterInsert
) );
5002 pIn2
= &aMem
[pOp
->p2
];
5003 assert( pIn2
->flags
& MEM_Blob
);
5004 if( pOp
->p5
& OPFLAG_NCHANGE
) p
->nChange
++;
5005 assert( pC
->eCurType
==CURTYPE_BTREE
|| pOp
->opcode
==OP_SorterInsert
);
5006 assert( pC
->isTable
==0 );
5007 rc
= ExpandBlob(pIn2
);
5008 if( rc
) goto abort_due_to_error
;
5009 if( pOp
->opcode
==OP_SorterInsert
){
5010 rc
= sqlite3VdbeSorterWrite(pC
, pIn2
);
5017 rc
= sqlite3BtreeInsert(pC
->uc
.pCursor
, &x
, pOp
->p3
,
5018 ((pOp
->p5
& OPFLAG_USESEEKRESULT
) ? pC
->seekResult
: 0)
5020 assert( pC
->deferredMoveto
==0 );
5021 pC
->cacheStatus
= CACHE_STALE
;
5023 if( rc
) goto abort_due_to_error
;
5027 /* Opcode: IdxDelete P1 P2 P3 * *
5028 ** Synopsis: key=r[P2@P3]
5030 ** The content of P3 registers starting at register P2 form
5031 ** an unpacked index key. This opcode removes that entry from the
5032 ** index opened by cursor P1.
5034 case OP_IdxDelete
: {
5040 assert( pOp
->p3
>0 );
5041 assert( pOp
->p2
>0 && pOp
->p2
+pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
)+1 );
5042 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5043 pC
= p
->apCsr
[pOp
->p1
];
5045 assert( pC
->eCurType
==CURTYPE_BTREE
);
5046 pCrsr
= pC
->uc
.pCursor
;
5048 assert( pOp
->p5
==0 );
5049 r
.pKeyInfo
= pC
->pKeyInfo
;
5050 r
.nField
= (u16
)pOp
->p3
;
5052 r
.aMem
= &aMem
[pOp
->p2
];
5053 rc
= sqlite3BtreeMovetoUnpacked(pCrsr
, &r
, 0, 0, &res
);
5054 if( rc
) goto abort_due_to_error
;
5056 rc
= sqlite3BtreeDelete(pCrsr
, BTREE_AUXDELETE
);
5057 if( rc
) goto abort_due_to_error
;
5059 assert( pC
->deferredMoveto
==0 );
5060 pC
->cacheStatus
= CACHE_STALE
;
5064 /* Opcode: Seek P1 * P3 P4 *
5065 ** Synopsis: Move P3 to P1.rowid
5067 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5068 ** table. This opcode does a deferred seek of the P3 table cursor
5069 ** to the row that corresponds to the current row of P1.
5071 ** This is a deferred seek. Nothing actually happens until
5072 ** the cursor is used to read a record. That way, if no reads
5073 ** occur, no unnecessary I/O happens.
5075 ** P4 may be an array of integers (type P4_INTARRAY) containing
5076 ** one entry for each column in the P3 table. If array entry a(i)
5077 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5078 ** equivalent to performing the deferred seek and then reading column i
5079 ** from P1. This information is stored in P3 and used to redirect
5080 ** reads against P3 over to P1, thus possibly avoiding the need to
5081 ** seek and read cursor P3.
5083 /* Opcode: IdxRowid P1 P2 * * *
5084 ** Synopsis: r[P2]=rowid
5086 ** Write into register P2 an integer which is the last entry in the record at
5087 ** the end of the index key pointed to by cursor P1. This integer should be
5088 ** the rowid of the table entry to which this index entry points.
5090 ** See also: Rowid, MakeRecord.
5093 case OP_IdxRowid
: { /* out2 */
5094 VdbeCursor
*pC
; /* The P1 index cursor */
5095 VdbeCursor
*pTabCur
; /* The P2 table cursor (OP_Seek only) */
5096 i64 rowid
; /* Rowid that P1 current points to */
5098 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5099 pC
= p
->apCsr
[pOp
->p1
];
5101 assert( pC
->eCurType
==CURTYPE_BTREE
);
5102 assert( pC
->uc
.pCursor
!=0 );
5103 assert( pC
->isTable
==0 );
5104 assert( pC
->deferredMoveto
==0 );
5105 assert( !pC
->nullRow
|| pOp
->opcode
==OP_IdxRowid
);
5107 /* The IdxRowid and Seek opcodes are combined because of the commonality
5108 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5109 rc
= sqlite3VdbeCursorRestore(pC
);
5111 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5112 ** out from under the cursor. That will never happens for an IdxRowid
5113 ** or Seek opcode */
5114 if( NEVER(rc
!=SQLITE_OK
) ) goto abort_due_to_error
;
5117 rowid
= 0; /* Not needed. Only used to silence a warning. */
5118 rc
= sqlite3VdbeIdxRowid(db
, pC
->uc
.pCursor
, &rowid
);
5119 if( rc
!=SQLITE_OK
){
5120 goto abort_due_to_error
;
5122 if( pOp
->opcode
==OP_Seek
){
5123 assert( pOp
->p3
>=0 && pOp
->p3
<p
->nCursor
);
5124 pTabCur
= p
->apCsr
[pOp
->p3
];
5125 assert( pTabCur
!=0 );
5126 assert( pTabCur
->eCurType
==CURTYPE_BTREE
);
5127 assert( pTabCur
->uc
.pCursor
!=0 );
5128 assert( pTabCur
->isTable
);
5129 pTabCur
->nullRow
= 0;
5130 pTabCur
->movetoTarget
= rowid
;
5131 pTabCur
->deferredMoveto
= 1;
5132 assert( pOp
->p4type
==P4_INTARRAY
|| pOp
->p4
.ai
==0 );
5133 pTabCur
->aAltMap
= pOp
->p4
.ai
;
5134 pTabCur
->pAltCursor
= pC
;
5136 pOut
= out2Prerelease(p
, pOp
);
5138 pOut
->flags
= MEM_Int
;
5141 assert( pOp
->opcode
==OP_IdxRowid
);
5142 sqlite3VdbeMemSetNull(&aMem
[pOp
->p2
]);
5147 /* Opcode: IdxGE P1 P2 P3 P4 P5
5148 ** Synopsis: key=r[P3@P4]
5150 ** The P4 register values beginning with P3 form an unpacked index
5151 ** key that omits the PRIMARY KEY. Compare this key value against the index
5152 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5153 ** fields at the end.
5155 ** If the P1 index entry is greater than or equal to the key value
5156 ** then jump to P2. Otherwise fall through to the next instruction.
5158 /* Opcode: IdxGT P1 P2 P3 P4 P5
5159 ** Synopsis: key=r[P3@P4]
5161 ** The P4 register values beginning with P3 form an unpacked index
5162 ** key that omits the PRIMARY KEY. Compare this key value against the index
5163 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5164 ** fields at the end.
5166 ** If the P1 index entry is greater than the key value
5167 ** then jump to P2. Otherwise fall through to the next instruction.
5169 /* Opcode: IdxLT P1 P2 P3 P4 P5
5170 ** Synopsis: key=r[P3@P4]
5172 ** The P4 register values beginning with P3 form an unpacked index
5173 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5174 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5175 ** ROWID on the P1 index.
5177 ** If the P1 index entry is less than the key value then jump to P2.
5178 ** Otherwise fall through to the next instruction.
5180 /* Opcode: IdxLE P1 P2 P3 P4 P5
5181 ** Synopsis: key=r[P3@P4]
5183 ** The P4 register values beginning with P3 form an unpacked index
5184 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5185 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5186 ** ROWID on the P1 index.
5188 ** If the P1 index entry is less than or equal to the key value then jump
5189 ** to P2. Otherwise fall through to the next instruction.
5191 case OP_IdxLE
: /* jump */
5192 case OP_IdxGT
: /* jump */
5193 case OP_IdxLT
: /* jump */
5194 case OP_IdxGE
: { /* jump */
5199 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5200 pC
= p
->apCsr
[pOp
->p1
];
5202 assert( pC
->isOrdered
);
5203 assert( pC
->eCurType
==CURTYPE_BTREE
);
5204 assert( pC
->uc
.pCursor
!=0);
5205 assert( pC
->deferredMoveto
==0 );
5206 assert( pOp
->p5
==0 || pOp
->p5
==1 );
5207 assert( pOp
->p4type
==P4_INT32
);
5208 r
.pKeyInfo
= pC
->pKeyInfo
;
5209 r
.nField
= (u16
)pOp
->p4
.i
;
5210 if( pOp
->opcode
<OP_IdxLT
){
5211 assert( pOp
->opcode
==OP_IdxLE
|| pOp
->opcode
==OP_IdxGT
);
5214 assert( pOp
->opcode
==OP_IdxGE
|| pOp
->opcode
==OP_IdxLT
);
5217 r
.aMem
= &aMem
[pOp
->p3
];
5219 { int i
; for(i
=0; i
<r
.nField
; i
++) assert( memIsValid(&r
.aMem
[i
]) ); }
5221 res
= 0; /* Not needed. Only used to silence a warning. */
5222 rc
= sqlite3VdbeIdxKeyCompare(db
, pC
, &r
, &res
);
5223 assert( (OP_IdxLE
&1)==(OP_IdxLT
&1) && (OP_IdxGE
&1)==(OP_IdxGT
&1) );
5224 if( (pOp
->opcode
&1)==(OP_IdxLT
&1) ){
5225 assert( pOp
->opcode
==OP_IdxLE
|| pOp
->opcode
==OP_IdxLT
);
5228 assert( pOp
->opcode
==OP_IdxGE
|| pOp
->opcode
==OP_IdxGT
);
5231 VdbeBranchTaken(res
>0,2);
5232 if( rc
) goto abort_due_to_error
;
5233 if( res
>0 ) goto jump_to_p2
;
5237 /* Opcode: Destroy P1 P2 P3 * *
5239 ** Delete an entire database table or index whose root page in the database
5240 ** file is given by P1.
5242 ** The table being destroyed is in the main database file if P3==0. If
5243 ** P3==1 then the table to be clear is in the auxiliary database file
5244 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5246 ** If AUTOVACUUM is enabled then it is possible that another root page
5247 ** might be moved into the newly deleted root page in order to keep all
5248 ** root pages contiguous at the beginning of the database. The former
5249 ** value of the root page that moved - its value before the move occurred -
5250 ** is stored in register P2. If no page
5251 ** movement was required (because the table being dropped was already
5252 ** the last one in the database) then a zero is stored in register P2.
5253 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
5257 case OP_Destroy
: { /* out2 */
5261 assert( p
->readOnly
==0 );
5262 assert( pOp
->p1
>1 );
5263 pOut
= out2Prerelease(p
, pOp
);
5264 pOut
->flags
= MEM_Null
;
5265 if( db
->nVdbeRead
> db
->nVDestroy
+1 ){
5267 p
->errorAction
= OE_Abort
;
5268 goto abort_due_to_error
;
5271 assert( DbMaskTest(p
->btreeMask
, iDb
) );
5272 iMoved
= 0; /* Not needed. Only to silence a warning. */
5273 rc
= sqlite3BtreeDropTable(db
->aDb
[iDb
].pBt
, pOp
->p1
, &iMoved
);
5274 pOut
->flags
= MEM_Int
;
5276 if( rc
) goto abort_due_to_error
;
5277 #ifndef SQLITE_OMIT_AUTOVACUUM
5279 sqlite3RootPageMoved(db
, iDb
, iMoved
, pOp
->p1
);
5280 /* All OP_Destroy operations occur on the same btree */
5281 assert( resetSchemaOnFault
==0 || resetSchemaOnFault
==iDb
+1 );
5282 resetSchemaOnFault
= iDb
+1;
5289 /* Opcode: Clear P1 P2 P3
5291 ** Delete all contents of the database table or index whose root page
5292 ** in the database file is given by P1. But, unlike Destroy, do not
5293 ** remove the table or index from the database file.
5295 ** The table being clear is in the main database file if P2==0. If
5296 ** P2==1 then the table to be clear is in the auxiliary database file
5297 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5299 ** If the P3 value is non-zero, then the table referred to must be an
5300 ** intkey table (an SQL table, not an index). In this case the row change
5301 ** count is incremented by the number of rows in the table being cleared.
5302 ** If P3 is greater than zero, then the value stored in register P3 is
5303 ** also incremented by the number of rows in the table being cleared.
5305 ** See also: Destroy
5311 assert( p
->readOnly
==0 );
5312 assert( DbMaskTest(p
->btreeMask
, pOp
->p2
) );
5313 rc
= sqlite3BtreeClearTable(
5314 db
->aDb
[pOp
->p2
].pBt
, pOp
->p1
, (pOp
->p3
? &nChange
: 0)
5317 p
->nChange
+= nChange
;
5319 assert( memIsValid(&aMem
[pOp
->p3
]) );
5320 memAboutToChange(p
, &aMem
[pOp
->p3
]);
5321 aMem
[pOp
->p3
].u
.i
+= nChange
;
5324 if( rc
) goto abort_due_to_error
;
5328 /* Opcode: ResetSorter P1 * * * *
5330 ** Delete all contents from the ephemeral table or sorter
5331 ** that is open on cursor P1.
5333 ** This opcode only works for cursors used for sorting and
5334 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5336 case OP_ResetSorter
: {
5339 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5340 pC
= p
->apCsr
[pOp
->p1
];
5343 sqlite3VdbeSorterReset(db
, pC
->uc
.pSorter
);
5345 assert( pC
->eCurType
==CURTYPE_BTREE
);
5346 assert( pC
->isEphemeral
);
5347 rc
= sqlite3BtreeClearTableOfCursor(pC
->uc
.pCursor
);
5348 if( rc
) goto abort_due_to_error
;
5353 /* Opcode: CreateTable P1 P2 * * *
5354 ** Synopsis: r[P2]=root iDb=P1
5356 ** Allocate a new table in the main database file if P1==0 or in the
5357 ** auxiliary database file if P1==1 or in an attached database if
5358 ** P1>1. Write the root page number of the new table into
5361 ** The difference between a table and an index is this: A table must
5362 ** have a 4-byte integer key and can have arbitrary data. An index
5363 ** has an arbitrary key but no data.
5365 ** See also: CreateIndex
5367 /* Opcode: CreateIndex P1 P2 * * *
5368 ** Synopsis: r[P2]=root iDb=P1
5370 ** Allocate a new index in the main database file if P1==0 or in the
5371 ** auxiliary database file if P1==1 or in an attached database if
5372 ** P1>1. Write the root page number of the new table into
5375 ** See documentation on OP_CreateTable for additional information.
5377 case OP_CreateIndex
: /* out2 */
5378 case OP_CreateTable
: { /* out2 */
5383 pOut
= out2Prerelease(p
, pOp
);
5385 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
5386 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
5387 assert( p
->readOnly
==0 );
5388 pDb
= &db
->aDb
[pOp
->p1
];
5389 assert( pDb
->pBt
!=0 );
5390 if( pOp
->opcode
==OP_CreateTable
){
5391 /* flags = BTREE_INTKEY; */
5392 flags
= BTREE_INTKEY
;
5394 flags
= BTREE_BLOBKEY
;
5396 rc
= sqlite3BtreeCreateTable(pDb
->pBt
, &pgno
, flags
);
5397 if( rc
) goto abort_due_to_error
;
5402 /* Opcode: ParseSchema P1 * * P4 *
5404 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5405 ** that match the WHERE clause P4.
5407 ** This opcode invokes the parser to create a new virtual machine,
5408 ** then runs the new virtual machine. It is thus a re-entrant opcode.
5410 case OP_ParseSchema
: {
5412 const char *zMaster
;
5416 /* Any prepared statement that invokes this opcode will hold mutexes
5417 ** on every btree. This is a prerequisite for invoking
5418 ** sqlite3InitCallback().
5421 for(iDb
=0; iDb
<db
->nDb
; iDb
++){
5422 assert( iDb
==1 || sqlite3BtreeHoldsMutex(db
->aDb
[iDb
].pBt
) );
5427 assert( iDb
>=0 && iDb
<db
->nDb
);
5428 assert( DbHasProperty(db
, iDb
, DB_SchemaLoaded
) );
5429 /* Used to be a conditional */ {
5430 zMaster
= SCHEMA_TABLE(iDb
);
5432 initData
.iDb
= pOp
->p1
;
5433 initData
.pzErrMsg
= &p
->zErrMsg
;
5434 zSql
= sqlite3MPrintf(db
,
5435 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5436 db
->aDb
[iDb
].zName
, zMaster
, pOp
->p4
.z
);
5438 rc
= SQLITE_NOMEM_BKPT
;
5440 assert( db
->init
.busy
==0 );
5442 initData
.rc
= SQLITE_OK
;
5443 assert( !db
->mallocFailed
);
5444 rc
= sqlite3_exec(db
, zSql
, sqlite3InitCallback
, &initData
, 0);
5445 if( rc
==SQLITE_OK
) rc
= initData
.rc
;
5446 sqlite3DbFree(db
, zSql
);
5451 sqlite3ResetAllSchemasOfConnection(db
);
5452 if( rc
==SQLITE_NOMEM
){
5455 goto abort_due_to_error
;
5460 #if !defined(SQLITE_OMIT_ANALYZE)
5461 /* Opcode: LoadAnalysis P1 * * * *
5463 ** Read the sqlite_stat1 table for database P1 and load the content
5464 ** of that table into the internal index hash table. This will cause
5465 ** the analysis to be used when preparing all subsequent queries.
5467 case OP_LoadAnalysis
: {
5468 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
5469 rc
= sqlite3AnalysisLoad(db
, pOp
->p1
);
5470 if( rc
) goto abort_due_to_error
;
5473 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5475 /* Opcode: DropTable P1 * * P4 *
5477 ** Remove the internal (in-memory) data structures that describe
5478 ** the table named P4 in database P1. This is called after a table
5479 ** is dropped from disk (using the Destroy opcode) in order to keep
5480 ** the internal representation of the
5481 ** schema consistent with what is on disk.
5483 case OP_DropTable
: {
5484 sqlite3UnlinkAndDeleteTable(db
, pOp
->p1
, pOp
->p4
.z
);
5488 /* Opcode: DropIndex P1 * * P4 *
5490 ** Remove the internal (in-memory) data structures that describe
5491 ** the index named P4 in database P1. This is called after an index
5492 ** is dropped from disk (using the Destroy opcode)
5493 ** in order to keep the internal representation of the
5494 ** schema consistent with what is on disk.
5496 case OP_DropIndex
: {
5497 sqlite3UnlinkAndDeleteIndex(db
, pOp
->p1
, pOp
->p4
.z
);
5501 /* Opcode: DropTrigger P1 * * P4 *
5503 ** Remove the internal (in-memory) data structures that describe
5504 ** the trigger named P4 in database P1. This is called after a trigger
5505 ** is dropped from disk (using the Destroy opcode) in order to keep
5506 ** the internal representation of the
5507 ** schema consistent with what is on disk.
5509 case OP_DropTrigger
: {
5510 sqlite3UnlinkAndDeleteTrigger(db
, pOp
->p1
, pOp
->p4
.z
);
5515 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5516 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
5518 ** Do an analysis of the currently open database. Store in
5519 ** register P1 the text of an error message describing any problems.
5520 ** If no problems are found, store a NULL in register P1.
5522 ** The register P3 contains the maximum number of allowed errors.
5523 ** At most reg(P3) errors will be reported.
5524 ** In other words, the analysis stops as soon as reg(P1) errors are
5525 ** seen. Reg(P1) is updated with the number of errors remaining.
5527 ** The root page numbers of all tables in the database are integers
5528 ** stored in P4_INTARRAY argument.
5530 ** If P5 is not zero, the check is done on the auxiliary database
5531 ** file, not the main database file.
5533 ** This opcode is used to implement the integrity_check pragma.
5535 case OP_IntegrityCk
: {
5536 int nRoot
; /* Number of tables to check. (Number of root pages.) */
5537 int *aRoot
; /* Array of rootpage numbers for tables to be checked */
5538 int nErr
; /* Number of errors reported */
5539 char *z
; /* Text of the error report */
5540 Mem
*pnErr
; /* Register keeping track of errors remaining */
5542 assert( p
->bIsReader
);
5546 assert( aRoot
[nRoot
]==0 );
5547 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
5548 pnErr
= &aMem
[pOp
->p3
];
5549 assert( (pnErr
->flags
& MEM_Int
)!=0 );
5550 assert( (pnErr
->flags
& (MEM_Str
|MEM_Blob
))==0 );
5551 pIn1
= &aMem
[pOp
->p1
];
5552 assert( pOp
->p5
<db
->nDb
);
5553 assert( DbMaskTest(p
->btreeMask
, pOp
->p5
) );
5554 z
= sqlite3BtreeIntegrityCheck(db
->aDb
[pOp
->p5
].pBt
, aRoot
, nRoot
,
5555 (int)pnErr
->u
.i
, &nErr
);
5557 sqlite3VdbeMemSetNull(pIn1
);
5563 sqlite3VdbeMemSetStr(pIn1
, z
, -1, SQLITE_UTF8
, sqlite3_free
);
5565 UPDATE_MAX_BLOBSIZE(pIn1
);
5566 sqlite3VdbeChangeEncoding(pIn1
, encoding
);
5569 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5571 /* Opcode: RowSetAdd P1 P2 * * *
5572 ** Synopsis: rowset(P1)=r[P2]
5574 ** Insert the integer value held by register P2 into a boolean index
5575 ** held in register P1.
5577 ** An assertion fails if P2 is not an integer.
5579 case OP_RowSetAdd
: { /* in1, in2 */
5580 pIn1
= &aMem
[pOp
->p1
];
5581 pIn2
= &aMem
[pOp
->p2
];
5582 assert( (pIn2
->flags
& MEM_Int
)!=0 );
5583 if( (pIn1
->flags
& MEM_RowSet
)==0 ){
5584 sqlite3VdbeMemSetRowSet(pIn1
);
5585 if( (pIn1
->flags
& MEM_RowSet
)==0 ) goto no_mem
;
5587 sqlite3RowSetInsert(pIn1
->u
.pRowSet
, pIn2
->u
.i
);
5591 /* Opcode: RowSetRead P1 P2 P3 * *
5592 ** Synopsis: r[P3]=rowset(P1)
5594 ** Extract the smallest value from boolean index P1 and put that value into
5595 ** register P3. Or, if boolean index P1 is initially empty, leave P3
5596 ** unchanged and jump to instruction P2.
5598 case OP_RowSetRead
: { /* jump, in1, out3 */
5601 pIn1
= &aMem
[pOp
->p1
];
5602 if( (pIn1
->flags
& MEM_RowSet
)==0
5603 || sqlite3RowSetNext(pIn1
->u
.pRowSet
, &val
)==0
5605 /* The boolean index is empty */
5606 sqlite3VdbeMemSetNull(pIn1
);
5607 VdbeBranchTaken(1,2);
5608 goto jump_to_p2_and_check_for_interrupt
;
5610 /* A value was pulled from the index */
5611 VdbeBranchTaken(0,2);
5612 sqlite3VdbeMemSetInt64(&aMem
[pOp
->p3
], val
);
5614 goto check_for_interrupt
;
5617 /* Opcode: RowSetTest P1 P2 P3 P4
5618 ** Synopsis: if r[P3] in rowset(P1) goto P2
5620 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5621 ** contains a RowSet object and that RowSet object contains
5622 ** the value held in P3, jump to register P2. Otherwise, insert the
5623 ** integer in P3 into the RowSet and continue on to the
5626 ** The RowSet object is optimized for the case where successive sets
5627 ** of integers, where each set contains no duplicates. Each set
5628 ** of values is identified by a unique P4 value. The first set
5629 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
5630 ** non-negative. For non-negative values of P4 only the lower 4
5631 ** bits are significant.
5633 ** This allows optimizations: (a) when P4==0 there is no need to test
5634 ** the rowset object for P3, as it is guaranteed not to contain it,
5635 ** (b) when P4==-1 there is no need to insert the value, as it will
5636 ** never be tested for, and (c) when a value that is part of set X is
5637 ** inserted, there is no need to search to see if the same value was
5638 ** previously inserted as part of set X (only if it was previously
5639 ** inserted as part of some other set).
5641 case OP_RowSetTest
: { /* jump, in1, in3 */
5645 pIn1
= &aMem
[pOp
->p1
];
5646 pIn3
= &aMem
[pOp
->p3
];
5648 assert( pIn3
->flags
&MEM_Int
);
5650 /* If there is anything other than a rowset object in memory cell P1,
5651 ** delete it now and initialize P1 with an empty rowset
5653 if( (pIn1
->flags
& MEM_RowSet
)==0 ){
5654 sqlite3VdbeMemSetRowSet(pIn1
);
5655 if( (pIn1
->flags
& MEM_RowSet
)==0 ) goto no_mem
;
5658 assert( pOp
->p4type
==P4_INT32
);
5659 assert( iSet
==-1 || iSet
>=0 );
5661 exists
= sqlite3RowSetTest(pIn1
->u
.pRowSet
, iSet
, pIn3
->u
.i
);
5662 VdbeBranchTaken(exists
!=0,2);
5663 if( exists
) goto jump_to_p2
;
5666 sqlite3RowSetInsert(pIn1
->u
.pRowSet
, pIn3
->u
.i
);
5672 #ifndef SQLITE_OMIT_TRIGGER
5674 /* Opcode: Program P1 P2 P3 P4 P5
5676 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5678 ** P1 contains the address of the memory cell that contains the first memory
5679 ** cell in an array of values used as arguments to the sub-program. P2
5680 ** contains the address to jump to if the sub-program throws an IGNORE
5681 ** exception using the RAISE() function. Register P3 contains the address
5682 ** of a memory cell in this (the parent) VM that is used to allocate the
5683 ** memory required by the sub-vdbe at runtime.
5685 ** P4 is a pointer to the VM containing the trigger program.
5687 ** If P5 is non-zero, then recursive program invocation is enabled.
5689 case OP_Program
: { /* jump */
5690 int nMem
; /* Number of memory registers for sub-program */
5691 int nByte
; /* Bytes of runtime space required for sub-program */
5692 Mem
*pRt
; /* Register to allocate runtime space */
5693 Mem
*pMem
; /* Used to iterate through memory cells */
5694 Mem
*pEnd
; /* Last memory cell in new array */
5695 VdbeFrame
*pFrame
; /* New vdbe frame to execute in */
5696 SubProgram
*pProgram
; /* Sub-program to execute */
5697 void *t
; /* Token identifying trigger */
5699 pProgram
= pOp
->p4
.pProgram
;
5700 pRt
= &aMem
[pOp
->p3
];
5701 assert( pProgram
->nOp
>0 );
5703 /* If the p5 flag is clear, then recursive invocation of triggers is
5704 ** disabled for backwards compatibility (p5 is set if this sub-program
5705 ** is really a trigger, not a foreign key action, and the flag set
5706 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
5708 ** It is recursive invocation of triggers, at the SQL level, that is
5709 ** disabled. In some cases a single trigger may generate more than one
5710 ** SubProgram (if the trigger may be executed with more than one different
5711 ** ON CONFLICT algorithm). SubProgram structures associated with a
5712 ** single trigger all have the same value for the SubProgram.token
5715 t
= pProgram
->token
;
5716 for(pFrame
=p
->pFrame
; pFrame
&& pFrame
->token
!=t
; pFrame
=pFrame
->pParent
);
5720 if( p
->nFrame
>=db
->aLimit
[SQLITE_LIMIT_TRIGGER_DEPTH
] ){
5722 sqlite3VdbeError(p
, "too many levels of trigger recursion");
5723 goto abort_due_to_error
;
5726 /* Register pRt is used to store the memory required to save the state
5727 ** of the current program, and the memory required at runtime to execute
5728 ** the trigger program. If this trigger has been fired before, then pRt
5729 ** is already allocated. Otherwise, it must be initialized. */
5730 if( (pRt
->flags
&MEM_Frame
)==0 ){
5731 /* SubProgram.nMem is set to the number of memory cells used by the
5732 ** program stored in SubProgram.aOp. As well as these, one memory
5733 ** cell is required for each cursor used by the program. Set local
5734 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
5736 nMem
= pProgram
->nMem
+ pProgram
->nCsr
;
5738 if( pProgram
->nCsr
==0 ) nMem
++;
5739 nByte
= ROUND8(sizeof(VdbeFrame
))
5740 + nMem
* sizeof(Mem
)
5741 + pProgram
->nCsr
* sizeof(VdbeCursor
*)
5742 + pProgram
->nOnce
* sizeof(u8
);
5743 pFrame
= sqlite3DbMallocZero(db
, nByte
);
5747 sqlite3VdbeMemRelease(pRt
);
5748 pRt
->flags
= MEM_Frame
;
5749 pRt
->u
.pFrame
= pFrame
;
5752 pFrame
->nChildMem
= nMem
;
5753 pFrame
->nChildCsr
= pProgram
->nCsr
;
5754 pFrame
->pc
= (int)(pOp
- aOp
);
5755 pFrame
->aMem
= p
->aMem
;
5756 pFrame
->nMem
= p
->nMem
;
5757 pFrame
->apCsr
= p
->apCsr
;
5758 pFrame
->nCursor
= p
->nCursor
;
5759 pFrame
->aOp
= p
->aOp
;
5760 pFrame
->nOp
= p
->nOp
;
5761 pFrame
->token
= pProgram
->token
;
5762 pFrame
->aOnceFlag
= p
->aOnceFlag
;
5763 pFrame
->nOnceFlag
= p
->nOnceFlag
;
5764 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
5765 pFrame
->anExec
= p
->anExec
;
5768 pEnd
= &VdbeFrameMem(pFrame
)[pFrame
->nChildMem
];
5769 for(pMem
=VdbeFrameMem(pFrame
); pMem
!=pEnd
; pMem
++){
5770 pMem
->flags
= MEM_Undefined
;
5774 pFrame
= pRt
->u
.pFrame
;
5775 assert( pProgram
->nMem
+pProgram
->nCsr
==pFrame
->nChildMem
5776 || (pProgram
->nCsr
==0 && pProgram
->nMem
+1==pFrame
->nChildMem
) );
5777 assert( pProgram
->nCsr
==pFrame
->nChildCsr
);
5778 assert( (int)(pOp
- aOp
)==pFrame
->pc
);
5782 pFrame
->pParent
= p
->pFrame
;
5783 pFrame
->lastRowid
= lastRowid
;
5784 pFrame
->nChange
= p
->nChange
;
5785 pFrame
->nDbChange
= p
->db
->nChange
;
5786 assert( pFrame
->pAuxData
==0 );
5787 pFrame
->pAuxData
= p
->pAuxData
;
5791 p
->aMem
= aMem
= VdbeFrameMem(pFrame
);
5792 p
->nMem
= pFrame
->nChildMem
;
5793 p
->nCursor
= (u16
)pFrame
->nChildCsr
;
5794 p
->apCsr
= (VdbeCursor
**)&aMem
[p
->nMem
];
5795 p
->aOp
= aOp
= pProgram
->aOp
;
5796 p
->nOp
= pProgram
->nOp
;
5797 p
->aOnceFlag
= (u8
*)&p
->apCsr
[p
->nCursor
];
5798 p
->nOnceFlag
= pProgram
->nOnce
;
5799 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
5803 memset(p
->aOnceFlag
, 0, p
->nOnceFlag
);
5808 /* Opcode: Param P1 P2 * * *
5810 ** This opcode is only ever present in sub-programs called via the
5811 ** OP_Program instruction. Copy a value currently stored in a memory
5812 ** cell of the calling (parent) frame to cell P2 in the current frames
5813 ** address space. This is used by trigger programs to access the new.*
5814 ** and old.* values.
5816 ** The address of the cell in the parent frame is determined by adding
5817 ** the value of the P1 argument to the value of the P1 argument to the
5818 ** calling OP_Program instruction.
5820 case OP_Param
: { /* out2 */
5823 pOut
= out2Prerelease(p
, pOp
);
5825 pIn
= &pFrame
->aMem
[pOp
->p1
+ pFrame
->aOp
[pFrame
->pc
].p1
];
5826 sqlite3VdbeMemShallowCopy(pOut
, pIn
, MEM_Ephem
);
5830 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
5832 #ifndef SQLITE_OMIT_FOREIGN_KEY
5833 /* Opcode: FkCounter P1 P2 * * *
5834 ** Synopsis: fkctr[P1]+=P2
5836 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
5837 ** If P1 is non-zero, the database constraint counter is incremented
5838 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
5839 ** statement counter is incremented (immediate foreign key constraints).
5841 case OP_FkCounter
: {
5842 if( db
->flags
& SQLITE_DeferFKs
){
5843 db
->nDeferredImmCons
+= pOp
->p2
;
5844 }else if( pOp
->p1
){
5845 db
->nDeferredCons
+= pOp
->p2
;
5847 p
->nFkConstraint
+= pOp
->p2
;
5852 /* Opcode: FkIfZero P1 P2 * * *
5853 ** Synopsis: if fkctr[P1]==0 goto P2
5855 ** This opcode tests if a foreign key constraint-counter is currently zero.
5856 ** If so, jump to instruction P2. Otherwise, fall through to the next
5859 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
5860 ** is zero (the one that counts deferred constraint violations). If P1 is
5861 ** zero, the jump is taken if the statement constraint-counter is zero
5862 ** (immediate foreign key constraint violations).
5864 case OP_FkIfZero
: { /* jump */
5866 VdbeBranchTaken(db
->nDeferredCons
==0 && db
->nDeferredImmCons
==0, 2);
5867 if( db
->nDeferredCons
==0 && db
->nDeferredImmCons
==0 ) goto jump_to_p2
;
5869 VdbeBranchTaken(p
->nFkConstraint
==0 && db
->nDeferredImmCons
==0, 2);
5870 if( p
->nFkConstraint
==0 && db
->nDeferredImmCons
==0 ) goto jump_to_p2
;
5874 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
5876 #ifndef SQLITE_OMIT_AUTOINCREMENT
5877 /* Opcode: MemMax P1 P2 * * *
5878 ** Synopsis: r[P1]=max(r[P1],r[P2])
5880 ** P1 is a register in the root frame of this VM (the root frame is
5881 ** different from the current frame if this instruction is being executed
5882 ** within a sub-program). Set the value of register P1 to the maximum of
5883 ** its current value and the value in register P2.
5885 ** This instruction throws an error if the memory cell is not initially
5888 case OP_MemMax
: { /* in2 */
5891 for(pFrame
=p
->pFrame
; pFrame
->pParent
; pFrame
=pFrame
->pParent
);
5892 pIn1
= &pFrame
->aMem
[pOp
->p1
];
5894 pIn1
= &aMem
[pOp
->p1
];
5896 assert( memIsValid(pIn1
) );
5897 sqlite3VdbeMemIntegerify(pIn1
);
5898 pIn2
= &aMem
[pOp
->p2
];
5899 sqlite3VdbeMemIntegerify(pIn2
);
5900 if( pIn1
->u
.i
<pIn2
->u
.i
){
5901 pIn1
->u
.i
= pIn2
->u
.i
;
5905 #endif /* SQLITE_OMIT_AUTOINCREMENT */
5907 /* Opcode: IfPos P1 P2 P3 * *
5908 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
5910 ** Register P1 must contain an integer.
5911 ** If the value of register P1 is 1 or greater, subtract P3 from the
5912 ** value in P1 and jump to P2.
5914 ** If the initial value of register P1 is less than 1, then the
5915 ** value is unchanged and control passes through to the next instruction.
5917 case OP_IfPos
: { /* jump, in1 */
5918 pIn1
= &aMem
[pOp
->p1
];
5919 assert( pIn1
->flags
&MEM_Int
);
5920 VdbeBranchTaken( pIn1
->u
.i
>0, 2);
5922 pIn1
->u
.i
-= pOp
->p3
;
5928 /* Opcode: OffsetLimit P1 P2 P3 * *
5929 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
5931 ** This opcode performs a commonly used computation associated with
5932 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
5933 ** holds the offset counter. The opcode computes the combined value
5934 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
5935 ** value computed is the total number of rows that will need to be
5936 ** visited in order to complete the query.
5938 ** If r[P3] is zero or negative, that means there is no OFFSET
5939 ** and r[P2] is set to be the value of the LIMIT, r[P1].
5941 ** if r[P1] is zero or negative, that means there is no LIMIT
5942 ** and r[P2] is set to -1.
5944 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
5946 case OP_OffsetLimit
: { /* in1, out2, in3 */
5947 pIn1
= &aMem
[pOp
->p1
];
5948 pIn3
= &aMem
[pOp
->p3
];
5949 pOut
= out2Prerelease(p
, pOp
);
5950 assert( pIn1
->flags
& MEM_Int
);
5951 assert( pIn3
->flags
& MEM_Int
);
5952 pOut
->u
.i
= pIn1
->u
.i
<=0 ? -1 : pIn1
->u
.i
+(pIn3
->u
.i
>0?pIn3
->u
.i
:0);
5956 /* Opcode: IfNotZero P1 P2 P3 * *
5957 ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
5959 ** Register P1 must contain an integer. If the content of register P1 is
5960 ** initially nonzero, then subtract P3 from the value in register P1 and
5961 ** jump to P2. If register P1 is initially zero, leave it unchanged
5962 ** and fall through.
5964 case OP_IfNotZero
: { /* jump, in1 */
5965 pIn1
= &aMem
[pOp
->p1
];
5966 assert( pIn1
->flags
&MEM_Int
);
5967 VdbeBranchTaken(pIn1
->u
.i
<0, 2);
5969 pIn1
->u
.i
-= pOp
->p3
;
5975 /* Opcode: DecrJumpZero P1 P2 * * *
5976 ** Synopsis: if (--r[P1])==0 goto P2
5978 ** Register P1 must hold an integer. Decrement the value in register P1
5979 ** then jump to P2 if the new value is exactly zero.
5981 case OP_DecrJumpZero
: { /* jump, in1 */
5982 pIn1
= &aMem
[pOp
->p1
];
5983 assert( pIn1
->flags
&MEM_Int
);
5985 VdbeBranchTaken(pIn1
->u
.i
==0, 2);
5986 if( pIn1
->u
.i
==0 ) goto jump_to_p2
;
5991 /* Opcode: AggStep0 * P2 P3 P4 P5
5992 ** Synopsis: accum=r[P3] step(r[P2@P5])
5994 ** Execute the step function for an aggregate. The
5995 ** function has P5 arguments. P4 is a pointer to the FuncDef
5996 ** structure that specifies the function. Register P3 is the
5999 ** The P5 arguments are taken from register P2 and its
6002 /* Opcode: AggStep * P2 P3 P4 P5
6003 ** Synopsis: accum=r[P3] step(r[P2@P5])
6005 ** Execute the step function for an aggregate. The
6006 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
6007 ** object that is used to run the function. Register P3 is
6008 ** as the accumulator.
6010 ** The P5 arguments are taken from register P2 and its
6013 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6014 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6015 ** the opcode is changed. In this way, the initialization of the
6016 ** sqlite3_context only happens once, instead of on each call to the
6021 sqlite3_context
*pCtx
;
6023 assert( pOp
->p4type
==P4_FUNCDEF
);
6025 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
6026 assert( n
==0 || (pOp
->p2
>0 && pOp
->p2
+n
<=(p
->nMem
+1 - p
->nCursor
)+1) );
6027 assert( pOp
->p3
<pOp
->p2
|| pOp
->p3
>=pOp
->p2
+n
);
6028 pCtx
= sqlite3DbMallocRawNN(db
, sizeof(*pCtx
) + (n
-1)*sizeof(sqlite3_value
*));
6029 if( pCtx
==0 ) goto no_mem
;
6031 pCtx
->pFunc
= pOp
->p4
.pFunc
;
6032 pCtx
->iOp
= (int)(pOp
- aOp
);
6035 pOp
->p4type
= P4_FUNCCTX
;
6036 pOp
->p4
.pCtx
= pCtx
;
6037 pOp
->opcode
= OP_AggStep
;
6038 /* Fall through into OP_AggStep */
6042 sqlite3_context
*pCtx
;
6046 assert( pOp
->p4type
==P4_FUNCCTX
);
6047 pCtx
= pOp
->p4
.pCtx
;
6048 pMem
= &aMem
[pOp
->p3
];
6050 /* If this function is inside of a trigger, the register array in aMem[]
6051 ** might change from one evaluation to the next. The next block of code
6052 ** checks to see if the register array has changed, and if so it
6053 ** reinitializes the relavant parts of the sqlite3_context object */
6054 if( pCtx
->pMem
!= pMem
){
6056 for(i
=pCtx
->argc
-1; i
>=0; i
--) pCtx
->argv
[i
] = &aMem
[pOp
->p2
+i
];
6060 for(i
=0; i
<pCtx
->argc
; i
++){
6061 assert( memIsValid(pCtx
->argv
[i
]) );
6062 REGISTER_TRACE(pOp
->p2
+i
, pCtx
->argv
[i
]);
6067 sqlite3VdbeMemInit(&t
, db
, MEM_Null
);
6069 pCtx
->fErrorOrAux
= 0;
6071 (pCtx
->pFunc
->xSFunc
)(pCtx
,pCtx
->argc
,pCtx
->argv
); /* IMP: R-24505-23230 */
6072 if( pCtx
->fErrorOrAux
){
6073 if( pCtx
->isError
){
6074 sqlite3VdbeError(p
, "%s", sqlite3_value_text(&t
));
6077 sqlite3VdbeMemRelease(&t
);
6078 if( rc
) goto abort_due_to_error
;
6080 assert( t
.flags
==MEM_Null
);
6082 if( pCtx
->skipFlag
){
6083 assert( pOp
[-1].opcode
==OP_CollSeq
);
6085 if( i
) sqlite3VdbeMemSetInt64(&aMem
[i
], 1);
6090 /* Opcode: AggFinal P1 P2 * P4 *
6091 ** Synopsis: accum=r[P1] N=P2
6093 ** Execute the finalizer function for an aggregate. P1 is
6094 ** the memory location that is the accumulator for the aggregate.
6096 ** P2 is the number of arguments that the step function takes and
6097 ** P4 is a pointer to the FuncDef for this function. The P2
6098 ** argument is not used by this opcode. It is only there to disambiguate
6099 ** functions that can take varying numbers of arguments. The
6100 ** P4 argument is only needed for the degenerate case where
6101 ** the step function was not previously called.
6105 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
6106 pMem
= &aMem
[pOp
->p1
];
6107 assert( (pMem
->flags
& ~(MEM_Null
|MEM_Agg
))==0 );
6108 rc
= sqlite3VdbeMemFinalize(pMem
, pOp
->p4
.pFunc
);
6110 sqlite3VdbeError(p
, "%s", sqlite3_value_text(pMem
));
6111 goto abort_due_to_error
;
6113 sqlite3VdbeChangeEncoding(pMem
, encoding
);
6114 UPDATE_MAX_BLOBSIZE(pMem
);
6115 if( sqlite3VdbeMemTooBig(pMem
) ){
6121 #ifndef SQLITE_OMIT_WAL
6122 /* Opcode: Checkpoint P1 P2 P3 * *
6124 ** Checkpoint database P1. This is a no-op if P1 is not currently in
6125 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
6126 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
6127 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
6128 ** WAL after the checkpoint into mem[P3+1] and the number of pages
6129 ** in the WAL that have been checkpointed after the checkpoint
6130 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
6131 ** mem[P3+2] are initialized to -1.
6133 case OP_Checkpoint
: {
6134 int i
; /* Loop counter */
6135 int aRes
[3]; /* Results */
6136 Mem
*pMem
; /* Write results here */
6138 assert( p
->readOnly
==0 );
6140 aRes
[1] = aRes
[2] = -1;
6141 assert( pOp
->p2
==SQLITE_CHECKPOINT_PASSIVE
6142 || pOp
->p2
==SQLITE_CHECKPOINT_FULL
6143 || pOp
->p2
==SQLITE_CHECKPOINT_RESTART
6144 || pOp
->p2
==SQLITE_CHECKPOINT_TRUNCATE
6146 rc
= sqlite3Checkpoint(db
, pOp
->p1
, pOp
->p2
, &aRes
[1], &aRes
[2]);
6148 if( rc
!=SQLITE_BUSY
) goto abort_due_to_error
;
6152 for(i
=0, pMem
= &aMem
[pOp
->p3
]; i
<3; i
++, pMem
++){
6153 sqlite3VdbeMemSetInt64(pMem
, (i64
)aRes
[i
]);
6159 #ifndef SQLITE_OMIT_PRAGMA
6160 /* Opcode: JournalMode P1 P2 P3 * *
6162 ** Change the journal mode of database P1 to P3. P3 must be one of the
6163 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
6164 ** modes (delete, truncate, persist, off and memory), this is a simple
6165 ** operation. No IO is required.
6167 ** If changing into or out of WAL mode the procedure is more complicated.
6169 ** Write a string containing the final journal-mode to register P2.
6171 case OP_JournalMode
: { /* out2 */
6172 Btree
*pBt
; /* Btree to change journal mode of */
6173 Pager
*pPager
; /* Pager associated with pBt */
6174 int eNew
; /* New journal mode */
6175 int eOld
; /* The old journal mode */
6176 #ifndef SQLITE_OMIT_WAL
6177 const char *zFilename
; /* Name of database file for pPager */
6180 pOut
= out2Prerelease(p
, pOp
);
6182 assert( eNew
==PAGER_JOURNALMODE_DELETE
6183 || eNew
==PAGER_JOURNALMODE_TRUNCATE
6184 || eNew
==PAGER_JOURNALMODE_PERSIST
6185 || eNew
==PAGER_JOURNALMODE_OFF
6186 || eNew
==PAGER_JOURNALMODE_MEMORY
6187 || eNew
==PAGER_JOURNALMODE_WAL
6188 || eNew
==PAGER_JOURNALMODE_QUERY
6190 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
6191 assert( p
->readOnly
==0 );
6193 pBt
= db
->aDb
[pOp
->p1
].pBt
;
6194 pPager
= sqlite3BtreePager(pBt
);
6195 eOld
= sqlite3PagerGetJournalMode(pPager
);
6196 if( eNew
==PAGER_JOURNALMODE_QUERY
) eNew
= eOld
;
6197 if( !sqlite3PagerOkToChangeJournalMode(pPager
) ) eNew
= eOld
;
6199 #ifndef SQLITE_OMIT_WAL
6200 zFilename
= sqlite3PagerFilename(pPager
, 1);
6202 /* Do not allow a transition to journal_mode=WAL for a database
6203 ** in temporary storage or if the VFS does not support shared memory
6205 if( eNew
==PAGER_JOURNALMODE_WAL
6206 && (sqlite3Strlen30(zFilename
)==0 /* Temp file */
6207 || !sqlite3PagerWalSupported(pPager
)) /* No shared-memory support */
6213 && (eOld
==PAGER_JOURNALMODE_WAL
|| eNew
==PAGER_JOURNALMODE_WAL
)
6215 if( !db
->autoCommit
|| db
->nVdbeRead
>1 ){
6218 "cannot change %s wal mode from within a transaction",
6219 (eNew
==PAGER_JOURNALMODE_WAL
? "into" : "out of")
6221 goto abort_due_to_error
;
6224 if( eOld
==PAGER_JOURNALMODE_WAL
){
6225 /* If leaving WAL mode, close the log file. If successful, the call
6226 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
6227 ** file. An EXCLUSIVE lock may still be held on the database file
6228 ** after a successful return.
6230 rc
= sqlite3PagerCloseWal(pPager
);
6231 if( rc
==SQLITE_OK
){
6232 sqlite3PagerSetJournalMode(pPager
, eNew
);
6234 }else if( eOld
==PAGER_JOURNALMODE_MEMORY
){
6235 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
6236 ** as an intermediate */
6237 sqlite3PagerSetJournalMode(pPager
, PAGER_JOURNALMODE_OFF
);
6240 /* Open a transaction on the database file. Regardless of the journal
6241 ** mode, this transaction always uses a rollback journal.
6243 assert( sqlite3BtreeIsInTrans(pBt
)==0 );
6244 if( rc
==SQLITE_OK
){
6245 rc
= sqlite3BtreeSetVersion(pBt
, (eNew
==PAGER_JOURNALMODE_WAL
? 2 : 1));
6249 #endif /* ifndef SQLITE_OMIT_WAL */
6251 if( rc
) eNew
= eOld
;
6252 eNew
= sqlite3PagerSetJournalMode(pPager
, eNew
);
6254 pOut
->flags
= MEM_Str
|MEM_Static
|MEM_Term
;
6255 pOut
->z
= (char *)sqlite3JournalModename(eNew
);
6256 pOut
->n
= sqlite3Strlen30(pOut
->z
);
6257 pOut
->enc
= SQLITE_UTF8
;
6258 sqlite3VdbeChangeEncoding(pOut
, encoding
);
6259 if( rc
) goto abort_due_to_error
;
6262 #endif /* SQLITE_OMIT_PRAGMA */
6264 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
6265 /* Opcode: Vacuum * * * * *
6267 ** Vacuum the entire database. This opcode will cause other virtual
6268 ** machines to be created and run. It may not be called from within
6272 assert( p
->readOnly
==0 );
6273 rc
= sqlite3RunVacuum(&p
->zErrMsg
, db
);
6274 if( rc
) goto abort_due_to_error
;
6279 #if !defined(SQLITE_OMIT_AUTOVACUUM)
6280 /* Opcode: IncrVacuum P1 P2 * * *
6282 ** Perform a single step of the incremental vacuum procedure on
6283 ** the P1 database. If the vacuum has finished, jump to instruction
6284 ** P2. Otherwise, fall through to the next instruction.
6286 case OP_IncrVacuum
: { /* jump */
6289 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
6290 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
6291 assert( p
->readOnly
==0 );
6292 pBt
= db
->aDb
[pOp
->p1
].pBt
;
6293 rc
= sqlite3BtreeIncrVacuum(pBt
);
6294 VdbeBranchTaken(rc
==SQLITE_DONE
,2);
6296 if( rc
!=SQLITE_DONE
) goto abort_due_to_error
;
6304 /* Opcode: Expire P1 * * * *
6306 ** Cause precompiled statements to expire. When an expired statement
6307 ** is executed using sqlite3_step() it will either automatically
6308 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
6309 ** or it will fail with SQLITE_SCHEMA.
6311 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
6312 ** then only the currently executing statement is expired.
6316 sqlite3ExpirePreparedStatements(db
);
6323 #ifndef SQLITE_OMIT_SHARED_CACHE
6324 /* Opcode: TableLock P1 P2 P3 P4 *
6325 ** Synopsis: iDb=P1 root=P2 write=P3
6327 ** Obtain a lock on a particular table. This instruction is only used when
6328 ** the shared-cache feature is enabled.
6330 ** P1 is the index of the database in sqlite3.aDb[] of the database
6331 ** on which the lock is acquired. A readlock is obtained if P3==0 or
6332 ** a write lock if P3==1.
6334 ** P2 contains the root-page of the table to lock.
6336 ** P4 contains a pointer to the name of the table being locked. This is only
6337 ** used to generate an error message if the lock cannot be obtained.
6339 case OP_TableLock
: {
6340 u8 isWriteLock
= (u8
)pOp
->p3
;
6341 if( isWriteLock
|| 0==(db
->flags
&SQLITE_ReadUncommitted
) ){
6343 assert( p1
>=0 && p1
<db
->nDb
);
6344 assert( DbMaskTest(p
->btreeMask
, p1
) );
6345 assert( isWriteLock
==0 || isWriteLock
==1 );
6346 rc
= sqlite3BtreeLockTable(db
->aDb
[p1
].pBt
, pOp
->p2
, isWriteLock
);
6348 if( (rc
&0xFF)==SQLITE_LOCKED
){
6349 const char *z
= pOp
->p4
.z
;
6350 sqlite3VdbeError(p
, "database table is locked: %s", z
);
6352 goto abort_due_to_error
;
6357 #endif /* SQLITE_OMIT_SHARED_CACHE */
6359 #ifndef SQLITE_OMIT_VIRTUALTABLE
6360 /* Opcode: VBegin * * * P4 *
6362 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
6363 ** xBegin method for that table.
6365 ** Also, whether or not P4 is set, check that this is not being called from
6366 ** within a callback to a virtual table xSync() method. If it is, the error
6367 ** code will be set to SQLITE_LOCKED.
6371 pVTab
= pOp
->p4
.pVtab
;
6372 rc
= sqlite3VtabBegin(db
, pVTab
);
6373 if( pVTab
) sqlite3VtabImportErrmsg(p
, pVTab
->pVtab
);
6374 if( rc
) goto abort_due_to_error
;
6377 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6379 #ifndef SQLITE_OMIT_VIRTUALTABLE
6380 /* Opcode: VCreate P1 P2 * * *
6382 ** P2 is a register that holds the name of a virtual table in database
6383 ** P1. Call the xCreate method for that table.
6386 Mem sMem
; /* For storing the record being decoded */
6387 const char *zTab
; /* Name of the virtual table */
6389 memset(&sMem
, 0, sizeof(sMem
));
6391 /* Because P2 is always a static string, it is impossible for the
6392 ** sqlite3VdbeMemCopy() to fail */
6393 assert( (aMem
[pOp
->p2
].flags
& MEM_Str
)!=0 );
6394 assert( (aMem
[pOp
->p2
].flags
& MEM_Static
)!=0 );
6395 rc
= sqlite3VdbeMemCopy(&sMem
, &aMem
[pOp
->p2
]);
6396 assert( rc
==SQLITE_OK
);
6397 zTab
= (const char*)sqlite3_value_text(&sMem
);
6398 assert( zTab
|| db
->mallocFailed
);
6400 rc
= sqlite3VtabCallCreate(db
, pOp
->p1
, zTab
, &p
->zErrMsg
);
6402 sqlite3VdbeMemRelease(&sMem
);
6403 if( rc
) goto abort_due_to_error
;
6406 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6408 #ifndef SQLITE_OMIT_VIRTUALTABLE
6409 /* Opcode: VDestroy P1 * * P4 *
6411 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
6416 rc
= sqlite3VtabCallDestroy(db
, pOp
->p1
, pOp
->p4
.z
);
6418 if( rc
) goto abort_due_to_error
;
6421 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6423 #ifndef SQLITE_OMIT_VIRTUALTABLE
6424 /* Opcode: VOpen P1 * * P4 *
6426 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6427 ** P1 is a cursor number. This opcode opens a cursor to the virtual
6428 ** table and stores that cursor in P1.
6432 sqlite3_vtab_cursor
*pVCur
;
6433 sqlite3_vtab
*pVtab
;
6434 const sqlite3_module
*pModule
;
6436 assert( p
->bIsReader
);
6439 pVtab
= pOp
->p4
.pVtab
->pVtab
;
6440 if( pVtab
==0 || NEVER(pVtab
->pModule
==0) ){
6442 goto abort_due_to_error
;
6444 pModule
= pVtab
->pModule
;
6445 rc
= pModule
->xOpen(pVtab
, &pVCur
);
6446 sqlite3VtabImportErrmsg(p
, pVtab
);
6447 if( rc
) goto abort_due_to_error
;
6449 /* Initialize sqlite3_vtab_cursor base class */
6450 pVCur
->pVtab
= pVtab
;
6452 /* Initialize vdbe cursor object */
6453 pCur
= allocateCursor(p
, pOp
->p1
, 0, -1, CURTYPE_VTAB
);
6455 pCur
->uc
.pVCur
= pVCur
;
6458 assert( db
->mallocFailed
);
6459 pModule
->xClose(pVCur
);
6464 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6466 #ifndef SQLITE_OMIT_VIRTUALTABLE
6467 /* Opcode: VFilter P1 P2 P3 P4 *
6468 ** Synopsis: iplan=r[P3] zplan='P4'
6470 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
6471 ** the filtered result set is empty.
6473 ** P4 is either NULL or a string that was generated by the xBestIndex
6474 ** method of the module. The interpretation of the P4 string is left
6475 ** to the module implementation.
6477 ** This opcode invokes the xFilter method on the virtual table specified
6478 ** by P1. The integer query plan parameter to xFilter is stored in register
6479 ** P3. Register P3+1 stores the argc parameter to be passed to the
6480 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6481 ** additional parameters which are passed to
6482 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6484 ** A jump is made to P2 if the result set after filtering would be empty.
6486 case OP_VFilter
: { /* jump */
6489 const sqlite3_module
*pModule
;
6492 sqlite3_vtab_cursor
*pVCur
;
6493 sqlite3_vtab
*pVtab
;
6499 pQuery
= &aMem
[pOp
->p3
];
6501 pCur
= p
->apCsr
[pOp
->p1
];
6502 assert( memIsValid(pQuery
) );
6503 REGISTER_TRACE(pOp
->p3
, pQuery
);
6504 assert( pCur
->eCurType
==CURTYPE_VTAB
);
6505 pVCur
= pCur
->uc
.pVCur
;
6506 pVtab
= pVCur
->pVtab
;
6507 pModule
= pVtab
->pModule
;
6509 /* Grab the index number and argc parameters */
6510 assert( (pQuery
->flags
&MEM_Int
)!=0 && pArgc
->flags
==MEM_Int
);
6511 nArg
= (int)pArgc
->u
.i
;
6512 iQuery
= (int)pQuery
->u
.i
;
6514 /* Invoke the xFilter method */
6517 for(i
= 0; i
<nArg
; i
++){
6518 apArg
[i
] = &pArgc
[i
+1];
6520 rc
= pModule
->xFilter(pVCur
, iQuery
, pOp
->p4
.z
, nArg
, apArg
);
6521 sqlite3VtabImportErrmsg(p
, pVtab
);
6522 if( rc
) goto abort_due_to_error
;
6523 res
= pModule
->xEof(pVCur
);
6525 VdbeBranchTaken(res
!=0,2);
6526 if( res
) goto jump_to_p2
;
6529 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6531 #ifndef SQLITE_OMIT_VIRTUALTABLE
6532 /* Opcode: VColumn P1 P2 P3 * *
6533 ** Synopsis: r[P3]=vcolumn(P2)
6535 ** Store the value of the P2-th column of
6536 ** the row of the virtual-table that the
6537 ** P1 cursor is pointing to into register P3.
6540 sqlite3_vtab
*pVtab
;
6541 const sqlite3_module
*pModule
;
6543 sqlite3_context sContext
;
6545 VdbeCursor
*pCur
= p
->apCsr
[pOp
->p1
];
6546 assert( pCur
->eCurType
==CURTYPE_VTAB
);
6547 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
6548 pDest
= &aMem
[pOp
->p3
];
6549 memAboutToChange(p
, pDest
);
6550 if( pCur
->nullRow
){
6551 sqlite3VdbeMemSetNull(pDest
);
6554 pVtab
= pCur
->uc
.pVCur
->pVtab
;
6555 pModule
= pVtab
->pModule
;
6556 assert( pModule
->xColumn
);
6557 memset(&sContext
, 0, sizeof(sContext
));
6558 sContext
.pOut
= pDest
;
6559 MemSetTypeFlag(pDest
, MEM_Null
);
6560 rc
= pModule
->xColumn(pCur
->uc
.pVCur
, &sContext
, pOp
->p2
);
6561 sqlite3VtabImportErrmsg(p
, pVtab
);
6562 if( sContext
.isError
){
6563 rc
= sContext
.isError
;
6565 sqlite3VdbeChangeEncoding(pDest
, encoding
);
6566 REGISTER_TRACE(pOp
->p3
, pDest
);
6567 UPDATE_MAX_BLOBSIZE(pDest
);
6569 if( sqlite3VdbeMemTooBig(pDest
) ){
6572 if( rc
) goto abort_due_to_error
;
6575 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6577 #ifndef SQLITE_OMIT_VIRTUALTABLE
6578 /* Opcode: VNext P1 P2 * * *
6580 ** Advance virtual table P1 to the next row in its result set and
6581 ** jump to instruction P2. Or, if the virtual table has reached
6582 ** the end of its result set, then fall through to the next instruction.
6584 case OP_VNext
: { /* jump */
6585 sqlite3_vtab
*pVtab
;
6586 const sqlite3_module
*pModule
;
6591 pCur
= p
->apCsr
[pOp
->p1
];
6592 assert( pCur
->eCurType
==CURTYPE_VTAB
);
6593 if( pCur
->nullRow
){
6596 pVtab
= pCur
->uc
.pVCur
->pVtab
;
6597 pModule
= pVtab
->pModule
;
6598 assert( pModule
->xNext
);
6600 /* Invoke the xNext() method of the module. There is no way for the
6601 ** underlying implementation to return an error if one occurs during
6602 ** xNext(). Instead, if an error occurs, true is returned (indicating that
6603 ** data is available) and the error code returned when xColumn or
6604 ** some other method is next invoked on the save virtual table cursor.
6606 rc
= pModule
->xNext(pCur
->uc
.pVCur
);
6607 sqlite3VtabImportErrmsg(p
, pVtab
);
6608 if( rc
) goto abort_due_to_error
;
6609 res
= pModule
->xEof(pCur
->uc
.pVCur
);
6610 VdbeBranchTaken(!res
,2);
6612 /* If there is data, jump to P2 */
6613 goto jump_to_p2_and_check_for_interrupt
;
6615 goto check_for_interrupt
;
6617 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6619 #ifndef SQLITE_OMIT_VIRTUALTABLE
6620 /* Opcode: VRename P1 * * P4 *
6622 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6623 ** This opcode invokes the corresponding xRename method. The value
6624 ** in register P1 is passed as the zName argument to the xRename method.
6627 sqlite3_vtab
*pVtab
;
6630 pVtab
= pOp
->p4
.pVtab
->pVtab
;
6631 pName
= &aMem
[pOp
->p1
];
6632 assert( pVtab
->pModule
->xRename
);
6633 assert( memIsValid(pName
) );
6634 assert( p
->readOnly
==0 );
6635 REGISTER_TRACE(pOp
->p1
, pName
);
6636 assert( pName
->flags
& MEM_Str
);
6637 testcase( pName
->enc
==SQLITE_UTF8
);
6638 testcase( pName
->enc
==SQLITE_UTF16BE
);
6639 testcase( pName
->enc
==SQLITE_UTF16LE
);
6640 rc
= sqlite3VdbeChangeEncoding(pName
, SQLITE_UTF8
);
6641 if( rc
) goto abort_due_to_error
;
6642 rc
= pVtab
->pModule
->xRename(pVtab
, pName
->z
);
6643 sqlite3VtabImportErrmsg(p
, pVtab
);
6645 if( rc
) goto abort_due_to_error
;
6650 #ifndef SQLITE_OMIT_VIRTUALTABLE
6651 /* Opcode: VUpdate P1 P2 P3 P4 P5
6652 ** Synopsis: data=r[P3@P2]
6654 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6655 ** This opcode invokes the corresponding xUpdate method. P2 values
6656 ** are contiguous memory cells starting at P3 to pass to the xUpdate
6657 ** invocation. The value in register (P3+P2-1) corresponds to the
6658 ** p2th element of the argv array passed to xUpdate.
6660 ** The xUpdate method will do a DELETE or an INSERT or both.
6661 ** The argv[0] element (which corresponds to memory cell P3)
6662 ** is the rowid of a row to delete. If argv[0] is NULL then no
6663 ** deletion occurs. The argv[1] element is the rowid of the new
6664 ** row. This can be NULL to have the virtual table select the new
6665 ** rowid for itself. The subsequent elements in the array are
6666 ** the values of columns in the new row.
6668 ** If P2==1 then no insert is performed. argv[0] is the rowid of
6671 ** P1 is a boolean flag. If it is set to true and the xUpdate call
6672 ** is successful, then the value returned by sqlite3_last_insert_rowid()
6673 ** is set to the value of the rowid for the row just inserted.
6675 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
6676 ** apply in the case of a constraint failure on an insert or update.
6679 sqlite3_vtab
*pVtab
;
6680 const sqlite3_module
*pModule
;
6687 assert( pOp
->p2
==1 || pOp
->p5
==OE_Fail
|| pOp
->p5
==OE_Rollback
6688 || pOp
->p5
==OE_Abort
|| pOp
->p5
==OE_Ignore
|| pOp
->p5
==OE_Replace
6690 assert( p
->readOnly
==0 );
6691 pVtab
= pOp
->p4
.pVtab
->pVtab
;
6692 if( pVtab
==0 || NEVER(pVtab
->pModule
==0) ){
6694 goto abort_due_to_error
;
6696 pModule
= pVtab
->pModule
;
6698 assert( pOp
->p4type
==P4_VTAB
);
6699 if( ALWAYS(pModule
->xUpdate
) ){
6700 u8 vtabOnConflict
= db
->vtabOnConflict
;
6702 pX
= &aMem
[pOp
->p3
];
6703 for(i
=0; i
<nArg
; i
++){
6704 assert( memIsValid(pX
) );
6705 memAboutToChange(p
, pX
);
6709 db
->vtabOnConflict
= pOp
->p5
;
6710 rc
= pModule
->xUpdate(pVtab
, nArg
, apArg
, &rowid
);
6711 db
->vtabOnConflict
= vtabOnConflict
;
6712 sqlite3VtabImportErrmsg(p
, pVtab
);
6713 if( rc
==SQLITE_OK
&& pOp
->p1
){
6714 assert( nArg
>1 && apArg
[0] && (apArg
[0]->flags
&MEM_Null
) );
6715 db
->lastRowid
= lastRowid
= rowid
;
6717 if( (rc
&0xff)==SQLITE_CONSTRAINT
&& pOp
->p4
.pVtab
->bConstraint
){
6718 if( pOp
->p5
==OE_Ignore
){
6721 p
->errorAction
= ((pOp
->p5
==OE_Replace
) ? OE_Abort
: pOp
->p5
);
6726 if( rc
) goto abort_due_to_error
;
6730 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6732 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6733 /* Opcode: Pagecount P1 P2 * * *
6735 ** Write the current number of pages in database P1 to memory cell P2.
6737 case OP_Pagecount
: { /* out2 */
6738 pOut
= out2Prerelease(p
, pOp
);
6739 pOut
->u
.i
= sqlite3BtreeLastPage(db
->aDb
[pOp
->p1
].pBt
);
6745 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
6746 /* Opcode: MaxPgcnt P1 P2 P3 * *
6748 ** Try to set the maximum page count for database P1 to the value in P3.
6749 ** Do not let the maximum page count fall below the current page count and
6750 ** do not change the maximum page count value if P3==0.
6752 ** Store the maximum page count after the change in register P2.
6754 case OP_MaxPgcnt
: { /* out2 */
6755 unsigned int newMax
;
6758 pOut
= out2Prerelease(p
, pOp
);
6759 pBt
= db
->aDb
[pOp
->p1
].pBt
;
6762 newMax
= sqlite3BtreeLastPage(pBt
);
6763 if( newMax
< (unsigned)pOp
->p3
) newMax
= (unsigned)pOp
->p3
;
6765 pOut
->u
.i
= sqlite3BtreeMaxPageCount(pBt
, newMax
);
6771 /* Opcode: Init * P2 * P4 *
6772 ** Synopsis: Start at P2
6774 ** Programs contain a single instance of this opcode as the very first
6777 ** If tracing is enabled (by the sqlite3_trace()) interface, then
6778 ** the UTF-8 string contained in P4 is emitted on the trace callback.
6779 ** Or if P4 is blank, use the string returned by sqlite3_sql().
6781 ** If P2 is not zero, jump to instruction P2.
6783 case OP_Init
: { /* jump */
6786 /* If the P4 argument is not NULL, then it must be an SQL comment string.
6787 ** The "--" string is broken up to prevent false-positives with srcck1.c.
6789 ** This assert() provides evidence for:
6790 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
6791 ** would have been returned by the legacy sqlite3_trace() interface by
6792 ** using the X argument when X begins with "--" and invoking
6793 ** sqlite3_expanded_sql(P) otherwise.
6795 assert( pOp
->p4
.z
==0 || strncmp(pOp
->p4
.z
, "-" "- ", 3)==0 );
6797 #ifndef SQLITE_OMIT_TRACE
6798 if( (db
->mTrace
& (SQLITE_TRACE_STMT
|SQLITE_TRACE_LEGACY
))!=0
6800 && (zTrace
= (pOp
->p4
.z
? pOp
->p4
.z
: p
->zSql
))!=0
6802 #ifndef SQLITE_OMIT_DEPRECATED
6803 if( db
->mTrace
& SQLITE_TRACE_LEGACY
){
6804 void (*x
)(void*,const char*) = (void(*)(void*,const char*))db
->xTrace
;
6805 char *z
= sqlite3VdbeExpandSql(p
, zTrace
);
6806 x(db
->pTraceArg
, z
);
6811 (void)db
->xTrace(SQLITE_TRACE_STMT
, db
->pTraceArg
, p
, zTrace
);
6814 #ifdef SQLITE_USE_FCNTL_TRACE
6815 zTrace
= (pOp
->p4
.z
? pOp
->p4
.z
: p
->zSql
);
6818 for(i
=0; i
<db
->nDb
; i
++){
6819 if( DbMaskTest(p
->btreeMask
, i
)==0 ) continue;
6820 sqlite3_file_control(db
, db
->aDb
[i
].zName
, SQLITE_FCNTL_TRACE
, zTrace
);
6823 #endif /* SQLITE_USE_FCNTL_TRACE */
6825 if( (db
->flags
& SQLITE_SqlTrace
)!=0
6826 && (zTrace
= (pOp
->p4
.z
? pOp
->p4
.z
: p
->zSql
))!=0
6828 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace
);
6830 #endif /* SQLITE_DEBUG */
6831 #endif /* SQLITE_OMIT_TRACE */
6832 if( pOp
->p2
) goto jump_to_p2
;
6836 #ifdef SQLITE_ENABLE_CURSOR_HINTS
6837 /* Opcode: CursorHint P1 * * P4 *
6839 ** Provide a hint to cursor P1 that it only needs to return rows that
6840 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
6841 ** to values currently held in registers. TK_COLUMN terms in the P4
6842 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
6844 case OP_CursorHint
: {
6847 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
6848 assert( pOp
->p4type
==P4_EXPR
);
6849 pC
= p
->apCsr
[pOp
->p1
];
6851 assert( pC
->eCurType
==CURTYPE_BTREE
);
6852 sqlite3BtreeCursorHint(pC
->uc
.pCursor
, BTREE_HINT_RANGE
,
6853 pOp
->p4
.pExpr
, aMem
);
6857 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
6859 /* Opcode: Noop * * * * *
6861 ** Do nothing. This instruction is often useful as a jump
6865 ** The magic Explain opcode are only inserted when explain==2 (which
6866 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
6867 ** This opcode records information from the optimizer. It is the
6868 ** the same as a no-op. This opcodesnever appears in a real VM program.
6870 default: { /* This is really OP_Noop and OP_Explain */
6871 assert( pOp
->opcode
==OP_Noop
|| pOp
->opcode
==OP_Explain
);
6875 /*****************************************************************************
6876 ** The cases of the switch statement above this line should all be indented
6877 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
6878 ** readability. From this point on down, the normal indentation rules are
6880 *****************************************************************************/
6885 u64 endTime
= sqlite3Hwtime();
6886 if( endTime
>start
) pOrigOp
->cycles
+= endTime
- start
;
6891 /* The following code adds nothing to the actual functionality
6892 ** of the program. It is only here for testing and debugging.
6893 ** On the other hand, it does burn CPU cycles every time through
6894 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
6897 assert( pOp
>=&aOp
[-1] && pOp
<&aOp
[p
->nOp
-1] );
6900 if( db
->flags
& SQLITE_VdbeTrace
){
6901 u8 opProperty
= sqlite3OpcodeProperty
[pOrigOp
->opcode
];
6902 if( rc
!=0 ) printf("rc=%d\n",rc
);
6903 if( opProperty
& (OPFLG_OUT2
) ){
6904 registerTrace(pOrigOp
->p2
, &aMem
[pOrigOp
->p2
]);
6906 if( opProperty
& OPFLG_OUT3
){
6907 registerTrace(pOrigOp
->p3
, &aMem
[pOrigOp
->p3
]);
6910 #endif /* SQLITE_DEBUG */
6912 } /* The end of the for(;;) loop the loops through opcodes */
6914 /* If we reach this point, it means that execution is finished with
6915 ** an error of some kind.
6918 if( db
->mallocFailed
) rc
= SQLITE_NOMEM_BKPT
;
6920 if( p
->zErrMsg
==0 && rc
!=SQLITE_IOERR_NOMEM
){
6921 sqlite3VdbeError(p
, "%s", sqlite3ErrStr(rc
));
6924 sqlite3SystemError(db
, rc
);
6925 testcase( sqlite3GlobalConfig
.xLog
!=0 );
6926 sqlite3_log(rc
, "statement aborts at %d: [%s] %s",
6927 (int)(pOp
- aOp
), p
->zSql
, p
->zErrMsg
);
6929 if( rc
==SQLITE_IOERR_NOMEM
) sqlite3OomFault(db
);
6931 if( resetSchemaOnFault
>0 ){
6932 sqlite3ResetOneSchema(db
, resetSchemaOnFault
-1);
6935 /* This is the only way out of this procedure. We have to
6936 ** release the mutexes on btrees that were acquired at the
6939 db
->lastRowid
= lastRowid
;
6940 testcase( nVmStep
>0 );
6941 p
->aCounter
[SQLITE_STMTSTATUS_VM_STEP
] += (int)nVmStep
;
6942 sqlite3VdbeLeave(p
);
6943 assert( rc
!=SQLITE_OK
|| nExtraDelete
==0
6944 || sqlite3_strlike("DELETE%",p
->zSql
,0)!=0
6948 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
6952 sqlite3VdbeError(p
, "string or blob too big");
6954 goto abort_due_to_error
;
6956 /* Jump to here if a malloc() fails.
6959 sqlite3OomFault(db
);
6960 sqlite3VdbeError(p
, "out of memory");
6961 rc
= SQLITE_NOMEM_BKPT
;
6962 goto abort_due_to_error
;
6964 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
6967 abort_due_to_interrupt
:
6968 assert( db
->u1
.isInterrupted
);
6969 rc
= db
->mallocFailed
? SQLITE_NOMEM_BKPT
: SQLITE_INTERRUPT
;
6971 sqlite3VdbeError(p
, "%s", sqlite3ErrStr(rc
));
6972 goto abort_due_to_error
;