Remove code that added a P4 parameter to the OP_Variable opcode. This is no longer...
[sqlite.git] / src / vdbe.c
blob709ebd9fb85ac491dbab3991aa72c761a048657d
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** The code in this file implements the function that runs the
13 ** bytecode of a prepared statement.
15 ** Various scripts scan this source file in order to generate HTML
16 ** documentation, headers files, or other derived files. The formatting
17 ** of the code in this file is, therefore, important. See other comments
18 ** in this file for details. If in doubt, do not deviate from existing
19 ** commenting and indentation practices when changing or adding code.
21 #include "sqliteInt.h"
22 #include "vdbeInt.h"
25 ** Invoke this macro on memory cells just prior to changing the
26 ** value of the cell. This macro verifies that shallow copies are
27 ** not misused. A shallow copy of a string or blob just copies a
28 ** pointer to the string or blob, not the content. If the original
29 ** is changed while the copy is still in use, the string or blob might
30 ** be changed out from under the copy. This macro verifies that nothing
31 ** like that ever happens.
33 #ifdef SQLITE_DEBUG
34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
35 #else
36 # define memAboutToChange(P,M)
37 #endif
40 ** The following global variable is incremented every time a cursor
41 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
42 ** procedures use this information to make sure that indices are
43 ** working correctly. This variable has no function other than to
44 ** help verify the correct operation of the library.
46 #ifdef SQLITE_TEST
47 int sqlite3_search_count = 0;
48 #endif
51 ** When this global variable is positive, it gets decremented once before
52 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
53 ** field of the sqlite3 structure is set in order to simulate an interrupt.
55 ** This facility is used for testing purposes only. It does not function
56 ** in an ordinary build.
58 #ifdef SQLITE_TEST
59 int sqlite3_interrupt_count = 0;
60 #endif
63 ** The next global variable is incremented each type the OP_Sort opcode
64 ** is executed. The test procedures use this information to make sure that
65 ** sorting is occurring or not occurring at appropriate times. This variable
66 ** has no function other than to help verify the correct operation of the
67 ** library.
69 #ifdef SQLITE_TEST
70 int sqlite3_sort_count = 0;
71 #endif
74 ** The next global variable records the size of the largest MEM_Blob
75 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
76 ** use this information to make sure that the zero-blob functionality
77 ** is working correctly. This variable has no function other than to
78 ** help verify the correct operation of the library.
80 #ifdef SQLITE_TEST
81 int sqlite3_max_blobsize = 0;
82 static void updateMaxBlobsize(Mem *p){
83 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
84 sqlite3_max_blobsize = p->n;
87 #endif
90 ** This macro evaluates to true if either the update hook or the preupdate
91 ** hook are enabled for database connect DB.
93 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
94 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
95 #else
96 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
97 #endif
100 ** The next global variable is incremented each time the OP_Found opcode
101 ** is executed. This is used to test whether or not the foreign key
102 ** operation implemented using OP_FkIsZero is working. This variable
103 ** has no function other than to help verify the correct operation of the
104 ** library.
106 #ifdef SQLITE_TEST
107 int sqlite3_found_count = 0;
108 #endif
111 ** Test a register to see if it exceeds the current maximum blob size.
112 ** If it does, record the new maximum blob size.
114 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
115 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
116 #else
117 # define UPDATE_MAX_BLOBSIZE(P)
118 #endif
120 #ifdef SQLITE_DEBUG
121 /* This routine provides a convenient place to set a breakpoint during
122 ** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after
123 ** each opcode is printed. Variables "pc" (program counter) and pOp are
124 ** available to add conditionals to the breakpoint. GDB example:
126 ** break test_trace_breakpoint if pc=22
128 ** Other useful labels for breakpoints include:
129 ** test_addop_breakpoint(pc,pOp)
130 ** sqlite3CorruptError(lineno)
131 ** sqlite3MisuseError(lineno)
132 ** sqlite3CantopenError(lineno)
134 static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
135 static u64 n = 0;
136 (void)pc;
137 (void)pOp;
138 (void)v;
139 n++;
140 if( n==LARGEST_UINT64 ) abort(); /* So that n is used, preventing a warning */
142 #endif
145 ** Invoke the VDBE coverage callback, if that callback is defined. This
146 ** feature is used for test suite validation only and does not appear an
147 ** production builds.
149 ** M is the type of branch. I is the direction taken for this instance of
150 ** the branch.
152 ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
153 ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
154 ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
156 ** In other words, if M is 2, then I is either 0 (for fall-through) or
157 ** 1 (for when the branch is taken). If M is 3, the I is 0 for an
158 ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
159 ** if the result of comparison is NULL. For M=3, I=2 the jump may or
160 ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
161 ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
162 ** depending on if the operands are less than, equal, or greater than.
164 ** iSrcLine is the source code line (from the __LINE__ macro) that
165 ** generated the VDBE instruction combined with flag bits. The source
166 ** code line number is in the lower 24 bits of iSrcLine and the upper
167 ** 8 bytes are flags. The lower three bits of the flags indicate
168 ** values for I that should never occur. For example, if the branch is
169 ** always taken, the flags should be 0x05 since the fall-through and
170 ** alternate branch are never taken. If a branch is never taken then
171 ** flags should be 0x06 since only the fall-through approach is allowed.
173 ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
174 ** interested in equal or not-equal. In other words, I==0 and I==2
175 ** should be treated as equivalent
177 ** Since only a line number is retained, not the filename, this macro
178 ** only works for amalgamation builds. But that is ok, since these macros
179 ** should be no-ops except for special builds used to measure test coverage.
181 #if !defined(SQLITE_VDBE_COVERAGE)
182 # define VdbeBranchTaken(I,M)
183 #else
184 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
185 static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
186 u8 mNever;
187 assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
188 assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
189 assert( I<M ); /* I can only be 2 if M is 3 or 4 */
190 /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
191 I = 1<<I;
192 /* The upper 8 bits of iSrcLine are flags. The lower three bits of
193 ** the flags indicate directions that the branch can never go. If
194 ** a branch really does go in one of those directions, assert right
195 ** away. */
196 mNever = iSrcLine >> 24;
197 assert( (I & mNever)==0 );
198 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
199 /* Invoke the branch coverage callback with three arguments:
200 ** iSrcLine - the line number of the VdbeCoverage() macro, with
201 ** flags removed.
202 ** I - Mask of bits 0x07 indicating which cases are are
203 ** fulfilled by this instance of the jump. 0x01 means
204 ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
205 ** impossible cases (ex: if the comparison is never NULL)
206 ** are filled in automatically so that the coverage
207 ** measurement logic does not flag those impossible cases
208 ** as missed coverage.
209 ** M - Type of jump. Same as M argument above
211 I |= mNever;
212 if( M==2 ) I |= 0x04;
213 if( M==4 ){
214 I |= 0x08;
215 if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
217 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
218 iSrcLine&0xffffff, I, M);
220 #endif
223 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
224 ** a pointer to a dynamically allocated string where some other entity
225 ** is responsible for deallocating that string. Because the register
226 ** does not control the string, it might be deleted without the register
227 ** knowing it.
229 ** This routine converts an ephemeral string into a dynamically allocated
230 ** string that the register itself controls. In other words, it
231 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
233 #define Deephemeralize(P) \
234 if( ((P)->flags&MEM_Ephem)!=0 \
235 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
237 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
238 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
241 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
242 ** if we run out of memory.
244 static VdbeCursor *allocateCursor(
245 Vdbe *p, /* The virtual machine */
246 int iCur, /* Index of the new VdbeCursor */
247 int nField, /* Number of fields in the table or index */
248 u8 eCurType /* Type of the new cursor */
250 /* Find the memory cell that will be used to store the blob of memory
251 ** required for this VdbeCursor structure. It is convenient to use a
252 ** vdbe memory cell to manage the memory allocation required for a
253 ** VdbeCursor structure for the following reasons:
255 ** * Sometimes cursor numbers are used for a couple of different
256 ** purposes in a vdbe program. The different uses might require
257 ** different sized allocations. Memory cells provide growable
258 ** allocations.
260 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
261 ** be freed lazily via the sqlite3_release_memory() API. This
262 ** minimizes the number of malloc calls made by the system.
264 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
265 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
266 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
268 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
270 int nByte;
271 VdbeCursor *pCx = 0;
272 nByte =
273 ROUND8P(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
274 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
276 assert( iCur>=0 && iCur<p->nCursor );
277 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
278 sqlite3VdbeFreeCursorNN(p, p->apCsr[iCur]);
279 p->apCsr[iCur] = 0;
282 /* There used to be a call to sqlite3VdbeMemClearAndResize() to make sure
283 ** the pMem used to hold space for the cursor has enough storage available
284 ** in pMem->zMalloc. But for the special case of the aMem[] entries used
285 ** to hold cursors, it is faster to in-line the logic. */
286 assert( pMem->flags==MEM_Undefined );
287 assert( (pMem->flags & MEM_Dyn)==0 );
288 assert( pMem->szMalloc==0 || pMem->z==pMem->zMalloc );
289 if( pMem->szMalloc<nByte ){
290 if( pMem->szMalloc>0 ){
291 sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
293 pMem->z = pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, nByte);
294 if( pMem->zMalloc==0 ){
295 pMem->szMalloc = 0;
296 return 0;
298 pMem->szMalloc = nByte;
301 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc;
302 memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
303 pCx->eCurType = eCurType;
304 pCx->nField = nField;
305 pCx->aOffset = &pCx->aType[nField];
306 if( eCurType==CURTYPE_BTREE ){
307 pCx->uc.pCursor = (BtCursor*)
308 &pMem->z[ROUND8P(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
309 sqlite3BtreeCursorZero(pCx->uc.pCursor);
311 return pCx;
315 ** The string in pRec is known to look like an integer and to have a
316 ** floating point value of rValue. Return true and set *piValue to the
317 ** integer value if the string is in range to be an integer. Otherwise,
318 ** return false.
320 static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){
321 i64 iValue;
322 iValue = sqlite3RealToI64(rValue);
323 if( sqlite3RealSameAsInt(rValue,iValue) ){
324 *piValue = iValue;
325 return 1;
327 return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
331 ** Try to convert a value into a numeric representation if we can
332 ** do so without loss of information. In other words, if the string
333 ** looks like a number, convert it into a number. If it does not
334 ** look like a number, leave it alone.
336 ** If the bTryForInt flag is true, then extra effort is made to give
337 ** an integer representation. Strings that look like floating point
338 ** values but which have no fractional component (example: '48.00')
339 ** will have a MEM_Int representation when bTryForInt is true.
341 ** If bTryForInt is false, then if the input string contains a decimal
342 ** point or exponential notation, the result is only MEM_Real, even
343 ** if there is an exact integer representation of the quantity.
345 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
346 double rValue;
347 u8 enc = pRec->enc;
348 int rc;
349 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
350 rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
351 if( rc<=0 ) return;
352 if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
353 pRec->flags |= MEM_Int;
354 }else{
355 pRec->u.r = rValue;
356 pRec->flags |= MEM_Real;
357 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
359 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
360 ** string representation after computing a numeric equivalent, because the
361 ** string representation might not be the canonical representation for the
362 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
363 pRec->flags &= ~MEM_Str;
367 ** Processing is determine by the affinity parameter:
369 ** SQLITE_AFF_INTEGER:
370 ** SQLITE_AFF_REAL:
371 ** SQLITE_AFF_NUMERIC:
372 ** Try to convert pRec to an integer representation or a
373 ** floating-point representation if an integer representation
374 ** is not possible. Note that the integer representation is
375 ** always preferred, even if the affinity is REAL, because
376 ** an integer representation is more space efficient on disk.
378 ** SQLITE_AFF_FLEXNUM:
379 ** If the value is text, then try to convert it into a number of
380 ** some kind (integer or real) but do not make any other changes.
382 ** SQLITE_AFF_TEXT:
383 ** Convert pRec to a text representation.
385 ** SQLITE_AFF_BLOB:
386 ** SQLITE_AFF_NONE:
387 ** No-op. pRec is unchanged.
389 static void applyAffinity(
390 Mem *pRec, /* The value to apply affinity to */
391 char affinity, /* The affinity to be applied */
392 u8 enc /* Use this text encoding */
394 if( affinity>=SQLITE_AFF_NUMERIC ){
395 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
396 || affinity==SQLITE_AFF_NUMERIC || affinity==SQLITE_AFF_FLEXNUM );
397 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
398 if( (pRec->flags & (MEM_Real|MEM_IntReal))==0 ){
399 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
400 }else if( affinity<=SQLITE_AFF_REAL ){
401 sqlite3VdbeIntegerAffinity(pRec);
404 }else if( affinity==SQLITE_AFF_TEXT ){
405 /* Only attempt the conversion to TEXT if there is an integer or real
406 ** representation (blob and NULL do not get converted) but no string
407 ** representation. It would be harmless to repeat the conversion if
408 ** there is already a string rep, but it is pointless to waste those
409 ** CPU cycles. */
410 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
411 if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
412 testcase( pRec->flags & MEM_Int );
413 testcase( pRec->flags & MEM_Real );
414 testcase( pRec->flags & MEM_IntReal );
415 sqlite3VdbeMemStringify(pRec, enc, 1);
418 pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
423 ** Try to convert the type of a function argument or a result column
424 ** into a numeric representation. Use either INTEGER or REAL whichever
425 ** is appropriate. But only do the conversion if it is possible without
426 ** loss of information and return the revised type of the argument.
428 int sqlite3_value_numeric_type(sqlite3_value *pVal){
429 int eType = sqlite3_value_type(pVal);
430 if( eType==SQLITE_TEXT ){
431 Mem *pMem = (Mem*)pVal;
432 applyNumericAffinity(pMem, 0);
433 eType = sqlite3_value_type(pVal);
435 return eType;
439 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
440 ** not the internal Mem* type.
442 void sqlite3ValueApplyAffinity(
443 sqlite3_value *pVal,
444 u8 affinity,
445 u8 enc
447 applyAffinity((Mem *)pVal, affinity, enc);
451 ** pMem currently only holds a string type (or maybe a BLOB that we can
452 ** interpret as a string if we want to). Compute its corresponding
453 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
454 ** accordingly.
456 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
457 int rc;
458 sqlite3_int64 ix;
459 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
460 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
461 if( ExpandBlob(pMem) ){
462 pMem->u.i = 0;
463 return MEM_Int;
465 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
466 if( rc<=0 ){
467 if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
468 pMem->u.i = ix;
469 return MEM_Int;
470 }else{
471 return MEM_Real;
473 }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
474 pMem->u.i = ix;
475 return MEM_Int;
477 return MEM_Real;
481 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
482 ** none.
484 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
485 ** But it does set pMem->u.r and pMem->u.i appropriately.
487 static u16 numericType(Mem *pMem){
488 assert( (pMem->flags & MEM_Null)==0
489 || pMem->db==0 || pMem->db->mallocFailed );
490 if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null) ){
491 testcase( pMem->flags & MEM_Int );
492 testcase( pMem->flags & MEM_Real );
493 testcase( pMem->flags & MEM_IntReal );
494 return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null);
496 assert( pMem->flags & (MEM_Str|MEM_Blob) );
497 testcase( pMem->flags & MEM_Str );
498 testcase( pMem->flags & MEM_Blob );
499 return computeNumericType(pMem);
500 return 0;
503 #ifdef SQLITE_DEBUG
505 ** Write a nice string representation of the contents of cell pMem
506 ** into buffer zBuf, length nBuf.
508 void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){
509 int f = pMem->flags;
510 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
511 if( f&MEM_Blob ){
512 int i;
513 char c;
514 if( f & MEM_Dyn ){
515 c = 'z';
516 assert( (f & (MEM_Static|MEM_Ephem))==0 );
517 }else if( f & MEM_Static ){
518 c = 't';
519 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
520 }else if( f & MEM_Ephem ){
521 c = 'e';
522 assert( (f & (MEM_Static|MEM_Dyn))==0 );
523 }else{
524 c = 's';
526 sqlite3_str_appendf(pStr, "%cx[", c);
527 for(i=0; i<25 && i<pMem->n; i++){
528 sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
530 sqlite3_str_appendf(pStr, "|");
531 for(i=0; i<25 && i<pMem->n; i++){
532 char z = pMem->z[i];
533 sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);
535 sqlite3_str_appendf(pStr,"]");
536 if( f & MEM_Zero ){
537 sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
539 }else if( f & MEM_Str ){
540 int j;
541 u8 c;
542 if( f & MEM_Dyn ){
543 c = 'z';
544 assert( (f & (MEM_Static|MEM_Ephem))==0 );
545 }else if( f & MEM_Static ){
546 c = 't';
547 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
548 }else if( f & MEM_Ephem ){
549 c = 'e';
550 assert( (f & (MEM_Static|MEM_Dyn))==0 );
551 }else{
552 c = 's';
554 sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
555 for(j=0; j<25 && j<pMem->n; j++){
556 c = pMem->z[j];
557 sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');
559 sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
560 if( f & MEM_Term ){
561 sqlite3_str_appendf(pStr, "(0-term)");
565 #endif
567 #ifdef SQLITE_DEBUG
569 ** Print the value of a register for tracing purposes:
571 static void memTracePrint(Mem *p){
572 if( p->flags & MEM_Undefined ){
573 printf(" undefined");
574 }else if( p->flags & MEM_Null ){
575 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
576 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
577 printf(" si:%lld", p->u.i);
578 }else if( (p->flags & (MEM_IntReal))!=0 ){
579 printf(" ir:%lld", p->u.i);
580 }else if( p->flags & MEM_Int ){
581 printf(" i:%lld", p->u.i);
582 #ifndef SQLITE_OMIT_FLOATING_POINT
583 }else if( p->flags & MEM_Real ){
584 printf(" r:%.17g", p->u.r);
585 #endif
586 }else if( sqlite3VdbeMemIsRowSet(p) ){
587 printf(" (rowset)");
588 }else{
589 StrAccum acc;
590 char zBuf[1000];
591 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
592 sqlite3VdbeMemPrettyPrint(p, &acc);
593 printf(" %s", sqlite3StrAccumFinish(&acc));
595 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
597 static void registerTrace(int iReg, Mem *p){
598 printf("R[%d] = ", iReg);
599 memTracePrint(p);
600 if( p->pScopyFrom ){
601 printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
603 printf("\n");
604 sqlite3VdbeCheckMemInvariants(p);
606 /**/ void sqlite3PrintMem(Mem *pMem){
607 memTracePrint(pMem);
608 printf("\n");
609 fflush(stdout);
611 #endif
613 #ifdef SQLITE_DEBUG
615 ** Show the values of all registers in the virtual machine. Used for
616 ** interactive debugging.
618 void sqlite3VdbeRegisterDump(Vdbe *v){
619 int i;
620 for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
622 #endif /* SQLITE_DEBUG */
625 #ifdef SQLITE_DEBUG
626 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
627 #else
628 # define REGISTER_TRACE(R,M)
629 #endif
631 #ifndef NDEBUG
633 ** This function is only called from within an assert() expression. It
634 ** checks that the sqlite3.nTransaction variable is correctly set to
635 ** the number of non-transaction savepoints currently in the
636 ** linked list starting at sqlite3.pSavepoint.
638 ** Usage:
640 ** assert( checkSavepointCount(db) );
642 static int checkSavepointCount(sqlite3 *db){
643 int n = 0;
644 Savepoint *p;
645 for(p=db->pSavepoint; p; p=p->pNext) n++;
646 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
647 return 1;
649 #endif
652 ** Return the register of pOp->p2 after first preparing it to be
653 ** overwritten with an integer value.
655 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
656 sqlite3VdbeMemSetNull(pOut);
657 pOut->flags = MEM_Int;
658 return pOut;
660 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
661 Mem *pOut;
662 assert( pOp->p2>0 );
663 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
664 pOut = &p->aMem[pOp->p2];
665 memAboutToChange(p, pOut);
666 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
667 return out2PrereleaseWithClear(pOut);
668 }else{
669 pOut->flags = MEM_Int;
670 return pOut;
675 ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
676 ** with pOp->p3. Return the hash.
678 static u64 filterHash(const Mem *aMem, const Op *pOp){
679 int i, mx;
680 u64 h = 0;
682 assert( pOp->p4type==P4_INT32 );
683 for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
684 const Mem *p = &aMem[i];
685 if( p->flags & (MEM_Int|MEM_IntReal) ){
686 h += p->u.i;
687 }else if( p->flags & MEM_Real ){
688 h += sqlite3VdbeIntValue(p);
689 }else if( p->flags & (MEM_Str|MEM_Blob) ){
690 /* All strings have the same hash and all blobs have the same hash,
691 ** though, at least, those hashes are different from each other and
692 ** from NULL. */
693 h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
696 return h;
701 ** For OP_Column, factor out the case where content is loaded from
702 ** overflow pages, so that the code to implement this case is separate
703 ** the common case where all content fits on the page. Factoring out
704 ** the code reduces register pressure and helps the common case
705 ** to run faster.
707 static SQLITE_NOINLINE int vdbeColumnFromOverflow(
708 VdbeCursor *pC, /* The BTree cursor from which we are reading */
709 int iCol, /* The column to read */
710 int t, /* The serial-type code for the column value */
711 i64 iOffset, /* Offset to the start of the content value */
712 u32 cacheStatus, /* Current Vdbe.cacheCtr value */
713 u32 colCacheCtr, /* Current value of the column cache counter */
714 Mem *pDest /* Store the value into this register. */
716 int rc;
717 sqlite3 *db = pDest->db;
718 int encoding = pDest->enc;
719 int len = sqlite3VdbeSerialTypeLen(t);
720 assert( pC->eCurType==CURTYPE_BTREE );
721 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) return SQLITE_TOOBIG;
722 if( len > 4000 && pC->pKeyInfo==0 ){
723 /* Cache large column values that are on overflow pages using
724 ** an RCStr (reference counted string) so that if they are reloaded,
725 ** that do not have to be copied a second time. The overhead of
726 ** creating and managing the cache is such that this is only
727 ** profitable for larger TEXT and BLOB values.
729 ** Only do this on table-btrees so that writes to index-btrees do not
730 ** need to clear the cache. This buys performance in the common case
731 ** in exchange for generality.
733 VdbeTxtBlbCache *pCache;
734 char *pBuf;
735 if( pC->colCache==0 ){
736 pC->pCache = sqlite3DbMallocZero(db, sizeof(VdbeTxtBlbCache) );
737 if( pC->pCache==0 ) return SQLITE_NOMEM;
738 pC->colCache = 1;
740 pCache = pC->pCache;
741 if( pCache->pCValue==0
742 || pCache->iCol!=iCol
743 || pCache->cacheStatus!=cacheStatus
744 || pCache->colCacheCtr!=colCacheCtr
745 || pCache->iOffset!=sqlite3BtreeOffset(pC->uc.pCursor)
747 if( pCache->pCValue ) sqlite3RCStrUnref(pCache->pCValue);
748 pBuf = pCache->pCValue = sqlite3RCStrNew( len+3 );
749 if( pBuf==0 ) return SQLITE_NOMEM;
750 rc = sqlite3BtreePayload(pC->uc.pCursor, iOffset, len, pBuf);
751 if( rc ) return rc;
752 pBuf[len] = 0;
753 pBuf[len+1] = 0;
754 pBuf[len+2] = 0;
755 pCache->iCol = iCol;
756 pCache->cacheStatus = cacheStatus;
757 pCache->colCacheCtr = colCacheCtr;
758 pCache->iOffset = sqlite3BtreeOffset(pC->uc.pCursor);
759 }else{
760 pBuf = pCache->pCValue;
762 assert( t>=12 );
763 sqlite3RCStrRef(pBuf);
764 if( t&1 ){
765 rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, encoding,
766 sqlite3RCStrUnref);
767 pDest->flags |= MEM_Term;
768 }else{
769 rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, 0,
770 sqlite3RCStrUnref);
772 }else{
773 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, iOffset, len, pDest);
774 if( rc ) return rc;
775 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
776 if( (t&1)!=0 && encoding==SQLITE_UTF8 ){
777 pDest->z[len] = 0;
778 pDest->flags |= MEM_Term;
781 pDest->flags &= ~MEM_Ephem;
782 return rc;
787 ** Return the symbolic name for the data type of a pMem
789 static const char *vdbeMemTypeName(Mem *pMem){
790 static const char *azTypes[] = {
791 /* SQLITE_INTEGER */ "INT",
792 /* SQLITE_FLOAT */ "REAL",
793 /* SQLITE_TEXT */ "TEXT",
794 /* SQLITE_BLOB */ "BLOB",
795 /* SQLITE_NULL */ "NULL"
797 return azTypes[sqlite3_value_type(pMem)-1];
801 ** Execute as much of a VDBE program as we can.
802 ** This is the core of sqlite3_step().
804 int sqlite3VdbeExec(
805 Vdbe *p /* The VDBE */
807 Op *aOp = p->aOp; /* Copy of p->aOp */
808 Op *pOp = aOp; /* Current operation */
809 #ifdef SQLITE_DEBUG
810 Op *pOrigOp; /* Value of pOp at the top of the loop */
811 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
812 u8 iCompareIsInit = 0; /* iCompare is initialized */
813 #endif
814 int rc = SQLITE_OK; /* Value to return */
815 sqlite3 *db = p->db; /* The database */
816 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
817 u8 encoding = ENC(db); /* The database encoding */
818 int iCompare = 0; /* Result of last comparison */
819 u64 nVmStep = 0; /* Number of virtual machine steps */
820 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
821 u64 nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
822 #endif
823 Mem *aMem = p->aMem; /* Copy of p->aMem */
824 Mem *pIn1 = 0; /* 1st input operand */
825 Mem *pIn2 = 0; /* 2nd input operand */
826 Mem *pIn3 = 0; /* 3rd input operand */
827 Mem *pOut = 0; /* Output operand */
828 u32 colCacheCtr = 0; /* Column cache counter */
829 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
830 u64 *pnCycle = 0;
831 int bStmtScanStatus = IS_STMT_SCANSTATUS(db)!=0;
832 #endif
833 /*** INSERT STACK UNION HERE ***/
835 assert( p->eVdbeState==VDBE_RUN_STATE ); /* sqlite3_step() verifies this */
836 if( DbMaskNonZero(p->lockMask) ){
837 sqlite3VdbeEnter(p);
839 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
840 if( db->xProgress ){
841 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
842 assert( 0 < db->nProgressOps );
843 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
844 }else{
845 nProgressLimit = LARGEST_UINT64;
847 #endif
848 if( p->rc==SQLITE_NOMEM ){
849 /* This happens if a malloc() inside a call to sqlite3_column_text() or
850 ** sqlite3_column_text16() failed. */
851 goto no_mem;
853 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
854 testcase( p->rc!=SQLITE_OK );
855 p->rc = SQLITE_OK;
856 assert( p->bIsReader || p->readOnly!=0 );
857 p->iCurrentTime = 0;
858 assert( p->explain==0 );
859 db->busyHandler.nBusy = 0;
860 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
861 sqlite3VdbeIOTraceSql(p);
862 #ifdef SQLITE_DEBUG
863 sqlite3BeginBenignMalloc();
864 if( p->pc==0
865 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
867 int i;
868 int once = 1;
869 sqlite3VdbePrintSql(p);
870 if( p->db->flags & SQLITE_VdbeListing ){
871 printf("VDBE Program Listing:\n");
872 for(i=0; i<p->nOp; i++){
873 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
876 if( p->db->flags & SQLITE_VdbeEQP ){
877 for(i=0; i<p->nOp; i++){
878 if( aOp[i].opcode==OP_Explain ){
879 if( once ) printf("VDBE Query Plan:\n");
880 printf("%s\n", aOp[i].p4.z);
881 once = 0;
885 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
887 sqlite3EndBenignMalloc();
888 #endif
889 for(pOp=&aOp[p->pc]; 1; pOp++){
890 /* Errors are detected by individual opcodes, with an immediate
891 ** jumps to abort_due_to_error. */
892 assert( rc==SQLITE_OK );
894 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
895 nVmStep++;
897 #if defined(VDBE_PROFILE)
898 pOp->nExec++;
899 pnCycle = &pOp->nCycle;
900 if( sqlite3NProfileCnt==0 ) *pnCycle -= sqlite3Hwtime();
901 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
902 if( bStmtScanStatus ){
903 pOp->nExec++;
904 pnCycle = &pOp->nCycle;
905 *pnCycle -= sqlite3Hwtime();
907 #endif
909 /* Only allow tracing if SQLITE_DEBUG is defined.
911 #ifdef SQLITE_DEBUG
912 if( db->flags & SQLITE_VdbeTrace ){
913 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
914 test_trace_breakpoint((int)(pOp - aOp),pOp,p);
916 #endif
919 /* Check to see if we need to simulate an interrupt. This only happens
920 ** if we have a special test build.
922 #ifdef SQLITE_TEST
923 if( sqlite3_interrupt_count>0 ){
924 sqlite3_interrupt_count--;
925 if( sqlite3_interrupt_count==0 ){
926 sqlite3_interrupt(db);
929 #endif
931 /* Sanity checking on other operands */
932 #ifdef SQLITE_DEBUG
934 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
935 if( (opProperty & OPFLG_IN1)!=0 ){
936 assert( pOp->p1>0 );
937 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
938 assert( memIsValid(&aMem[pOp->p1]) );
939 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
940 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
942 if( (opProperty & OPFLG_IN2)!=0 ){
943 assert( pOp->p2>0 );
944 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
945 assert( memIsValid(&aMem[pOp->p2]) );
946 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
947 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
949 if( (opProperty & OPFLG_IN3)!=0 ){
950 assert( pOp->p3>0 );
951 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
952 assert( memIsValid(&aMem[pOp->p3]) );
953 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
954 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
956 if( (opProperty & OPFLG_OUT2)!=0 ){
957 assert( pOp->p2>0 );
958 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
959 memAboutToChange(p, &aMem[pOp->p2]);
961 if( (opProperty & OPFLG_OUT3)!=0 ){
962 assert( pOp->p3>0 );
963 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
964 memAboutToChange(p, &aMem[pOp->p3]);
967 #endif
968 #ifdef SQLITE_DEBUG
969 pOrigOp = pOp;
970 #endif
972 switch( pOp->opcode ){
974 /*****************************************************************************
975 ** What follows is a massive switch statement where each case implements a
976 ** separate instruction in the virtual machine. If we follow the usual
977 ** indentation conventions, each case should be indented by 6 spaces. But
978 ** that is a lot of wasted space on the left margin. So the code within
979 ** the switch statement will break with convention and be flush-left. Another
980 ** big comment (similar to this one) will mark the point in the code where
981 ** we transition back to normal indentation.
983 ** The formatting of each case is important. The makefile for SQLite
984 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
985 ** file looking for lines that begin with "case OP_". The opcodes.h files
986 ** will be filled with #defines that give unique integer values to each
987 ** opcode and the opcodes.c file is filled with an array of strings where
988 ** each string is the symbolic name for the corresponding opcode. If the
989 ** case statement is followed by a comment of the form "/# same as ... #/"
990 ** that comment is used to determine the particular value of the opcode.
992 ** Other keywords in the comment that follows each case are used to
993 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
994 ** Keywords include: in1, in2, in3, out2, out3. See
995 ** the mkopcodeh.awk script for additional information.
997 ** Documentation about VDBE opcodes is generated by scanning this file
998 ** for lines of that contain "Opcode:". That line and all subsequent
999 ** comment lines are used in the generation of the opcode.html documentation
1000 ** file.
1002 ** SUMMARY:
1004 ** Formatting is important to scripts that scan this file.
1005 ** Do not deviate from the formatting style currently in use.
1007 *****************************************************************************/
1009 /* Opcode: Goto * P2 * * *
1011 ** An unconditional jump to address P2.
1012 ** The next instruction executed will be
1013 ** the one at index P2 from the beginning of
1014 ** the program.
1016 ** The P1 parameter is not actually used by this opcode. However, it
1017 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
1018 ** that this Goto is the bottom of a loop and that the lines from P2 down
1019 ** to the current line should be indented for EXPLAIN output.
1021 case OP_Goto: { /* jump */
1023 #ifdef SQLITE_DEBUG
1024 /* In debugging mode, when the p5 flags is set on an OP_Goto, that
1025 ** means we should really jump back to the preceding OP_ReleaseReg
1026 ** instruction. */
1027 if( pOp->p5 ){
1028 assert( pOp->p2 < (int)(pOp - aOp) );
1029 assert( pOp->p2 > 1 );
1030 pOp = &aOp[pOp->p2 - 2];
1031 assert( pOp[1].opcode==OP_ReleaseReg );
1032 goto check_for_interrupt;
1034 #endif
1036 jump_to_p2_and_check_for_interrupt:
1037 pOp = &aOp[pOp->p2 - 1];
1039 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
1040 ** OP_VNext, or OP_SorterNext) all jump here upon
1041 ** completion. Check to see if sqlite3_interrupt() has been called
1042 ** or if the progress callback needs to be invoked.
1044 ** This code uses unstructured "goto" statements and does not look clean.
1045 ** But that is not due to sloppy coding habits. The code is written this
1046 ** way for performance, to avoid having to run the interrupt and progress
1047 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
1048 ** faster according to "valgrind --tool=cachegrind" */
1049 check_for_interrupt:
1050 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
1051 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1052 /* Call the progress callback if it is configured and the required number
1053 ** of VDBE ops have been executed (either since this invocation of
1054 ** sqlite3VdbeExec() or since last time the progress callback was called).
1055 ** If the progress callback returns non-zero, exit the virtual machine with
1056 ** a return code SQLITE_ABORT.
1058 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
1059 assert( db->nProgressOps!=0 );
1060 nProgressLimit += db->nProgressOps;
1061 if( db->xProgress(db->pProgressArg) ){
1062 nProgressLimit = LARGEST_UINT64;
1063 rc = SQLITE_INTERRUPT;
1064 goto abort_due_to_error;
1067 #endif
1069 break;
1072 /* Opcode: Gosub P1 P2 * * *
1074 ** Write the current address onto register P1
1075 ** and then jump to address P2.
1077 case OP_Gosub: { /* jump */
1078 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1079 pIn1 = &aMem[pOp->p1];
1080 assert( VdbeMemDynamic(pIn1)==0 );
1081 memAboutToChange(p, pIn1);
1082 pIn1->flags = MEM_Int;
1083 pIn1->u.i = (int)(pOp-aOp);
1084 REGISTER_TRACE(pOp->p1, pIn1);
1085 goto jump_to_p2_and_check_for_interrupt;
1088 /* Opcode: Return P1 P2 P3 * *
1090 ** Jump to the address stored in register P1. If P1 is a return address
1091 ** register, then this accomplishes a return from a subroutine.
1093 ** If P3 is 1, then the jump is only taken if register P1 holds an integer
1094 ** values, otherwise execution falls through to the next opcode, and the
1095 ** OP_Return becomes a no-op. If P3 is 0, then register P1 must hold an
1096 ** integer or else an assert() is raised. P3 should be set to 1 when
1097 ** this opcode is used in combination with OP_BeginSubrtn, and set to 0
1098 ** otherwise.
1100 ** The value in register P1 is unchanged by this opcode.
1102 ** P2 is not used by the byte-code engine. However, if P2 is positive
1103 ** and also less than the current address, then the "EXPLAIN" output
1104 ** formatter in the CLI will indent all opcodes from the P2 opcode up
1105 ** to be not including the current Return. P2 should be the first opcode
1106 ** in the subroutine from which this opcode is returning. Thus the P2
1107 ** value is a byte-code indentation hint. See tag-20220407a in
1108 ** wherecode.c and shell.c.
1110 case OP_Return: { /* in1 */
1111 pIn1 = &aMem[pOp->p1];
1112 if( pIn1->flags & MEM_Int ){
1113 if( pOp->p3 ){ VdbeBranchTaken(1, 2); }
1114 pOp = &aOp[pIn1->u.i];
1115 }else if( ALWAYS(pOp->p3) ){
1116 VdbeBranchTaken(0, 2);
1118 break;
1121 /* Opcode: InitCoroutine P1 P2 P3 * *
1123 ** Set up register P1 so that it will Yield to the coroutine
1124 ** located at address P3.
1126 ** If P2!=0 then the coroutine implementation immediately follows
1127 ** this opcode. So jump over the coroutine implementation to
1128 ** address P2.
1130 ** See also: EndCoroutine
1132 case OP_InitCoroutine: { /* jump */
1133 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1134 assert( pOp->p2>=0 && pOp->p2<p->nOp );
1135 assert( pOp->p3>=0 && pOp->p3<p->nOp );
1136 pOut = &aMem[pOp->p1];
1137 assert( !VdbeMemDynamic(pOut) );
1138 pOut->u.i = pOp->p3 - 1;
1139 pOut->flags = MEM_Int;
1140 if( pOp->p2==0 ) break;
1142 /* Most jump operations do a goto to this spot in order to update
1143 ** the pOp pointer. */
1144 jump_to_p2:
1145 assert( pOp->p2>0 ); /* There are never any jumps to instruction 0 */
1146 assert( pOp->p2<p->nOp ); /* Jumps must be in range */
1147 pOp = &aOp[pOp->p2 - 1];
1148 break;
1151 /* Opcode: EndCoroutine P1 * * * *
1153 ** The instruction at the address in register P1 is a Yield.
1154 ** Jump to the P2 parameter of that Yield.
1155 ** After the jump, register P1 becomes undefined.
1157 ** See also: InitCoroutine
1159 case OP_EndCoroutine: { /* in1 */
1160 VdbeOp *pCaller;
1161 pIn1 = &aMem[pOp->p1];
1162 assert( pIn1->flags==MEM_Int );
1163 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
1164 pCaller = &aOp[pIn1->u.i];
1165 assert( pCaller->opcode==OP_Yield );
1166 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
1167 pOp = &aOp[pCaller->p2 - 1];
1168 pIn1->flags = MEM_Undefined;
1169 break;
1172 /* Opcode: Yield P1 P2 * * *
1174 ** Swap the program counter with the value in register P1. This
1175 ** has the effect of yielding to a coroutine.
1177 ** If the coroutine that is launched by this instruction ends with
1178 ** Yield or Return then continue to the next instruction. But if
1179 ** the coroutine launched by this instruction ends with
1180 ** EndCoroutine, then jump to P2 rather than continuing with the
1181 ** next instruction.
1183 ** See also: InitCoroutine
1185 case OP_Yield: { /* in1, jump */
1186 int pcDest;
1187 pIn1 = &aMem[pOp->p1];
1188 assert( VdbeMemDynamic(pIn1)==0 );
1189 pIn1->flags = MEM_Int;
1190 pcDest = (int)pIn1->u.i;
1191 pIn1->u.i = (int)(pOp - aOp);
1192 REGISTER_TRACE(pOp->p1, pIn1);
1193 pOp = &aOp[pcDest];
1194 break;
1197 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
1198 ** Synopsis: if r[P3]=null halt
1200 ** Check the value in register P3. If it is NULL then Halt using
1201 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
1202 ** value in register P3 is not NULL, then this routine is a no-op.
1203 ** The P5 parameter should be 1.
1205 case OP_HaltIfNull: { /* in3 */
1206 pIn3 = &aMem[pOp->p3];
1207 #ifdef SQLITE_DEBUG
1208 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1209 #endif
1210 if( (pIn3->flags & MEM_Null)==0 ) break;
1211 /* Fall through into OP_Halt */
1212 /* no break */ deliberate_fall_through
1215 /* Opcode: Halt P1 P2 * P4 P5
1217 ** Exit immediately. All open cursors, etc are closed
1218 ** automatically.
1220 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
1221 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
1222 ** For errors, it can be some other value. If P1!=0 then P2 will determine
1223 ** whether or not to rollback the current transaction. Do not rollback
1224 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
1225 ** then back out all changes that have occurred during this execution of the
1226 ** VDBE, but do not rollback the transaction.
1228 ** If P4 is not null then it is an error message string.
1230 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
1232 ** 0: (no change)
1233 ** 1: NOT NULL constraint failed: P4
1234 ** 2: UNIQUE constraint failed: P4
1235 ** 3: CHECK constraint failed: P4
1236 ** 4: FOREIGN KEY constraint failed: P4
1238 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
1239 ** omitted.
1241 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
1242 ** every program. So a jump past the last instruction of the program
1243 ** is the same as executing Halt.
1245 case OP_Halt: {
1246 VdbeFrame *pFrame;
1247 int pcx;
1249 #ifdef SQLITE_DEBUG
1250 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1251 #endif
1253 /* A deliberately coded "OP_Halt SQLITE_INTERNAL * * * *" opcode indicates
1254 ** something is wrong with the code generator. Raise an assertion in order
1255 ** to bring this to the attention of fuzzers and other testing tools. */
1256 assert( pOp->p1!=SQLITE_INTERNAL );
1258 if( p->pFrame && pOp->p1==SQLITE_OK ){
1259 /* Halt the sub-program. Return control to the parent frame. */
1260 pFrame = p->pFrame;
1261 p->pFrame = pFrame->pParent;
1262 p->nFrame--;
1263 sqlite3VdbeSetChanges(db, p->nChange);
1264 pcx = sqlite3VdbeFrameRestore(pFrame);
1265 if( pOp->p2==OE_Ignore ){
1266 /* Instruction pcx is the OP_Program that invoked the sub-program
1267 ** currently being halted. If the p2 instruction of this OP_Halt
1268 ** instruction is set to OE_Ignore, then the sub-program is throwing
1269 ** an IGNORE exception. In this case jump to the address specified
1270 ** as the p2 of the calling OP_Program. */
1271 pcx = p->aOp[pcx].p2-1;
1273 aOp = p->aOp;
1274 aMem = p->aMem;
1275 pOp = &aOp[pcx];
1276 break;
1278 p->rc = pOp->p1;
1279 p->errorAction = (u8)pOp->p2;
1280 assert( pOp->p5<=4 );
1281 if( p->rc ){
1282 if( pOp->p5 ){
1283 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
1284 "FOREIGN KEY" };
1285 testcase( pOp->p5==1 );
1286 testcase( pOp->p5==2 );
1287 testcase( pOp->p5==3 );
1288 testcase( pOp->p5==4 );
1289 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
1290 if( pOp->p4.z ){
1291 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
1293 }else{
1294 sqlite3VdbeError(p, "%s", pOp->p4.z);
1296 pcx = (int)(pOp - aOp);
1297 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
1299 rc = sqlite3VdbeHalt(p);
1300 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1301 if( rc==SQLITE_BUSY ){
1302 p->rc = SQLITE_BUSY;
1303 }else{
1304 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1305 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1306 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1308 goto vdbe_return;
1311 /* Opcode: Integer P1 P2 * * *
1312 ** Synopsis: r[P2]=P1
1314 ** The 32-bit integer value P1 is written into register P2.
1316 case OP_Integer: { /* out2 */
1317 pOut = out2Prerelease(p, pOp);
1318 pOut->u.i = pOp->p1;
1319 break;
1322 /* Opcode: Int64 * P2 * P4 *
1323 ** Synopsis: r[P2]=P4
1325 ** P4 is a pointer to a 64-bit integer value.
1326 ** Write that value into register P2.
1328 case OP_Int64: { /* out2 */
1329 pOut = out2Prerelease(p, pOp);
1330 assert( pOp->p4.pI64!=0 );
1331 pOut->u.i = *pOp->p4.pI64;
1332 break;
1335 #ifndef SQLITE_OMIT_FLOATING_POINT
1336 /* Opcode: Real * P2 * P4 *
1337 ** Synopsis: r[P2]=P4
1339 ** P4 is a pointer to a 64-bit floating point value.
1340 ** Write that value into register P2.
1342 case OP_Real: { /* same as TK_FLOAT, out2 */
1343 pOut = out2Prerelease(p, pOp);
1344 pOut->flags = MEM_Real;
1345 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1346 pOut->u.r = *pOp->p4.pReal;
1347 break;
1349 #endif
1351 /* Opcode: String8 * P2 * P4 *
1352 ** Synopsis: r[P2]='P4'
1354 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1355 ** into a String opcode before it is executed for the first time. During
1356 ** this transformation, the length of string P4 is computed and stored
1357 ** as the P1 parameter.
1359 case OP_String8: { /* same as TK_STRING, out2 */
1360 assert( pOp->p4.z!=0 );
1361 pOut = out2Prerelease(p, pOp);
1362 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1364 #ifndef SQLITE_OMIT_UTF16
1365 if( encoding!=SQLITE_UTF8 ){
1366 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1367 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1368 if( rc ) goto too_big;
1369 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1370 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1371 assert( VdbeMemDynamic(pOut)==0 );
1372 pOut->szMalloc = 0;
1373 pOut->flags |= MEM_Static;
1374 if( pOp->p4type==P4_DYNAMIC ){
1375 sqlite3DbFree(db, pOp->p4.z);
1377 pOp->p4type = P4_DYNAMIC;
1378 pOp->p4.z = pOut->z;
1379 pOp->p1 = pOut->n;
1381 #endif
1382 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1383 goto too_big;
1385 pOp->opcode = OP_String;
1386 assert( rc==SQLITE_OK );
1387 /* Fall through to the next case, OP_String */
1388 /* no break */ deliberate_fall_through
1391 /* Opcode: String P1 P2 P3 P4 P5
1392 ** Synopsis: r[P2]='P4' (len=P1)
1394 ** The string value P4 of length P1 (bytes) is stored in register P2.
1396 ** If P3 is not zero and the content of register P3 is equal to P5, then
1397 ** the datatype of the register P2 is converted to BLOB. The content is
1398 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1399 ** of a string, as if it had been CAST. In other words:
1401 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1403 case OP_String: { /* out2 */
1404 assert( pOp->p4.z!=0 );
1405 pOut = out2Prerelease(p, pOp);
1406 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1407 pOut->z = pOp->p4.z;
1408 pOut->n = pOp->p1;
1409 pOut->enc = encoding;
1410 UPDATE_MAX_BLOBSIZE(pOut);
1411 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1412 if( pOp->p3>0 ){
1413 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1414 pIn3 = &aMem[pOp->p3];
1415 assert( pIn3->flags & MEM_Int );
1416 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1418 #endif
1419 break;
1422 /* Opcode: BeginSubrtn * P2 * * *
1423 ** Synopsis: r[P2]=NULL
1425 ** Mark the beginning of a subroutine that can be entered in-line
1426 ** or that can be called using OP_Gosub. The subroutine should
1427 ** be terminated by an OP_Return instruction that has a P1 operand that
1428 ** is the same as the P2 operand to this opcode and that has P3 set to 1.
1429 ** If the subroutine is entered in-line, then the OP_Return will simply
1430 ** fall through. But if the subroutine is entered using OP_Gosub, then
1431 ** the OP_Return will jump back to the first instruction after the OP_Gosub.
1433 ** This routine works by loading a NULL into the P2 register. When the
1434 ** return address register contains a NULL, the OP_Return instruction is
1435 ** a no-op that simply falls through to the next instruction (assuming that
1436 ** the OP_Return opcode has a P3 value of 1). Thus if the subroutine is
1437 ** entered in-line, then the OP_Return will cause in-line execution to
1438 ** continue. But if the subroutine is entered via OP_Gosub, then the
1439 ** OP_Return will cause a return to the address following the OP_Gosub.
1441 ** This opcode is identical to OP_Null. It has a different name
1442 ** only to make the byte code easier to read and verify.
1444 /* Opcode: Null P1 P2 P3 * *
1445 ** Synopsis: r[P2..P3]=NULL
1447 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1448 ** NULL into register P3 and every register in between P2 and P3. If P3
1449 ** is less than P2 (typically P3 is zero) then only register P2 is
1450 ** set to NULL.
1452 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1453 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1454 ** OP_Ne or OP_Eq.
1456 case OP_BeginSubrtn:
1457 case OP_Null: { /* out2 */
1458 int cnt;
1459 u16 nullFlag;
1460 pOut = out2Prerelease(p, pOp);
1461 cnt = pOp->p3-pOp->p2;
1462 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1463 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1464 pOut->n = 0;
1465 #ifdef SQLITE_DEBUG
1466 pOut->uTemp = 0;
1467 #endif
1468 while( cnt>0 ){
1469 pOut++;
1470 memAboutToChange(p, pOut);
1471 sqlite3VdbeMemSetNull(pOut);
1472 pOut->flags = nullFlag;
1473 pOut->n = 0;
1474 cnt--;
1476 break;
1479 /* Opcode: SoftNull P1 * * * *
1480 ** Synopsis: r[P1]=NULL
1482 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1483 ** instruction, but do not free any string or blob memory associated with
1484 ** the register, so that if the value was a string or blob that was
1485 ** previously copied using OP_SCopy, the copies will continue to be valid.
1487 case OP_SoftNull: {
1488 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1489 pOut = &aMem[pOp->p1];
1490 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1491 break;
1494 /* Opcode: Blob P1 P2 * P4 *
1495 ** Synopsis: r[P2]=P4 (len=P1)
1497 ** P4 points to a blob of data P1 bytes long. Store this
1498 ** blob in register P2. If P4 is a NULL pointer, then construct
1499 ** a zero-filled blob that is P1 bytes long in P2.
1501 case OP_Blob: { /* out2 */
1502 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1503 pOut = out2Prerelease(p, pOp);
1504 if( pOp->p4.z==0 ){
1505 sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
1506 if( sqlite3VdbeMemExpandBlob(pOut) ) goto no_mem;
1507 }else{
1508 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1510 pOut->enc = encoding;
1511 UPDATE_MAX_BLOBSIZE(pOut);
1512 break;
1515 /* Opcode: Variable P1 P2 * * *
1516 ** Synopsis: r[P2]=parameter(P1)
1518 ** Transfer the values of bound parameter P1 into register P2
1520 case OP_Variable: { /* out2 */
1521 Mem *pVar; /* Value being transferred */
1523 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1524 pVar = &p->aVar[pOp->p1 - 1];
1525 if( sqlite3VdbeMemTooBig(pVar) ){
1526 goto too_big;
1528 pOut = &aMem[pOp->p2];
1529 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
1530 memcpy(pOut, pVar, MEMCELLSIZE);
1531 pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
1532 pOut->flags |= MEM_Static|MEM_FromBind;
1533 UPDATE_MAX_BLOBSIZE(pOut);
1534 break;
1537 /* Opcode: Move P1 P2 P3 * *
1538 ** Synopsis: r[P2@P3]=r[P1@P3]
1540 ** Move the P3 values in register P1..P1+P3-1 over into
1541 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1542 ** left holding a NULL. It is an error for register ranges
1543 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1544 ** for P3 to be less than 1.
1546 case OP_Move: {
1547 int n; /* Number of registers left to copy */
1548 int p1; /* Register to copy from */
1549 int p2; /* Register to copy to */
1551 n = pOp->p3;
1552 p1 = pOp->p1;
1553 p2 = pOp->p2;
1554 assert( n>0 && p1>0 && p2>0 );
1555 assert( p1+n<=p2 || p2+n<=p1 );
1557 pIn1 = &aMem[p1];
1558 pOut = &aMem[p2];
1560 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1561 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1562 assert( memIsValid(pIn1) );
1563 memAboutToChange(p, pOut);
1564 sqlite3VdbeMemMove(pOut, pIn1);
1565 #ifdef SQLITE_DEBUG
1566 pIn1->pScopyFrom = 0;
1567 { int i;
1568 for(i=1; i<p->nMem; i++){
1569 if( aMem[i].pScopyFrom==pIn1 ){
1570 aMem[i].pScopyFrom = pOut;
1574 #endif
1575 Deephemeralize(pOut);
1576 REGISTER_TRACE(p2++, pOut);
1577 pIn1++;
1578 pOut++;
1579 }while( --n );
1580 break;
1583 /* Opcode: Copy P1 P2 P3 * P5
1584 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1586 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1588 ** If the 0x0002 bit of P5 is set then also clear the MEM_Subtype flag in the
1589 ** destination. The 0x0001 bit of P5 indicates that this Copy opcode cannot
1590 ** be merged. The 0x0001 bit is used by the query planner and does not
1591 ** come into play during query execution.
1593 ** This instruction makes a deep copy of the value. A duplicate
1594 ** is made of any string or blob constant. See also OP_SCopy.
1596 case OP_Copy: {
1597 int n;
1599 n = pOp->p3;
1600 pIn1 = &aMem[pOp->p1];
1601 pOut = &aMem[pOp->p2];
1602 assert( pOut!=pIn1 );
1603 while( 1 ){
1604 memAboutToChange(p, pOut);
1605 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1606 Deephemeralize(pOut);
1607 if( (pOut->flags & MEM_Subtype)!=0 && (pOp->p5 & 0x0002)!=0 ){
1608 pOut->flags &= ~MEM_Subtype;
1610 #ifdef SQLITE_DEBUG
1611 pOut->pScopyFrom = 0;
1612 #endif
1613 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1614 if( (n--)==0 ) break;
1615 pOut++;
1616 pIn1++;
1618 break;
1621 /* Opcode: SCopy P1 P2 * * *
1622 ** Synopsis: r[P2]=r[P1]
1624 ** Make a shallow copy of register P1 into register P2.
1626 ** This instruction makes a shallow copy of the value. If the value
1627 ** is a string or blob, then the copy is only a pointer to the
1628 ** original and hence if the original changes so will the copy.
1629 ** Worse, if the original is deallocated, the copy becomes invalid.
1630 ** Thus the program must guarantee that the original will not change
1631 ** during the lifetime of the copy. Use OP_Copy to make a complete
1632 ** copy.
1634 case OP_SCopy: { /* out2 */
1635 pIn1 = &aMem[pOp->p1];
1636 pOut = &aMem[pOp->p2];
1637 assert( pOut!=pIn1 );
1638 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1639 #ifdef SQLITE_DEBUG
1640 pOut->pScopyFrom = pIn1;
1641 pOut->mScopyFlags = pIn1->flags;
1642 #endif
1643 break;
1646 /* Opcode: IntCopy P1 P2 * * *
1647 ** Synopsis: r[P2]=r[P1]
1649 ** Transfer the integer value held in register P1 into register P2.
1651 ** This is an optimized version of SCopy that works only for integer
1652 ** values.
1654 case OP_IntCopy: { /* out2 */
1655 pIn1 = &aMem[pOp->p1];
1656 assert( (pIn1->flags & MEM_Int)!=0 );
1657 pOut = &aMem[pOp->p2];
1658 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1659 break;
1662 /* Opcode: FkCheck * * * * *
1664 ** Halt with an SQLITE_CONSTRAINT error if there are any unresolved
1665 ** foreign key constraint violations. If there are no foreign key
1666 ** constraint violations, this is a no-op.
1668 ** FK constraint violations are also checked when the prepared statement
1669 ** exits. This opcode is used to raise foreign key constraint errors prior
1670 ** to returning results such as a row change count or the result of a
1671 ** RETURNING clause.
1673 case OP_FkCheck: {
1674 if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){
1675 goto abort_due_to_error;
1677 break;
1680 /* Opcode: ResultRow P1 P2 * * *
1681 ** Synopsis: output=r[P1@P2]
1683 ** The registers P1 through P1+P2-1 contain a single row of
1684 ** results. This opcode causes the sqlite3_step() call to terminate
1685 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1686 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1687 ** the result row.
1689 case OP_ResultRow: {
1690 assert( p->nResColumn==pOp->p2 );
1691 assert( pOp->p1>0 || CORRUPT_DB );
1692 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1694 p->cacheCtr = (p->cacheCtr + 2)|1;
1695 p->pResultRow = &aMem[pOp->p1];
1696 #ifdef SQLITE_DEBUG
1698 Mem *pMem = p->pResultRow;
1699 int i;
1700 for(i=0; i<pOp->p2; i++){
1701 assert( memIsValid(&pMem[i]) );
1702 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1703 /* The registers in the result will not be used again when the
1704 ** prepared statement restarts. This is because sqlite3_column()
1705 ** APIs might have caused type conversions of made other changes to
1706 ** the register values. Therefore, we can go ahead and break any
1707 ** OP_SCopy dependencies. */
1708 pMem[i].pScopyFrom = 0;
1711 #endif
1712 if( db->mallocFailed ) goto no_mem;
1713 if( db->mTrace & SQLITE_TRACE_ROW ){
1714 db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1716 p->pc = (int)(pOp - aOp) + 1;
1717 rc = SQLITE_ROW;
1718 goto vdbe_return;
1721 /* Opcode: Concat P1 P2 P3 * *
1722 ** Synopsis: r[P3]=r[P2]+r[P1]
1724 ** Add the text in register P1 onto the end of the text in
1725 ** register P2 and store the result in register P3.
1726 ** If either the P1 or P2 text are NULL then store NULL in P3.
1728 ** P3 = P2 || P1
1730 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1731 ** if P3 is the same register as P2, the implementation is able
1732 ** to avoid a memcpy().
1734 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1735 i64 nByte; /* Total size of the output string or blob */
1736 u16 flags1; /* Initial flags for P1 */
1737 u16 flags2; /* Initial flags for P2 */
1739 pIn1 = &aMem[pOp->p1];
1740 pIn2 = &aMem[pOp->p2];
1741 pOut = &aMem[pOp->p3];
1742 testcase( pOut==pIn2 );
1743 assert( pIn1!=pOut );
1744 flags1 = pIn1->flags;
1745 testcase( flags1 & MEM_Null );
1746 testcase( pIn2->flags & MEM_Null );
1747 if( (flags1 | pIn2->flags) & MEM_Null ){
1748 sqlite3VdbeMemSetNull(pOut);
1749 break;
1751 if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
1752 if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
1753 flags1 = pIn1->flags & ~MEM_Str;
1754 }else if( (flags1 & MEM_Zero)!=0 ){
1755 if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
1756 flags1 = pIn1->flags & ~MEM_Str;
1758 flags2 = pIn2->flags;
1759 if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
1760 if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
1761 flags2 = pIn2->flags & ~MEM_Str;
1762 }else if( (flags2 & MEM_Zero)!=0 ){
1763 if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
1764 flags2 = pIn2->flags & ~MEM_Str;
1766 nByte = pIn1->n + pIn2->n;
1767 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1768 goto too_big;
1770 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1771 goto no_mem;
1773 MemSetTypeFlag(pOut, MEM_Str);
1774 if( pOut!=pIn2 ){
1775 memcpy(pOut->z, pIn2->z, pIn2->n);
1776 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
1777 pIn2->flags = flags2;
1779 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1780 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1781 pIn1->flags = flags1;
1782 if( encoding>SQLITE_UTF8 ) nByte &= ~1;
1783 pOut->z[nByte]=0;
1784 pOut->z[nByte+1] = 0;
1785 pOut->flags |= MEM_Term;
1786 pOut->n = (int)nByte;
1787 pOut->enc = encoding;
1788 UPDATE_MAX_BLOBSIZE(pOut);
1789 break;
1792 /* Opcode: Add P1 P2 P3 * *
1793 ** Synopsis: r[P3]=r[P1]+r[P2]
1795 ** Add the value in register P1 to the value in register P2
1796 ** and store the result in register P3.
1797 ** If either input is NULL, the result is NULL.
1799 /* Opcode: Multiply P1 P2 P3 * *
1800 ** Synopsis: r[P3]=r[P1]*r[P2]
1803 ** Multiply the value in register P1 by the value in register P2
1804 ** and store the result in register P3.
1805 ** If either input is NULL, the result is NULL.
1807 /* Opcode: Subtract P1 P2 P3 * *
1808 ** Synopsis: r[P3]=r[P2]-r[P1]
1810 ** Subtract the value in register P1 from the value in register P2
1811 ** and store the result in register P3.
1812 ** If either input is NULL, the result is NULL.
1814 /* Opcode: Divide P1 P2 P3 * *
1815 ** Synopsis: r[P3]=r[P2]/r[P1]
1817 ** Divide the value in register P1 by the value in register P2
1818 ** and store the result in register P3 (P3=P2/P1). If the value in
1819 ** register P1 is zero, then the result is NULL. If either input is
1820 ** NULL, the result is NULL.
1822 /* Opcode: Remainder P1 P2 P3 * *
1823 ** Synopsis: r[P3]=r[P2]%r[P1]
1825 ** Compute the remainder after integer register P2 is divided by
1826 ** register P1 and store the result in register P3.
1827 ** If the value in register P1 is zero the result is NULL.
1828 ** If either operand is NULL, the result is NULL.
1830 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1831 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1832 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1833 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1834 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1835 u16 type1; /* Numeric type of left operand */
1836 u16 type2; /* Numeric type of right operand */
1837 i64 iA; /* Integer value of left operand */
1838 i64 iB; /* Integer value of right operand */
1839 double rA; /* Real value of left operand */
1840 double rB; /* Real value of right operand */
1842 pIn1 = &aMem[pOp->p1];
1843 type1 = pIn1->flags;
1844 pIn2 = &aMem[pOp->p2];
1845 type2 = pIn2->flags;
1846 pOut = &aMem[pOp->p3];
1847 if( (type1 & type2 & MEM_Int)!=0 ){
1848 int_math:
1849 iA = pIn1->u.i;
1850 iB = pIn2->u.i;
1851 switch( pOp->opcode ){
1852 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1853 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1854 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1855 case OP_Divide: {
1856 if( iA==0 ) goto arithmetic_result_is_null;
1857 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1858 iB /= iA;
1859 break;
1861 default: {
1862 if( iA==0 ) goto arithmetic_result_is_null;
1863 if( iA==-1 ) iA = 1;
1864 iB %= iA;
1865 break;
1868 pOut->u.i = iB;
1869 MemSetTypeFlag(pOut, MEM_Int);
1870 }else if( ((type1 | type2) & MEM_Null)!=0 ){
1871 goto arithmetic_result_is_null;
1872 }else{
1873 type1 = numericType(pIn1);
1874 type2 = numericType(pIn2);
1875 if( (type1 & type2 & MEM_Int)!=0 ) goto int_math;
1876 fp_math:
1877 rA = sqlite3VdbeRealValue(pIn1);
1878 rB = sqlite3VdbeRealValue(pIn2);
1879 switch( pOp->opcode ){
1880 case OP_Add: rB += rA; break;
1881 case OP_Subtract: rB -= rA; break;
1882 case OP_Multiply: rB *= rA; break;
1883 case OP_Divide: {
1884 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1885 if( rA==(double)0 ) goto arithmetic_result_is_null;
1886 rB /= rA;
1887 break;
1889 default: {
1890 iA = sqlite3VdbeIntValue(pIn1);
1891 iB = sqlite3VdbeIntValue(pIn2);
1892 if( iA==0 ) goto arithmetic_result_is_null;
1893 if( iA==-1 ) iA = 1;
1894 rB = (double)(iB % iA);
1895 break;
1898 #ifdef SQLITE_OMIT_FLOATING_POINT
1899 pOut->u.i = rB;
1900 MemSetTypeFlag(pOut, MEM_Int);
1901 #else
1902 if( sqlite3IsNaN(rB) ){
1903 goto arithmetic_result_is_null;
1905 pOut->u.r = rB;
1906 MemSetTypeFlag(pOut, MEM_Real);
1907 #endif
1909 break;
1911 arithmetic_result_is_null:
1912 sqlite3VdbeMemSetNull(pOut);
1913 break;
1916 /* Opcode: CollSeq P1 * * P4
1918 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1919 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1920 ** be returned. This is used by the built-in min(), max() and nullif()
1921 ** functions.
1923 ** If P1 is not zero, then it is a register that a subsequent min() or
1924 ** max() aggregate will set to 1 if the current row is not the minimum or
1925 ** maximum. The P1 register is initialized to 0 by this instruction.
1927 ** The interface used by the implementation of the aforementioned functions
1928 ** to retrieve the collation sequence set by this opcode is not available
1929 ** publicly. Only built-in functions have access to this feature.
1931 case OP_CollSeq: {
1932 assert( pOp->p4type==P4_COLLSEQ );
1933 if( pOp->p1 ){
1934 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1936 break;
1939 /* Opcode: BitAnd P1 P2 P3 * *
1940 ** Synopsis: r[P3]=r[P1]&r[P2]
1942 ** Take the bit-wise AND of the values in register P1 and P2 and
1943 ** store the result in register P3.
1944 ** If either input is NULL, the result is NULL.
1946 /* Opcode: BitOr P1 P2 P3 * *
1947 ** Synopsis: r[P3]=r[P1]|r[P2]
1949 ** Take the bit-wise OR of the values in register P1 and P2 and
1950 ** store the result in register P3.
1951 ** If either input is NULL, the result is NULL.
1953 /* Opcode: ShiftLeft P1 P2 P3 * *
1954 ** Synopsis: r[P3]=r[P2]<<r[P1]
1956 ** Shift the integer value in register P2 to the left by the
1957 ** number of bits specified by the integer in register P1.
1958 ** Store the result in register P3.
1959 ** If either input is NULL, the result is NULL.
1961 /* Opcode: ShiftRight P1 P2 P3 * *
1962 ** Synopsis: r[P3]=r[P2]>>r[P1]
1964 ** Shift the integer value in register P2 to the right by the
1965 ** number of bits specified by the integer in register P1.
1966 ** Store the result in register P3.
1967 ** If either input is NULL, the result is NULL.
1969 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1970 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1971 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1972 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1973 i64 iA;
1974 u64 uA;
1975 i64 iB;
1976 u8 op;
1978 pIn1 = &aMem[pOp->p1];
1979 pIn2 = &aMem[pOp->p2];
1980 pOut = &aMem[pOp->p3];
1981 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1982 sqlite3VdbeMemSetNull(pOut);
1983 break;
1985 iA = sqlite3VdbeIntValue(pIn2);
1986 iB = sqlite3VdbeIntValue(pIn1);
1987 op = pOp->opcode;
1988 if( op==OP_BitAnd ){
1989 iA &= iB;
1990 }else if( op==OP_BitOr ){
1991 iA |= iB;
1992 }else if( iB!=0 ){
1993 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1995 /* If shifting by a negative amount, shift in the other direction */
1996 if( iB<0 ){
1997 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1998 op = 2*OP_ShiftLeft + 1 - op;
1999 iB = iB>(-64) ? -iB : 64;
2002 if( iB>=64 ){
2003 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
2004 }else{
2005 memcpy(&uA, &iA, sizeof(uA));
2006 if( op==OP_ShiftLeft ){
2007 uA <<= iB;
2008 }else{
2009 uA >>= iB;
2010 /* Sign-extend on a right shift of a negative number */
2011 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
2013 memcpy(&iA, &uA, sizeof(iA));
2016 pOut->u.i = iA;
2017 MemSetTypeFlag(pOut, MEM_Int);
2018 break;
2021 /* Opcode: AddImm P1 P2 * * *
2022 ** Synopsis: r[P1]=r[P1]+P2
2024 ** Add the constant P2 to the value in register P1.
2025 ** The result is always an integer.
2027 ** To force any register to be an integer, just add 0.
2029 case OP_AddImm: { /* in1 */
2030 pIn1 = &aMem[pOp->p1];
2031 memAboutToChange(p, pIn1);
2032 sqlite3VdbeMemIntegerify(pIn1);
2033 *(u64*)&pIn1->u.i += (u64)pOp->p2;
2034 break;
2037 /* Opcode: MustBeInt P1 P2 * * *
2039 ** Force the value in register P1 to be an integer. If the value
2040 ** in P1 is not an integer and cannot be converted into an integer
2041 ** without data loss, then jump immediately to P2, or if P2==0
2042 ** raise an SQLITE_MISMATCH exception.
2044 case OP_MustBeInt: { /* jump, in1 */
2045 pIn1 = &aMem[pOp->p1];
2046 if( (pIn1->flags & MEM_Int)==0 ){
2047 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
2048 if( (pIn1->flags & MEM_Int)==0 ){
2049 VdbeBranchTaken(1, 2);
2050 if( pOp->p2==0 ){
2051 rc = SQLITE_MISMATCH;
2052 goto abort_due_to_error;
2053 }else{
2054 goto jump_to_p2;
2058 VdbeBranchTaken(0, 2);
2059 MemSetTypeFlag(pIn1, MEM_Int);
2060 break;
2063 #ifndef SQLITE_OMIT_FLOATING_POINT
2064 /* Opcode: RealAffinity P1 * * * *
2066 ** If register P1 holds an integer convert it to a real value.
2068 ** This opcode is used when extracting information from a column that
2069 ** has REAL affinity. Such column values may still be stored as
2070 ** integers, for space efficiency, but after extraction we want them
2071 ** to have only a real value.
2073 case OP_RealAffinity: { /* in1 */
2074 pIn1 = &aMem[pOp->p1];
2075 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
2076 testcase( pIn1->flags & MEM_Int );
2077 testcase( pIn1->flags & MEM_IntReal );
2078 sqlite3VdbeMemRealify(pIn1);
2079 REGISTER_TRACE(pOp->p1, pIn1);
2081 break;
2083 #endif
2085 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_ANALYZE)
2086 /* Opcode: Cast P1 P2 * * *
2087 ** Synopsis: affinity(r[P1])
2089 ** Force the value in register P1 to be the type defined by P2.
2091 ** <ul>
2092 ** <li> P2=='A' &rarr; BLOB
2093 ** <li> P2=='B' &rarr; TEXT
2094 ** <li> P2=='C' &rarr; NUMERIC
2095 ** <li> P2=='D' &rarr; INTEGER
2096 ** <li> P2=='E' &rarr; REAL
2097 ** </ul>
2099 ** A NULL value is not changed by this routine. It remains NULL.
2101 case OP_Cast: { /* in1 */
2102 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
2103 testcase( pOp->p2==SQLITE_AFF_TEXT );
2104 testcase( pOp->p2==SQLITE_AFF_BLOB );
2105 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
2106 testcase( pOp->p2==SQLITE_AFF_INTEGER );
2107 testcase( pOp->p2==SQLITE_AFF_REAL );
2108 pIn1 = &aMem[pOp->p1];
2109 memAboutToChange(p, pIn1);
2110 rc = ExpandBlob(pIn1);
2111 if( rc ) goto abort_due_to_error;
2112 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
2113 if( rc ) goto abort_due_to_error;
2114 UPDATE_MAX_BLOBSIZE(pIn1);
2115 REGISTER_TRACE(pOp->p1, pIn1);
2116 break;
2118 #endif /* SQLITE_OMIT_CAST */
2120 /* Opcode: Eq P1 P2 P3 P4 P5
2121 ** Synopsis: IF r[P3]==r[P1]
2123 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
2124 ** jump to address P2.
2126 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2127 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2128 ** to coerce both inputs according to this affinity before the
2129 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2130 ** affinity is used. Note that the affinity conversions are stored
2131 ** back into the input registers P1 and P3. So this opcode can cause
2132 ** persistent changes to registers P1 and P3.
2134 ** Once any conversions have taken place, and neither value is NULL,
2135 ** the values are compared. If both values are blobs then memcmp() is
2136 ** used to determine the results of the comparison. If both values
2137 ** are text, then the appropriate collating function specified in
2138 ** P4 is used to do the comparison. If P4 is not specified then
2139 ** memcmp() is used to compare text string. If both values are
2140 ** numeric, then a numeric comparison is used. If the two values
2141 ** are of different types, then numbers are considered less than
2142 ** strings and strings are considered less than blobs.
2144 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
2145 ** true or false and is never NULL. If both operands are NULL then the result
2146 ** of comparison is true. If either operand is NULL then the result is false.
2147 ** If neither operand is NULL the result is the same as it would be if
2148 ** the SQLITE_NULLEQ flag were omitted from P5.
2150 ** This opcode saves the result of comparison for use by the new
2151 ** OP_Jump opcode.
2153 /* Opcode: Ne P1 P2 P3 P4 P5
2154 ** Synopsis: IF r[P3]!=r[P1]
2156 ** This works just like the Eq opcode except that the jump is taken if
2157 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
2158 ** additional information.
2160 /* Opcode: Lt P1 P2 P3 P4 P5
2161 ** Synopsis: IF r[P3]<r[P1]
2163 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
2164 ** jump to address P2.
2166 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
2167 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
2168 ** bit is clear then fall through if either operand is NULL.
2170 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2171 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2172 ** to coerce both inputs according to this affinity before the
2173 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2174 ** affinity is used. Note that the affinity conversions are stored
2175 ** back into the input registers P1 and P3. So this opcode can cause
2176 ** persistent changes to registers P1 and P3.
2178 ** Once any conversions have taken place, and neither value is NULL,
2179 ** the values are compared. If both values are blobs then memcmp() is
2180 ** used to determine the results of the comparison. If both values
2181 ** are text, then the appropriate collating function specified in
2182 ** P4 is used to do the comparison. If P4 is not specified then
2183 ** memcmp() is used to compare text string. If both values are
2184 ** numeric, then a numeric comparison is used. If the two values
2185 ** are of different types, then numbers are considered less than
2186 ** strings and strings are considered less than blobs.
2188 ** This opcode saves the result of comparison for use by the new
2189 ** OP_Jump opcode.
2191 /* Opcode: Le P1 P2 P3 P4 P5
2192 ** Synopsis: IF r[P3]<=r[P1]
2194 ** This works just like the Lt opcode except that the jump is taken if
2195 ** the content of register P3 is less than or equal to the content of
2196 ** register P1. See the Lt opcode for additional information.
2198 /* Opcode: Gt P1 P2 P3 P4 P5
2199 ** Synopsis: IF r[P3]>r[P1]
2201 ** This works just like the Lt opcode except that the jump is taken if
2202 ** the content of register P3 is greater than the content of
2203 ** register P1. See the Lt opcode for additional information.
2205 /* Opcode: Ge P1 P2 P3 P4 P5
2206 ** Synopsis: IF r[P3]>=r[P1]
2208 ** This works just like the Lt opcode except that the jump is taken if
2209 ** the content of register P3 is greater than or equal to the content of
2210 ** register P1. See the Lt opcode for additional information.
2212 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
2213 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
2214 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
2215 case OP_Le: /* same as TK_LE, jump, in1, in3 */
2216 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
2217 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
2218 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
2219 char affinity; /* Affinity to use for comparison */
2220 u16 flags1; /* Copy of initial value of pIn1->flags */
2221 u16 flags3; /* Copy of initial value of pIn3->flags */
2223 pIn1 = &aMem[pOp->p1];
2224 pIn3 = &aMem[pOp->p3];
2225 flags1 = pIn1->flags;
2226 flags3 = pIn3->flags;
2227 if( (flags1 & flags3 & MEM_Int)!=0 ){
2228 /* Common case of comparison of two integers */
2229 if( pIn3->u.i > pIn1->u.i ){
2230 if( sqlite3aGTb[pOp->opcode] ){
2231 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2232 goto jump_to_p2;
2234 iCompare = +1;
2235 VVA_ONLY( iCompareIsInit = 1; )
2236 }else if( pIn3->u.i < pIn1->u.i ){
2237 if( sqlite3aLTb[pOp->opcode] ){
2238 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2239 goto jump_to_p2;
2241 iCompare = -1;
2242 VVA_ONLY( iCompareIsInit = 1; )
2243 }else{
2244 if( sqlite3aEQb[pOp->opcode] ){
2245 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2246 goto jump_to_p2;
2248 iCompare = 0;
2249 VVA_ONLY( iCompareIsInit = 1; )
2251 VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2252 break;
2254 if( (flags1 | flags3)&MEM_Null ){
2255 /* One or both operands are NULL */
2256 if( pOp->p5 & SQLITE_NULLEQ ){
2257 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
2258 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
2259 ** or not both operands are null.
2261 assert( (flags1 & MEM_Cleared)==0 );
2262 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
2263 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
2264 if( (flags1&flags3&MEM_Null)!=0
2265 && (flags3&MEM_Cleared)==0
2267 res = 0; /* Operands are equal */
2268 }else{
2269 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
2271 }else{
2272 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
2273 ** then the result is always NULL.
2274 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
2276 VdbeBranchTaken(2,3);
2277 if( pOp->p5 & SQLITE_JUMPIFNULL ){
2278 goto jump_to_p2;
2280 iCompare = 1; /* Operands are not equal */
2281 VVA_ONLY( iCompareIsInit = 1; )
2282 break;
2284 }else{
2285 /* Neither operand is NULL and we couldn't do the special high-speed
2286 ** integer comparison case. So do a general-case comparison. */
2287 affinity = pOp->p5 & SQLITE_AFF_MASK;
2288 if( affinity>=SQLITE_AFF_NUMERIC ){
2289 if( (flags1 | flags3)&MEM_Str ){
2290 if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2291 applyNumericAffinity(pIn1,0);
2292 assert( flags3==pIn3->flags || CORRUPT_DB );
2293 flags3 = pIn3->flags;
2295 if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2296 applyNumericAffinity(pIn3,0);
2299 }else if( affinity==SQLITE_AFF_TEXT && ((flags1 | flags3) & MEM_Str)!=0 ){
2300 if( (flags1 & MEM_Str)!=0 ){
2301 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
2302 }else if( (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2303 testcase( pIn1->flags & MEM_Int );
2304 testcase( pIn1->flags & MEM_Real );
2305 testcase( pIn1->flags & MEM_IntReal );
2306 sqlite3VdbeMemStringify(pIn1, encoding, 1);
2307 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
2308 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
2309 if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
2311 if( (flags3 & MEM_Str)!=0 ){
2312 pIn3->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
2313 }else if( (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2314 testcase( pIn3->flags & MEM_Int );
2315 testcase( pIn3->flags & MEM_Real );
2316 testcase( pIn3->flags & MEM_IntReal );
2317 sqlite3VdbeMemStringify(pIn3, encoding, 1);
2318 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
2319 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
2322 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
2323 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
2326 /* At this point, res is negative, zero, or positive if reg[P1] is
2327 ** less than, equal to, or greater than reg[P3], respectively. Compute
2328 ** the answer to this operator in res2, depending on what the comparison
2329 ** operator actually is. The next block of code depends on the fact
2330 ** that the 6 comparison operators are consecutive integers in this
2331 ** order: NE, EQ, GT, LE, LT, GE */
2332 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
2333 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
2334 if( res<0 ){
2335 res2 = sqlite3aLTb[pOp->opcode];
2336 }else if( res==0 ){
2337 res2 = sqlite3aEQb[pOp->opcode];
2338 }else{
2339 res2 = sqlite3aGTb[pOp->opcode];
2341 iCompare = res;
2342 VVA_ONLY( iCompareIsInit = 1; )
2344 /* Undo any changes made by applyAffinity() to the input registers. */
2345 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
2346 pIn3->flags = flags3;
2347 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
2348 pIn1->flags = flags1;
2350 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2351 if( res2 ){
2352 goto jump_to_p2;
2354 break;
2357 /* Opcode: ElseEq * P2 * * *
2359 ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
2360 ** can be zero or more OP_ReleaseReg opcodes intervening, but no other
2361 ** opcodes are allowed to occur between this instruction and the previous
2362 ** OP_Lt or OP_Gt.
2364 ** If the result of an OP_Eq comparison on the same two operands as
2365 ** the prior OP_Lt or OP_Gt would have been true, then jump to P2. If
2366 ** the result of an OP_Eq comparison on the two previous operands
2367 ** would have been false or NULL, then fall through.
2369 case OP_ElseEq: { /* same as TK_ESCAPE, jump */
2371 #ifdef SQLITE_DEBUG
2372 /* Verify the preconditions of this opcode - that it follows an OP_Lt or
2373 ** OP_Gt with zero or more intervening OP_ReleaseReg opcodes */
2374 int iAddr;
2375 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
2376 if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
2377 assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
2378 break;
2380 #endif /* SQLITE_DEBUG */
2381 assert( iCompareIsInit );
2382 VdbeBranchTaken(iCompare==0, 2);
2383 if( iCompare==0 ) goto jump_to_p2;
2384 break;
2388 /* Opcode: Permutation * * * P4 *
2390 ** Set the permutation used by the OP_Compare operator in the next
2391 ** instruction. The permutation is stored in the P4 operand.
2393 ** The permutation is only valid for the next opcode which must be
2394 ** an OP_Compare that has the OPFLAG_PERMUTE bit set in P5.
2396 ** The first integer in the P4 integer array is the length of the array
2397 ** and does not become part of the permutation.
2399 case OP_Permutation: {
2400 assert( pOp->p4type==P4_INTARRAY );
2401 assert( pOp->p4.ai );
2402 assert( pOp[1].opcode==OP_Compare );
2403 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2404 break;
2407 /* Opcode: Compare P1 P2 P3 P4 P5
2408 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2410 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2411 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2412 ** the comparison for use by the next OP_Jump instruct.
2414 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2415 ** determined by the most recent OP_Permutation operator. If the
2416 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2417 ** order.
2419 ** P4 is a KeyInfo structure that defines collating sequences and sort
2420 ** orders for the comparison. The permutation applies to registers
2421 ** only. The KeyInfo elements are used sequentially.
2423 ** The comparison is a sort comparison, so NULLs compare equal,
2424 ** NULLs are less than numbers, numbers are less than strings,
2425 ** and strings are less than blobs.
2427 ** This opcode must be immediately followed by an OP_Jump opcode.
2429 case OP_Compare: {
2430 int n;
2431 int i;
2432 int p1;
2433 int p2;
2434 const KeyInfo *pKeyInfo;
2435 u32 idx;
2436 CollSeq *pColl; /* Collating sequence to use on this term */
2437 int bRev; /* True for DESCENDING sort order */
2438 u32 *aPermute; /* The permutation */
2440 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2441 aPermute = 0;
2442 }else{
2443 assert( pOp>aOp );
2444 assert( pOp[-1].opcode==OP_Permutation );
2445 assert( pOp[-1].p4type==P4_INTARRAY );
2446 aPermute = pOp[-1].p4.ai + 1;
2447 assert( aPermute!=0 );
2449 n = pOp->p3;
2450 pKeyInfo = pOp->p4.pKeyInfo;
2451 assert( n>0 );
2452 assert( pKeyInfo!=0 );
2453 p1 = pOp->p1;
2454 p2 = pOp->p2;
2455 #ifdef SQLITE_DEBUG
2456 if( aPermute ){
2457 int k, mx = 0;
2458 for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
2459 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2460 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2461 }else{
2462 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2463 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2465 #endif /* SQLITE_DEBUG */
2466 for(i=0; i<n; i++){
2467 idx = aPermute ? aPermute[i] : (u32)i;
2468 assert( memIsValid(&aMem[p1+idx]) );
2469 assert( memIsValid(&aMem[p2+idx]) );
2470 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2471 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2472 assert( i<pKeyInfo->nKeyField );
2473 pColl = pKeyInfo->aColl[i];
2474 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
2475 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2476 VVA_ONLY( iCompareIsInit = 1; )
2477 if( iCompare ){
2478 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
2479 && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
2481 iCompare = -iCompare;
2483 if( bRev ) iCompare = -iCompare;
2484 break;
2487 assert( pOp[1].opcode==OP_Jump );
2488 break;
2491 /* Opcode: Jump P1 P2 P3 * *
2493 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2494 ** in the most recent OP_Compare instruction the P1 vector was less than,
2495 ** equal to, or greater than the P2 vector, respectively.
2497 ** This opcode must immediately follow an OP_Compare opcode.
2499 case OP_Jump: { /* jump */
2500 assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
2501 assert( iCompareIsInit );
2502 if( iCompare<0 ){
2503 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
2504 }else if( iCompare==0 ){
2505 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
2506 }else{
2507 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
2509 break;
2512 /* Opcode: And P1 P2 P3 * *
2513 ** Synopsis: r[P3]=(r[P1] && r[P2])
2515 ** Take the logical AND of the values in registers P1 and P2 and
2516 ** write the result into register P3.
2518 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2519 ** the other input is NULL. A NULL and true or two NULLs give
2520 ** a NULL output.
2522 /* Opcode: Or P1 P2 P3 * *
2523 ** Synopsis: r[P3]=(r[P1] || r[P2])
2525 ** Take the logical OR of the values in register P1 and P2 and
2526 ** store the answer in register P3.
2528 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2529 ** even if the other input is NULL. A NULL and false or two NULLs
2530 ** give a NULL output.
2532 case OP_And: /* same as TK_AND, in1, in2, out3 */
2533 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2534 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2535 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2537 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2538 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2539 if( pOp->opcode==OP_And ){
2540 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2541 v1 = and_logic[v1*3+v2];
2542 }else{
2543 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2544 v1 = or_logic[v1*3+v2];
2546 pOut = &aMem[pOp->p3];
2547 if( v1==2 ){
2548 MemSetTypeFlag(pOut, MEM_Null);
2549 }else{
2550 pOut->u.i = v1;
2551 MemSetTypeFlag(pOut, MEM_Int);
2553 break;
2556 /* Opcode: IsTrue P1 P2 P3 P4 *
2557 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2559 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2560 ** IS NOT FALSE operators.
2562 ** Interpret the value in register P1 as a boolean value. Store that
2563 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2564 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2565 ** is 1.
2567 ** The logic is summarized like this:
2569 ** <ul>
2570 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2571 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2572 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2573 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2574 ** </ul>
2576 case OP_IsTrue: { /* in1, out2 */
2577 assert( pOp->p4type==P4_INT32 );
2578 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2579 assert( pOp->p3==0 || pOp->p3==1 );
2580 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2581 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2582 break;
2585 /* Opcode: Not P1 P2 * * *
2586 ** Synopsis: r[P2]= !r[P1]
2588 ** Interpret the value in register P1 as a boolean value. Store the
2589 ** boolean complement in register P2. If the value in register P1 is
2590 ** NULL, then a NULL is stored in P2.
2592 case OP_Not: { /* same as TK_NOT, in1, out2 */
2593 pIn1 = &aMem[pOp->p1];
2594 pOut = &aMem[pOp->p2];
2595 if( (pIn1->flags & MEM_Null)==0 ){
2596 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2597 }else{
2598 sqlite3VdbeMemSetNull(pOut);
2600 break;
2603 /* Opcode: BitNot P1 P2 * * *
2604 ** Synopsis: r[P2]= ~r[P1]
2606 ** Interpret the content of register P1 as an integer. Store the
2607 ** ones-complement of the P1 value into register P2. If P1 holds
2608 ** a NULL then store a NULL in P2.
2610 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2611 pIn1 = &aMem[pOp->p1];
2612 pOut = &aMem[pOp->p2];
2613 sqlite3VdbeMemSetNull(pOut);
2614 if( (pIn1->flags & MEM_Null)==0 ){
2615 pOut->flags = MEM_Int;
2616 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2618 break;
2621 /* Opcode: Once P1 P2 * * *
2623 ** Fall through to the next instruction the first time this opcode is
2624 ** encountered on each invocation of the byte-code program. Jump to P2
2625 ** on the second and all subsequent encounters during the same invocation.
2627 ** Top-level programs determine first invocation by comparing the P1
2628 ** operand against the P1 operand on the OP_Init opcode at the beginning
2629 ** of the program. If the P1 values differ, then fall through and make
2630 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2631 ** the same then take the jump.
2633 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2634 ** whether or not the jump should be taken. The bitmask is necessary
2635 ** because the self-altering code trick does not work for recursive
2636 ** triggers.
2638 case OP_Once: { /* jump */
2639 u32 iAddr; /* Address of this instruction */
2640 assert( p->aOp[0].opcode==OP_Init );
2641 if( p->pFrame ){
2642 iAddr = (int)(pOp - p->aOp);
2643 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2644 VdbeBranchTaken(1, 2);
2645 goto jump_to_p2;
2647 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2648 }else{
2649 if( p->aOp[0].p1==pOp->p1 ){
2650 VdbeBranchTaken(1, 2);
2651 goto jump_to_p2;
2654 VdbeBranchTaken(0, 2);
2655 pOp->p1 = p->aOp[0].p1;
2656 break;
2659 /* Opcode: If P1 P2 P3 * *
2661 ** Jump to P2 if the value in register P1 is true. The value
2662 ** is considered true if it is numeric and non-zero. If the value
2663 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2665 case OP_If: { /* jump, in1 */
2666 int c;
2667 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2668 VdbeBranchTaken(c!=0, 2);
2669 if( c ) goto jump_to_p2;
2670 break;
2673 /* Opcode: IfNot P1 P2 P3 * *
2675 ** Jump to P2 if the value in register P1 is False. The value
2676 ** is considered false if it has a numeric value of zero. If the value
2677 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2679 case OP_IfNot: { /* jump, in1 */
2680 int c;
2681 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2682 VdbeBranchTaken(c!=0, 2);
2683 if( c ) goto jump_to_p2;
2684 break;
2687 /* Opcode: IsNull P1 P2 * * *
2688 ** Synopsis: if r[P1]==NULL goto P2
2690 ** Jump to P2 if the value in register P1 is NULL.
2692 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2693 pIn1 = &aMem[pOp->p1];
2694 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2695 if( (pIn1->flags & MEM_Null)!=0 ){
2696 goto jump_to_p2;
2698 break;
2701 /* Opcode: IsType P1 P2 P3 P4 P5
2702 ** Synopsis: if typeof(P1.P3) in P5 goto P2
2704 ** Jump to P2 if the type of a column in a btree is one of the types specified
2705 ** by the P5 bitmask.
2707 ** P1 is normally a cursor on a btree for which the row decode cache is
2708 ** valid through at least column P3. In other words, there should have been
2709 ** a prior OP_Column for column P3 or greater. If the cursor is not valid,
2710 ** then this opcode might give spurious results.
2711 ** The the btree row has fewer than P3 columns, then use P4 as the
2712 ** datatype.
2714 ** If P1 is -1, then P3 is a register number and the datatype is taken
2715 ** from the value in that register.
2717 ** P5 is a bitmask of data types. SQLITE_INTEGER is the least significant
2718 ** (0x01) bit. SQLITE_FLOAT is the 0x02 bit. SQLITE_TEXT is 0x04.
2719 ** SQLITE_BLOB is 0x08. SQLITE_NULL is 0x10.
2721 ** WARNING: This opcode does not reliably distinguish between NULL and REAL
2722 ** when P1>=0. If the database contains a NaN value, this opcode will think
2723 ** that the datatype is REAL when it should be NULL. When P1<0 and the value
2724 ** is already stored in register P3, then this opcode does reliably
2725 ** distinguish between NULL and REAL. The problem only arises then P1>=0.
2727 ** Take the jump to address P2 if and only if the datatype of the
2728 ** value determined by P1 and P3 corresponds to one of the bits in the
2729 ** P5 bitmask.
2732 case OP_IsType: { /* jump */
2733 VdbeCursor *pC;
2734 u16 typeMask;
2735 u32 serialType;
2737 assert( pOp->p1>=(-1) && pOp->p1<p->nCursor );
2738 assert( pOp->p1>=0 || (pOp->p3>=0 && pOp->p3<=(p->nMem+1 - p->nCursor)) );
2739 if( pOp->p1>=0 ){
2740 pC = p->apCsr[pOp->p1];
2741 assert( pC!=0 );
2742 assert( pOp->p3>=0 );
2743 if( pOp->p3<pC->nHdrParsed ){
2744 serialType = pC->aType[pOp->p3];
2745 if( serialType>=12 ){
2746 if( serialType&1 ){
2747 typeMask = 0x04; /* SQLITE_TEXT */
2748 }else{
2749 typeMask = 0x08; /* SQLITE_BLOB */
2751 }else{
2752 static const unsigned char aMask[] = {
2753 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2,
2754 0x01, 0x01, 0x10, 0x10
2756 testcase( serialType==0 );
2757 testcase( serialType==1 );
2758 testcase( serialType==2 );
2759 testcase( serialType==3 );
2760 testcase( serialType==4 );
2761 testcase( serialType==5 );
2762 testcase( serialType==6 );
2763 testcase( serialType==7 );
2764 testcase( serialType==8 );
2765 testcase( serialType==9 );
2766 testcase( serialType==10 );
2767 testcase( serialType==11 );
2768 typeMask = aMask[serialType];
2770 }else{
2771 typeMask = 1 << (pOp->p4.i - 1);
2772 testcase( typeMask==0x01 );
2773 testcase( typeMask==0x02 );
2774 testcase( typeMask==0x04 );
2775 testcase( typeMask==0x08 );
2776 testcase( typeMask==0x10 );
2778 }else{
2779 assert( memIsValid(&aMem[pOp->p3]) );
2780 typeMask = 1 << (sqlite3_value_type((sqlite3_value*)&aMem[pOp->p3])-1);
2781 testcase( typeMask==0x01 );
2782 testcase( typeMask==0x02 );
2783 testcase( typeMask==0x04 );
2784 testcase( typeMask==0x08 );
2785 testcase( typeMask==0x10 );
2787 VdbeBranchTaken( (typeMask & pOp->p5)!=0, 2);
2788 if( typeMask & pOp->p5 ){
2789 goto jump_to_p2;
2791 break;
2794 /* Opcode: ZeroOrNull P1 P2 P3 * *
2795 ** Synopsis: r[P2] = 0 OR NULL
2797 ** If both registers P1 and P3 are NOT NULL, then store a zero in
2798 ** register P2. If either registers P1 or P3 are NULL then put
2799 ** a NULL in register P2.
2801 case OP_ZeroOrNull: { /* in1, in2, out2, in3 */
2802 if( (aMem[pOp->p1].flags & MEM_Null)!=0
2803 || (aMem[pOp->p3].flags & MEM_Null)!=0
2805 sqlite3VdbeMemSetNull(aMem + pOp->p2);
2806 }else{
2807 sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
2809 break;
2812 /* Opcode: NotNull P1 P2 * * *
2813 ** Synopsis: if r[P1]!=NULL goto P2
2815 ** Jump to P2 if the value in register P1 is not NULL.
2817 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2818 pIn1 = &aMem[pOp->p1];
2819 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2820 if( (pIn1->flags & MEM_Null)==0 ){
2821 goto jump_to_p2;
2823 break;
2826 /* Opcode: IfNullRow P1 P2 P3 * *
2827 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2829 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2830 ** If it is, then set register P3 to NULL and jump immediately to P2.
2831 ** If P1 is not on a NULL row, then fall through without making any
2832 ** changes.
2834 ** If P1 is not an open cursor, then this opcode is a no-op.
2836 case OP_IfNullRow: { /* jump */
2837 VdbeCursor *pC;
2838 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2839 pC = p->apCsr[pOp->p1];
2840 if( pC && pC->nullRow ){
2841 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2842 goto jump_to_p2;
2844 break;
2847 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2848 /* Opcode: Offset P1 P2 P3 * *
2849 ** Synopsis: r[P3] = sqlite_offset(P1)
2851 ** Store in register r[P3] the byte offset into the database file that is the
2852 ** start of the payload for the record at which that cursor P1 is currently
2853 ** pointing.
2855 ** P2 is the column number for the argument to the sqlite_offset() function.
2856 ** This opcode does not use P2 itself, but the P2 value is used by the
2857 ** code generator. The P1, P2, and P3 operands to this opcode are the
2858 ** same as for OP_Column.
2860 ** This opcode is only available if SQLite is compiled with the
2861 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2863 case OP_Offset: { /* out3 */
2864 VdbeCursor *pC; /* The VDBE cursor */
2865 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2866 pC = p->apCsr[pOp->p1];
2867 pOut = &p->aMem[pOp->p3];
2868 if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
2869 sqlite3VdbeMemSetNull(pOut);
2870 }else{
2871 if( pC->deferredMoveto ){
2872 rc = sqlite3VdbeFinishMoveto(pC);
2873 if( rc ) goto abort_due_to_error;
2875 if( sqlite3BtreeEof(pC->uc.pCursor) ){
2876 sqlite3VdbeMemSetNull(pOut);
2877 }else{
2878 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2881 break;
2883 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2885 /* Opcode: Column P1 P2 P3 P4 P5
2886 ** Synopsis: r[P3]=PX cursor P1 column P2
2888 ** Interpret the data that cursor P1 points to as a structure built using
2889 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2890 ** information about the format of the data.) Extract the P2-th column
2891 ** from this record. If there are less than (P2+1)
2892 ** values in the record, extract a NULL.
2894 ** The value extracted is stored in register P3.
2896 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2897 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2898 ** the result.
2900 ** If the OPFLAG_LENGTHARG bit is set in P5 then the result is guaranteed
2901 ** to only be used by the length() function or the equivalent. The content
2902 ** of large blobs is not loaded, thus saving CPU cycles. If the
2903 ** OPFLAG_TYPEOFARG bit is set then the result will only be used by the
2904 ** typeof() function or the IS NULL or IS NOT NULL operators or the
2905 ** equivalent. In this case, all content loading can be omitted.
2907 case OP_Column: { /* ncycle */
2908 u32 p2; /* column number to retrieve */
2909 VdbeCursor *pC; /* The VDBE cursor */
2910 BtCursor *pCrsr; /* The B-Tree cursor corresponding to pC */
2911 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2912 int len; /* The length of the serialized data for the column */
2913 int i; /* Loop counter */
2914 Mem *pDest; /* Where to write the extracted value */
2915 Mem sMem; /* For storing the record being decoded */
2916 const u8 *zData; /* Part of the record being decoded */
2917 const u8 *zHdr; /* Next unparsed byte of the header */
2918 const u8 *zEndHdr; /* Pointer to first byte after the header */
2919 u64 offset64; /* 64-bit offset */
2920 u32 t; /* A type code from the record header */
2921 Mem *pReg; /* PseudoTable input register */
2923 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2924 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2925 pC = p->apCsr[pOp->p1];
2926 p2 = (u32)pOp->p2;
2928 op_column_restart:
2929 assert( pC!=0 );
2930 assert( p2<(u32)pC->nField
2931 || (pC->eCurType==CURTYPE_PSEUDO && pC->seekResult==0) );
2932 aOffset = pC->aOffset;
2933 assert( aOffset==pC->aType+pC->nField );
2934 assert( pC->eCurType!=CURTYPE_VTAB );
2935 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2936 assert( pC->eCurType!=CURTYPE_SORTER );
2938 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2939 if( pC->nullRow ){
2940 if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
2941 /* For the special case of as pseudo-cursor, the seekResult field
2942 ** identifies the register that holds the record */
2943 pReg = &aMem[pC->seekResult];
2944 assert( pReg->flags & MEM_Blob );
2945 assert( memIsValid(pReg) );
2946 pC->payloadSize = pC->szRow = pReg->n;
2947 pC->aRow = (u8*)pReg->z;
2948 }else{
2949 pDest = &aMem[pOp->p3];
2950 memAboutToChange(p, pDest);
2951 sqlite3VdbeMemSetNull(pDest);
2952 goto op_column_out;
2954 }else{
2955 pCrsr = pC->uc.pCursor;
2956 if( pC->deferredMoveto ){
2957 u32 iMap;
2958 assert( !pC->isEphemeral );
2959 if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0 ){
2960 pC = pC->pAltCursor;
2961 p2 = iMap - 1;
2962 goto op_column_restart;
2964 rc = sqlite3VdbeFinishMoveto(pC);
2965 if( rc ) goto abort_due_to_error;
2966 }else if( sqlite3BtreeCursorHasMoved(pCrsr) ){
2967 rc = sqlite3VdbeHandleMovedCursor(pC);
2968 if( rc ) goto abort_due_to_error;
2969 goto op_column_restart;
2971 assert( pC->eCurType==CURTYPE_BTREE );
2972 assert( pCrsr );
2973 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2974 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2975 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2976 assert( pC->szRow<=pC->payloadSize );
2977 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2979 pC->cacheStatus = p->cacheCtr;
2980 if( (aOffset[0] = pC->aRow[0])<0x80 ){
2981 pC->iHdrOffset = 1;
2982 }else{
2983 pC->iHdrOffset = sqlite3GetVarint32(pC->aRow, aOffset);
2985 pC->nHdrParsed = 0;
2987 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2988 /* pC->aRow does not have to hold the entire row, but it does at least
2989 ** need to cover the header of the record. If pC->aRow does not contain
2990 ** the complete header, then set it to zero, forcing the header to be
2991 ** dynamically allocated. */
2992 pC->aRow = 0;
2993 pC->szRow = 0;
2995 /* Make sure a corrupt database has not given us an oversize header.
2996 ** Do this now to avoid an oversize memory allocation.
2998 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2999 ** types use so much data space that there can only be 4096 and 32 of
3000 ** them, respectively. So the maximum header length results from a
3001 ** 3-byte type for each of the maximum of 32768 columns plus three
3002 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
3004 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
3005 goto op_column_corrupt;
3007 }else{
3008 /* This is an optimization. By skipping over the first few tests
3009 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
3010 ** measurable performance gain.
3012 ** This branch is taken even if aOffset[0]==0. Such a record is never
3013 ** generated by SQLite, and could be considered corruption, but we
3014 ** accept it for historical reasons. When aOffset[0]==0, the code this
3015 ** branch jumps to reads past the end of the record, but never more
3016 ** than a few bytes. Even if the record occurs at the end of the page
3017 ** content area, the "page header" comes after the page content and so
3018 ** this overread is harmless. Similar overreads can occur for a corrupt
3019 ** database file.
3021 zData = pC->aRow;
3022 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
3023 testcase( aOffset[0]==0 );
3024 goto op_column_read_header;
3026 }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
3027 rc = sqlite3VdbeHandleMovedCursor(pC);
3028 if( rc ) goto abort_due_to_error;
3029 goto op_column_restart;
3032 /* Make sure at least the first p2+1 entries of the header have been
3033 ** parsed and valid information is in aOffset[] and pC->aType[].
3035 if( pC->nHdrParsed<=p2 ){
3036 /* If there is more header available for parsing in the record, try
3037 ** to extract additional fields up through the p2+1-th field
3039 if( pC->iHdrOffset<aOffset[0] ){
3040 /* Make sure zData points to enough of the record to cover the header. */
3041 if( pC->aRow==0 ){
3042 memset(&sMem, 0, sizeof(sMem));
3043 rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
3044 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3045 zData = (u8*)sMem.z;
3046 }else{
3047 zData = pC->aRow;
3050 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
3051 op_column_read_header:
3052 i = pC->nHdrParsed;
3053 offset64 = aOffset[i];
3054 zHdr = zData + pC->iHdrOffset;
3055 zEndHdr = zData + aOffset[0];
3056 testcase( zHdr>=zEndHdr );
3058 if( (pC->aType[i] = t = zHdr[0])<0x80 ){
3059 zHdr++;
3060 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
3061 }else{
3062 zHdr += sqlite3GetVarint32(zHdr, &t);
3063 pC->aType[i] = t;
3064 offset64 += sqlite3VdbeSerialTypeLen(t);
3066 aOffset[++i] = (u32)(offset64 & 0xffffffff);
3067 }while( (u32)i<=p2 && zHdr<zEndHdr );
3069 /* The record is corrupt if any of the following are true:
3070 ** (1) the bytes of the header extend past the declared header size
3071 ** (2) the entire header was used but not all data was used
3072 ** (3) the end of the data extends beyond the end of the record.
3074 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
3075 || (offset64 > pC->payloadSize)
3077 if( aOffset[0]==0 ){
3078 i = 0;
3079 zHdr = zEndHdr;
3080 }else{
3081 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
3082 goto op_column_corrupt;
3086 pC->nHdrParsed = i;
3087 pC->iHdrOffset = (u32)(zHdr - zData);
3088 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
3089 }else{
3090 t = 0;
3093 /* If after trying to extract new entries from the header, nHdrParsed is
3094 ** still not up to p2, that means that the record has fewer than p2
3095 ** columns. So the result will be either the default value or a NULL.
3097 if( pC->nHdrParsed<=p2 ){
3098 pDest = &aMem[pOp->p3];
3099 memAboutToChange(p, pDest);
3100 if( pOp->p4type==P4_MEM ){
3101 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
3102 }else{
3103 sqlite3VdbeMemSetNull(pDest);
3105 goto op_column_out;
3107 }else{
3108 t = pC->aType[p2];
3111 /* Extract the content for the p2+1-th column. Control can only
3112 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
3113 ** all valid.
3115 assert( p2<pC->nHdrParsed );
3116 assert( rc==SQLITE_OK );
3117 pDest = &aMem[pOp->p3];
3118 memAboutToChange(p, pDest);
3119 assert( sqlite3VdbeCheckMemInvariants(pDest) );
3120 if( VdbeMemDynamic(pDest) ){
3121 sqlite3VdbeMemSetNull(pDest);
3123 assert( t==pC->aType[p2] );
3124 if( pC->szRow>=aOffset[p2+1] ){
3125 /* This is the common case where the desired content fits on the original
3126 ** page - where the content is not on an overflow page */
3127 zData = pC->aRow + aOffset[p2];
3128 if( t<12 ){
3129 sqlite3VdbeSerialGet(zData, t, pDest);
3130 }else{
3131 /* If the column value is a string, we need a persistent value, not
3132 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
3133 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
3135 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
3136 pDest->n = len = (t-12)/2;
3137 pDest->enc = encoding;
3138 if( pDest->szMalloc < len+2 ){
3139 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
3140 pDest->flags = MEM_Null;
3141 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
3142 }else{
3143 pDest->z = pDest->zMalloc;
3145 memcpy(pDest->z, zData, len);
3146 pDest->z[len] = 0;
3147 pDest->z[len+1] = 0;
3148 pDest->flags = aFlag[t&1];
3150 }else{
3151 u8 p5;
3152 pDest->enc = encoding;
3153 assert( pDest->db==db );
3154 /* This branch happens only when content is on overflow pages */
3155 if( ((p5 = (pOp->p5 & OPFLAG_BYTELENARG))!=0
3156 && (p5==OPFLAG_TYPEOFARG
3157 || (t>=12 && ((t&1)==0 || p5==OPFLAG_BYTELENARG))
3160 || sqlite3VdbeSerialTypeLen(t)==0
3162 /* Content is irrelevant for
3163 ** 1. the typeof() function,
3164 ** 2. the length(X) function if X is a blob, and
3165 ** 3. if the content length is zero.
3166 ** So we might as well use bogus content rather than reading
3167 ** content from disk.
3169 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
3170 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
3171 ** read more. Use the global constant sqlite3CtypeMap[] as the array,
3172 ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
3173 ** and it begins with a bunch of zeros.
3175 sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
3176 }else{
3177 rc = vdbeColumnFromOverflow(pC, p2, t, aOffset[p2],
3178 p->cacheCtr, colCacheCtr, pDest);
3179 if( rc ){
3180 if( rc==SQLITE_NOMEM ) goto no_mem;
3181 if( rc==SQLITE_TOOBIG ) goto too_big;
3182 goto abort_due_to_error;
3187 op_column_out:
3188 UPDATE_MAX_BLOBSIZE(pDest);
3189 REGISTER_TRACE(pOp->p3, pDest);
3190 break;
3192 op_column_corrupt:
3193 if( aOp[0].p3>0 ){
3194 pOp = &aOp[aOp[0].p3-1];
3195 break;
3196 }else{
3197 rc = SQLITE_CORRUPT_BKPT;
3198 goto abort_due_to_error;
3202 /* Opcode: TypeCheck P1 P2 P3 P4 *
3203 ** Synopsis: typecheck(r[P1@P2])
3205 ** Apply affinities to the range of P2 registers beginning with P1.
3206 ** Take the affinities from the Table object in P4. If any value
3207 ** cannot be coerced into the correct type, then raise an error.
3209 ** This opcode is similar to OP_Affinity except that this opcode
3210 ** forces the register type to the Table column type. This is used
3211 ** to implement "strict affinity".
3213 ** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
3214 ** is zero. When P3 is non-zero, no type checking occurs for
3215 ** static generated columns. Virtual columns are computed at query time
3216 ** and so they are never checked.
3218 ** Preconditions:
3220 ** <ul>
3221 ** <li> P2 should be the number of non-virtual columns in the
3222 ** table of P4.
3223 ** <li> Table P4 should be a STRICT table.
3224 ** </ul>
3226 ** If any precondition is false, an assertion fault occurs.
3228 case OP_TypeCheck: {
3229 Table *pTab;
3230 Column *aCol;
3231 int i;
3233 assert( pOp->p4type==P4_TABLE );
3234 pTab = pOp->p4.pTab;
3235 assert( pTab->tabFlags & TF_Strict );
3236 assert( pTab->nNVCol==pOp->p2 );
3237 aCol = pTab->aCol;
3238 pIn1 = &aMem[pOp->p1];
3239 for(i=0; i<pTab->nCol; i++){
3240 if( aCol[i].colFlags & COLFLAG_GENERATED ){
3241 if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
3242 if( pOp->p3 ){ pIn1++; continue; }
3244 assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
3245 applyAffinity(pIn1, aCol[i].affinity, encoding);
3246 if( (pIn1->flags & MEM_Null)==0 ){
3247 switch( aCol[i].eCType ){
3248 case COLTYPE_BLOB: {
3249 if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
3250 break;
3252 case COLTYPE_INTEGER:
3253 case COLTYPE_INT: {
3254 if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
3255 break;
3257 case COLTYPE_TEXT: {
3258 if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
3259 break;
3261 case COLTYPE_REAL: {
3262 testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
3263 assert( (pIn1->flags & MEM_IntReal)==0 );
3264 if( pIn1->flags & MEM_Int ){
3265 /* When applying REAL affinity, if the result is still an MEM_Int
3266 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3267 ** so that we keep the high-resolution integer value but know that
3268 ** the type really wants to be REAL. */
3269 testcase( pIn1->u.i==140737488355328LL );
3270 testcase( pIn1->u.i==140737488355327LL );
3271 testcase( pIn1->u.i==-140737488355328LL );
3272 testcase( pIn1->u.i==-140737488355329LL );
3273 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
3274 pIn1->flags |= MEM_IntReal;
3275 pIn1->flags &= ~MEM_Int;
3276 }else{
3277 pIn1->u.r = (double)pIn1->u.i;
3278 pIn1->flags |= MEM_Real;
3279 pIn1->flags &= ~MEM_Int;
3281 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
3282 goto vdbe_type_error;
3284 break;
3286 default: {
3287 /* COLTYPE_ANY. Accept anything. */
3288 break;
3292 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3293 pIn1++;
3295 assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
3296 break;
3298 vdbe_type_error:
3299 sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
3300 vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
3301 pTab->zName, aCol[i].zCnName);
3302 rc = SQLITE_CONSTRAINT_DATATYPE;
3303 goto abort_due_to_error;
3306 /* Opcode: Affinity P1 P2 * P4 *
3307 ** Synopsis: affinity(r[P1@P2])
3309 ** Apply affinities to a range of P2 registers starting with P1.
3311 ** P4 is a string that is P2 characters long. The N-th character of the
3312 ** string indicates the column affinity that should be used for the N-th
3313 ** memory cell in the range.
3315 case OP_Affinity: {
3316 const char *zAffinity; /* The affinity to be applied */
3318 zAffinity = pOp->p4.z;
3319 assert( zAffinity!=0 );
3320 assert( pOp->p2>0 );
3321 assert( zAffinity[pOp->p2]==0 );
3322 pIn1 = &aMem[pOp->p1];
3323 while( 1 /*exit-by-break*/ ){
3324 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
3325 assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
3326 applyAffinity(pIn1, zAffinity[0], encoding);
3327 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
3328 /* When applying REAL affinity, if the result is still an MEM_Int
3329 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3330 ** so that we keep the high-resolution integer value but know that
3331 ** the type really wants to be REAL. */
3332 testcase( pIn1->u.i==140737488355328LL );
3333 testcase( pIn1->u.i==140737488355327LL );
3334 testcase( pIn1->u.i==-140737488355328LL );
3335 testcase( pIn1->u.i==-140737488355329LL );
3336 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
3337 pIn1->flags |= MEM_IntReal;
3338 pIn1->flags &= ~MEM_Int;
3339 }else{
3340 pIn1->u.r = (double)pIn1->u.i;
3341 pIn1->flags |= MEM_Real;
3342 pIn1->flags &= ~(MEM_Int|MEM_Str);
3345 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3346 zAffinity++;
3347 if( zAffinity[0]==0 ) break;
3348 pIn1++;
3350 break;
3353 /* Opcode: MakeRecord P1 P2 P3 P4 *
3354 ** Synopsis: r[P3]=mkrec(r[P1@P2])
3356 ** Convert P2 registers beginning with P1 into the [record format]
3357 ** use as a data record in a database table or as a key
3358 ** in an index. The OP_Column opcode can decode the record later.
3360 ** P4 may be a string that is P2 characters long. The N-th character of the
3361 ** string indicates the column affinity that should be used for the N-th
3362 ** field of the index key.
3364 ** The mapping from character to affinity is given by the SQLITE_AFF_
3365 ** macros defined in sqliteInt.h.
3367 ** If P4 is NULL then all index fields have the affinity BLOB.
3369 ** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
3370 ** compile-time option is enabled:
3372 ** * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
3373 ** of the right-most table that can be null-trimmed.
3375 ** * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
3376 ** OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
3377 ** accept no-change records with serial_type 10. This value is
3378 ** only used inside an assert() and does not affect the end result.
3380 case OP_MakeRecord: {
3381 Mem *pRec; /* The new record */
3382 u64 nData; /* Number of bytes of data space */
3383 int nHdr; /* Number of bytes of header space */
3384 i64 nByte; /* Data space required for this record */
3385 i64 nZero; /* Number of zero bytes at the end of the record */
3386 int nVarint; /* Number of bytes in a varint */
3387 u32 serial_type; /* Type field */
3388 Mem *pData0; /* First field to be combined into the record */
3389 Mem *pLast; /* Last field of the record */
3390 int nField; /* Number of fields in the record */
3391 char *zAffinity; /* The affinity string for the record */
3392 u32 len; /* Length of a field */
3393 u8 *zHdr; /* Where to write next byte of the header */
3394 u8 *zPayload; /* Where to write next byte of the payload */
3396 /* Assuming the record contains N fields, the record format looks
3397 ** like this:
3399 ** ------------------------------------------------------------------------
3400 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
3401 ** ------------------------------------------------------------------------
3403 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
3404 ** and so forth.
3406 ** Each type field is a varint representing the serial type of the
3407 ** corresponding data element (see sqlite3VdbeSerialType()). The
3408 ** hdr-size field is also a varint which is the offset from the beginning
3409 ** of the record to data0.
3411 nData = 0; /* Number of bytes of data space */
3412 nHdr = 0; /* Number of bytes of header space */
3413 nZero = 0; /* Number of zero bytes at the end of the record */
3414 nField = pOp->p1;
3415 zAffinity = pOp->p4.z;
3416 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
3417 pData0 = &aMem[nField];
3418 nField = pOp->p2;
3419 pLast = &pData0[nField-1];
3421 /* Identify the output register */
3422 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
3423 pOut = &aMem[pOp->p3];
3424 memAboutToChange(p, pOut);
3426 /* Apply the requested affinity to all inputs
3428 assert( pData0<=pLast );
3429 if( zAffinity ){
3430 pRec = pData0;
3432 applyAffinity(pRec, zAffinity[0], encoding);
3433 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
3434 pRec->flags |= MEM_IntReal;
3435 pRec->flags &= ~(MEM_Int);
3437 REGISTER_TRACE((int)(pRec-aMem), pRec);
3438 zAffinity++;
3439 pRec++;
3440 assert( zAffinity[0]==0 || pRec<=pLast );
3441 }while( zAffinity[0] );
3444 #ifdef SQLITE_ENABLE_NULL_TRIM
3445 /* NULLs can be safely trimmed from the end of the record, as long as
3446 ** as the schema format is 2 or more and none of the omitted columns
3447 ** have a non-NULL default value. Also, the record must be left with
3448 ** at least one field. If P5>0 then it will be one more than the
3449 ** index of the right-most column with a non-NULL default value */
3450 if( pOp->p5 ){
3451 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
3452 pLast--;
3453 nField--;
3456 #endif
3458 /* Loop through the elements that will make up the record to figure
3459 ** out how much space is required for the new record. After this loop,
3460 ** the Mem.uTemp field of each term should hold the serial-type that will
3461 ** be used for that term in the generated record:
3463 ** Mem.uTemp value type
3464 ** --------------- ---------------
3465 ** 0 NULL
3466 ** 1 1-byte signed integer
3467 ** 2 2-byte signed integer
3468 ** 3 3-byte signed integer
3469 ** 4 4-byte signed integer
3470 ** 5 6-byte signed integer
3471 ** 6 8-byte signed integer
3472 ** 7 IEEE float
3473 ** 8 Integer constant 0
3474 ** 9 Integer constant 1
3475 ** 10,11 reserved for expansion
3476 ** N>=12 and even BLOB
3477 ** N>=13 and odd text
3479 ** The following additional values are computed:
3480 ** nHdr Number of bytes needed for the record header
3481 ** nData Number of bytes of data space needed for the record
3482 ** nZero Zero bytes at the end of the record
3484 pRec = pLast;
3486 assert( memIsValid(pRec) );
3487 if( pRec->flags & MEM_Null ){
3488 if( pRec->flags & MEM_Zero ){
3489 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
3490 ** table methods that never invoke sqlite3_result_xxxxx() while
3491 ** computing an unchanging column value in an UPDATE statement.
3492 ** Give such values a special internal-use-only serial-type of 10
3493 ** so that they can be passed through to xUpdate and have
3494 ** a true sqlite3_value_nochange(). */
3495 #ifndef SQLITE_ENABLE_NULL_TRIM
3496 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
3497 #endif
3498 pRec->uTemp = 10;
3499 }else{
3500 pRec->uTemp = 0;
3502 nHdr++;
3503 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
3504 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3505 i64 i = pRec->u.i;
3506 u64 uu;
3507 testcase( pRec->flags & MEM_Int );
3508 testcase( pRec->flags & MEM_IntReal );
3509 if( i<0 ){
3510 uu = ~i;
3511 }else{
3512 uu = i;
3514 nHdr++;
3515 testcase( uu==127 ); testcase( uu==128 );
3516 testcase( uu==32767 ); testcase( uu==32768 );
3517 testcase( uu==8388607 ); testcase( uu==8388608 );
3518 testcase( uu==2147483647 ); testcase( uu==2147483648LL );
3519 testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
3520 if( uu<=127 ){
3521 if( (i&1)==i && p->minWriteFileFormat>=4 ){
3522 pRec->uTemp = 8+(u32)uu;
3523 }else{
3524 nData++;
3525 pRec->uTemp = 1;
3527 }else if( uu<=32767 ){
3528 nData += 2;
3529 pRec->uTemp = 2;
3530 }else if( uu<=8388607 ){
3531 nData += 3;
3532 pRec->uTemp = 3;
3533 }else if( uu<=2147483647 ){
3534 nData += 4;
3535 pRec->uTemp = 4;
3536 }else if( uu<=140737488355327LL ){
3537 nData += 6;
3538 pRec->uTemp = 5;
3539 }else{
3540 nData += 8;
3541 if( pRec->flags & MEM_IntReal ){
3542 /* If the value is IntReal and is going to take up 8 bytes to store
3543 ** as an integer, then we might as well make it an 8-byte floating
3544 ** point value */
3545 pRec->u.r = (double)pRec->u.i;
3546 pRec->flags &= ~MEM_IntReal;
3547 pRec->flags |= MEM_Real;
3548 pRec->uTemp = 7;
3549 }else{
3550 pRec->uTemp = 6;
3553 }else if( pRec->flags & MEM_Real ){
3554 nHdr++;
3555 nData += 8;
3556 pRec->uTemp = 7;
3557 }else{
3558 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
3559 assert( pRec->n>=0 );
3560 len = (u32)pRec->n;
3561 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
3562 if( pRec->flags & MEM_Zero ){
3563 serial_type += pRec->u.nZero*2;
3564 if( nData ){
3565 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
3566 len += pRec->u.nZero;
3567 }else{
3568 nZero += pRec->u.nZero;
3571 nData += len;
3572 nHdr += sqlite3VarintLen(serial_type);
3573 pRec->uTemp = serial_type;
3575 if( pRec==pData0 ) break;
3576 pRec--;
3577 }while(1);
3579 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
3580 ** which determines the total number of bytes in the header. The varint
3581 ** value is the size of the header in bytes including the size varint
3582 ** itself. */
3583 testcase( nHdr==126 );
3584 testcase( nHdr==127 );
3585 if( nHdr<=126 ){
3586 /* The common case */
3587 nHdr += 1;
3588 }else{
3589 /* Rare case of a really large header */
3590 nVarint = sqlite3VarintLen(nHdr);
3591 nHdr += nVarint;
3592 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
3594 nByte = nHdr+nData;
3596 /* Make sure the output register has a buffer large enough to store
3597 ** the new record. The output register (pOp->p3) is not allowed to
3598 ** be one of the input registers (because the following call to
3599 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
3601 if( nByte+nZero<=pOut->szMalloc ){
3602 /* The output register is already large enough to hold the record.
3603 ** No error checks or buffer enlargement is required */
3604 pOut->z = pOut->zMalloc;
3605 }else{
3606 /* Need to make sure that the output is not too big and then enlarge
3607 ** the output register to hold the full result */
3608 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3609 goto too_big;
3611 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
3612 goto no_mem;
3615 pOut->n = (int)nByte;
3616 pOut->flags = MEM_Blob;
3617 if( nZero ){
3618 pOut->u.nZero = nZero;
3619 pOut->flags |= MEM_Zero;
3621 UPDATE_MAX_BLOBSIZE(pOut);
3622 zHdr = (u8 *)pOut->z;
3623 zPayload = zHdr + nHdr;
3625 /* Write the record */
3626 if( nHdr<0x80 ){
3627 *(zHdr++) = nHdr;
3628 }else{
3629 zHdr += sqlite3PutVarint(zHdr,nHdr);
3631 assert( pData0<=pLast );
3632 pRec = pData0;
3633 while( 1 /*exit-by-break*/ ){
3634 serial_type = pRec->uTemp;
3635 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
3636 ** additional varints, one per column.
3637 ** EVIDENCE-OF: R-64536-51728 The values for each column in the record
3638 ** immediately follow the header. */
3639 if( serial_type<=7 ){
3640 *(zHdr++) = serial_type;
3641 if( serial_type==0 ){
3642 /* NULL value. No change in zPayload */
3643 }else{
3644 u64 v;
3645 if( serial_type==7 ){
3646 assert( sizeof(v)==sizeof(pRec->u.r) );
3647 memcpy(&v, &pRec->u.r, sizeof(v));
3648 swapMixedEndianFloat(v);
3649 }else{
3650 v = pRec->u.i;
3652 len = sqlite3SmallTypeSizes[serial_type];
3653 assert( len>=1 && len<=8 && len!=5 && len!=7 );
3654 switch( len ){
3655 default: zPayload[7] = (u8)(v&0xff); v >>= 8;
3656 zPayload[6] = (u8)(v&0xff); v >>= 8;
3657 /* no break */ deliberate_fall_through
3658 case 6: zPayload[5] = (u8)(v&0xff); v >>= 8;
3659 zPayload[4] = (u8)(v&0xff); v >>= 8;
3660 /* no break */ deliberate_fall_through
3661 case 4: zPayload[3] = (u8)(v&0xff); v >>= 8;
3662 /* no break */ deliberate_fall_through
3663 case 3: zPayload[2] = (u8)(v&0xff); v >>= 8;
3664 /* no break */ deliberate_fall_through
3665 case 2: zPayload[1] = (u8)(v&0xff); v >>= 8;
3666 /* no break */ deliberate_fall_through
3667 case 1: zPayload[0] = (u8)(v&0xff);
3669 zPayload += len;
3671 }else if( serial_type<0x80 ){
3672 *(zHdr++) = serial_type;
3673 if( serial_type>=14 && pRec->n>0 ){
3674 assert( pRec->z!=0 );
3675 memcpy(zPayload, pRec->z, pRec->n);
3676 zPayload += pRec->n;
3678 }else{
3679 zHdr += sqlite3PutVarint(zHdr, serial_type);
3680 if( pRec->n ){
3681 assert( pRec->z!=0 );
3682 memcpy(zPayload, pRec->z, pRec->n);
3683 zPayload += pRec->n;
3686 if( pRec==pLast ) break;
3687 pRec++;
3689 assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
3690 assert( nByte==(int)(zPayload - (u8*)pOut->z) );
3692 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
3693 REGISTER_TRACE(pOp->p3, pOut);
3694 break;
3697 /* Opcode: Count P1 P2 P3 * *
3698 ** Synopsis: r[P2]=count()
3700 ** Store the number of entries (an integer value) in the table or index
3701 ** opened by cursor P1 in register P2.
3703 ** If P3==0, then an exact count is obtained, which involves visiting
3704 ** every btree page of the table. But if P3 is non-zero, an estimate
3705 ** is returned based on the current cursor position.
3707 case OP_Count: { /* out2 */
3708 i64 nEntry;
3709 BtCursor *pCrsr;
3711 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
3712 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
3713 assert( pCrsr );
3714 if( pOp->p3 ){
3715 nEntry = sqlite3BtreeRowCountEst(pCrsr);
3716 }else{
3717 nEntry = 0; /* Not needed. Only used to silence a warning. */
3718 rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
3719 if( rc ) goto abort_due_to_error;
3721 pOut = out2Prerelease(p, pOp);
3722 pOut->u.i = nEntry;
3723 goto check_for_interrupt;
3726 /* Opcode: Savepoint P1 * * P4 *
3728 ** Open, release or rollback the savepoint named by parameter P4, depending
3729 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
3730 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
3731 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
3733 case OP_Savepoint: {
3734 int p1; /* Value of P1 operand */
3735 char *zName; /* Name of savepoint */
3736 int nName;
3737 Savepoint *pNew;
3738 Savepoint *pSavepoint;
3739 Savepoint *pTmp;
3740 int iSavepoint;
3741 int ii;
3743 p1 = pOp->p1;
3744 zName = pOp->p4.z;
3746 /* Assert that the p1 parameter is valid. Also that if there is no open
3747 ** transaction, then there cannot be any savepoints.
3749 assert( db->pSavepoint==0 || db->autoCommit==0 );
3750 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
3751 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
3752 assert( checkSavepointCount(db) );
3753 assert( p->bIsReader );
3755 if( p1==SAVEPOINT_BEGIN ){
3756 if( db->nVdbeWrite>0 ){
3757 /* A new savepoint cannot be created if there are active write
3758 ** statements (i.e. open read/write incremental blob handles).
3760 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
3761 rc = SQLITE_BUSY;
3762 }else{
3763 nName = sqlite3Strlen30(zName);
3765 #ifndef SQLITE_OMIT_VIRTUALTABLE
3766 /* This call is Ok even if this savepoint is actually a transaction
3767 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3768 ** If this is a transaction savepoint being opened, it is guaranteed
3769 ** that the db->aVTrans[] array is empty. */
3770 assert( db->autoCommit==0 || db->nVTrans==0 );
3771 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
3772 db->nStatement+db->nSavepoint);
3773 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3774 #endif
3776 /* Create a new savepoint structure. */
3777 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
3778 if( pNew ){
3779 pNew->zName = (char *)&pNew[1];
3780 memcpy(pNew->zName, zName, nName+1);
3782 /* If there is no open transaction, then mark this as a special
3783 ** "transaction savepoint". */
3784 if( db->autoCommit ){
3785 db->autoCommit = 0;
3786 db->isTransactionSavepoint = 1;
3787 }else{
3788 db->nSavepoint++;
3791 /* Link the new savepoint into the database handle's list. */
3792 pNew->pNext = db->pSavepoint;
3793 db->pSavepoint = pNew;
3794 pNew->nDeferredCons = db->nDeferredCons;
3795 pNew->nDeferredImmCons = db->nDeferredImmCons;
3798 }else{
3799 assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
3800 iSavepoint = 0;
3802 /* Find the named savepoint. If there is no such savepoint, then an
3803 ** an error is returned to the user. */
3804 for(
3805 pSavepoint = db->pSavepoint;
3806 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3807 pSavepoint = pSavepoint->pNext
3809 iSavepoint++;
3811 if( !pSavepoint ){
3812 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3813 rc = SQLITE_ERROR;
3814 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3815 /* It is not possible to release (commit) a savepoint if there are
3816 ** active write statements.
3818 sqlite3VdbeError(p, "cannot release savepoint - "
3819 "SQL statements in progress");
3820 rc = SQLITE_BUSY;
3821 }else{
3823 /* Determine whether or not this is a transaction savepoint. If so,
3824 ** and this is a RELEASE command, then the current transaction
3825 ** is committed.
3827 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3828 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3829 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3830 goto vdbe_return;
3832 db->autoCommit = 1;
3833 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3834 p->pc = (int)(pOp - aOp);
3835 db->autoCommit = 0;
3836 p->rc = rc = SQLITE_BUSY;
3837 goto vdbe_return;
3839 rc = p->rc;
3840 if( rc ){
3841 db->autoCommit = 0;
3842 }else{
3843 db->isTransactionSavepoint = 0;
3845 }else{
3846 int isSchemaChange;
3847 iSavepoint = db->nSavepoint - iSavepoint - 1;
3848 if( p1==SAVEPOINT_ROLLBACK ){
3849 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3850 for(ii=0; ii<db->nDb; ii++){
3851 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3852 SQLITE_ABORT_ROLLBACK,
3853 isSchemaChange==0);
3854 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3856 }else{
3857 assert( p1==SAVEPOINT_RELEASE );
3858 isSchemaChange = 0;
3860 for(ii=0; ii<db->nDb; ii++){
3861 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3862 if( rc!=SQLITE_OK ){
3863 goto abort_due_to_error;
3866 if( isSchemaChange ){
3867 sqlite3ExpirePreparedStatements(db, 0);
3868 sqlite3ResetAllSchemasOfConnection(db);
3869 db->mDbFlags |= DBFLAG_SchemaChange;
3872 if( rc ) goto abort_due_to_error;
3874 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3875 ** savepoints nested inside of the savepoint being operated on. */
3876 while( db->pSavepoint!=pSavepoint ){
3877 pTmp = db->pSavepoint;
3878 db->pSavepoint = pTmp->pNext;
3879 sqlite3DbFree(db, pTmp);
3880 db->nSavepoint--;
3883 /* If it is a RELEASE, then destroy the savepoint being operated on
3884 ** too. If it is a ROLLBACK TO, then set the number of deferred
3885 ** constraint violations present in the database to the value stored
3886 ** when the savepoint was created. */
3887 if( p1==SAVEPOINT_RELEASE ){
3888 assert( pSavepoint==db->pSavepoint );
3889 db->pSavepoint = pSavepoint->pNext;
3890 sqlite3DbFree(db, pSavepoint);
3891 if( !isTransaction ){
3892 db->nSavepoint--;
3894 }else{
3895 assert( p1==SAVEPOINT_ROLLBACK );
3896 db->nDeferredCons = pSavepoint->nDeferredCons;
3897 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3900 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3901 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3902 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3906 if( rc ) goto abort_due_to_error;
3907 if( p->eVdbeState==VDBE_HALT_STATE ){
3908 rc = SQLITE_DONE;
3909 goto vdbe_return;
3911 break;
3914 /* Opcode: AutoCommit P1 P2 * * *
3916 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3917 ** back any currently active btree transactions. If there are any active
3918 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3919 ** there are active writing VMs or active VMs that use shared cache.
3921 ** This instruction causes the VM to halt.
3923 case OP_AutoCommit: {
3924 int desiredAutoCommit;
3925 int iRollback;
3927 desiredAutoCommit = pOp->p1;
3928 iRollback = pOp->p2;
3929 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3930 assert( desiredAutoCommit==1 || iRollback==0 );
3931 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3932 assert( p->bIsReader );
3934 if( desiredAutoCommit!=db->autoCommit ){
3935 if( iRollback ){
3936 assert( desiredAutoCommit==1 );
3937 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3938 db->autoCommit = 1;
3939 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3940 /* If this instruction implements a COMMIT and other VMs are writing
3941 ** return an error indicating that the other VMs must complete first.
3943 sqlite3VdbeError(p, "cannot commit transaction - "
3944 "SQL statements in progress");
3945 rc = SQLITE_BUSY;
3946 goto abort_due_to_error;
3947 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3948 goto vdbe_return;
3949 }else{
3950 db->autoCommit = (u8)desiredAutoCommit;
3952 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3953 p->pc = (int)(pOp - aOp);
3954 db->autoCommit = (u8)(1-desiredAutoCommit);
3955 p->rc = rc = SQLITE_BUSY;
3956 goto vdbe_return;
3958 sqlite3CloseSavepoints(db);
3959 if( p->rc==SQLITE_OK ){
3960 rc = SQLITE_DONE;
3961 }else{
3962 rc = SQLITE_ERROR;
3964 goto vdbe_return;
3965 }else{
3966 sqlite3VdbeError(p,
3967 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3968 (iRollback)?"cannot rollback - no transaction is active":
3969 "cannot commit - no transaction is active"));
3971 rc = SQLITE_ERROR;
3972 goto abort_due_to_error;
3974 /*NOTREACHED*/ assert(0);
3977 /* Opcode: Transaction P1 P2 P3 P4 P5
3979 ** Begin a transaction on database P1 if a transaction is not already
3980 ** active.
3981 ** If P2 is non-zero, then a write-transaction is started, or if a
3982 ** read-transaction is already active, it is upgraded to a write-transaction.
3983 ** If P2 is zero, then a read-transaction is started. If P2 is 2 or more
3984 ** then an exclusive transaction is started.
3986 ** P1 is the index of the database file on which the transaction is
3987 ** started. Index 0 is the main database file and index 1 is the
3988 ** file used for temporary tables. Indices of 2 or more are used for
3989 ** attached databases.
3991 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3992 ** true (this flag is set if the Vdbe may modify more than one row and may
3993 ** throw an ABORT exception), a statement transaction may also be opened.
3994 ** More specifically, a statement transaction is opened iff the database
3995 ** connection is currently not in autocommit mode, or if there are other
3996 ** active statements. A statement transaction allows the changes made by this
3997 ** VDBE to be rolled back after an error without having to roll back the
3998 ** entire transaction. If no error is encountered, the statement transaction
3999 ** will automatically commit when the VDBE halts.
4001 ** If P5!=0 then this opcode also checks the schema cookie against P3
4002 ** and the schema generation counter against P4.
4003 ** The cookie changes its value whenever the database schema changes.
4004 ** This operation is used to detect when that the cookie has changed
4005 ** and that the current process needs to reread the schema. If the schema
4006 ** cookie in P3 differs from the schema cookie in the database header or
4007 ** if the schema generation counter in P4 differs from the current
4008 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
4009 ** halts. The sqlite3_step() wrapper function might then reprepare the
4010 ** statement and rerun it from the beginning.
4012 case OP_Transaction: {
4013 Btree *pBt;
4014 Db *pDb;
4015 int iMeta = 0;
4017 assert( p->bIsReader );
4018 assert( p->readOnly==0 || pOp->p2==0 );
4019 assert( pOp->p2>=0 && pOp->p2<=2 );
4020 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4021 assert( DbMaskTest(p->btreeMask, pOp->p1) );
4022 assert( rc==SQLITE_OK );
4023 if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
4024 if( db->flags & SQLITE_QueryOnly ){
4025 /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
4026 rc = SQLITE_READONLY;
4027 }else{
4028 /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
4029 ** transaction */
4030 rc = SQLITE_CORRUPT;
4032 goto abort_due_to_error;
4034 pDb = &db->aDb[pOp->p1];
4035 pBt = pDb->pBt;
4037 if( pBt ){
4038 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
4039 testcase( rc==SQLITE_BUSY_SNAPSHOT );
4040 testcase( rc==SQLITE_BUSY_RECOVERY );
4041 if( rc!=SQLITE_OK ){
4042 if( (rc&0xff)==SQLITE_BUSY ){
4043 p->pc = (int)(pOp - aOp);
4044 p->rc = rc;
4045 goto vdbe_return;
4047 goto abort_due_to_error;
4050 if( p->usesStmtJournal
4051 && pOp->p2
4052 && (db->autoCommit==0 || db->nVdbeRead>1)
4054 assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
4055 if( p->iStatement==0 ){
4056 assert( db->nStatement>=0 && db->nSavepoint>=0 );
4057 db->nStatement++;
4058 p->iStatement = db->nSavepoint + db->nStatement;
4061 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
4062 if( rc==SQLITE_OK ){
4063 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
4066 /* Store the current value of the database handles deferred constraint
4067 ** counter. If the statement transaction needs to be rolled back,
4068 ** the value of this counter needs to be restored too. */
4069 p->nStmtDefCons = db->nDeferredCons;
4070 p->nStmtDefImmCons = db->nDeferredImmCons;
4073 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
4074 if( rc==SQLITE_OK
4075 && pOp->p5
4076 && (iMeta!=pOp->p3 || pDb->pSchema->iGeneration!=pOp->p4.i)
4079 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
4080 ** version is checked to ensure that the schema has not changed since the
4081 ** SQL statement was prepared.
4083 sqlite3DbFree(db, p->zErrMsg);
4084 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
4085 /* If the schema-cookie from the database file matches the cookie
4086 ** stored with the in-memory representation of the schema, do
4087 ** not reload the schema from the database file.
4089 ** If virtual-tables are in use, this is not just an optimization.
4090 ** Often, v-tables store their data in other SQLite tables, which
4091 ** are queried from within xNext() and other v-table methods using
4092 ** prepared queries. If such a query is out-of-date, we do not want to
4093 ** discard the database schema, as the user code implementing the
4094 ** v-table would have to be ready for the sqlite3_vtab structure itself
4095 ** to be invalidated whenever sqlite3_step() is called from within
4096 ** a v-table method.
4098 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
4099 sqlite3ResetOneSchema(db, pOp->p1);
4101 p->expired = 1;
4102 rc = SQLITE_SCHEMA;
4104 /* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
4105 ** from being modified in sqlite3VdbeHalt(). If this statement is
4106 ** reprepared, changeCntOn will be set again. */
4107 p->changeCntOn = 0;
4109 if( rc ) goto abort_due_to_error;
4110 break;
4113 /* Opcode: ReadCookie P1 P2 P3 * *
4115 ** Read cookie number P3 from database P1 and write it into register P2.
4116 ** P3==1 is the schema version. P3==2 is the database format.
4117 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
4118 ** the main database file and P1==1 is the database file used to store
4119 ** temporary tables.
4121 ** There must be a read-lock on the database (either a transaction
4122 ** must be started or there must be an open cursor) before
4123 ** executing this instruction.
4125 case OP_ReadCookie: { /* out2 */
4126 int iMeta;
4127 int iDb;
4128 int iCookie;
4130 assert( p->bIsReader );
4131 iDb = pOp->p1;
4132 iCookie = pOp->p3;
4133 assert( pOp->p3<SQLITE_N_BTREE_META );
4134 assert( iDb>=0 && iDb<db->nDb );
4135 assert( db->aDb[iDb].pBt!=0 );
4136 assert( DbMaskTest(p->btreeMask, iDb) );
4138 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
4139 pOut = out2Prerelease(p, pOp);
4140 pOut->u.i = iMeta;
4141 break;
4144 /* Opcode: SetCookie P1 P2 P3 * P5
4146 ** Write the integer value P3 into cookie number P2 of database P1.
4147 ** P2==1 is the schema version. P2==2 is the database format.
4148 ** P2==3 is the recommended pager cache
4149 ** size, and so forth. P1==0 is the main database file and P1==1 is the
4150 ** database file used to store temporary tables.
4152 ** A transaction must be started before executing this opcode.
4154 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
4155 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
4156 ** has P5 set to 1, so that the internal schema version will be different
4157 ** from the database schema version, resulting in a schema reset.
4159 case OP_SetCookie: {
4160 Db *pDb;
4162 sqlite3VdbeIncrWriteCounter(p, 0);
4163 assert( pOp->p2<SQLITE_N_BTREE_META );
4164 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4165 assert( DbMaskTest(p->btreeMask, pOp->p1) );
4166 assert( p->readOnly==0 );
4167 pDb = &db->aDb[pOp->p1];
4168 assert( pDb->pBt!=0 );
4169 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
4170 /* See note about index shifting on OP_ReadCookie */
4171 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
4172 if( pOp->p2==BTREE_SCHEMA_VERSION ){
4173 /* When the schema cookie changes, record the new cookie internally */
4174 *(u32*)&pDb->pSchema->schema_cookie = *(u32*)&pOp->p3 - pOp->p5;
4175 db->mDbFlags |= DBFLAG_SchemaChange;
4176 sqlite3FkClearTriggerCache(db, pOp->p1);
4177 }else if( pOp->p2==BTREE_FILE_FORMAT ){
4178 /* Record changes in the file format */
4179 pDb->pSchema->file_format = pOp->p3;
4181 if( pOp->p1==1 ){
4182 /* Invalidate all prepared statements whenever the TEMP database
4183 ** schema is changed. Ticket #1644 */
4184 sqlite3ExpirePreparedStatements(db, 0);
4185 p->expired = 0;
4187 if( rc ) goto abort_due_to_error;
4188 break;
4191 /* Opcode: OpenRead P1 P2 P3 P4 P5
4192 ** Synopsis: root=P2 iDb=P3
4194 ** Open a read-only cursor for the database table whose root page is
4195 ** P2 in a database file. The database file is determined by P3.
4196 ** P3==0 means the main database, P3==1 means the database used for
4197 ** temporary tables, and P3>1 means used the corresponding attached
4198 ** database. Give the new cursor an identifier of P1. The P1
4199 ** values need not be contiguous but all P1 values should be small integers.
4200 ** It is an error for P1 to be negative.
4202 ** Allowed P5 bits:
4203 ** <ul>
4204 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4205 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4206 ** of OP_SeekLE/OP_IdxLT)
4207 ** </ul>
4209 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4210 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4211 ** object, then table being opened must be an [index b-tree] where the
4212 ** KeyInfo object defines the content and collating
4213 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4214 ** value, then the table being opened must be a [table b-tree] with a
4215 ** number of columns no less than the value of P4.
4217 ** See also: OpenWrite, ReopenIdx
4219 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
4220 ** Synopsis: root=P2 iDb=P3
4222 ** The ReopenIdx opcode works like OP_OpenRead except that it first
4223 ** checks to see if the cursor on P1 is already open on the same
4224 ** b-tree and if it is this opcode becomes a no-op. In other words,
4225 ** if the cursor is already open, do not reopen it.
4227 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
4228 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
4229 ** be the same as every other ReopenIdx or OpenRead for the same cursor
4230 ** number.
4232 ** Allowed P5 bits:
4233 ** <ul>
4234 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4235 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4236 ** of OP_SeekLE/OP_IdxLT)
4237 ** </ul>
4239 ** See also: OP_OpenRead, OP_OpenWrite
4241 /* Opcode: OpenWrite P1 P2 P3 P4 P5
4242 ** Synopsis: root=P2 iDb=P3
4244 ** Open a read/write cursor named P1 on the table or index whose root
4245 ** page is P2 (or whose root page is held in register P2 if the
4246 ** OPFLAG_P2ISREG bit is set in P5 - see below).
4248 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4249 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4250 ** object, then table being opened must be an [index b-tree] where the
4251 ** KeyInfo object defines the content and collating
4252 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4253 ** value, then the table being opened must be a [table b-tree] with a
4254 ** number of columns no less than the value of P4.
4256 ** Allowed P5 bits:
4257 ** <ul>
4258 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4259 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4260 ** of OP_SeekLE/OP_IdxLT)
4261 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
4262 ** and subsequently delete entries in an index btree. This is a
4263 ** hint to the storage engine that the storage engine is allowed to
4264 ** ignore. The hint is not used by the official SQLite b*tree storage
4265 ** engine, but is used by COMDB2.
4266 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
4267 ** as the root page, not the value of P2 itself.
4268 ** </ul>
4270 ** This instruction works like OpenRead except that it opens the cursor
4271 ** in read/write mode.
4273 ** See also: OP_OpenRead, OP_ReopenIdx
4275 case OP_ReopenIdx: { /* ncycle */
4276 int nField;
4277 KeyInfo *pKeyInfo;
4278 u32 p2;
4279 int iDb;
4280 int wrFlag;
4281 Btree *pX;
4282 VdbeCursor *pCur;
4283 Db *pDb;
4285 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4286 assert( pOp->p4type==P4_KEYINFO );
4287 pCur = p->apCsr[pOp->p1];
4288 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
4289 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
4290 assert( pCur->eCurType==CURTYPE_BTREE );
4291 sqlite3BtreeClearCursor(pCur->uc.pCursor);
4292 goto open_cursor_set_hints;
4294 /* If the cursor is not currently open or is open on a different
4295 ** index, then fall through into OP_OpenRead to force a reopen */
4296 case OP_OpenRead: /* ncycle */
4297 case OP_OpenWrite:
4299 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4300 assert( p->bIsReader );
4301 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
4302 || p->readOnly==0 );
4304 if( p->expired==1 ){
4305 rc = SQLITE_ABORT_ROLLBACK;
4306 goto abort_due_to_error;
4309 nField = 0;
4310 pKeyInfo = 0;
4311 p2 = (u32)pOp->p2;
4312 iDb = pOp->p3;
4313 assert( iDb>=0 && iDb<db->nDb );
4314 assert( DbMaskTest(p->btreeMask, iDb) );
4315 pDb = &db->aDb[iDb];
4316 pX = pDb->pBt;
4317 assert( pX!=0 );
4318 if( pOp->opcode==OP_OpenWrite ){
4319 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
4320 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
4321 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4322 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
4323 p->minWriteFileFormat = pDb->pSchema->file_format;
4325 }else{
4326 wrFlag = 0;
4328 if( pOp->p5 & OPFLAG_P2ISREG ){
4329 assert( p2>0 );
4330 assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
4331 assert( pOp->opcode==OP_OpenWrite );
4332 pIn2 = &aMem[p2];
4333 assert( memIsValid(pIn2) );
4334 assert( (pIn2->flags & MEM_Int)!=0 );
4335 sqlite3VdbeMemIntegerify(pIn2);
4336 p2 = (int)pIn2->u.i;
4337 /* The p2 value always comes from a prior OP_CreateBtree opcode and
4338 ** that opcode will always set the p2 value to 2 or more or else fail.
4339 ** If there were a failure, the prepared statement would have halted
4340 ** before reaching this instruction. */
4341 assert( p2>=2 );
4343 if( pOp->p4type==P4_KEYINFO ){
4344 pKeyInfo = pOp->p4.pKeyInfo;
4345 assert( pKeyInfo->enc==ENC(db) );
4346 assert( pKeyInfo->db==db );
4347 nField = pKeyInfo->nAllField;
4348 }else if( pOp->p4type==P4_INT32 ){
4349 nField = pOp->p4.i;
4351 assert( pOp->p1>=0 );
4352 assert( nField>=0 );
4353 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
4354 pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
4355 if( pCur==0 ) goto no_mem;
4356 pCur->iDb = iDb;
4357 pCur->nullRow = 1;
4358 pCur->isOrdered = 1;
4359 pCur->pgnoRoot = p2;
4360 #ifdef SQLITE_DEBUG
4361 pCur->wrFlag = wrFlag;
4362 #endif
4363 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
4364 pCur->pKeyInfo = pKeyInfo;
4365 /* Set the VdbeCursor.isTable variable. Previous versions of
4366 ** SQLite used to check if the root-page flags were sane at this point
4367 ** and report database corruption if they were not, but this check has
4368 ** since moved into the btree layer. */
4369 pCur->isTable = pOp->p4type!=P4_KEYINFO;
4371 open_cursor_set_hints:
4372 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
4373 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
4374 testcase( pOp->p5 & OPFLAG_BULKCSR );
4375 testcase( pOp->p2 & OPFLAG_SEEKEQ );
4376 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
4377 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
4378 if( rc ) goto abort_due_to_error;
4379 break;
4382 /* Opcode: OpenDup P1 P2 * * *
4384 ** Open a new cursor P1 that points to the same ephemeral table as
4385 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
4386 ** opcode. Only ephemeral cursors may be duplicated.
4388 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
4390 case OP_OpenDup: { /* ncycle */
4391 VdbeCursor *pOrig; /* The original cursor to be duplicated */
4392 VdbeCursor *pCx; /* The new cursor */
4394 pOrig = p->apCsr[pOp->p2];
4395 assert( pOrig );
4396 assert( pOrig->isEphemeral ); /* Only ephemeral cursors can be duplicated */
4398 pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
4399 if( pCx==0 ) goto no_mem;
4400 pCx->nullRow = 1;
4401 pCx->isEphemeral = 1;
4402 pCx->pKeyInfo = pOrig->pKeyInfo;
4403 pCx->isTable = pOrig->isTable;
4404 pCx->pgnoRoot = pOrig->pgnoRoot;
4405 pCx->isOrdered = pOrig->isOrdered;
4406 pCx->ub.pBtx = pOrig->ub.pBtx;
4407 pCx->noReuse = 1;
4408 pOrig->noReuse = 1;
4409 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4410 pCx->pKeyInfo, pCx->uc.pCursor);
4411 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
4412 ** opened for a database. Since there is already an open cursor when this
4413 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
4414 assert( rc==SQLITE_OK );
4415 break;
4419 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5
4420 ** Synopsis: nColumn=P2
4422 ** Open a new cursor P1 to a transient table.
4423 ** The cursor is always opened read/write even if
4424 ** the main database is read-only. The ephemeral
4425 ** table is deleted automatically when the cursor is closed.
4427 ** If the cursor P1 is already opened on an ephemeral table, the table
4428 ** is cleared (all content is erased).
4430 ** P2 is the number of columns in the ephemeral table.
4431 ** The cursor points to a BTree table if P4==0 and to a BTree index
4432 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
4433 ** that defines the format of keys in the index.
4435 ** The P5 parameter can be a mask of the BTREE_* flags defined
4436 ** in btree.h. These flags control aspects of the operation of
4437 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
4438 ** added automatically.
4440 ** If P3 is positive, then reg[P3] is modified slightly so that it
4441 ** can be used as zero-length data for OP_Insert. This is an optimization
4442 ** that avoids an extra OP_Blob opcode to initialize that register.
4444 /* Opcode: OpenAutoindex P1 P2 * P4 *
4445 ** Synopsis: nColumn=P2
4447 ** This opcode works the same as OP_OpenEphemeral. It has a
4448 ** different name to distinguish its use. Tables created using
4449 ** by this opcode will be used for automatically created transient
4450 ** indices in joins.
4452 case OP_OpenAutoindex: /* ncycle */
4453 case OP_OpenEphemeral: { /* ncycle */
4454 VdbeCursor *pCx;
4455 KeyInfo *pKeyInfo;
4457 static const int vfsFlags =
4458 SQLITE_OPEN_READWRITE |
4459 SQLITE_OPEN_CREATE |
4460 SQLITE_OPEN_EXCLUSIVE |
4461 SQLITE_OPEN_DELETEONCLOSE |
4462 SQLITE_OPEN_TRANSIENT_DB;
4463 assert( pOp->p1>=0 );
4464 assert( pOp->p2>=0 );
4465 if( pOp->p3>0 ){
4466 /* Make register reg[P3] into a value that can be used as the data
4467 ** form sqlite3BtreeInsert() where the length of the data is zero. */
4468 assert( pOp->p2==0 ); /* Only used when number of columns is zero */
4469 assert( pOp->opcode==OP_OpenEphemeral );
4470 assert( aMem[pOp->p3].flags & MEM_Null );
4471 aMem[pOp->p3].n = 0;
4472 aMem[pOp->p3].z = "";
4474 pCx = p->apCsr[pOp->p1];
4475 if( pCx && !pCx->noReuse && ALWAYS(pOp->p2<=pCx->nField) ){
4476 /* If the ephemeral table is already open and has no duplicates from
4477 ** OP_OpenDup, then erase all existing content so that the table is
4478 ** empty again, rather than creating a new table. */
4479 assert( pCx->isEphemeral );
4480 pCx->seqCount = 0;
4481 pCx->cacheStatus = CACHE_STALE;
4482 rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
4483 }else{
4484 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
4485 if( pCx==0 ) goto no_mem;
4486 pCx->isEphemeral = 1;
4487 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
4488 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
4489 vfsFlags);
4490 if( rc==SQLITE_OK ){
4491 rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
4492 if( rc==SQLITE_OK ){
4493 /* If a transient index is required, create it by calling
4494 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
4495 ** opening it. If a transient table is required, just use the
4496 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
4498 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
4499 assert( pOp->p4type==P4_KEYINFO );
4500 rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
4501 BTREE_BLOBKEY | pOp->p5);
4502 if( rc==SQLITE_OK ){
4503 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
4504 assert( pKeyInfo->db==db );
4505 assert( pKeyInfo->enc==ENC(db) );
4506 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4507 pKeyInfo, pCx->uc.pCursor);
4509 pCx->isTable = 0;
4510 }else{
4511 pCx->pgnoRoot = SCHEMA_ROOT;
4512 rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
4513 0, pCx->uc.pCursor);
4514 pCx->isTable = 1;
4517 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
4518 if( rc ){
4519 sqlite3BtreeClose(pCx->ub.pBtx);
4523 if( rc ) goto abort_due_to_error;
4524 pCx->nullRow = 1;
4525 break;
4528 /* Opcode: SorterOpen P1 P2 P3 P4 *
4530 ** This opcode works like OP_OpenEphemeral except that it opens
4531 ** a transient index that is specifically designed to sort large
4532 ** tables using an external merge-sort algorithm.
4534 ** If argument P3 is non-zero, then it indicates that the sorter may
4535 ** assume that a stable sort considering the first P3 fields of each
4536 ** key is sufficient to produce the required results.
4538 case OP_SorterOpen: {
4539 VdbeCursor *pCx;
4541 assert( pOp->p1>=0 );
4542 assert( pOp->p2>=0 );
4543 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
4544 if( pCx==0 ) goto no_mem;
4545 pCx->pKeyInfo = pOp->p4.pKeyInfo;
4546 assert( pCx->pKeyInfo->db==db );
4547 assert( pCx->pKeyInfo->enc==ENC(db) );
4548 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4549 if( rc ) goto abort_due_to_error;
4550 break;
4553 /* Opcode: SequenceTest P1 P2 * * *
4554 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4556 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4557 ** to P2. Regardless of whether or not the jump is taken, increment the
4558 ** the sequence value.
4560 case OP_SequenceTest: {
4561 VdbeCursor *pC;
4562 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4563 pC = p->apCsr[pOp->p1];
4564 assert( isSorter(pC) );
4565 if( (pC->seqCount++)==0 ){
4566 goto jump_to_p2;
4568 break;
4571 /* Opcode: OpenPseudo P1 P2 P3 * *
4572 ** Synopsis: P3 columns in r[P2]
4574 ** Open a new cursor that points to a fake table that contains a single
4575 ** row of data. The content of that one row is the content of memory
4576 ** register P2. In other words, cursor P1 becomes an alias for the
4577 ** MEM_Blob content contained in register P2.
4579 ** A pseudo-table created by this opcode is used to hold a single
4580 ** row output from the sorter so that the row can be decomposed into
4581 ** individual columns using the OP_Column opcode. The OP_Column opcode
4582 ** is the only cursor opcode that works with a pseudo-table.
4584 ** P3 is the number of fields in the records that will be stored by
4585 ** the pseudo-table.
4587 case OP_OpenPseudo: {
4588 VdbeCursor *pCx;
4590 assert( pOp->p1>=0 );
4591 assert( pOp->p3>=0 );
4592 pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
4593 if( pCx==0 ) goto no_mem;
4594 pCx->nullRow = 1;
4595 pCx->seekResult = pOp->p2;
4596 pCx->isTable = 1;
4597 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4598 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
4599 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4600 ** which is a performance optimization */
4601 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4602 assert( pOp->p5==0 );
4603 break;
4606 /* Opcode: Close P1 * * * *
4608 ** Close a cursor previously opened as P1. If P1 is not
4609 ** currently open, this instruction is a no-op.
4611 case OP_Close: { /* ncycle */
4612 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4613 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4614 p->apCsr[pOp->p1] = 0;
4615 break;
4618 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4619 /* Opcode: ColumnsUsed P1 * * P4 *
4621 ** This opcode (which only exists if SQLite was compiled with
4622 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4623 ** table or index for cursor P1 are used. P4 is a 64-bit integer
4624 ** (P4_INT64) in which the first 63 bits are one for each of the
4625 ** first 63 columns of the table or index that are actually used
4626 ** by the cursor. The high-order bit is set if any column after
4627 ** the 64th is used.
4629 case OP_ColumnsUsed: {
4630 VdbeCursor *pC;
4631 pC = p->apCsr[pOp->p1];
4632 assert( pC->eCurType==CURTYPE_BTREE );
4633 pC->maskUsed = *(u64*)pOp->p4.pI64;
4634 break;
4636 #endif
4638 /* Opcode: SeekGE P1 P2 P3 P4 *
4639 ** Synopsis: key=r[P3@P4]
4641 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4642 ** use the value in register P3 as the key. If cursor P1 refers
4643 ** to an SQL index, then P3 is the first in an array of P4 registers
4644 ** that are used as an unpacked index key.
4646 ** Reposition cursor P1 so that it points to the smallest entry that
4647 ** is greater than or equal to the key value. If there are no records
4648 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4650 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4651 ** opcode will either land on a record that exactly matches the key, or
4652 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4653 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4654 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4655 ** IdxGT opcode will be used on subsequent loop iterations. The
4656 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4657 ** is an equality search.
4659 ** This opcode leaves the cursor configured to move in forward order,
4660 ** from the beginning toward the end. In other words, the cursor is
4661 ** configured to use Next, not Prev.
4663 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4665 /* Opcode: SeekGT P1 P2 P3 P4 *
4666 ** Synopsis: key=r[P3@P4]
4668 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4669 ** use the value in register P3 as a key. If cursor P1 refers
4670 ** to an SQL index, then P3 is the first in an array of P4 registers
4671 ** that are used as an unpacked index key.
4673 ** Reposition cursor P1 so that it points to the smallest entry that
4674 ** is greater than the key value. If there are no records greater than
4675 ** the key and P2 is not zero, then jump to P2.
4677 ** This opcode leaves the cursor configured to move in forward order,
4678 ** from the beginning toward the end. In other words, the cursor is
4679 ** configured to use Next, not Prev.
4681 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4683 /* Opcode: SeekLT P1 P2 P3 P4 *
4684 ** Synopsis: key=r[P3@P4]
4686 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4687 ** use the value in register P3 as a key. If cursor P1 refers
4688 ** to an SQL index, then P3 is the first in an array of P4 registers
4689 ** that are used as an unpacked index key.
4691 ** Reposition cursor P1 so that it points to the largest entry that
4692 ** is less than the key value. If there are no records less than
4693 ** the key and P2 is not zero, then jump to P2.
4695 ** This opcode leaves the cursor configured to move in reverse order,
4696 ** from the end toward the beginning. In other words, the cursor is
4697 ** configured to use Prev, not Next.
4699 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4701 /* Opcode: SeekLE P1 P2 P3 P4 *
4702 ** Synopsis: key=r[P3@P4]
4704 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4705 ** use the value in register P3 as a key. If cursor P1 refers
4706 ** to an SQL index, then P3 is the first in an array of P4 registers
4707 ** that are used as an unpacked index key.
4709 ** Reposition cursor P1 so that it points to the largest entry that
4710 ** is less than or equal to the key value. If there are no records
4711 ** less than or equal to the key and P2 is not zero, then jump to P2.
4713 ** This opcode leaves the cursor configured to move in reverse order,
4714 ** from the end toward the beginning. In other words, the cursor is
4715 ** configured to use Prev, not Next.
4717 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4718 ** opcode will either land on a record that exactly matches the key, or
4719 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4720 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4721 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4722 ** IdxGE opcode will be used on subsequent loop iterations. The
4723 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4724 ** is an equality search.
4726 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4728 case OP_SeekLT: /* jump, in3, group, ncycle */
4729 case OP_SeekLE: /* jump, in3, group, ncycle */
4730 case OP_SeekGE: /* jump, in3, group, ncycle */
4731 case OP_SeekGT: { /* jump, in3, group, ncycle */
4732 int res; /* Comparison result */
4733 int oc; /* Opcode */
4734 VdbeCursor *pC; /* The cursor to seek */
4735 UnpackedRecord r; /* The key to seek for */
4736 int nField; /* Number of columns or fields in the key */
4737 i64 iKey; /* The rowid we are to seek to */
4738 int eqOnly; /* Only interested in == results */
4740 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4741 assert( pOp->p2!=0 );
4742 pC = p->apCsr[pOp->p1];
4743 assert( pC!=0 );
4744 assert( pC->eCurType==CURTYPE_BTREE );
4745 assert( OP_SeekLE == OP_SeekLT+1 );
4746 assert( OP_SeekGE == OP_SeekLT+2 );
4747 assert( OP_SeekGT == OP_SeekLT+3 );
4748 assert( pC->isOrdered );
4749 assert( pC->uc.pCursor!=0 );
4750 oc = pOp->opcode;
4751 eqOnly = 0;
4752 pC->nullRow = 0;
4753 #ifdef SQLITE_DEBUG
4754 pC->seekOp = pOp->opcode;
4755 #endif
4757 pC->deferredMoveto = 0;
4758 pC->cacheStatus = CACHE_STALE;
4759 if( pC->isTable ){
4760 u16 flags3, newType;
4761 /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4762 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4763 || CORRUPT_DB );
4765 /* The input value in P3 might be of any type: integer, real, string,
4766 ** blob, or NULL. But it needs to be an integer before we can do
4767 ** the seek, so convert it. */
4768 pIn3 = &aMem[pOp->p3];
4769 flags3 = pIn3->flags;
4770 if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4771 applyNumericAffinity(pIn3, 0);
4773 iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4774 newType = pIn3->flags; /* Record the type after applying numeric affinity */
4775 pIn3->flags = flags3; /* But convert the type back to its original */
4777 /* If the P3 value could not be converted into an integer without
4778 ** loss of information, then special processing is required... */
4779 if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4780 int c;
4781 if( (newType & MEM_Real)==0 ){
4782 if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4783 VdbeBranchTaken(1,2);
4784 goto jump_to_p2;
4785 }else{
4786 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4787 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4788 goto seek_not_found;
4791 c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
4793 /* If the approximation iKey is larger than the actual real search
4794 ** term, substitute >= for > and < for <=. e.g. if the search term
4795 ** is 4.9 and the integer approximation 5:
4797 ** (x > 4.9) -> (x >= 5)
4798 ** (x <= 4.9) -> (x < 5)
4800 if( c>0 ){
4801 assert( OP_SeekGE==(OP_SeekGT-1) );
4802 assert( OP_SeekLT==(OP_SeekLE-1) );
4803 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4804 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4807 /* If the approximation iKey is smaller than the actual real search
4808 ** term, substitute <= for < and > for >=. */
4809 else if( c<0 ){
4810 assert( OP_SeekLE==(OP_SeekLT+1) );
4811 assert( OP_SeekGT==(OP_SeekGE+1) );
4812 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4813 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4816 rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
4817 pC->movetoTarget = iKey; /* Used by OP_Delete */
4818 if( rc!=SQLITE_OK ){
4819 goto abort_due_to_error;
4821 }else{
4822 /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4823 ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4824 ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4825 ** with the same key.
4827 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4828 eqOnly = 1;
4829 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4830 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4831 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4832 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4833 assert( pOp[1].p1==pOp[0].p1 );
4834 assert( pOp[1].p2==pOp[0].p2 );
4835 assert( pOp[1].p3==pOp[0].p3 );
4836 assert( pOp[1].p4.i==pOp[0].p4.i );
4839 nField = pOp->p4.i;
4840 assert( pOp->p4type==P4_INT32 );
4841 assert( nField>0 );
4842 r.pKeyInfo = pC->pKeyInfo;
4843 r.nField = (u16)nField;
4845 /* The next line of code computes as follows, only faster:
4846 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
4847 ** r.default_rc = -1;
4848 ** }else{
4849 ** r.default_rc = +1;
4850 ** }
4852 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4853 assert( oc!=OP_SeekGT || r.default_rc==-1 );
4854 assert( oc!=OP_SeekLE || r.default_rc==-1 );
4855 assert( oc!=OP_SeekGE || r.default_rc==+1 );
4856 assert( oc!=OP_SeekLT || r.default_rc==+1 );
4858 r.aMem = &aMem[pOp->p3];
4859 #ifdef SQLITE_DEBUG
4861 int i;
4862 for(i=0; i<r.nField; i++){
4863 assert( memIsValid(&r.aMem[i]) );
4864 if( i>0 ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
4867 #endif
4868 r.eqSeen = 0;
4869 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
4870 if( rc!=SQLITE_OK ){
4871 goto abort_due_to_error;
4873 if( eqOnly && r.eqSeen==0 ){
4874 assert( res!=0 );
4875 goto seek_not_found;
4878 #ifdef SQLITE_TEST
4879 sqlite3_search_count++;
4880 #endif
4881 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
4882 if( res<0 || (res==0 && oc==OP_SeekGT) ){
4883 res = 0;
4884 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4885 if( rc!=SQLITE_OK ){
4886 if( rc==SQLITE_DONE ){
4887 rc = SQLITE_OK;
4888 res = 1;
4889 }else{
4890 goto abort_due_to_error;
4893 }else{
4894 res = 0;
4896 }else{
4897 assert( oc==OP_SeekLT || oc==OP_SeekLE );
4898 if( res>0 || (res==0 && oc==OP_SeekLT) ){
4899 res = 0;
4900 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4901 if( rc!=SQLITE_OK ){
4902 if( rc==SQLITE_DONE ){
4903 rc = SQLITE_OK;
4904 res = 1;
4905 }else{
4906 goto abort_due_to_error;
4909 }else{
4910 /* res might be negative because the table is empty. Check to
4911 ** see if this is the case.
4913 res = sqlite3BtreeEof(pC->uc.pCursor);
4916 seek_not_found:
4917 assert( pOp->p2>0 );
4918 VdbeBranchTaken(res!=0,2);
4919 if( res ){
4920 goto jump_to_p2;
4921 }else if( eqOnly ){
4922 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4923 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4925 break;
4929 /* Opcode: SeekScan P1 P2 * * P5
4930 ** Synopsis: Scan-ahead up to P1 rows
4932 ** This opcode is a prefix opcode to OP_SeekGE. In other words, this
4933 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4934 ** checked by assert() statements.
4936 ** This opcode uses the P1 through P4 operands of the subsequent
4937 ** OP_SeekGE. In the text that follows, the operands of the subsequent
4938 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4. Only
4939 ** the P1, P2 and P5 operands of this opcode are also used, and are called
4940 ** This.P1, This.P2 and This.P5.
4942 ** This opcode helps to optimize IN operators on a multi-column index
4943 ** where the IN operator is on the later terms of the index by avoiding
4944 ** unnecessary seeks on the btree, substituting steps to the next row
4945 ** of the b-tree instead. A correct answer is obtained if this opcode
4946 ** is omitted or is a no-op.
4948 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4949 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4950 ** to. Call this SeekGE.P3/P4 row the "target".
4952 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4953 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4955 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4956 ** might be the target row, or it might be near and slightly before the
4957 ** target row, or it might be after the target row. If the cursor is
4958 ** currently before the target row, then this opcode attempts to position
4959 ** the cursor on or after the target row by invoking sqlite3BtreeStep()
4960 ** on the cursor between 1 and This.P1 times.
4962 ** The This.P5 parameter is a flag that indicates what to do if the
4963 ** cursor ends up pointing at a valid row that is past the target
4964 ** row. If This.P5 is false (0) then a jump is made to SeekGE.P2. If
4965 ** This.P5 is true (non-zero) then a jump is made to This.P2. The P5==0
4966 ** case occurs when there are no inequality constraints to the right of
4967 ** the IN constraint. The jump to SeekGE.P2 ends the loop. The P5!=0 case
4968 ** occurs when there are inequality constraints to the right of the IN
4969 ** operator. In that case, the This.P2 will point either directly to or
4970 ** to setup code prior to the OP_IdxGT or OP_IdxGE opcode that checks for
4971 ** loop terminate.
4973 ** Possible outcomes from this opcode:<ol>
4975 ** <li> If the cursor is initially not pointed to any valid row, then
4976 ** fall through into the subsequent OP_SeekGE opcode.
4978 ** <li> If the cursor is left pointing to a row that is before the target
4979 ** row, even after making as many as This.P1 calls to
4980 ** sqlite3BtreeNext(), then also fall through into OP_SeekGE.
4982 ** <li> If the cursor is left pointing at the target row, either because it
4983 ** was at the target row to begin with or because one or more
4984 ** sqlite3BtreeNext() calls moved the cursor to the target row,
4985 ** then jump to This.P2..,
4987 ** <li> If the cursor started out before the target row and a call to
4988 ** to sqlite3BtreeNext() moved the cursor off the end of the index
4989 ** (indicating that the target row definitely does not exist in the
4990 ** btree) then jump to SeekGE.P2, ending the loop.
4992 ** <li> If the cursor ends up on a valid row that is past the target row
4993 ** (indicating that the target row does not exist in the btree) then
4994 ** jump to SeekOP.P2 if This.P5==0 or to This.P2 if This.P5>0.
4995 ** </ol>
4997 case OP_SeekScan: { /* ncycle */
4998 VdbeCursor *pC;
4999 int res;
5000 int nStep;
5001 UnpackedRecord r;
5003 assert( pOp[1].opcode==OP_SeekGE );
5005 /* If pOp->p5 is clear, then pOp->p2 points to the first instruction past the
5006 ** OP_IdxGT that follows the OP_SeekGE. Otherwise, it points to the first
5007 ** opcode past the OP_SeekGE itself. */
5008 assert( pOp->p2>=(int)(pOp-aOp)+2 );
5009 #ifdef SQLITE_DEBUG
5010 if( pOp->p5==0 ){
5011 /* There are no inequality constraints following the IN constraint. */
5012 assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
5013 assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
5014 assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
5015 assert( aOp[pOp->p2-1].opcode==OP_IdxGT
5016 || aOp[pOp->p2-1].opcode==OP_IdxGE );
5017 testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
5018 }else{
5019 /* There are inequality constraints. */
5020 assert( pOp->p2==(int)(pOp-aOp)+2 );
5021 assert( aOp[pOp->p2-1].opcode==OP_SeekGE );
5023 #endif
5025 assert( pOp->p1>0 );
5026 pC = p->apCsr[pOp[1].p1];
5027 assert( pC!=0 );
5028 assert( pC->eCurType==CURTYPE_BTREE );
5029 assert( !pC->isTable );
5030 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
5031 #ifdef SQLITE_DEBUG
5032 if( db->flags&SQLITE_VdbeTrace ){
5033 printf("... cursor not valid - fall through\n");
5035 #endif
5036 break;
5038 nStep = pOp->p1;
5039 assert( nStep>=1 );
5040 r.pKeyInfo = pC->pKeyInfo;
5041 r.nField = (u16)pOp[1].p4.i;
5042 r.default_rc = 0;
5043 r.aMem = &aMem[pOp[1].p3];
5044 #ifdef SQLITE_DEBUG
5046 int i;
5047 for(i=0; i<r.nField; i++){
5048 assert( memIsValid(&r.aMem[i]) );
5049 REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
5052 #endif
5053 res = 0; /* Not needed. Only used to silence a warning. */
5054 while(1){
5055 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5056 if( rc ) goto abort_due_to_error;
5057 if( res>0 && pOp->p5==0 ){
5058 seekscan_search_fail:
5059 /* Jump to SeekGE.P2, ending the loop */
5060 #ifdef SQLITE_DEBUG
5061 if( db->flags&SQLITE_VdbeTrace ){
5062 printf("... %d steps and then skip\n", pOp->p1 - nStep);
5064 #endif
5065 VdbeBranchTaken(1,3);
5066 pOp++;
5067 goto jump_to_p2;
5069 if( res>=0 ){
5070 /* Jump to This.P2, bypassing the OP_SeekGE opcode */
5071 #ifdef SQLITE_DEBUG
5072 if( db->flags&SQLITE_VdbeTrace ){
5073 printf("... %d steps and then success\n", pOp->p1 - nStep);
5075 #endif
5076 VdbeBranchTaken(2,3);
5077 goto jump_to_p2;
5078 break;
5080 if( nStep<=0 ){
5081 #ifdef SQLITE_DEBUG
5082 if( db->flags&SQLITE_VdbeTrace ){
5083 printf("... fall through after %d steps\n", pOp->p1);
5085 #endif
5086 VdbeBranchTaken(0,3);
5087 break;
5089 nStep--;
5090 pC->cacheStatus = CACHE_STALE;
5091 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
5092 if( rc ){
5093 if( rc==SQLITE_DONE ){
5094 rc = SQLITE_OK;
5095 goto seekscan_search_fail;
5096 }else{
5097 goto abort_due_to_error;
5102 break;
5106 /* Opcode: SeekHit P1 P2 P3 * *
5107 ** Synopsis: set P2<=seekHit<=P3
5109 ** Increase or decrease the seekHit value for cursor P1, if necessary,
5110 ** so that it is no less than P2 and no greater than P3.
5112 ** The seekHit integer represents the maximum of terms in an index for which
5113 ** there is known to be at least one match. If the seekHit value is smaller
5114 ** than the total number of equality terms in an index lookup, then the
5115 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
5116 ** early, thus saving work. This is part of the IN-early-out optimization.
5118 ** P1 must be a valid b-tree cursor.
5120 case OP_SeekHit: { /* ncycle */
5121 VdbeCursor *pC;
5122 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5123 pC = p->apCsr[pOp->p1];
5124 assert( pC!=0 );
5125 assert( pOp->p3>=pOp->p2 );
5126 if( pC->seekHit<pOp->p2 ){
5127 #ifdef SQLITE_DEBUG
5128 if( db->flags&SQLITE_VdbeTrace ){
5129 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
5131 #endif
5132 pC->seekHit = pOp->p2;
5133 }else if( pC->seekHit>pOp->p3 ){
5134 #ifdef SQLITE_DEBUG
5135 if( db->flags&SQLITE_VdbeTrace ){
5136 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
5138 #endif
5139 pC->seekHit = pOp->p3;
5141 break;
5144 /* Opcode: IfNotOpen P1 P2 * * *
5145 ** Synopsis: if( !csr[P1] ) goto P2
5147 ** If cursor P1 is not open or if P1 is set to a NULL row using the
5148 ** OP_NullRow opcode, then jump to instruction P2. Otherwise, fall through.
5150 case OP_IfNotOpen: { /* jump */
5151 VdbeCursor *pCur;
5153 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5154 pCur = p->apCsr[pOp->p1];
5155 VdbeBranchTaken(pCur==0 || pCur->nullRow, 2);
5156 if( pCur==0 || pCur->nullRow ){
5157 goto jump_to_p2_and_check_for_interrupt;
5159 break;
5162 /* Opcode: Found P1 P2 P3 P4 *
5163 ** Synopsis: key=r[P3@P4]
5165 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5166 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5167 ** record.
5169 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5170 ** is a prefix of any entry in P1 then a jump is made to P2 and
5171 ** P1 is left pointing at the matching entry.
5173 ** This operation leaves the cursor in a state where it can be
5174 ** advanced in the forward direction. The Next instruction will work,
5175 ** but not the Prev instruction.
5177 ** See also: NotFound, NoConflict, NotExists. SeekGe
5179 /* Opcode: NotFound P1 P2 P3 P4 *
5180 ** Synopsis: key=r[P3@P4]
5182 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5183 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5184 ** record.
5186 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5187 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
5188 ** does contain an entry whose prefix matches the P3/P4 record then control
5189 ** falls through to the next instruction and P1 is left pointing at the
5190 ** matching entry.
5192 ** This operation leaves the cursor in a state where it cannot be
5193 ** advanced in either direction. In other words, the Next and Prev
5194 ** opcodes do not work after this operation.
5196 ** See also: Found, NotExists, NoConflict, IfNoHope
5198 /* Opcode: IfNoHope P1 P2 P3 P4 *
5199 ** Synopsis: key=r[P3@P4]
5201 ** Register P3 is the first of P4 registers that form an unpacked
5202 ** record. Cursor P1 is an index btree. P2 is a jump destination.
5203 ** In other words, the operands to this opcode are the same as the
5204 ** operands to OP_NotFound and OP_IdxGT.
5206 ** This opcode is an optimization attempt only. If this opcode always
5207 ** falls through, the correct answer is still obtained, but extra work
5208 ** is performed.
5210 ** A value of N in the seekHit flag of cursor P1 means that there exists
5211 ** a key P3:N that will match some record in the index. We want to know
5212 ** if it is possible for a record P3:P4 to match some record in the
5213 ** index. If it is not possible, we can skip some work. So if seekHit
5214 ** is less than P4, attempt to find out if a match is possible by running
5215 ** OP_NotFound.
5217 ** This opcode is used in IN clause processing for a multi-column key.
5218 ** If an IN clause is attached to an element of the key other than the
5219 ** left-most element, and if there are no matches on the most recent
5220 ** seek over the whole key, then it might be that one of the key element
5221 ** to the left is prohibiting a match, and hence there is "no hope" of
5222 ** any match regardless of how many IN clause elements are checked.
5223 ** In such a case, we abandon the IN clause search early, using this
5224 ** opcode. The opcode name comes from the fact that the
5225 ** jump is taken if there is "no hope" of achieving a match.
5227 ** See also: NotFound, SeekHit
5229 /* Opcode: NoConflict P1 P2 P3 P4 *
5230 ** Synopsis: key=r[P3@P4]
5232 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5233 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5234 ** record.
5236 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5237 ** contains any NULL value, jump immediately to P2. If all terms of the
5238 ** record are not-NULL then a check is done to determine if any row in the
5239 ** P1 index btree has a matching key prefix. If there are no matches, jump
5240 ** immediately to P2. If there is a match, fall through and leave the P1
5241 ** cursor pointing to the matching row.
5243 ** This opcode is similar to OP_NotFound with the exceptions that the
5244 ** branch is always taken if any part of the search key input is NULL.
5246 ** This operation leaves the cursor in a state where it cannot be
5247 ** advanced in either direction. In other words, the Next and Prev
5248 ** opcodes do not work after this operation.
5250 ** See also: NotFound, Found, NotExists
5252 case OP_IfNoHope: { /* jump, in3, ncycle */
5253 VdbeCursor *pC;
5254 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5255 pC = p->apCsr[pOp->p1];
5256 assert( pC!=0 );
5257 #ifdef SQLITE_DEBUG
5258 if( db->flags&SQLITE_VdbeTrace ){
5259 printf("seekHit is %d\n", pC->seekHit);
5261 #endif
5262 if( pC->seekHit>=pOp->p4.i ) break;
5263 /* Fall through into OP_NotFound */
5264 /* no break */ deliberate_fall_through
5266 case OP_NoConflict: /* jump, in3, ncycle */
5267 case OP_NotFound: /* jump, in3, ncycle */
5268 case OP_Found: { /* jump, in3, ncycle */
5269 int alreadyExists;
5270 int ii;
5271 VdbeCursor *pC;
5272 UnpackedRecord *pIdxKey;
5273 UnpackedRecord r;
5275 #ifdef SQLITE_TEST
5276 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
5277 #endif
5279 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5280 assert( pOp->p4type==P4_INT32 );
5281 pC = p->apCsr[pOp->p1];
5282 assert( pC!=0 );
5283 #ifdef SQLITE_DEBUG
5284 pC->seekOp = pOp->opcode;
5285 #endif
5286 r.aMem = &aMem[pOp->p3];
5287 assert( pC->eCurType==CURTYPE_BTREE );
5288 assert( pC->uc.pCursor!=0 );
5289 assert( pC->isTable==0 );
5290 r.nField = (u16)pOp->p4.i;
5291 if( r.nField>0 ){
5292 /* Key values in an array of registers */
5293 r.pKeyInfo = pC->pKeyInfo;
5294 r.default_rc = 0;
5295 #ifdef SQLITE_DEBUG
5296 for(ii=0; ii<r.nField; ii++){
5297 assert( memIsValid(&r.aMem[ii]) );
5298 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
5299 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
5301 #endif
5302 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &pC->seekResult);
5303 }else{
5304 /* Composite key generated by OP_MakeRecord */
5305 assert( r.aMem->flags & MEM_Blob );
5306 assert( pOp->opcode!=OP_NoConflict );
5307 rc = ExpandBlob(r.aMem);
5308 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
5309 if( rc ) goto no_mem;
5310 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
5311 if( pIdxKey==0 ) goto no_mem;
5312 sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);
5313 pIdxKey->default_rc = 0;
5314 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);
5315 sqlite3DbFreeNN(db, pIdxKey);
5317 if( rc!=SQLITE_OK ){
5318 goto abort_due_to_error;
5320 alreadyExists = (pC->seekResult==0);
5321 pC->nullRow = 1-alreadyExists;
5322 pC->deferredMoveto = 0;
5323 pC->cacheStatus = CACHE_STALE;
5324 if( pOp->opcode==OP_Found ){
5325 VdbeBranchTaken(alreadyExists!=0,2);
5326 if( alreadyExists ) goto jump_to_p2;
5327 }else{
5328 if( !alreadyExists ){
5329 VdbeBranchTaken(1,2);
5330 goto jump_to_p2;
5332 if( pOp->opcode==OP_NoConflict ){
5333 /* For the OP_NoConflict opcode, take the jump if any of the
5334 ** input fields are NULL, since any key with a NULL will not
5335 ** conflict */
5336 for(ii=0; ii<r.nField; ii++){
5337 if( r.aMem[ii].flags & MEM_Null ){
5338 VdbeBranchTaken(1,2);
5339 goto jump_to_p2;
5343 VdbeBranchTaken(0,2);
5344 if( pOp->opcode==OP_IfNoHope ){
5345 pC->seekHit = pOp->p4.i;
5348 break;
5351 /* Opcode: SeekRowid P1 P2 P3 * *
5352 ** Synopsis: intkey=r[P3]
5354 ** P1 is the index of a cursor open on an SQL table btree (with integer
5355 ** keys). If register P3 does not contain an integer or if P1 does not
5356 ** contain a record with rowid P3 then jump immediately to P2.
5357 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
5358 ** a record with rowid P3 then
5359 ** leave the cursor pointing at that record and fall through to the next
5360 ** instruction.
5362 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
5363 ** the P3 register must be guaranteed to contain an integer value. With this
5364 ** opcode, register P3 might not contain an integer.
5366 ** The OP_NotFound opcode performs the same operation on index btrees
5367 ** (with arbitrary multi-value keys).
5369 ** This opcode leaves the cursor in a state where it cannot be advanced
5370 ** in either direction. In other words, the Next and Prev opcodes will
5371 ** not work following this opcode.
5373 ** See also: Found, NotFound, NoConflict, SeekRowid
5375 /* Opcode: NotExists P1 P2 P3 * *
5376 ** Synopsis: intkey=r[P3]
5378 ** P1 is the index of a cursor open on an SQL table btree (with integer
5379 ** keys). P3 is an integer rowid. If P1 does not contain a record with
5380 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
5381 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
5382 ** leave the cursor pointing at that record and fall through to the next
5383 ** instruction.
5385 ** The OP_SeekRowid opcode performs the same operation but also allows the
5386 ** P3 register to contain a non-integer value, in which case the jump is
5387 ** always taken. This opcode requires that P3 always contain an integer.
5389 ** The OP_NotFound opcode performs the same operation on index btrees
5390 ** (with arbitrary multi-value keys).
5392 ** This opcode leaves the cursor in a state where it cannot be advanced
5393 ** in either direction. In other words, the Next and Prev opcodes will
5394 ** not work following this opcode.
5396 ** See also: Found, NotFound, NoConflict, SeekRowid
5398 case OP_SeekRowid: { /* jump, in3, ncycle */
5399 VdbeCursor *pC;
5400 BtCursor *pCrsr;
5401 int res;
5402 u64 iKey;
5404 pIn3 = &aMem[pOp->p3];
5405 testcase( pIn3->flags & MEM_Int );
5406 testcase( pIn3->flags & MEM_IntReal );
5407 testcase( pIn3->flags & MEM_Real );
5408 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
5409 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
5410 /* If pIn3->u.i does not contain an integer, compute iKey as the
5411 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
5412 ** into an integer without loss of information. Take care to avoid
5413 ** changing the datatype of pIn3, however, as it is used by other
5414 ** parts of the prepared statement. */
5415 Mem x = pIn3[0];
5416 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
5417 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
5418 iKey = x.u.i;
5419 goto notExistsWithKey;
5421 /* Fall through into OP_NotExists */
5422 /* no break */ deliberate_fall_through
5423 case OP_NotExists: /* jump, in3, ncycle */
5424 pIn3 = &aMem[pOp->p3];
5425 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
5426 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5427 iKey = pIn3->u.i;
5428 notExistsWithKey:
5429 pC = p->apCsr[pOp->p1];
5430 assert( pC!=0 );
5431 #ifdef SQLITE_DEBUG
5432 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
5433 #endif
5434 assert( pC->isTable );
5435 assert( pC->eCurType==CURTYPE_BTREE );
5436 pCrsr = pC->uc.pCursor;
5437 assert( pCrsr!=0 );
5438 res = 0;
5439 rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
5440 assert( rc==SQLITE_OK || res==0 );
5441 pC->movetoTarget = iKey; /* Used by OP_Delete */
5442 pC->nullRow = 0;
5443 pC->cacheStatus = CACHE_STALE;
5444 pC->deferredMoveto = 0;
5445 VdbeBranchTaken(res!=0,2);
5446 pC->seekResult = res;
5447 if( res!=0 ){
5448 assert( rc==SQLITE_OK );
5449 if( pOp->p2==0 ){
5450 rc = SQLITE_CORRUPT_BKPT;
5451 }else{
5452 goto jump_to_p2;
5455 if( rc ) goto abort_due_to_error;
5456 break;
5459 /* Opcode: Sequence P1 P2 * * *
5460 ** Synopsis: r[P2]=cursor[P1].ctr++
5462 ** Find the next available sequence number for cursor P1.
5463 ** Write the sequence number into register P2.
5464 ** The sequence number on the cursor is incremented after this
5465 ** instruction.
5467 case OP_Sequence: { /* out2 */
5468 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5469 assert( p->apCsr[pOp->p1]!=0 );
5470 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
5471 pOut = out2Prerelease(p, pOp);
5472 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
5473 break;
5477 /* Opcode: NewRowid P1 P2 P3 * *
5478 ** Synopsis: r[P2]=rowid
5480 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
5481 ** The record number is not previously used as a key in the database
5482 ** table that cursor P1 points to. The new record number is written
5483 ** written to register P2.
5485 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
5486 ** the largest previously generated record number. No new record numbers are
5487 ** allowed to be less than this value. When this value reaches its maximum,
5488 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
5489 ** generated record number. This P3 mechanism is used to help implement the
5490 ** AUTOINCREMENT feature.
5492 case OP_NewRowid: { /* out2 */
5493 i64 v; /* The new rowid */
5494 VdbeCursor *pC; /* Cursor of table to get the new rowid */
5495 int res; /* Result of an sqlite3BtreeLast() */
5496 int cnt; /* Counter to limit the number of searches */
5497 #ifndef SQLITE_OMIT_AUTOINCREMENT
5498 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
5499 VdbeFrame *pFrame; /* Root frame of VDBE */
5500 #endif
5502 v = 0;
5503 res = 0;
5504 pOut = out2Prerelease(p, pOp);
5505 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5506 pC = p->apCsr[pOp->p1];
5507 assert( pC!=0 );
5508 assert( pC->isTable );
5509 assert( pC->eCurType==CURTYPE_BTREE );
5510 assert( pC->uc.pCursor!=0 );
5512 /* The next rowid or record number (different terms for the same
5513 ** thing) is obtained in a two-step algorithm.
5515 ** First we attempt to find the largest existing rowid and add one
5516 ** to that. But if the largest existing rowid is already the maximum
5517 ** positive integer, we have to fall through to the second
5518 ** probabilistic algorithm
5520 ** The second algorithm is to select a rowid at random and see if
5521 ** it already exists in the table. If it does not exist, we have
5522 ** succeeded. If the random rowid does exist, we select a new one
5523 ** and try again, up to 100 times.
5525 assert( pC->isTable );
5527 #ifdef SQLITE_32BIT_ROWID
5528 # define MAX_ROWID 0x7fffffff
5529 #else
5530 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
5531 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
5532 ** to provide the constant while making all compilers happy.
5534 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
5535 #endif
5537 if( !pC->useRandomRowid ){
5538 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
5539 if( rc!=SQLITE_OK ){
5540 goto abort_due_to_error;
5542 if( res ){
5543 v = 1; /* IMP: R-61914-48074 */
5544 }else{
5545 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
5546 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5547 if( v>=MAX_ROWID ){
5548 pC->useRandomRowid = 1;
5549 }else{
5550 v++; /* IMP: R-29538-34987 */
5555 #ifndef SQLITE_OMIT_AUTOINCREMENT
5556 if( pOp->p3 ){
5557 /* Assert that P3 is a valid memory cell. */
5558 assert( pOp->p3>0 );
5559 if( p->pFrame ){
5560 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5561 /* Assert that P3 is a valid memory cell. */
5562 assert( pOp->p3<=pFrame->nMem );
5563 pMem = &pFrame->aMem[pOp->p3];
5564 }else{
5565 /* Assert that P3 is a valid memory cell. */
5566 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
5567 pMem = &aMem[pOp->p3];
5568 memAboutToChange(p, pMem);
5570 assert( memIsValid(pMem) );
5572 REGISTER_TRACE(pOp->p3, pMem);
5573 sqlite3VdbeMemIntegerify(pMem);
5574 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
5575 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
5576 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
5577 goto abort_due_to_error;
5579 if( v<pMem->u.i+1 ){
5580 v = pMem->u.i + 1;
5582 pMem->u.i = v;
5584 #endif
5585 if( pC->useRandomRowid ){
5586 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
5587 ** largest possible integer (9223372036854775807) then the database
5588 ** engine starts picking positive candidate ROWIDs at random until
5589 ** it finds one that is not previously used. */
5590 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
5591 ** an AUTOINCREMENT table. */
5592 cnt = 0;
5594 sqlite3_randomness(sizeof(v), &v);
5595 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
5596 }while( ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
5597 0, &res))==SQLITE_OK)
5598 && (res==0)
5599 && (++cnt<100));
5600 if( rc ) goto abort_due_to_error;
5601 if( res==0 ){
5602 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
5603 goto abort_due_to_error;
5605 assert( v>0 ); /* EV: R-40812-03570 */
5607 pC->deferredMoveto = 0;
5608 pC->cacheStatus = CACHE_STALE;
5610 pOut->u.i = v;
5611 break;
5614 /* Opcode: Insert P1 P2 P3 P4 P5
5615 ** Synopsis: intkey=r[P3] data=r[P2]
5617 ** Write an entry into the table of cursor P1. A new entry is
5618 ** created if it doesn't already exist or the data for an existing
5619 ** entry is overwritten. The data is the value MEM_Blob stored in register
5620 ** number P2. The key is stored in register P3. The key must
5621 ** be a MEM_Int.
5623 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5624 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
5625 ** then rowid is stored for subsequent return by the
5626 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5628 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5629 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5630 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5631 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5633 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5634 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
5635 ** is part of an INSERT operation. The difference is only important to
5636 ** the update hook.
5638 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5639 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5640 ** following a successful insert.
5642 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5643 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5644 ** and register P2 becomes ephemeral. If the cursor is changed, the
5645 ** value of register P2 will then change. Make sure this does not
5646 ** cause any problems.)
5648 ** This instruction only works on tables. The equivalent instruction
5649 ** for indices is OP_IdxInsert.
5651 case OP_Insert: {
5652 Mem *pData; /* MEM cell holding data for the record to be inserted */
5653 Mem *pKey; /* MEM cell holding key for the record */
5654 VdbeCursor *pC; /* Cursor to table into which insert is written */
5655 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
5656 const char *zDb; /* database name - used by the update hook */
5657 Table *pTab; /* Table structure - used by update and pre-update hooks */
5658 BtreePayload x; /* Payload to be inserted */
5660 pData = &aMem[pOp->p2];
5661 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5662 assert( memIsValid(pData) );
5663 pC = p->apCsr[pOp->p1];
5664 assert( pC!=0 );
5665 assert( pC->eCurType==CURTYPE_BTREE );
5666 assert( pC->deferredMoveto==0 );
5667 assert( pC->uc.pCursor!=0 );
5668 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5669 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5670 REGISTER_TRACE(pOp->p2, pData);
5671 sqlite3VdbeIncrWriteCounter(p, pC);
5673 pKey = &aMem[pOp->p3];
5674 assert( pKey->flags & MEM_Int );
5675 assert( memIsValid(pKey) );
5676 REGISTER_TRACE(pOp->p3, pKey);
5677 x.nKey = pKey->u.i;
5679 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5680 assert( pC->iDb>=0 );
5681 zDb = db->aDb[pC->iDb].zDbSName;
5682 pTab = pOp->p4.pTab;
5683 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5684 }else{
5685 pTab = 0;
5686 zDb = 0;
5689 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5690 /* Invoke the pre-update hook, if any */
5691 if( pTab ){
5692 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5693 sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
5695 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5696 /* Prevent post-update hook from running in cases when it should not */
5697 pTab = 0;
5700 if( pOp->p5 & OPFLAG_ISNOOP ) break;
5701 #endif
5703 assert( (pOp->p5 & OPFLAG_LASTROWID)==0 || (pOp->p5 & OPFLAG_NCHANGE)!=0 );
5704 if( pOp->p5 & OPFLAG_NCHANGE ){
5705 p->nChange++;
5706 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5708 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5709 x.pData = pData->z;
5710 x.nData = pData->n;
5711 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5712 if( pData->flags & MEM_Zero ){
5713 x.nZero = pData->u.nZero;
5714 }else{
5715 x.nZero = 0;
5717 x.pKey = 0;
5718 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
5719 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5720 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5721 seekResult
5723 pC->deferredMoveto = 0;
5724 pC->cacheStatus = CACHE_STALE;
5725 colCacheCtr++;
5727 /* Invoke the update-hook if required. */
5728 if( rc ) goto abort_due_to_error;
5729 if( pTab ){
5730 assert( db->xUpdateCallback!=0 );
5731 assert( pTab->aCol!=0 );
5732 db->xUpdateCallback(db->pUpdateArg,
5733 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5734 zDb, pTab->zName, x.nKey);
5736 break;
5739 /* Opcode: RowCell P1 P2 P3 * *
5741 ** P1 and P2 are both open cursors. Both must be opened on the same type
5742 ** of table - intkey or index. This opcode is used as part of copying
5743 ** the current row from P2 into P1. If the cursors are opened on intkey
5744 ** tables, register P3 contains the rowid to use with the new record in
5745 ** P1. If they are opened on index tables, P3 is not used.
5747 ** This opcode must be followed by either an Insert or InsertIdx opcode
5748 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
5750 case OP_RowCell: {
5751 VdbeCursor *pDest; /* Cursor to write to */
5752 VdbeCursor *pSrc; /* Cursor to read from */
5753 i64 iKey; /* Rowid value to insert with */
5754 assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
5755 assert( pOp[1].opcode==OP_Insert || pOp->p3==0 );
5756 assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
5757 assert( pOp[1].p5 & OPFLAG_PREFORMAT );
5758 pDest = p->apCsr[pOp->p1];
5759 pSrc = p->apCsr[pOp->p2];
5760 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
5761 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
5762 if( rc!=SQLITE_OK ) goto abort_due_to_error;
5763 break;
5766 /* Opcode: Delete P1 P2 P3 P4 P5
5768 ** Delete the record at which the P1 cursor is currently pointing.
5770 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5771 ** the cursor will be left pointing at either the next or the previous
5772 ** record in the table. If it is left pointing at the next record, then
5773 ** the next Next instruction will be a no-op. As a result, in this case
5774 ** it is ok to delete a record from within a Next loop. If
5775 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5776 ** left in an undefined state.
5778 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5779 ** delete is one of several associated with deleting a table row and
5780 ** all its associated index entries. Exactly one of those deletes is
5781 ** the "primary" delete. The others are all on OPFLAG_FORDELETE
5782 ** cursors or else are marked with the AUXDELETE flag.
5784 ** If the OPFLAG_NCHANGE (0x01) flag of P2 (NB: P2 not P5) is set, then
5785 ** the row change count is incremented (otherwise not).
5787 ** If the OPFLAG_ISNOOP (0x40) flag of P2 (not P5!) is set, then the
5788 ** pre-update-hook for deletes is run, but the btree is otherwise unchanged.
5789 ** This happens when the OP_Delete is to be shortly followed by an OP_Insert
5790 ** with the same key, causing the btree entry to be overwritten.
5792 ** P1 must not be pseudo-table. It has to be a real table with
5793 ** multiple rows.
5795 ** If P4 is not NULL then it points to a Table object. In this case either
5796 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5797 ** have been positioned using OP_NotFound prior to invoking this opcode in
5798 ** this case. Specifically, if one is configured, the pre-update hook is
5799 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5800 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5802 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5803 ** of the memory cell that contains the value that the rowid of the row will
5804 ** be set to by the update.
5806 case OP_Delete: {
5807 VdbeCursor *pC;
5808 const char *zDb;
5809 Table *pTab;
5810 int opflags;
5812 opflags = pOp->p2;
5813 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5814 pC = p->apCsr[pOp->p1];
5815 assert( pC!=0 );
5816 assert( pC->eCurType==CURTYPE_BTREE );
5817 assert( pC->uc.pCursor!=0 );
5818 assert( pC->deferredMoveto==0 );
5819 sqlite3VdbeIncrWriteCounter(p, pC);
5821 #ifdef SQLITE_DEBUG
5822 if( pOp->p4type==P4_TABLE
5823 && HasRowid(pOp->p4.pTab)
5824 && pOp->p5==0
5825 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5827 /* If p5 is zero, the seek operation that positioned the cursor prior to
5828 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5829 ** the row that is being deleted */
5830 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5831 assert( CORRUPT_DB || pC->movetoTarget==iKey );
5833 #endif
5835 /* If the update-hook or pre-update-hook will be invoked, set zDb to
5836 ** the name of the db to pass as to it. Also set local pTab to a copy
5837 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5838 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5839 ** VdbeCursor.movetoTarget to the current rowid. */
5840 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5841 assert( pC->iDb>=0 );
5842 assert( pOp->p4.pTab!=0 );
5843 zDb = db->aDb[pC->iDb].zDbSName;
5844 pTab = pOp->p4.pTab;
5845 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5846 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5848 }else{
5849 zDb = 0;
5850 pTab = 0;
5853 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5854 /* Invoke the pre-update-hook if required. */
5855 assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
5856 if( db->xPreUpdateCallback && pTab ){
5857 assert( !(opflags & OPFLAG_ISUPDATE)
5858 || HasRowid(pTab)==0
5859 || (aMem[pOp->p3].flags & MEM_Int)
5861 sqlite3VdbePreUpdateHook(p, pC,
5862 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5863 zDb, pTab, pC->movetoTarget,
5864 pOp->p3, -1
5867 if( opflags & OPFLAG_ISNOOP ) break;
5868 #endif
5870 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5871 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5872 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5873 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5875 #ifdef SQLITE_DEBUG
5876 if( p->pFrame==0 ){
5877 if( pC->isEphemeral==0
5878 && (pOp->p5 & OPFLAG_AUXDELETE)==0
5879 && (pC->wrFlag & OPFLAG_FORDELETE)==0
5881 nExtraDelete++;
5883 if( pOp->p2 & OPFLAG_NCHANGE ){
5884 nExtraDelete--;
5887 #endif
5889 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5890 pC->cacheStatus = CACHE_STALE;
5891 colCacheCtr++;
5892 pC->seekResult = 0;
5893 if( rc ) goto abort_due_to_error;
5895 /* Invoke the update-hook if required. */
5896 if( opflags & OPFLAG_NCHANGE ){
5897 p->nChange++;
5898 if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
5899 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5900 pC->movetoTarget);
5901 assert( pC->iDb>=0 );
5905 break;
5907 /* Opcode: ResetCount * * * * *
5909 ** The value of the change counter is copied to the database handle
5910 ** change counter (returned by subsequent calls to sqlite3_changes()).
5911 ** Then the VMs internal change counter resets to 0.
5912 ** This is used by trigger programs.
5914 case OP_ResetCount: {
5915 sqlite3VdbeSetChanges(db, p->nChange);
5916 p->nChange = 0;
5917 break;
5920 /* Opcode: SorterCompare P1 P2 P3 P4
5921 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5923 ** P1 is a sorter cursor. This instruction compares a prefix of the
5924 ** record blob in register P3 against a prefix of the entry that
5925 ** the sorter cursor currently points to. Only the first P4 fields
5926 ** of r[P3] and the sorter record are compared.
5928 ** If either P3 or the sorter contains a NULL in one of their significant
5929 ** fields (not counting the P4 fields at the end which are ignored) then
5930 ** the comparison is assumed to be equal.
5932 ** Fall through to next instruction if the two records compare equal to
5933 ** each other. Jump to P2 if they are different.
5935 case OP_SorterCompare: {
5936 VdbeCursor *pC;
5937 int res;
5938 int nKeyCol;
5940 pC = p->apCsr[pOp->p1];
5941 assert( isSorter(pC) );
5942 assert( pOp->p4type==P4_INT32 );
5943 pIn3 = &aMem[pOp->p3];
5944 nKeyCol = pOp->p4.i;
5945 res = 0;
5946 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5947 VdbeBranchTaken(res!=0,2);
5948 if( rc ) goto abort_due_to_error;
5949 if( res ) goto jump_to_p2;
5950 break;
5953 /* Opcode: SorterData P1 P2 P3 * *
5954 ** Synopsis: r[P2]=data
5956 ** Write into register P2 the current sorter data for sorter cursor P1.
5957 ** Then clear the column header cache on cursor P3.
5959 ** This opcode is normally used to move a record out of the sorter and into
5960 ** a register that is the source for a pseudo-table cursor created using
5961 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
5962 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
5963 ** us from having to issue a separate NullRow instruction to clear that cache.
5965 case OP_SorterData: { /* ncycle */
5966 VdbeCursor *pC;
5968 pOut = &aMem[pOp->p2];
5969 pC = p->apCsr[pOp->p1];
5970 assert( isSorter(pC) );
5971 rc = sqlite3VdbeSorterRowkey(pC, pOut);
5972 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5973 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5974 if( rc ) goto abort_due_to_error;
5975 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5976 break;
5979 /* Opcode: RowData P1 P2 P3 * *
5980 ** Synopsis: r[P2]=data
5982 ** Write into register P2 the complete row content for the row at
5983 ** which cursor P1 is currently pointing.
5984 ** There is no interpretation of the data.
5985 ** It is just copied onto the P2 register exactly as
5986 ** it is found in the database file.
5988 ** If cursor P1 is an index, then the content is the key of the row.
5989 ** If cursor P2 is a table, then the content extracted is the data.
5991 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5992 ** of a real table, not a pseudo-table.
5994 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5995 ** into the database page. That means that the content of the output
5996 ** register will be invalidated as soon as the cursor moves - including
5997 ** moves caused by other cursors that "save" the current cursors
5998 ** position in order that they can write to the same table. If P3==0
5999 ** then a copy of the data is made into memory. P3!=0 is faster, but
6000 ** P3==0 is safer.
6002 ** If P3!=0 then the content of the P2 register is unsuitable for use
6003 ** in OP_Result and any OP_Result will invalidate the P2 register content.
6004 ** The P2 register content is invalidated by opcodes like OP_Function or
6005 ** by any use of another cursor pointing to the same table.
6007 case OP_RowData: {
6008 VdbeCursor *pC;
6009 BtCursor *pCrsr;
6010 u32 n;
6012 pOut = out2Prerelease(p, pOp);
6014 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6015 pC = p->apCsr[pOp->p1];
6016 assert( pC!=0 );
6017 assert( pC->eCurType==CURTYPE_BTREE );
6018 assert( isSorter(pC)==0 );
6019 assert( pC->nullRow==0 );
6020 assert( pC->uc.pCursor!=0 );
6021 pCrsr = pC->uc.pCursor;
6023 /* The OP_RowData opcodes always follow OP_NotExists or
6024 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
6025 ** that might invalidate the cursor.
6026 ** If this where not the case, on of the following assert()s
6027 ** would fail. Should this ever change (because of changes in the code
6028 ** generator) then the fix would be to insert a call to
6029 ** sqlite3VdbeCursorMoveto().
6031 assert( pC->deferredMoveto==0 );
6032 assert( sqlite3BtreeCursorIsValid(pCrsr) );
6034 n = sqlite3BtreePayloadSize(pCrsr);
6035 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
6036 goto too_big;
6038 testcase( n==0 );
6039 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
6040 if( rc ) goto abort_due_to_error;
6041 if( !pOp->p3 ) Deephemeralize(pOut);
6042 UPDATE_MAX_BLOBSIZE(pOut);
6043 REGISTER_TRACE(pOp->p2, pOut);
6044 break;
6047 /* Opcode: Rowid P1 P2 * * *
6048 ** Synopsis: r[P2]=PX rowid of P1
6050 ** Store in register P2 an integer which is the key of the table entry that
6051 ** P1 is currently point to.
6053 ** P1 can be either an ordinary table or a virtual table. There used to
6054 ** be a separate OP_VRowid opcode for use with virtual tables, but this
6055 ** one opcode now works for both table types.
6057 case OP_Rowid: { /* out2, ncycle */
6058 VdbeCursor *pC;
6059 i64 v;
6060 sqlite3_vtab *pVtab;
6061 const sqlite3_module *pModule;
6063 pOut = out2Prerelease(p, pOp);
6064 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6065 pC = p->apCsr[pOp->p1];
6066 assert( pC!=0 );
6067 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
6068 if( pC->nullRow ){
6069 pOut->flags = MEM_Null;
6070 break;
6071 }else if( pC->deferredMoveto ){
6072 v = pC->movetoTarget;
6073 #ifndef SQLITE_OMIT_VIRTUALTABLE
6074 }else if( pC->eCurType==CURTYPE_VTAB ){
6075 assert( pC->uc.pVCur!=0 );
6076 pVtab = pC->uc.pVCur->pVtab;
6077 pModule = pVtab->pModule;
6078 assert( pModule->xRowid );
6079 rc = pModule->xRowid(pC->uc.pVCur, &v);
6080 sqlite3VtabImportErrmsg(p, pVtab);
6081 if( rc ) goto abort_due_to_error;
6082 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6083 }else{
6084 assert( pC->eCurType==CURTYPE_BTREE );
6085 assert( pC->uc.pCursor!=0 );
6086 rc = sqlite3VdbeCursorRestore(pC);
6087 if( rc ) goto abort_due_to_error;
6088 if( pC->nullRow ){
6089 pOut->flags = MEM_Null;
6090 break;
6092 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
6094 pOut->u.i = v;
6095 break;
6098 /* Opcode: NullRow P1 * * * *
6100 ** Move the cursor P1 to a null row. Any OP_Column operations
6101 ** that occur while the cursor is on the null row will always
6102 ** write a NULL.
6104 ** If cursor P1 is not previously opened, open it now to a special
6105 ** pseudo-cursor that always returns NULL for every column.
6107 case OP_NullRow: {
6108 VdbeCursor *pC;
6110 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6111 pC = p->apCsr[pOp->p1];
6112 if( pC==0 ){
6113 /* If the cursor is not already open, create a special kind of
6114 ** pseudo-cursor that always gives null rows. */
6115 pC = allocateCursor(p, pOp->p1, 1, CURTYPE_PSEUDO);
6116 if( pC==0 ) goto no_mem;
6117 pC->seekResult = 0;
6118 pC->isTable = 1;
6119 pC->noReuse = 1;
6120 pC->uc.pCursor = sqlite3BtreeFakeValidCursor();
6122 pC->nullRow = 1;
6123 pC->cacheStatus = CACHE_STALE;
6124 if( pC->eCurType==CURTYPE_BTREE ){
6125 assert( pC->uc.pCursor!=0 );
6126 sqlite3BtreeClearCursor(pC->uc.pCursor);
6128 #ifdef SQLITE_DEBUG
6129 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
6130 #endif
6131 break;
6134 /* Opcode: SeekEnd P1 * * * *
6136 ** Position cursor P1 at the end of the btree for the purpose of
6137 ** appending a new entry onto the btree.
6139 ** It is assumed that the cursor is used only for appending and so
6140 ** if the cursor is valid, then the cursor must already be pointing
6141 ** at the end of the btree and so no changes are made to
6142 ** the cursor.
6144 /* Opcode: Last P1 P2 * * *
6146 ** The next use of the Rowid or Column or Prev instruction for P1
6147 ** will refer to the last entry in the database table or index.
6148 ** If the table or index is empty and P2>0, then jump immediately to P2.
6149 ** If P2 is 0 or if the table or index is not empty, fall through
6150 ** to the following instruction.
6152 ** This opcode leaves the cursor configured to move in reverse order,
6153 ** from the end toward the beginning. In other words, the cursor is
6154 ** configured to use Prev, not Next.
6156 case OP_SeekEnd: /* ncycle */
6157 case OP_Last: { /* jump, ncycle */
6158 VdbeCursor *pC;
6159 BtCursor *pCrsr;
6160 int res;
6162 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6163 pC = p->apCsr[pOp->p1];
6164 assert( pC!=0 );
6165 assert( pC->eCurType==CURTYPE_BTREE );
6166 pCrsr = pC->uc.pCursor;
6167 res = 0;
6168 assert( pCrsr!=0 );
6169 #ifdef SQLITE_DEBUG
6170 pC->seekOp = pOp->opcode;
6171 #endif
6172 if( pOp->opcode==OP_SeekEnd ){
6173 assert( pOp->p2==0 );
6174 pC->seekResult = -1;
6175 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
6176 break;
6179 rc = sqlite3BtreeLast(pCrsr, &res);
6180 pC->nullRow = (u8)res;
6181 pC->deferredMoveto = 0;
6182 pC->cacheStatus = CACHE_STALE;
6183 if( rc ) goto abort_due_to_error;
6184 if( pOp->p2>0 ){
6185 VdbeBranchTaken(res!=0,2);
6186 if( res ) goto jump_to_p2;
6188 break;
6191 /* Opcode: IfSizeBetween P1 P2 P3 P4 *
6193 ** Let N be the approximate number of rows in the table or index
6194 ** with cursor P1 and let X be 10*log2(N) if N is positive or -1
6195 ** if N is zero. Thus X will be within the range of -1 to 640, inclusive
6196 ** Jump to P2 if X is in between P3 and P4, inclusive.
6198 case OP_IfSizeBetween: { /* jump */
6199 VdbeCursor *pC;
6200 BtCursor *pCrsr;
6201 int res;
6202 i64 sz;
6204 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6205 assert( pOp->p4type==P4_INT32 );
6206 assert( pOp->p3>=-1 && pOp->p3<=640 );
6207 assert( pOp->p4.i>=-1 && pOp->p4.i<=640 );
6208 pC = p->apCsr[pOp->p1];
6209 assert( pC!=0 );
6210 pCrsr = pC->uc.pCursor;
6211 assert( pCrsr );
6212 rc = sqlite3BtreeFirst(pCrsr, &res);
6213 if( rc ) goto abort_due_to_error;
6214 if( res!=0 ){
6215 sz = -1; /* -Infinity encoding */
6216 }else{
6217 sz = sqlite3BtreeRowCountEst(pCrsr);
6218 assert( sz>0 );
6219 sz = sqlite3LogEst((u64)sz);
6221 res = sz>=pOp->p3 && sz<=pOp->p4.i;
6222 VdbeBranchTaken(res!=0,2);
6223 if( res ) goto jump_to_p2;
6224 break;
6228 /* Opcode: SorterSort P1 P2 * * *
6230 ** After all records have been inserted into the Sorter object
6231 ** identified by P1, invoke this opcode to actually do the sorting.
6232 ** Jump to P2 if there are no records to be sorted.
6234 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
6235 ** for Sorter objects.
6237 /* Opcode: Sort P1 P2 * * *
6239 ** This opcode does exactly the same thing as OP_Rewind except that
6240 ** it increments an undocumented global variable used for testing.
6242 ** Sorting is accomplished by writing records into a sorting index,
6243 ** then rewinding that index and playing it back from beginning to
6244 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
6245 ** rewinding so that the global variable will be incremented and
6246 ** regression tests can determine whether or not the optimizer is
6247 ** correctly optimizing out sorts.
6249 case OP_SorterSort: /* jump ncycle */
6250 case OP_Sort: { /* jump ncycle */
6251 #ifdef SQLITE_TEST
6252 sqlite3_sort_count++;
6253 sqlite3_search_count--;
6254 #endif
6255 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
6256 /* Fall through into OP_Rewind */
6257 /* no break */ deliberate_fall_through
6259 /* Opcode: Rewind P1 P2 * * *
6261 ** The next use of the Rowid or Column or Next instruction for P1
6262 ** will refer to the first entry in the database table or index.
6263 ** If the table or index is empty, jump immediately to P2.
6264 ** If the table or index is not empty, fall through to the following
6265 ** instruction.
6267 ** If P2 is zero, that is an assertion that the P1 table is never
6268 ** empty and hence the jump will never be taken.
6270 ** This opcode leaves the cursor configured to move in forward order,
6271 ** from the beginning toward the end. In other words, the cursor is
6272 ** configured to use Next, not Prev.
6274 case OP_Rewind: { /* jump, ncycle */
6275 VdbeCursor *pC;
6276 BtCursor *pCrsr;
6277 int res;
6279 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6280 assert( pOp->p5==0 );
6281 assert( pOp->p2>=0 && pOp->p2<p->nOp );
6283 pC = p->apCsr[pOp->p1];
6284 assert( pC!=0 );
6285 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
6286 res = 1;
6287 #ifdef SQLITE_DEBUG
6288 pC->seekOp = OP_Rewind;
6289 #endif
6290 if( isSorter(pC) ){
6291 rc = sqlite3VdbeSorterRewind(pC, &res);
6292 }else{
6293 assert( pC->eCurType==CURTYPE_BTREE );
6294 pCrsr = pC->uc.pCursor;
6295 assert( pCrsr );
6296 rc = sqlite3BtreeFirst(pCrsr, &res);
6297 pC->deferredMoveto = 0;
6298 pC->cacheStatus = CACHE_STALE;
6300 if( rc ) goto abort_due_to_error;
6301 pC->nullRow = (u8)res;
6302 if( pOp->p2>0 ){
6303 VdbeBranchTaken(res!=0,2);
6304 if( res ) goto jump_to_p2;
6306 break;
6309 /* Opcode: Next P1 P2 P3 * P5
6311 ** Advance cursor P1 so that it points to the next key/data pair in its
6312 ** table or index. If there are no more key/value pairs then fall through
6313 ** to the following instruction. But if the cursor advance was successful,
6314 ** jump immediately to P2.
6316 ** The Next opcode is only valid following an SeekGT, SeekGE, or
6317 ** OP_Rewind opcode used to position the cursor. Next is not allowed
6318 ** to follow SeekLT, SeekLE, or OP_Last.
6320 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
6321 ** been opened prior to this opcode or the program will segfault.
6323 ** The P3 value is a hint to the btree implementation. If P3==1, that
6324 ** means P1 is an SQL index and that this instruction could have been
6325 ** omitted if that index had been unique. P3 is usually 0. P3 is
6326 ** always either 0 or 1.
6328 ** If P5 is positive and the jump is taken, then event counter
6329 ** number P5-1 in the prepared statement is incremented.
6331 ** See also: Prev
6333 /* Opcode: Prev P1 P2 P3 * P5
6335 ** Back up cursor P1 so that it points to the previous key/data pair in its
6336 ** table or index. If there is no previous key/value pairs then fall through
6337 ** to the following instruction. But if the cursor backup was successful,
6338 ** jump immediately to P2.
6341 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
6342 ** OP_Last opcode used to position the cursor. Prev is not allowed
6343 ** to follow SeekGT, SeekGE, or OP_Rewind.
6345 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
6346 ** not open then the behavior is undefined.
6348 ** The P3 value is a hint to the btree implementation. If P3==1, that
6349 ** means P1 is an SQL index and that this instruction could have been
6350 ** omitted if that index had been unique. P3 is usually 0. P3 is
6351 ** always either 0 or 1.
6353 ** If P5 is positive and the jump is taken, then event counter
6354 ** number P5-1 in the prepared statement is incremented.
6356 /* Opcode: SorterNext P1 P2 * * P5
6358 ** This opcode works just like OP_Next except that P1 must be a
6359 ** sorter object for which the OP_SorterSort opcode has been
6360 ** invoked. This opcode advances the cursor to the next sorted
6361 ** record, or jumps to P2 if there are no more sorted records.
6363 case OP_SorterNext: { /* jump */
6364 VdbeCursor *pC;
6366 pC = p->apCsr[pOp->p1];
6367 assert( isSorter(pC) );
6368 rc = sqlite3VdbeSorterNext(db, pC);
6369 goto next_tail;
6371 case OP_Prev: /* jump, ncycle */
6372 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6373 assert( pOp->p5==0
6374 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6375 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6376 pC = p->apCsr[pOp->p1];
6377 assert( pC!=0 );
6378 assert( pC->deferredMoveto==0 );
6379 assert( pC->eCurType==CURTYPE_BTREE );
6380 assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
6381 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
6382 || pC->seekOp==OP_NullRow);
6383 rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
6384 goto next_tail;
6386 case OP_Next: /* jump, ncycle */
6387 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6388 assert( pOp->p5==0
6389 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6390 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6391 pC = p->apCsr[pOp->p1];
6392 assert( pC!=0 );
6393 assert( pC->deferredMoveto==0 );
6394 assert( pC->eCurType==CURTYPE_BTREE );
6395 assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
6396 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
6397 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
6398 || pC->seekOp==OP_IfNoHope);
6399 rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
6401 next_tail:
6402 pC->cacheStatus = CACHE_STALE;
6403 VdbeBranchTaken(rc==SQLITE_OK,2);
6404 if( rc==SQLITE_OK ){
6405 pC->nullRow = 0;
6406 p->aCounter[pOp->p5]++;
6407 #ifdef SQLITE_TEST
6408 sqlite3_search_count++;
6409 #endif
6410 goto jump_to_p2_and_check_for_interrupt;
6412 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6413 rc = SQLITE_OK;
6414 pC->nullRow = 1;
6415 goto check_for_interrupt;
6418 /* Opcode: IdxInsert P1 P2 P3 P4 P5
6419 ** Synopsis: key=r[P2]
6421 ** Register P2 holds an SQL index key made using the
6422 ** MakeRecord instructions. This opcode writes that key
6423 ** into the index P1. Data for the entry is nil.
6425 ** If P4 is not zero, then it is the number of values in the unpacked
6426 ** key of reg(P2). In that case, P3 is the index of the first register
6427 ** for the unpacked key. The availability of the unpacked key can sometimes
6428 ** be an optimization.
6430 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
6431 ** that this insert is likely to be an append.
6433 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
6434 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
6435 ** then the change counter is unchanged.
6437 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
6438 ** run faster by avoiding an unnecessary seek on cursor P1. However,
6439 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
6440 ** seeks on the cursor or if the most recent seek used a key equivalent
6441 ** to P2.
6443 ** This instruction only works for indices. The equivalent instruction
6444 ** for tables is OP_Insert.
6446 case OP_IdxInsert: { /* in2 */
6447 VdbeCursor *pC;
6448 BtreePayload x;
6450 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6451 pC = p->apCsr[pOp->p1];
6452 sqlite3VdbeIncrWriteCounter(p, pC);
6453 assert( pC!=0 );
6454 assert( !isSorter(pC) );
6455 pIn2 = &aMem[pOp->p2];
6456 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
6457 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
6458 assert( pC->eCurType==CURTYPE_BTREE );
6459 assert( pC->isTable==0 );
6460 rc = ExpandBlob(pIn2);
6461 if( rc ) goto abort_due_to_error;
6462 x.nKey = pIn2->n;
6463 x.pKey = pIn2->z;
6464 x.aMem = aMem + pOp->p3;
6465 x.nMem = (u16)pOp->p4.i;
6466 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
6467 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
6468 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
6470 assert( pC->deferredMoveto==0 );
6471 pC->cacheStatus = CACHE_STALE;
6472 if( rc) goto abort_due_to_error;
6473 break;
6476 /* Opcode: SorterInsert P1 P2 * * *
6477 ** Synopsis: key=r[P2]
6479 ** Register P2 holds an SQL index key made using the
6480 ** MakeRecord instructions. This opcode writes that key
6481 ** into the sorter P1. Data for the entry is nil.
6483 case OP_SorterInsert: { /* in2 */
6484 VdbeCursor *pC;
6486 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6487 pC = p->apCsr[pOp->p1];
6488 sqlite3VdbeIncrWriteCounter(p, pC);
6489 assert( pC!=0 );
6490 assert( isSorter(pC) );
6491 pIn2 = &aMem[pOp->p2];
6492 assert( pIn2->flags & MEM_Blob );
6493 assert( pC->isTable==0 );
6494 rc = ExpandBlob(pIn2);
6495 if( rc ) goto abort_due_to_error;
6496 rc = sqlite3VdbeSorterWrite(pC, pIn2);
6497 if( rc) goto abort_due_to_error;
6498 break;
6501 /* Opcode: IdxDelete P1 P2 P3 * P5
6502 ** Synopsis: key=r[P2@P3]
6504 ** The content of P3 registers starting at register P2 form
6505 ** an unpacked index key. This opcode removes that entry from the
6506 ** index opened by cursor P1.
6508 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
6509 ** if no matching index entry is found. This happens when running
6510 ** an UPDATE or DELETE statement and the index entry to be updated
6511 ** or deleted is not found. For some uses of IdxDelete
6512 ** (example: the EXCEPT operator) it does not matter that no matching
6513 ** entry is found. For those cases, P5 is zero. Also, do not raise
6514 ** this (self-correcting and non-critical) error if in writable_schema mode.
6516 case OP_IdxDelete: {
6517 VdbeCursor *pC;
6518 BtCursor *pCrsr;
6519 int res;
6520 UnpackedRecord r;
6522 assert( pOp->p3>0 );
6523 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
6524 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6525 pC = p->apCsr[pOp->p1];
6526 assert( pC!=0 );
6527 assert( pC->eCurType==CURTYPE_BTREE );
6528 sqlite3VdbeIncrWriteCounter(p, pC);
6529 pCrsr = pC->uc.pCursor;
6530 assert( pCrsr!=0 );
6531 r.pKeyInfo = pC->pKeyInfo;
6532 r.nField = (u16)pOp->p3;
6533 r.default_rc = 0;
6534 r.aMem = &aMem[pOp->p2];
6535 rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
6536 if( rc ) goto abort_due_to_error;
6537 if( res==0 ){
6538 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
6539 if( rc ) goto abort_due_to_error;
6540 }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
6541 rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
6542 goto abort_due_to_error;
6544 assert( pC->deferredMoveto==0 );
6545 pC->cacheStatus = CACHE_STALE;
6546 pC->seekResult = 0;
6547 break;
6550 /* Opcode: DeferredSeek P1 * P3 P4 *
6551 ** Synopsis: Move P3 to P1.rowid if needed
6553 ** P1 is an open index cursor and P3 is a cursor on the corresponding
6554 ** table. This opcode does a deferred seek of the P3 table cursor
6555 ** to the row that corresponds to the current row of P1.
6557 ** This is a deferred seek. Nothing actually happens until
6558 ** the cursor is used to read a record. That way, if no reads
6559 ** occur, no unnecessary I/O happens.
6561 ** P4 may be an array of integers (type P4_INTARRAY) containing
6562 ** one entry for each column in the P3 table. If array entry a(i)
6563 ** is non-zero, then reading column a(i)-1 from cursor P3 is
6564 ** equivalent to performing the deferred seek and then reading column i
6565 ** from P1. This information is stored in P3 and used to redirect
6566 ** reads against P3 over to P1, thus possibly avoiding the need to
6567 ** seek and read cursor P3.
6569 /* Opcode: IdxRowid P1 P2 * * *
6570 ** Synopsis: r[P2]=rowid
6572 ** Write into register P2 an integer which is the last entry in the record at
6573 ** the end of the index key pointed to by cursor P1. This integer should be
6574 ** the rowid of the table entry to which this index entry points.
6576 ** See also: Rowid, MakeRecord.
6578 case OP_DeferredSeek: /* ncycle */
6579 case OP_IdxRowid: { /* out2, ncycle */
6580 VdbeCursor *pC; /* The P1 index cursor */
6581 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
6582 i64 rowid; /* Rowid that P1 current points to */
6584 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6585 pC = p->apCsr[pOp->p1];
6586 assert( pC!=0 );
6587 assert( pC->eCurType==CURTYPE_BTREE || IsNullCursor(pC) );
6588 assert( pC->uc.pCursor!=0 );
6589 assert( pC->isTable==0 || IsNullCursor(pC) );
6590 assert( pC->deferredMoveto==0 );
6591 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
6593 /* The IdxRowid and Seek opcodes are combined because of the commonality
6594 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
6595 rc = sqlite3VdbeCursorRestore(pC);
6597 /* sqlite3VdbeCursorRestore() may fail if the cursor has been disturbed
6598 ** since it was last positioned and an error (e.g. OOM or an IO error)
6599 ** occurs while trying to reposition it. */
6600 if( rc!=SQLITE_OK ) goto abort_due_to_error;
6602 if( !pC->nullRow ){
6603 rowid = 0; /* Not needed. Only used to silence a warning. */
6604 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
6605 if( rc!=SQLITE_OK ){
6606 goto abort_due_to_error;
6608 if( pOp->opcode==OP_DeferredSeek ){
6609 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
6610 pTabCur = p->apCsr[pOp->p3];
6611 assert( pTabCur!=0 );
6612 assert( pTabCur->eCurType==CURTYPE_BTREE );
6613 assert( pTabCur->uc.pCursor!=0 );
6614 assert( pTabCur->isTable );
6615 pTabCur->nullRow = 0;
6616 pTabCur->movetoTarget = rowid;
6617 pTabCur->deferredMoveto = 1;
6618 pTabCur->cacheStatus = CACHE_STALE;
6619 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
6620 assert( !pTabCur->isEphemeral );
6621 pTabCur->ub.aAltMap = pOp->p4.ai;
6622 assert( !pC->isEphemeral );
6623 pTabCur->pAltCursor = pC;
6624 }else{
6625 pOut = out2Prerelease(p, pOp);
6626 pOut->u.i = rowid;
6628 }else{
6629 assert( pOp->opcode==OP_IdxRowid );
6630 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
6632 break;
6635 /* Opcode: FinishSeek P1 * * * *
6637 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
6638 ** seek operation now, without further delay. If the cursor seek has
6639 ** already occurred, this instruction is a no-op.
6641 case OP_FinishSeek: { /* ncycle */
6642 VdbeCursor *pC; /* The P1 index cursor */
6644 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6645 pC = p->apCsr[pOp->p1];
6646 if( pC->deferredMoveto ){
6647 rc = sqlite3VdbeFinishMoveto(pC);
6648 if( rc ) goto abort_due_to_error;
6650 break;
6653 /* Opcode: IdxGE P1 P2 P3 P4 *
6654 ** Synopsis: key=r[P3@P4]
6656 ** The P4 register values beginning with P3 form an unpacked index
6657 ** key that omits the PRIMARY KEY. Compare this key value against the index
6658 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6659 ** fields at the end.
6661 ** If the P1 index entry is greater than or equal to the key value
6662 ** then jump to P2. Otherwise fall through to the next instruction.
6664 /* Opcode: IdxGT P1 P2 P3 P4 *
6665 ** Synopsis: key=r[P3@P4]
6667 ** The P4 register values beginning with P3 form an unpacked index
6668 ** key that omits the PRIMARY KEY. Compare this key value against the index
6669 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6670 ** fields at the end.
6672 ** If the P1 index entry is greater than the key value
6673 ** then jump to P2. Otherwise fall through to the next instruction.
6675 /* Opcode: IdxLT P1 P2 P3 P4 *
6676 ** Synopsis: key=r[P3@P4]
6678 ** The P4 register values beginning with P3 form an unpacked index
6679 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6680 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6681 ** ROWID on the P1 index.
6683 ** If the P1 index entry is less than the key value then jump to P2.
6684 ** Otherwise fall through to the next instruction.
6686 /* Opcode: IdxLE P1 P2 P3 P4 *
6687 ** Synopsis: key=r[P3@P4]
6689 ** The P4 register values beginning with P3 form an unpacked index
6690 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6691 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6692 ** ROWID on the P1 index.
6694 ** If the P1 index entry is less than or equal to the key value then jump
6695 ** to P2. Otherwise fall through to the next instruction.
6697 case OP_IdxLE: /* jump, ncycle */
6698 case OP_IdxGT: /* jump, ncycle */
6699 case OP_IdxLT: /* jump, ncycle */
6700 case OP_IdxGE: { /* jump, ncycle */
6701 VdbeCursor *pC;
6702 int res;
6703 UnpackedRecord r;
6705 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6706 pC = p->apCsr[pOp->p1];
6707 assert( pC!=0 );
6708 assert( pC->isOrdered );
6709 assert( pC->eCurType==CURTYPE_BTREE );
6710 assert( pC->uc.pCursor!=0);
6711 assert( pC->deferredMoveto==0 );
6712 assert( pOp->p4type==P4_INT32 );
6713 r.pKeyInfo = pC->pKeyInfo;
6714 r.nField = (u16)pOp->p4.i;
6715 if( pOp->opcode<OP_IdxLT ){
6716 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6717 r.default_rc = -1;
6718 }else{
6719 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6720 r.default_rc = 0;
6722 r.aMem = &aMem[pOp->p3];
6723 #ifdef SQLITE_DEBUG
6725 int i;
6726 for(i=0; i<r.nField; i++){
6727 assert( memIsValid(&r.aMem[i]) );
6728 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6731 #endif
6733 /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6735 i64 nCellKey = 0;
6736 BtCursor *pCur;
6737 Mem m;
6739 assert( pC->eCurType==CURTYPE_BTREE );
6740 pCur = pC->uc.pCursor;
6741 assert( sqlite3BtreeCursorIsValid(pCur) );
6742 nCellKey = sqlite3BtreePayloadSize(pCur);
6743 /* nCellKey will always be between 0 and 0xffffffff because of the way
6744 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6745 if( nCellKey<=0 || nCellKey>0x7fffffff ){
6746 rc = SQLITE_CORRUPT_BKPT;
6747 goto abort_due_to_error;
6749 sqlite3VdbeMemInit(&m, db, 0);
6750 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6751 if( rc ) goto abort_due_to_error;
6752 res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6753 sqlite3VdbeMemReleaseMalloc(&m);
6755 /* End of inlined sqlite3VdbeIdxKeyCompare() */
6757 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6758 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6759 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6760 res = -res;
6761 }else{
6762 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6763 res++;
6765 VdbeBranchTaken(res>0,2);
6766 assert( rc==SQLITE_OK );
6767 if( res>0 ) goto jump_to_p2;
6768 break;
6771 /* Opcode: Destroy P1 P2 P3 * *
6773 ** Delete an entire database table or index whose root page in the database
6774 ** file is given by P1.
6776 ** The table being destroyed is in the main database file if P3==0. If
6777 ** P3==1 then the table to be destroyed is in the auxiliary database file
6778 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6780 ** If AUTOVACUUM is enabled then it is possible that another root page
6781 ** might be moved into the newly deleted root page in order to keep all
6782 ** root pages contiguous at the beginning of the database. The former
6783 ** value of the root page that moved - its value before the move occurred -
6784 ** is stored in register P2. If no page movement was required (because the
6785 ** table being dropped was already the last one in the database) then a
6786 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
6787 ** is stored in register P2.
6789 ** This opcode throws an error if there are any active reader VMs when
6790 ** it is invoked. This is done to avoid the difficulty associated with
6791 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6792 ** database. This error is thrown even if the database is not an AUTOVACUUM
6793 ** db in order to avoid introducing an incompatibility between autovacuum
6794 ** and non-autovacuum modes.
6796 ** See also: Clear
6798 case OP_Destroy: { /* out2 */
6799 int iMoved;
6800 int iDb;
6802 sqlite3VdbeIncrWriteCounter(p, 0);
6803 assert( p->readOnly==0 );
6804 assert( pOp->p1>1 );
6805 pOut = out2Prerelease(p, pOp);
6806 pOut->flags = MEM_Null;
6807 if( db->nVdbeRead > db->nVDestroy+1 ){
6808 rc = SQLITE_LOCKED;
6809 p->errorAction = OE_Abort;
6810 goto abort_due_to_error;
6811 }else{
6812 iDb = pOp->p3;
6813 assert( DbMaskTest(p->btreeMask, iDb) );
6814 iMoved = 0; /* Not needed. Only to silence a warning. */
6815 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6816 pOut->flags = MEM_Int;
6817 pOut->u.i = iMoved;
6818 if( rc ) goto abort_due_to_error;
6819 #ifndef SQLITE_OMIT_AUTOVACUUM
6820 if( iMoved!=0 ){
6821 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6822 /* All OP_Destroy operations occur on the same btree */
6823 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6824 resetSchemaOnFault = iDb+1;
6826 #endif
6828 break;
6831 /* Opcode: Clear P1 P2 P3
6833 ** Delete all contents of the database table or index whose root page
6834 ** in the database file is given by P1. But, unlike Destroy, do not
6835 ** remove the table or index from the database file.
6837 ** The table being cleared is in the main database file if P2==0. If
6838 ** P2==1 then the table to be cleared is in the auxiliary database file
6839 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6841 ** If the P3 value is non-zero, then the row change count is incremented
6842 ** by the number of rows in the table being cleared. If P3 is greater
6843 ** than zero, then the value stored in register P3 is also incremented
6844 ** by the number of rows in the table being cleared.
6846 ** See also: Destroy
6848 case OP_Clear: {
6849 i64 nChange;
6851 sqlite3VdbeIncrWriteCounter(p, 0);
6852 nChange = 0;
6853 assert( p->readOnly==0 );
6854 assert( DbMaskTest(p->btreeMask, pOp->p2) );
6855 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
6856 if( pOp->p3 ){
6857 p->nChange += nChange;
6858 if( pOp->p3>0 ){
6859 assert( memIsValid(&aMem[pOp->p3]) );
6860 memAboutToChange(p, &aMem[pOp->p3]);
6861 aMem[pOp->p3].u.i += nChange;
6864 if( rc ) goto abort_due_to_error;
6865 break;
6868 /* Opcode: ResetSorter P1 * * * *
6870 ** Delete all contents from the ephemeral table or sorter
6871 ** that is open on cursor P1.
6873 ** This opcode only works for cursors used for sorting and
6874 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6876 case OP_ResetSorter: {
6877 VdbeCursor *pC;
6879 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6880 pC = p->apCsr[pOp->p1];
6881 assert( pC!=0 );
6882 if( isSorter(pC) ){
6883 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6884 }else{
6885 assert( pC->eCurType==CURTYPE_BTREE );
6886 assert( pC->isEphemeral );
6887 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6888 if( rc ) goto abort_due_to_error;
6890 break;
6893 /* Opcode: CreateBtree P1 P2 P3 * *
6894 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6896 ** Allocate a new b-tree in the main database file if P1==0 or in the
6897 ** TEMP database file if P1==1 or in an attached database if
6898 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6899 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6900 ** The root page number of the new b-tree is stored in register P2.
6902 case OP_CreateBtree: { /* out2 */
6903 Pgno pgno;
6904 Db *pDb;
6906 sqlite3VdbeIncrWriteCounter(p, 0);
6907 pOut = out2Prerelease(p, pOp);
6908 pgno = 0;
6909 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6910 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6911 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6912 assert( p->readOnly==0 );
6913 pDb = &db->aDb[pOp->p1];
6914 assert( pDb->pBt!=0 );
6915 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6916 if( rc ) goto abort_due_to_error;
6917 pOut->u.i = pgno;
6918 break;
6921 /* Opcode: SqlExec P1 P2 * P4 *
6923 ** Run the SQL statement or statements specified in the P4 string.
6925 ** The P1 parameter is a bitmask of options:
6927 ** 0x0001 Disable Auth and Trace callbacks while the statements
6928 ** in P4 are running.
6930 ** 0x0002 Set db->nAnalysisLimit to P2 while the statements in
6931 ** P4 are running.
6934 case OP_SqlExec: {
6935 char *zErr;
6936 #ifndef SQLITE_OMIT_AUTHORIZATION
6937 sqlite3_xauth xAuth;
6938 #endif
6939 u8 mTrace;
6940 int savedAnalysisLimit;
6942 sqlite3VdbeIncrWriteCounter(p, 0);
6943 db->nSqlExec++;
6944 zErr = 0;
6945 #ifndef SQLITE_OMIT_AUTHORIZATION
6946 xAuth = db->xAuth;
6947 #endif
6948 mTrace = db->mTrace;
6949 savedAnalysisLimit = db->nAnalysisLimit;
6950 if( pOp->p1 & 0x0001 ){
6951 #ifndef SQLITE_OMIT_AUTHORIZATION
6952 db->xAuth = 0;
6953 #endif
6954 db->mTrace = 0;
6956 if( pOp->p1 & 0x0002 ){
6957 db->nAnalysisLimit = pOp->p2;
6959 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, &zErr);
6960 db->nSqlExec--;
6961 #ifndef SQLITE_OMIT_AUTHORIZATION
6962 db->xAuth = xAuth;
6963 #endif
6964 db->mTrace = mTrace;
6965 db->nAnalysisLimit = savedAnalysisLimit;
6966 if( zErr || rc ){
6967 sqlite3VdbeError(p, "%s", zErr);
6968 sqlite3_free(zErr);
6969 if( rc==SQLITE_NOMEM ) goto no_mem;
6970 goto abort_due_to_error;
6972 break;
6975 /* Opcode: ParseSchema P1 * * P4 *
6977 ** Read and parse all entries from the schema table of database P1
6978 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
6979 ** entire schema for P1 is reparsed.
6981 ** This opcode invokes the parser to create a new virtual machine,
6982 ** then runs the new virtual machine. It is thus a re-entrant opcode.
6984 case OP_ParseSchema: {
6985 int iDb;
6986 const char *zSchema;
6987 char *zSql;
6988 InitData initData;
6990 /* Any prepared statement that invokes this opcode will hold mutexes
6991 ** on every btree. This is a prerequisite for invoking
6992 ** sqlite3InitCallback().
6994 #ifdef SQLITE_DEBUG
6995 for(iDb=0; iDb<db->nDb; iDb++){
6996 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
6998 #endif
7000 iDb = pOp->p1;
7001 assert( iDb>=0 && iDb<db->nDb );
7002 assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
7003 || db->mallocFailed
7004 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
7006 #ifndef SQLITE_OMIT_ALTERTABLE
7007 if( pOp->p4.z==0 ){
7008 sqlite3SchemaClear(db->aDb[iDb].pSchema);
7009 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
7010 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
7011 db->mDbFlags |= DBFLAG_SchemaChange;
7012 p->expired = 0;
7013 }else
7014 #endif
7016 zSchema = LEGACY_SCHEMA_TABLE;
7017 initData.db = db;
7018 initData.iDb = iDb;
7019 initData.pzErrMsg = &p->zErrMsg;
7020 initData.mInitFlags = 0;
7021 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
7022 zSql = sqlite3MPrintf(db,
7023 "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
7024 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
7025 if( zSql==0 ){
7026 rc = SQLITE_NOMEM_BKPT;
7027 }else{
7028 assert( db->init.busy==0 );
7029 db->init.busy = 1;
7030 initData.rc = SQLITE_OK;
7031 initData.nInitRow = 0;
7032 assert( !db->mallocFailed );
7033 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
7034 if( rc==SQLITE_OK ) rc = initData.rc;
7035 if( rc==SQLITE_OK && initData.nInitRow==0 ){
7036 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
7037 ** at least one SQL statement. Any less than that indicates that
7038 ** the sqlite_schema table is corrupt. */
7039 rc = SQLITE_CORRUPT_BKPT;
7041 sqlite3DbFreeNN(db, zSql);
7042 db->init.busy = 0;
7045 if( rc ){
7046 sqlite3ResetAllSchemasOfConnection(db);
7047 if( rc==SQLITE_NOMEM ){
7048 goto no_mem;
7050 goto abort_due_to_error;
7052 break;
7055 #if !defined(SQLITE_OMIT_ANALYZE)
7056 /* Opcode: LoadAnalysis P1 * * * *
7058 ** Read the sqlite_stat1 table for database P1 and load the content
7059 ** of that table into the internal index hash table. This will cause
7060 ** the analysis to be used when preparing all subsequent queries.
7062 case OP_LoadAnalysis: {
7063 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7064 rc = sqlite3AnalysisLoad(db, pOp->p1);
7065 if( rc ) goto abort_due_to_error;
7066 break;
7068 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
7070 /* Opcode: DropTable P1 * * P4 *
7072 ** Remove the internal (in-memory) data structures that describe
7073 ** the table named P4 in database P1. This is called after a table
7074 ** is dropped from disk (using the Destroy opcode) in order to keep
7075 ** the internal representation of the
7076 ** schema consistent with what is on disk.
7078 case OP_DropTable: {
7079 sqlite3VdbeIncrWriteCounter(p, 0);
7080 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
7081 break;
7084 /* Opcode: DropIndex P1 * * P4 *
7086 ** Remove the internal (in-memory) data structures that describe
7087 ** the index named P4 in database P1. This is called after an index
7088 ** is dropped from disk (using the Destroy opcode)
7089 ** in order to keep the internal representation of the
7090 ** schema consistent with what is on disk.
7092 case OP_DropIndex: {
7093 sqlite3VdbeIncrWriteCounter(p, 0);
7094 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
7095 break;
7098 /* Opcode: DropTrigger P1 * * P4 *
7100 ** Remove the internal (in-memory) data structures that describe
7101 ** the trigger named P4 in database P1. This is called after a trigger
7102 ** is dropped from disk (using the Destroy opcode) in order to keep
7103 ** the internal representation of the
7104 ** schema consistent with what is on disk.
7106 case OP_DropTrigger: {
7107 sqlite3VdbeIncrWriteCounter(p, 0);
7108 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
7109 break;
7113 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
7114 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
7116 ** Do an analysis of the currently open database. Store in
7117 ** register (P1+1) the text of an error message describing any problems.
7118 ** If no problems are found, store a NULL in register (P1+1).
7120 ** The register (P1) contains one less than the maximum number of allowed
7121 ** errors. At most reg(P1) errors will be reported.
7122 ** In other words, the analysis stops as soon as reg(P1) errors are
7123 ** seen. Reg(P1) is updated with the number of errors remaining.
7125 ** The root page numbers of all tables in the database are integers
7126 ** stored in P4_INTARRAY argument.
7128 ** If P5 is not zero, the check is done on the auxiliary database
7129 ** file, not the main database file.
7131 ** This opcode is used to implement the integrity_check pragma.
7133 case OP_IntegrityCk: {
7134 int nRoot; /* Number of tables to check. (Number of root pages.) */
7135 Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */
7136 int nErr; /* Number of errors reported */
7137 char *z; /* Text of the error report */
7138 Mem *pnErr; /* Register keeping track of errors remaining */
7140 assert( p->bIsReader );
7141 assert( pOp->p4type==P4_INTARRAY );
7142 nRoot = pOp->p2;
7143 aRoot = pOp->p4.ai;
7144 assert( nRoot>0 );
7145 assert( aRoot!=0 );
7146 assert( aRoot[0]==(Pgno)nRoot );
7147 assert( pOp->p1>0 && (pOp->p1+1)<=(p->nMem+1 - p->nCursor) );
7148 pnErr = &aMem[pOp->p1];
7149 assert( (pnErr->flags & MEM_Int)!=0 );
7150 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
7151 pIn1 = &aMem[pOp->p1+1];
7152 assert( pOp->p5<db->nDb );
7153 assert( DbMaskTest(p->btreeMask, pOp->p5) );
7154 rc = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1],
7155 &aMem[pOp->p3], nRoot, (int)pnErr->u.i+1, &nErr, &z);
7156 sqlite3VdbeMemSetNull(pIn1);
7157 if( nErr==0 ){
7158 assert( z==0 );
7159 }else if( rc ){
7160 sqlite3_free(z);
7161 goto abort_due_to_error;
7162 }else{
7163 pnErr->u.i -= nErr-1;
7164 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
7166 UPDATE_MAX_BLOBSIZE(pIn1);
7167 sqlite3VdbeChangeEncoding(pIn1, encoding);
7168 goto check_for_interrupt;
7170 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
7172 /* Opcode: RowSetAdd P1 P2 * * *
7173 ** Synopsis: rowset(P1)=r[P2]
7175 ** Insert the integer value held by register P2 into a RowSet object
7176 ** held in register P1.
7178 ** An assertion fails if P2 is not an integer.
7180 case OP_RowSetAdd: { /* in1, in2 */
7181 pIn1 = &aMem[pOp->p1];
7182 pIn2 = &aMem[pOp->p2];
7183 assert( (pIn2->flags & MEM_Int)!=0 );
7184 if( (pIn1->flags & MEM_Blob)==0 ){
7185 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7187 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7188 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
7189 break;
7192 /* Opcode: RowSetRead P1 P2 P3 * *
7193 ** Synopsis: r[P3]=rowset(P1)
7195 ** Extract the smallest value from the RowSet object in P1
7196 ** and put that value into register P3.
7197 ** Or, if RowSet object P1 is initially empty, leave P3
7198 ** unchanged and jump to instruction P2.
7200 case OP_RowSetRead: { /* jump, in1, out3 */
7201 i64 val;
7203 pIn1 = &aMem[pOp->p1];
7204 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
7205 if( (pIn1->flags & MEM_Blob)==0
7206 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
7208 /* The boolean index is empty */
7209 sqlite3VdbeMemSetNull(pIn1);
7210 VdbeBranchTaken(1,2);
7211 goto jump_to_p2_and_check_for_interrupt;
7212 }else{
7213 /* A value was pulled from the index */
7214 VdbeBranchTaken(0,2);
7215 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
7217 goto check_for_interrupt;
7220 /* Opcode: RowSetTest P1 P2 P3 P4
7221 ** Synopsis: if r[P3] in rowset(P1) goto P2
7223 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
7224 ** contains a RowSet object and that RowSet object contains
7225 ** the value held in P3, jump to register P2. Otherwise, insert the
7226 ** integer in P3 into the RowSet and continue on to the
7227 ** next opcode.
7229 ** The RowSet object is optimized for the case where sets of integers
7230 ** are inserted in distinct phases, which each set contains no duplicates.
7231 ** Each set is identified by a unique P4 value. The first set
7232 ** must have P4==0, the final set must have P4==-1, and for all other sets
7233 ** must have P4>0.
7235 ** This allows optimizations: (a) when P4==0 there is no need to test
7236 ** the RowSet object for P3, as it is guaranteed not to contain it,
7237 ** (b) when P4==-1 there is no need to insert the value, as it will
7238 ** never be tested for, and (c) when a value that is part of set X is
7239 ** inserted, there is no need to search to see if the same value was
7240 ** previously inserted as part of set X (only if it was previously
7241 ** inserted as part of some other set).
7243 case OP_RowSetTest: { /* jump, in1, in3 */
7244 int iSet;
7245 int exists;
7247 pIn1 = &aMem[pOp->p1];
7248 pIn3 = &aMem[pOp->p3];
7249 iSet = pOp->p4.i;
7250 assert( pIn3->flags&MEM_Int );
7252 /* If there is anything other than a rowset object in memory cell P1,
7253 ** delete it now and initialize P1 with an empty rowset
7255 if( (pIn1->flags & MEM_Blob)==0 ){
7256 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7258 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7259 assert( pOp->p4type==P4_INT32 );
7260 assert( iSet==-1 || iSet>=0 );
7261 if( iSet ){
7262 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
7263 VdbeBranchTaken(exists!=0,2);
7264 if( exists ) goto jump_to_p2;
7266 if( iSet>=0 ){
7267 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
7269 break;
7273 #ifndef SQLITE_OMIT_TRIGGER
7275 /* Opcode: Program P1 P2 P3 P4 P5
7277 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
7279 ** P1 contains the address of the memory cell that contains the first memory
7280 ** cell in an array of values used as arguments to the sub-program. P2
7281 ** contains the address to jump to if the sub-program throws an IGNORE
7282 ** exception using the RAISE() function. Register P3 contains the address
7283 ** of a memory cell in this (the parent) VM that is used to allocate the
7284 ** memory required by the sub-vdbe at runtime.
7286 ** P4 is a pointer to the VM containing the trigger program.
7288 ** If P5 is non-zero, then recursive program invocation is enabled.
7290 case OP_Program: { /* jump */
7291 int nMem; /* Number of memory registers for sub-program */
7292 int nByte; /* Bytes of runtime space required for sub-program */
7293 Mem *pRt; /* Register to allocate runtime space */
7294 Mem *pMem; /* Used to iterate through memory cells */
7295 Mem *pEnd; /* Last memory cell in new array */
7296 VdbeFrame *pFrame; /* New vdbe frame to execute in */
7297 SubProgram *pProgram; /* Sub-program to execute */
7298 void *t; /* Token identifying trigger */
7300 pProgram = pOp->p4.pProgram;
7301 pRt = &aMem[pOp->p3];
7302 assert( pProgram->nOp>0 );
7304 /* If the p5 flag is clear, then recursive invocation of triggers is
7305 ** disabled for backwards compatibility (p5 is set if this sub-program
7306 ** is really a trigger, not a foreign key action, and the flag set
7307 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
7309 ** It is recursive invocation of triggers, at the SQL level, that is
7310 ** disabled. In some cases a single trigger may generate more than one
7311 ** SubProgram (if the trigger may be executed with more than one different
7312 ** ON CONFLICT algorithm). SubProgram structures associated with a
7313 ** single trigger all have the same value for the SubProgram.token
7314 ** variable. */
7315 if( pOp->p5 ){
7316 t = pProgram->token;
7317 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
7318 if( pFrame ) break;
7321 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
7322 rc = SQLITE_ERROR;
7323 sqlite3VdbeError(p, "too many levels of trigger recursion");
7324 goto abort_due_to_error;
7327 /* Register pRt is used to store the memory required to save the state
7328 ** of the current program, and the memory required at runtime to execute
7329 ** the trigger program. If this trigger has been fired before, then pRt
7330 ** is already allocated. Otherwise, it must be initialized. */
7331 if( (pRt->flags&MEM_Blob)==0 ){
7332 /* SubProgram.nMem is set to the number of memory cells used by the
7333 ** program stored in SubProgram.aOp. As well as these, one memory
7334 ** cell is required for each cursor used by the program. Set local
7335 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
7337 nMem = pProgram->nMem + pProgram->nCsr;
7338 assert( nMem>0 );
7339 if( pProgram->nCsr==0 ) nMem++;
7340 nByte = ROUND8(sizeof(VdbeFrame))
7341 + nMem * sizeof(Mem)
7342 + pProgram->nCsr * sizeof(VdbeCursor*)
7343 + (pProgram->nOp + 7)/8;
7344 pFrame = sqlite3DbMallocZero(db, nByte);
7345 if( !pFrame ){
7346 goto no_mem;
7348 sqlite3VdbeMemRelease(pRt);
7349 pRt->flags = MEM_Blob|MEM_Dyn;
7350 pRt->z = (char*)pFrame;
7351 pRt->n = nByte;
7352 pRt->xDel = sqlite3VdbeFrameMemDel;
7354 pFrame->v = p;
7355 pFrame->nChildMem = nMem;
7356 pFrame->nChildCsr = pProgram->nCsr;
7357 pFrame->pc = (int)(pOp - aOp);
7358 pFrame->aMem = p->aMem;
7359 pFrame->nMem = p->nMem;
7360 pFrame->apCsr = p->apCsr;
7361 pFrame->nCursor = p->nCursor;
7362 pFrame->aOp = p->aOp;
7363 pFrame->nOp = p->nOp;
7364 pFrame->token = pProgram->token;
7365 #ifdef SQLITE_DEBUG
7366 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
7367 #endif
7369 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
7370 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
7371 pMem->flags = MEM_Undefined;
7372 pMem->db = db;
7374 }else{
7375 pFrame = (VdbeFrame*)pRt->z;
7376 assert( pRt->xDel==sqlite3VdbeFrameMemDel );
7377 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
7378 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
7379 assert( pProgram->nCsr==pFrame->nChildCsr );
7380 assert( (int)(pOp - aOp)==pFrame->pc );
7383 p->nFrame++;
7384 pFrame->pParent = p->pFrame;
7385 pFrame->lastRowid = db->lastRowid;
7386 pFrame->nChange = p->nChange;
7387 pFrame->nDbChange = p->db->nChange;
7388 assert( pFrame->pAuxData==0 );
7389 pFrame->pAuxData = p->pAuxData;
7390 p->pAuxData = 0;
7391 p->nChange = 0;
7392 p->pFrame = pFrame;
7393 p->aMem = aMem = VdbeFrameMem(pFrame);
7394 p->nMem = pFrame->nChildMem;
7395 p->nCursor = (u16)pFrame->nChildCsr;
7396 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
7397 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
7398 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
7399 p->aOp = aOp = pProgram->aOp;
7400 p->nOp = pProgram->nOp;
7401 #ifdef SQLITE_DEBUG
7402 /* Verify that second and subsequent executions of the same trigger do not
7403 ** try to reuse register values from the first use. */
7405 int i;
7406 for(i=0; i<p->nMem; i++){
7407 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
7408 MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
7411 #endif
7412 pOp = &aOp[-1];
7413 goto check_for_interrupt;
7416 /* Opcode: Param P1 P2 * * *
7418 ** This opcode is only ever present in sub-programs called via the
7419 ** OP_Program instruction. Copy a value currently stored in a memory
7420 ** cell of the calling (parent) frame to cell P2 in the current frames
7421 ** address space. This is used by trigger programs to access the new.*
7422 ** and old.* values.
7424 ** The address of the cell in the parent frame is determined by adding
7425 ** the value of the P1 argument to the value of the P1 argument to the
7426 ** calling OP_Program instruction.
7428 case OP_Param: { /* out2 */
7429 VdbeFrame *pFrame;
7430 Mem *pIn;
7431 pOut = out2Prerelease(p, pOp);
7432 pFrame = p->pFrame;
7433 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
7434 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
7435 break;
7438 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
7440 #ifndef SQLITE_OMIT_FOREIGN_KEY
7441 /* Opcode: FkCounter P1 P2 * * *
7442 ** Synopsis: fkctr[P1]+=P2
7444 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
7445 ** If P1 is non-zero, the database constraint counter is incremented
7446 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
7447 ** statement counter is incremented (immediate foreign key constraints).
7449 case OP_FkCounter: {
7450 if( db->flags & SQLITE_DeferFKs ){
7451 db->nDeferredImmCons += pOp->p2;
7452 }else if( pOp->p1 ){
7453 db->nDeferredCons += pOp->p2;
7454 }else{
7455 p->nFkConstraint += pOp->p2;
7457 break;
7460 /* Opcode: FkIfZero P1 P2 * * *
7461 ** Synopsis: if fkctr[P1]==0 goto P2
7463 ** This opcode tests if a foreign key constraint-counter is currently zero.
7464 ** If so, jump to instruction P2. Otherwise, fall through to the next
7465 ** instruction.
7467 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
7468 ** is zero (the one that counts deferred constraint violations). If P1 is
7469 ** zero, the jump is taken if the statement constraint-counter is zero
7470 ** (immediate foreign key constraint violations).
7472 case OP_FkIfZero: { /* jump */
7473 if( pOp->p1 ){
7474 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
7475 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7476 }else{
7477 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
7478 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7480 break;
7482 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
7484 #ifndef SQLITE_OMIT_AUTOINCREMENT
7485 /* Opcode: MemMax P1 P2 * * *
7486 ** Synopsis: r[P1]=max(r[P1],r[P2])
7488 ** P1 is a register in the root frame of this VM (the root frame is
7489 ** different from the current frame if this instruction is being executed
7490 ** within a sub-program). Set the value of register P1 to the maximum of
7491 ** its current value and the value in register P2.
7493 ** This instruction throws an error if the memory cell is not initially
7494 ** an integer.
7496 case OP_MemMax: { /* in2 */
7497 VdbeFrame *pFrame;
7498 if( p->pFrame ){
7499 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
7500 pIn1 = &pFrame->aMem[pOp->p1];
7501 }else{
7502 pIn1 = &aMem[pOp->p1];
7504 assert( memIsValid(pIn1) );
7505 sqlite3VdbeMemIntegerify(pIn1);
7506 pIn2 = &aMem[pOp->p2];
7507 sqlite3VdbeMemIntegerify(pIn2);
7508 if( pIn1->u.i<pIn2->u.i){
7509 pIn1->u.i = pIn2->u.i;
7511 break;
7513 #endif /* SQLITE_OMIT_AUTOINCREMENT */
7515 /* Opcode: IfPos P1 P2 P3 * *
7516 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
7518 ** Register P1 must contain an integer.
7519 ** If the value of register P1 is 1 or greater, subtract P3 from the
7520 ** value in P1 and jump to P2.
7522 ** If the initial value of register P1 is less than 1, then the
7523 ** value is unchanged and control passes through to the next instruction.
7525 case OP_IfPos: { /* jump, in1 */
7526 pIn1 = &aMem[pOp->p1];
7527 assert( pIn1->flags&MEM_Int );
7528 VdbeBranchTaken( pIn1->u.i>0, 2);
7529 if( pIn1->u.i>0 ){
7530 pIn1->u.i -= pOp->p3;
7531 goto jump_to_p2;
7533 break;
7536 /* Opcode: OffsetLimit P1 P2 P3 * *
7537 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
7539 ** This opcode performs a commonly used computation associated with
7540 ** LIMIT and OFFSET processing. r[P1] holds the limit counter. r[P3]
7541 ** holds the offset counter. The opcode computes the combined value
7542 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
7543 ** value computed is the total number of rows that will need to be
7544 ** visited in order to complete the query.
7546 ** If r[P3] is zero or negative, that means there is no OFFSET
7547 ** and r[P2] is set to be the value of the LIMIT, r[P1].
7549 ** if r[P1] is zero or negative, that means there is no LIMIT
7550 ** and r[P2] is set to -1.
7552 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
7554 case OP_OffsetLimit: { /* in1, out2, in3 */
7555 i64 x;
7556 pIn1 = &aMem[pOp->p1];
7557 pIn3 = &aMem[pOp->p3];
7558 pOut = out2Prerelease(p, pOp);
7559 assert( pIn1->flags & MEM_Int );
7560 assert( pIn3->flags & MEM_Int );
7561 x = pIn1->u.i;
7562 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
7563 /* If the LIMIT is less than or equal to zero, loop forever. This
7564 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
7565 ** also loop forever. This is undocumented. In fact, one could argue
7566 ** that the loop should terminate. But assuming 1 billion iterations
7567 ** per second (far exceeding the capabilities of any current hardware)
7568 ** it would take nearly 300 years to actually reach the limit. So
7569 ** looping forever is a reasonable approximation. */
7570 pOut->u.i = -1;
7571 }else{
7572 pOut->u.i = x;
7574 break;
7577 /* Opcode: IfNotZero P1 P2 * * *
7578 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
7580 ** Register P1 must contain an integer. If the content of register P1 is
7581 ** initially greater than zero, then decrement the value in register P1.
7582 ** If it is non-zero (negative or positive) and then also jump to P2.
7583 ** If register P1 is initially zero, leave it unchanged and fall through.
7585 case OP_IfNotZero: { /* jump, in1 */
7586 pIn1 = &aMem[pOp->p1];
7587 assert( pIn1->flags&MEM_Int );
7588 VdbeBranchTaken(pIn1->u.i<0, 2);
7589 if( pIn1->u.i ){
7590 if( pIn1->u.i>0 ) pIn1->u.i--;
7591 goto jump_to_p2;
7593 break;
7596 /* Opcode: DecrJumpZero P1 P2 * * *
7597 ** Synopsis: if (--r[P1])==0 goto P2
7599 ** Register P1 must hold an integer. Decrement the value in P1
7600 ** and jump to P2 if the new value is exactly zero.
7602 case OP_DecrJumpZero: { /* jump, in1 */
7603 pIn1 = &aMem[pOp->p1];
7604 assert( pIn1->flags&MEM_Int );
7605 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
7606 VdbeBranchTaken(pIn1->u.i==0, 2);
7607 if( pIn1->u.i==0 ) goto jump_to_p2;
7608 break;
7612 /* Opcode: AggStep * P2 P3 P4 P5
7613 ** Synopsis: accum=r[P3] step(r[P2@P5])
7615 ** Execute the xStep function for an aggregate.
7616 ** The function has P5 arguments. P4 is a pointer to the
7617 ** FuncDef structure that specifies the function. Register P3 is the
7618 ** accumulator.
7620 ** The P5 arguments are taken from register P2 and its
7621 ** successors.
7623 /* Opcode: AggInverse * P2 P3 P4 P5
7624 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
7626 ** Execute the xInverse function for an aggregate.
7627 ** The function has P5 arguments. P4 is a pointer to the
7628 ** FuncDef structure that specifies the function. Register P3 is the
7629 ** accumulator.
7631 ** The P5 arguments are taken from register P2 and its
7632 ** successors.
7634 /* Opcode: AggStep1 P1 P2 P3 P4 P5
7635 ** Synopsis: accum=r[P3] step(r[P2@P5])
7637 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
7638 ** aggregate. The function has P5 arguments. P4 is a pointer to the
7639 ** FuncDef structure that specifies the function. Register P3 is the
7640 ** accumulator.
7642 ** The P5 arguments are taken from register P2 and its
7643 ** successors.
7645 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
7646 ** the FuncDef stored in P4 is converted into an sqlite3_context and
7647 ** the opcode is changed. In this way, the initialization of the
7648 ** sqlite3_context only happens once, instead of on each call to the
7649 ** step function.
7651 case OP_AggInverse:
7652 case OP_AggStep: {
7653 int n;
7654 sqlite3_context *pCtx;
7656 assert( pOp->p4type==P4_FUNCDEF );
7657 n = pOp->p5;
7658 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7659 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7660 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7661 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
7662 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
7663 if( pCtx==0 ) goto no_mem;
7664 pCtx->pMem = 0;
7665 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
7666 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
7667 pCtx->pFunc = pOp->p4.pFunc;
7668 pCtx->iOp = (int)(pOp - aOp);
7669 pCtx->pVdbe = p;
7670 pCtx->skipFlag = 0;
7671 pCtx->isError = 0;
7672 pCtx->enc = encoding;
7673 pCtx->argc = n;
7674 pOp->p4type = P4_FUNCCTX;
7675 pOp->p4.pCtx = pCtx;
7677 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
7678 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
7680 pOp->opcode = OP_AggStep1;
7681 /* Fall through into OP_AggStep */
7682 /* no break */ deliberate_fall_through
7684 case OP_AggStep1: {
7685 int i;
7686 sqlite3_context *pCtx;
7687 Mem *pMem;
7689 assert( pOp->p4type==P4_FUNCCTX );
7690 pCtx = pOp->p4.pCtx;
7691 pMem = &aMem[pOp->p3];
7693 #ifdef SQLITE_DEBUG
7694 if( pOp->p1 ){
7695 /* This is an OP_AggInverse call. Verify that xStep has always
7696 ** been called at least once prior to any xInverse call. */
7697 assert( pMem->uTemp==0x1122e0e3 );
7698 }else{
7699 /* This is an OP_AggStep call. Mark it as such. */
7700 pMem->uTemp = 0x1122e0e3;
7702 #endif
7704 /* If this function is inside of a trigger, the register array in aMem[]
7705 ** might change from one evaluation to the next. The next block of code
7706 ** checks to see if the register array has changed, and if so it
7707 ** reinitializes the relevant parts of the sqlite3_context object */
7708 if( pCtx->pMem != pMem ){
7709 pCtx->pMem = pMem;
7710 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7713 #ifdef SQLITE_DEBUG
7714 for(i=0; i<pCtx->argc; i++){
7715 assert( memIsValid(pCtx->argv[i]) );
7716 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7718 #endif
7720 pMem->n++;
7721 assert( pCtx->pOut->flags==MEM_Null );
7722 assert( pCtx->isError==0 );
7723 assert( pCtx->skipFlag==0 );
7724 #ifndef SQLITE_OMIT_WINDOWFUNC
7725 if( pOp->p1 ){
7726 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7727 }else
7728 #endif
7729 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7731 if( pCtx->isError ){
7732 if( pCtx->isError>0 ){
7733 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7734 rc = pCtx->isError;
7736 if( pCtx->skipFlag ){
7737 assert( pOp[-1].opcode==OP_CollSeq );
7738 i = pOp[-1].p1;
7739 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7740 pCtx->skipFlag = 0;
7742 sqlite3VdbeMemRelease(pCtx->pOut);
7743 pCtx->pOut->flags = MEM_Null;
7744 pCtx->isError = 0;
7745 if( rc ) goto abort_due_to_error;
7747 assert( pCtx->pOut->flags==MEM_Null );
7748 assert( pCtx->skipFlag==0 );
7749 break;
7752 /* Opcode: AggFinal P1 P2 * P4 *
7753 ** Synopsis: accum=r[P1] N=P2
7755 ** P1 is the memory location that is the accumulator for an aggregate
7756 ** or window function. Execute the finalizer function
7757 ** for an aggregate and store the result in P1.
7759 ** P2 is the number of arguments that the step function takes and
7760 ** P4 is a pointer to the FuncDef for this function. The P2
7761 ** argument is not used by this opcode. It is only there to disambiguate
7762 ** functions that can take varying numbers of arguments. The
7763 ** P4 argument is only needed for the case where
7764 ** the step function was not previously called.
7766 /* Opcode: AggValue * P2 P3 P4 *
7767 ** Synopsis: r[P3]=value N=P2
7769 ** Invoke the xValue() function and store the result in register P3.
7771 ** P2 is the number of arguments that the step function takes and
7772 ** P4 is a pointer to the FuncDef for this function. The P2
7773 ** argument is not used by this opcode. It is only there to disambiguate
7774 ** functions that can take varying numbers of arguments. The
7775 ** P4 argument is only needed for the case where
7776 ** the step function was not previously called.
7778 case OP_AggValue:
7779 case OP_AggFinal: {
7780 Mem *pMem;
7781 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7782 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7783 pMem = &aMem[pOp->p1];
7784 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7785 #ifndef SQLITE_OMIT_WINDOWFUNC
7786 if( pOp->p3 ){
7787 memAboutToChange(p, &aMem[pOp->p3]);
7788 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7789 pMem = &aMem[pOp->p3];
7790 }else
7791 #endif
7793 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7796 if( rc ){
7797 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7798 goto abort_due_to_error;
7800 sqlite3VdbeChangeEncoding(pMem, encoding);
7801 UPDATE_MAX_BLOBSIZE(pMem);
7802 REGISTER_TRACE((int)(pMem-aMem), pMem);
7803 break;
7806 #ifndef SQLITE_OMIT_WAL
7807 /* Opcode: Checkpoint P1 P2 P3 * *
7809 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7810 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7811 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
7812 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
7813 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7814 ** in the WAL that have been checkpointed after the checkpoint
7815 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
7816 ** mem[P3+2] are initialized to -1.
7818 case OP_Checkpoint: {
7819 int i; /* Loop counter */
7820 int aRes[3]; /* Results */
7821 Mem *pMem; /* Write results here */
7823 assert( p->readOnly==0 );
7824 aRes[0] = 0;
7825 aRes[1] = aRes[2] = -1;
7826 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7827 || pOp->p2==SQLITE_CHECKPOINT_FULL
7828 || pOp->p2==SQLITE_CHECKPOINT_RESTART
7829 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7831 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7832 if( rc ){
7833 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7834 rc = SQLITE_OK;
7835 aRes[0] = 1;
7837 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7838 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7840 break;
7842 #endif
7844 #ifndef SQLITE_OMIT_PRAGMA
7845 /* Opcode: JournalMode P1 P2 P3 * *
7847 ** Change the journal mode of database P1 to P3. P3 must be one of the
7848 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7849 ** modes (delete, truncate, persist, off and memory), this is a simple
7850 ** operation. No IO is required.
7852 ** If changing into or out of WAL mode the procedure is more complicated.
7854 ** Write a string containing the final journal-mode to register P2.
7856 case OP_JournalMode: { /* out2 */
7857 Btree *pBt; /* Btree to change journal mode of */
7858 Pager *pPager; /* Pager associated with pBt */
7859 int eNew; /* New journal mode */
7860 int eOld; /* The old journal mode */
7861 #ifndef SQLITE_OMIT_WAL
7862 const char *zFilename; /* Name of database file for pPager */
7863 #endif
7865 pOut = out2Prerelease(p, pOp);
7866 eNew = pOp->p3;
7867 assert( eNew==PAGER_JOURNALMODE_DELETE
7868 || eNew==PAGER_JOURNALMODE_TRUNCATE
7869 || eNew==PAGER_JOURNALMODE_PERSIST
7870 || eNew==PAGER_JOURNALMODE_OFF
7871 || eNew==PAGER_JOURNALMODE_MEMORY
7872 || eNew==PAGER_JOURNALMODE_WAL
7873 || eNew==PAGER_JOURNALMODE_QUERY
7875 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7876 assert( p->readOnly==0 );
7878 pBt = db->aDb[pOp->p1].pBt;
7879 pPager = sqlite3BtreePager(pBt);
7880 eOld = sqlite3PagerGetJournalMode(pPager);
7881 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7882 assert( sqlite3BtreeHoldsMutex(pBt) );
7883 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7885 #ifndef SQLITE_OMIT_WAL
7886 zFilename = sqlite3PagerFilename(pPager, 1);
7888 /* Do not allow a transition to journal_mode=WAL for a database
7889 ** in temporary storage or if the VFS does not support shared memory
7891 if( eNew==PAGER_JOURNALMODE_WAL
7892 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
7893 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
7895 eNew = eOld;
7898 if( (eNew!=eOld)
7899 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7901 if( !db->autoCommit || db->nVdbeRead>1 ){
7902 rc = SQLITE_ERROR;
7903 sqlite3VdbeError(p,
7904 "cannot change %s wal mode from within a transaction",
7905 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7907 goto abort_due_to_error;
7908 }else{
7910 if( eOld==PAGER_JOURNALMODE_WAL ){
7911 /* If leaving WAL mode, close the log file. If successful, the call
7912 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7913 ** file. An EXCLUSIVE lock may still be held on the database file
7914 ** after a successful return.
7916 rc = sqlite3PagerCloseWal(pPager, db);
7917 if( rc==SQLITE_OK ){
7918 sqlite3PagerSetJournalMode(pPager, eNew);
7920 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7921 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
7922 ** as an intermediate */
7923 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7926 /* Open a transaction on the database file. Regardless of the journal
7927 ** mode, this transaction always uses a rollback journal.
7929 assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7930 if( rc==SQLITE_OK ){
7931 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7935 #endif /* ifndef SQLITE_OMIT_WAL */
7937 if( rc ) eNew = eOld;
7938 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7940 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7941 pOut->z = (char *)sqlite3JournalModename(eNew);
7942 pOut->n = sqlite3Strlen30(pOut->z);
7943 pOut->enc = SQLITE_UTF8;
7944 sqlite3VdbeChangeEncoding(pOut, encoding);
7945 if( rc ) goto abort_due_to_error;
7946 break;
7948 #endif /* SQLITE_OMIT_PRAGMA */
7950 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7951 /* Opcode: Vacuum P1 P2 * * *
7953 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
7954 ** for an attached database. The "temp" database may not be vacuumed.
7956 ** If P2 is not zero, then it is a register holding a string which is
7957 ** the file into which the result of vacuum should be written. When
7958 ** P2 is zero, the vacuum overwrites the original database.
7960 case OP_Vacuum: {
7961 assert( p->readOnly==0 );
7962 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7963 pOp->p2 ? &aMem[pOp->p2] : 0);
7964 if( rc ) goto abort_due_to_error;
7965 break;
7967 #endif
7969 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7970 /* Opcode: IncrVacuum P1 P2 * * *
7972 ** Perform a single step of the incremental vacuum procedure on
7973 ** the P1 database. If the vacuum has finished, jump to instruction
7974 ** P2. Otherwise, fall through to the next instruction.
7976 case OP_IncrVacuum: { /* jump */
7977 Btree *pBt;
7979 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7980 assert( DbMaskTest(p->btreeMask, pOp->p1) );
7981 assert( p->readOnly==0 );
7982 pBt = db->aDb[pOp->p1].pBt;
7983 rc = sqlite3BtreeIncrVacuum(pBt);
7984 VdbeBranchTaken(rc==SQLITE_DONE,2);
7985 if( rc ){
7986 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7987 rc = SQLITE_OK;
7988 goto jump_to_p2;
7990 break;
7992 #endif
7994 /* Opcode: Expire P1 P2 * * *
7996 ** Cause precompiled statements to expire. When an expired statement
7997 ** is executed using sqlite3_step() it will either automatically
7998 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
7999 ** or it will fail with SQLITE_SCHEMA.
8001 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
8002 ** then only the currently executing statement is expired.
8004 ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
8005 ** then running SQL statements are allowed to continue to run to completion.
8006 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
8007 ** that might help the statement run faster but which does not affect the
8008 ** correctness of operation.
8010 case OP_Expire: {
8011 assert( pOp->p2==0 || pOp->p2==1 );
8012 if( !pOp->p1 ){
8013 sqlite3ExpirePreparedStatements(db, pOp->p2);
8014 }else{
8015 p->expired = pOp->p2+1;
8017 break;
8020 /* Opcode: CursorLock P1 * * * *
8022 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
8023 ** written by an other cursor.
8025 case OP_CursorLock: {
8026 VdbeCursor *pC;
8027 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8028 pC = p->apCsr[pOp->p1];
8029 assert( pC!=0 );
8030 assert( pC->eCurType==CURTYPE_BTREE );
8031 sqlite3BtreeCursorPin(pC->uc.pCursor);
8032 break;
8035 /* Opcode: CursorUnlock P1 * * * *
8037 ** Unlock the btree to which cursor P1 is pointing so that it can be
8038 ** written by other cursors.
8040 case OP_CursorUnlock: {
8041 VdbeCursor *pC;
8042 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8043 pC = p->apCsr[pOp->p1];
8044 assert( pC!=0 );
8045 assert( pC->eCurType==CURTYPE_BTREE );
8046 sqlite3BtreeCursorUnpin(pC->uc.pCursor);
8047 break;
8050 #ifndef SQLITE_OMIT_SHARED_CACHE
8051 /* Opcode: TableLock P1 P2 P3 P4 *
8052 ** Synopsis: iDb=P1 root=P2 write=P3
8054 ** Obtain a lock on a particular table. This instruction is only used when
8055 ** the shared-cache feature is enabled.
8057 ** P1 is the index of the database in sqlite3.aDb[] of the database
8058 ** on which the lock is acquired. A readlock is obtained if P3==0 or
8059 ** a write lock if P3==1.
8061 ** P2 contains the root-page of the table to lock.
8063 ** P4 contains a pointer to the name of the table being locked. This is only
8064 ** used to generate an error message if the lock cannot be obtained.
8066 case OP_TableLock: {
8067 u8 isWriteLock = (u8)pOp->p3;
8068 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
8069 int p1 = pOp->p1;
8070 assert( p1>=0 && p1<db->nDb );
8071 assert( DbMaskTest(p->btreeMask, p1) );
8072 assert( isWriteLock==0 || isWriteLock==1 );
8073 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
8074 if( rc ){
8075 if( (rc&0xFF)==SQLITE_LOCKED ){
8076 const char *z = pOp->p4.z;
8077 sqlite3VdbeError(p, "database table is locked: %s", z);
8079 goto abort_due_to_error;
8082 break;
8084 #endif /* SQLITE_OMIT_SHARED_CACHE */
8086 #ifndef SQLITE_OMIT_VIRTUALTABLE
8087 /* Opcode: VBegin * * * P4 *
8089 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
8090 ** xBegin method for that table.
8092 ** Also, whether or not P4 is set, check that this is not being called from
8093 ** within a callback to a virtual table xSync() method. If it is, the error
8094 ** code will be set to SQLITE_LOCKED.
8096 case OP_VBegin: {
8097 VTable *pVTab;
8098 pVTab = pOp->p4.pVtab;
8099 rc = sqlite3VtabBegin(db, pVTab);
8100 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
8101 if( rc ) goto abort_due_to_error;
8102 break;
8104 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8106 #ifndef SQLITE_OMIT_VIRTUALTABLE
8107 /* Opcode: VCreate P1 P2 * * *
8109 ** P2 is a register that holds the name of a virtual table in database
8110 ** P1. Call the xCreate method for that table.
8112 case OP_VCreate: {
8113 Mem sMem; /* For storing the record being decoded */
8114 const char *zTab; /* Name of the virtual table */
8116 memset(&sMem, 0, sizeof(sMem));
8117 sMem.db = db;
8118 /* Because P2 is always a static string, it is impossible for the
8119 ** sqlite3VdbeMemCopy() to fail */
8120 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
8121 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
8122 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
8123 assert( rc==SQLITE_OK );
8124 zTab = (const char*)sqlite3_value_text(&sMem);
8125 assert( zTab || db->mallocFailed );
8126 if( zTab ){
8127 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
8129 sqlite3VdbeMemRelease(&sMem);
8130 if( rc ) goto abort_due_to_error;
8131 break;
8133 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8135 #ifndef SQLITE_OMIT_VIRTUALTABLE
8136 /* Opcode: VDestroy P1 * * P4 *
8138 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
8139 ** of that table.
8141 case OP_VDestroy: {
8142 db->nVDestroy++;
8143 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
8144 db->nVDestroy--;
8145 assert( p->errorAction==OE_Abort && p->usesStmtJournal );
8146 if( rc ) goto abort_due_to_error;
8147 break;
8149 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8151 #ifndef SQLITE_OMIT_VIRTUALTABLE
8152 /* Opcode: VOpen P1 * * P4 *
8154 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8155 ** P1 is a cursor number. This opcode opens a cursor to the virtual
8156 ** table and stores that cursor in P1.
8158 case OP_VOpen: { /* ncycle */
8159 VdbeCursor *pCur;
8160 sqlite3_vtab_cursor *pVCur;
8161 sqlite3_vtab *pVtab;
8162 const sqlite3_module *pModule;
8164 assert( p->bIsReader );
8165 pCur = 0;
8166 pVCur = 0;
8167 pVtab = pOp->p4.pVtab->pVtab;
8168 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8169 rc = SQLITE_LOCKED;
8170 goto abort_due_to_error;
8172 pModule = pVtab->pModule;
8173 rc = pModule->xOpen(pVtab, &pVCur);
8174 sqlite3VtabImportErrmsg(p, pVtab);
8175 if( rc ) goto abort_due_to_error;
8177 /* Initialize sqlite3_vtab_cursor base class */
8178 pVCur->pVtab = pVtab;
8180 /* Initialize vdbe cursor object */
8181 pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
8182 if( pCur ){
8183 pCur->uc.pVCur = pVCur;
8184 pVtab->nRef++;
8185 }else{
8186 assert( db->mallocFailed );
8187 pModule->xClose(pVCur);
8188 goto no_mem;
8190 break;
8192 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8194 #ifndef SQLITE_OMIT_VIRTUALTABLE
8195 /* Opcode: VCheck P1 P2 P3 P4 *
8197 ** P4 is a pointer to a Table object that is a virtual table in schema P1
8198 ** that supports the xIntegrity() method. This opcode runs the xIntegrity()
8199 ** method for that virtual table, using P3 as the integer argument. If
8200 ** an error is reported back, the table name is prepended to the error
8201 ** message and that message is stored in P2. If no errors are seen,
8202 ** register P2 is set to NULL.
8204 case OP_VCheck: { /* out2 */
8205 Table *pTab;
8206 sqlite3_vtab *pVtab;
8207 const sqlite3_module *pModule;
8208 char *zErr = 0;
8210 pOut = &aMem[pOp->p2];
8211 sqlite3VdbeMemSetNull(pOut); /* Innocent until proven guilty */
8212 assert( pOp->p4type==P4_TABLEREF );
8213 pTab = pOp->p4.pTab;
8214 assert( pTab!=0 );
8215 assert( pTab->nTabRef>0 );
8216 assert( IsVirtual(pTab) );
8217 if( pTab->u.vtab.p==0 ) break;
8218 pVtab = pTab->u.vtab.p->pVtab;
8219 assert( pVtab!=0 );
8220 pModule = pVtab->pModule;
8221 assert( pModule!=0 );
8222 assert( pModule->iVersion>=4 );
8223 assert( pModule->xIntegrity!=0 );
8224 sqlite3VtabLock(pTab->u.vtab.p);
8225 assert( pOp->p1>=0 && pOp->p1<db->nDb );
8226 rc = pModule->xIntegrity(pVtab, db->aDb[pOp->p1].zDbSName, pTab->zName,
8227 pOp->p3, &zErr);
8228 sqlite3VtabUnlock(pTab->u.vtab.p);
8229 if( rc ){
8230 sqlite3_free(zErr);
8231 goto abort_due_to_error;
8233 if( zErr ){
8234 sqlite3VdbeMemSetStr(pOut, zErr, -1, SQLITE_UTF8, sqlite3_free);
8236 break;
8238 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8240 #ifndef SQLITE_OMIT_VIRTUALTABLE
8241 /* Opcode: VInitIn P1 P2 P3 * *
8242 ** Synopsis: r[P2]=ValueList(P1,P3)
8244 ** Set register P2 to be a pointer to a ValueList object for cursor P1
8245 ** with cache register P3 and output register P3+1. This ValueList object
8246 ** can be used as the first argument to sqlite3_vtab_in_first() and
8247 ** sqlite3_vtab_in_next() to extract all of the values stored in the P1
8248 ** cursor. Register P3 is used to hold the values returned by
8249 ** sqlite3_vtab_in_first() and sqlite3_vtab_in_next().
8251 case OP_VInitIn: { /* out2, ncycle */
8252 VdbeCursor *pC; /* The cursor containing the RHS values */
8253 ValueList *pRhs; /* New ValueList object to put in reg[P2] */
8255 pC = p->apCsr[pOp->p1];
8256 pRhs = sqlite3_malloc64( sizeof(*pRhs) );
8257 if( pRhs==0 ) goto no_mem;
8258 pRhs->pCsr = pC->uc.pCursor;
8259 pRhs->pOut = &aMem[pOp->p3];
8260 pOut = out2Prerelease(p, pOp);
8261 pOut->flags = MEM_Null;
8262 sqlite3VdbeMemSetPointer(pOut, pRhs, "ValueList", sqlite3VdbeValueListFree);
8263 break;
8265 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8268 #ifndef SQLITE_OMIT_VIRTUALTABLE
8269 /* Opcode: VFilter P1 P2 P3 P4 *
8270 ** Synopsis: iplan=r[P3] zplan='P4'
8272 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
8273 ** the filtered result set is empty.
8275 ** P4 is either NULL or a string that was generated by the xBestIndex
8276 ** method of the module. The interpretation of the P4 string is left
8277 ** to the module implementation.
8279 ** This opcode invokes the xFilter method on the virtual table specified
8280 ** by P1. The integer query plan parameter to xFilter is stored in register
8281 ** P3. Register P3+1 stores the argc parameter to be passed to the
8282 ** xFilter method. Registers P3+2..P3+1+argc are the argc
8283 ** additional parameters which are passed to
8284 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
8286 ** A jump is made to P2 if the result set after filtering would be empty.
8288 case OP_VFilter: { /* jump, ncycle */
8289 int nArg;
8290 int iQuery;
8291 const sqlite3_module *pModule;
8292 Mem *pQuery;
8293 Mem *pArgc;
8294 sqlite3_vtab_cursor *pVCur;
8295 sqlite3_vtab *pVtab;
8296 VdbeCursor *pCur;
8297 int res;
8298 int i;
8299 Mem **apArg;
8301 pQuery = &aMem[pOp->p3];
8302 pArgc = &pQuery[1];
8303 pCur = p->apCsr[pOp->p1];
8304 assert( memIsValid(pQuery) );
8305 REGISTER_TRACE(pOp->p3, pQuery);
8306 assert( pCur!=0 );
8307 assert( pCur->eCurType==CURTYPE_VTAB );
8308 pVCur = pCur->uc.pVCur;
8309 pVtab = pVCur->pVtab;
8310 pModule = pVtab->pModule;
8312 /* Grab the index number and argc parameters */
8313 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
8314 nArg = (int)pArgc->u.i;
8315 iQuery = (int)pQuery->u.i;
8317 /* Invoke the xFilter method */
8318 apArg = p->apArg;
8319 for(i = 0; i<nArg; i++){
8320 apArg[i] = &pArgc[i+1];
8322 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
8323 sqlite3VtabImportErrmsg(p, pVtab);
8324 if( rc ) goto abort_due_to_error;
8325 res = pModule->xEof(pVCur);
8326 pCur->nullRow = 0;
8327 VdbeBranchTaken(res!=0,2);
8328 if( res ) goto jump_to_p2;
8329 break;
8331 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8333 #ifndef SQLITE_OMIT_VIRTUALTABLE
8334 /* Opcode: VColumn P1 P2 P3 * P5
8335 ** Synopsis: r[P3]=vcolumn(P2)
8337 ** Store in register P3 the value of the P2-th column of
8338 ** the current row of the virtual-table of cursor P1.
8340 ** If the VColumn opcode is being used to fetch the value of
8341 ** an unchanging column during an UPDATE operation, then the P5
8342 ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
8343 ** function to return true inside the xColumn method of the virtual
8344 ** table implementation. The P5 column might also contain other
8345 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
8346 ** unused by OP_VColumn.
8348 case OP_VColumn: { /* ncycle */
8349 sqlite3_vtab *pVtab;
8350 const sqlite3_module *pModule;
8351 Mem *pDest;
8352 sqlite3_context sContext;
8353 FuncDef nullFunc;
8355 VdbeCursor *pCur = p->apCsr[pOp->p1];
8356 assert( pCur!=0 );
8357 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
8358 pDest = &aMem[pOp->p3];
8359 memAboutToChange(p, pDest);
8360 if( pCur->nullRow ){
8361 sqlite3VdbeMemSetNull(pDest);
8362 break;
8364 assert( pCur->eCurType==CURTYPE_VTAB );
8365 pVtab = pCur->uc.pVCur->pVtab;
8366 pModule = pVtab->pModule;
8367 assert( pModule->xColumn );
8368 memset(&sContext, 0, sizeof(sContext));
8369 sContext.pOut = pDest;
8370 sContext.enc = encoding;
8371 nullFunc.pUserData = 0;
8372 nullFunc.funcFlags = SQLITE_RESULT_SUBTYPE;
8373 sContext.pFunc = &nullFunc;
8374 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
8375 if( pOp->p5 & OPFLAG_NOCHNG ){
8376 sqlite3VdbeMemSetNull(pDest);
8377 pDest->flags = MEM_Null|MEM_Zero;
8378 pDest->u.nZero = 0;
8379 }else{
8380 MemSetTypeFlag(pDest, MEM_Null);
8382 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
8383 sqlite3VtabImportErrmsg(p, pVtab);
8384 if( sContext.isError>0 ){
8385 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
8386 rc = sContext.isError;
8388 sqlite3VdbeChangeEncoding(pDest, encoding);
8389 REGISTER_TRACE(pOp->p3, pDest);
8390 UPDATE_MAX_BLOBSIZE(pDest);
8392 if( rc ) goto abort_due_to_error;
8393 break;
8395 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8397 #ifndef SQLITE_OMIT_VIRTUALTABLE
8398 /* Opcode: VNext P1 P2 * * *
8400 ** Advance virtual table P1 to the next row in its result set and
8401 ** jump to instruction P2. Or, if the virtual table has reached
8402 ** the end of its result set, then fall through to the next instruction.
8404 case OP_VNext: { /* jump, ncycle */
8405 sqlite3_vtab *pVtab;
8406 const sqlite3_module *pModule;
8407 int res;
8408 VdbeCursor *pCur;
8410 pCur = p->apCsr[pOp->p1];
8411 assert( pCur!=0 );
8412 assert( pCur->eCurType==CURTYPE_VTAB );
8413 if( pCur->nullRow ){
8414 break;
8416 pVtab = pCur->uc.pVCur->pVtab;
8417 pModule = pVtab->pModule;
8418 assert( pModule->xNext );
8420 /* Invoke the xNext() method of the module. There is no way for the
8421 ** underlying implementation to return an error if one occurs during
8422 ** xNext(). Instead, if an error occurs, true is returned (indicating that
8423 ** data is available) and the error code returned when xColumn or
8424 ** some other method is next invoked on the save virtual table cursor.
8426 rc = pModule->xNext(pCur->uc.pVCur);
8427 sqlite3VtabImportErrmsg(p, pVtab);
8428 if( rc ) goto abort_due_to_error;
8429 res = pModule->xEof(pCur->uc.pVCur);
8430 VdbeBranchTaken(!res,2);
8431 if( !res ){
8432 /* If there is data, jump to P2 */
8433 goto jump_to_p2_and_check_for_interrupt;
8435 goto check_for_interrupt;
8437 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8439 #ifndef SQLITE_OMIT_VIRTUALTABLE
8440 /* Opcode: VRename P1 * * P4 *
8442 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8443 ** This opcode invokes the corresponding xRename method. The value
8444 ** in register P1 is passed as the zName argument to the xRename method.
8446 case OP_VRename: {
8447 sqlite3_vtab *pVtab;
8448 Mem *pName;
8449 int isLegacy;
8451 isLegacy = (db->flags & SQLITE_LegacyAlter);
8452 db->flags |= SQLITE_LegacyAlter;
8453 pVtab = pOp->p4.pVtab->pVtab;
8454 pName = &aMem[pOp->p1];
8455 assert( pVtab->pModule->xRename );
8456 assert( memIsValid(pName) );
8457 assert( p->readOnly==0 );
8458 REGISTER_TRACE(pOp->p1, pName);
8459 assert( pName->flags & MEM_Str );
8460 testcase( pName->enc==SQLITE_UTF8 );
8461 testcase( pName->enc==SQLITE_UTF16BE );
8462 testcase( pName->enc==SQLITE_UTF16LE );
8463 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
8464 if( rc ) goto abort_due_to_error;
8465 rc = pVtab->pModule->xRename(pVtab, pName->z);
8466 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
8467 sqlite3VtabImportErrmsg(p, pVtab);
8468 p->expired = 0;
8469 if( rc ) goto abort_due_to_error;
8470 break;
8472 #endif
8474 #ifndef SQLITE_OMIT_VIRTUALTABLE
8475 /* Opcode: VUpdate P1 P2 P3 P4 P5
8476 ** Synopsis: data=r[P3@P2]
8478 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8479 ** This opcode invokes the corresponding xUpdate method. P2 values
8480 ** are contiguous memory cells starting at P3 to pass to the xUpdate
8481 ** invocation. The value in register (P3+P2-1) corresponds to the
8482 ** p2th element of the argv array passed to xUpdate.
8484 ** The xUpdate method will do a DELETE or an INSERT or both.
8485 ** The argv[0] element (which corresponds to memory cell P3)
8486 ** is the rowid of a row to delete. If argv[0] is NULL then no
8487 ** deletion occurs. The argv[1] element is the rowid of the new
8488 ** row. This can be NULL to have the virtual table select the new
8489 ** rowid for itself. The subsequent elements in the array are
8490 ** the values of columns in the new row.
8492 ** If P2==1 then no insert is performed. argv[0] is the rowid of
8493 ** a row to delete.
8495 ** P1 is a boolean flag. If it is set to true and the xUpdate call
8496 ** is successful, then the value returned by sqlite3_last_insert_rowid()
8497 ** is set to the value of the rowid for the row just inserted.
8499 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
8500 ** apply in the case of a constraint failure on an insert or update.
8502 case OP_VUpdate: {
8503 sqlite3_vtab *pVtab;
8504 const sqlite3_module *pModule;
8505 int nArg;
8506 int i;
8507 sqlite_int64 rowid = 0;
8508 Mem **apArg;
8509 Mem *pX;
8511 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
8512 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
8514 assert( p->readOnly==0 );
8515 if( db->mallocFailed ) goto no_mem;
8516 sqlite3VdbeIncrWriteCounter(p, 0);
8517 pVtab = pOp->p4.pVtab->pVtab;
8518 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8519 rc = SQLITE_LOCKED;
8520 goto abort_due_to_error;
8522 pModule = pVtab->pModule;
8523 nArg = pOp->p2;
8524 assert( pOp->p4type==P4_VTAB );
8525 if( ALWAYS(pModule->xUpdate) ){
8526 u8 vtabOnConflict = db->vtabOnConflict;
8527 apArg = p->apArg;
8528 pX = &aMem[pOp->p3];
8529 for(i=0; i<nArg; i++){
8530 assert( memIsValid(pX) );
8531 memAboutToChange(p, pX);
8532 apArg[i] = pX;
8533 pX++;
8535 db->vtabOnConflict = pOp->p5;
8536 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
8537 db->vtabOnConflict = vtabOnConflict;
8538 sqlite3VtabImportErrmsg(p, pVtab);
8539 if( rc==SQLITE_OK && pOp->p1 ){
8540 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
8541 db->lastRowid = rowid;
8543 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
8544 if( pOp->p5==OE_Ignore ){
8545 rc = SQLITE_OK;
8546 }else{
8547 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
8549 }else{
8550 p->nChange++;
8552 if( rc ) goto abort_due_to_error;
8554 break;
8556 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8558 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8559 /* Opcode: Pagecount P1 P2 * * *
8561 ** Write the current number of pages in database P1 to memory cell P2.
8563 case OP_Pagecount: { /* out2 */
8564 pOut = out2Prerelease(p, pOp);
8565 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
8566 break;
8568 #endif
8571 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8572 /* Opcode: MaxPgcnt P1 P2 P3 * *
8574 ** Try to set the maximum page count for database P1 to the value in P3.
8575 ** Do not let the maximum page count fall below the current page count and
8576 ** do not change the maximum page count value if P3==0.
8578 ** Store the maximum page count after the change in register P2.
8580 case OP_MaxPgcnt: { /* out2 */
8581 unsigned int newMax;
8582 Btree *pBt;
8584 pOut = out2Prerelease(p, pOp);
8585 pBt = db->aDb[pOp->p1].pBt;
8586 newMax = 0;
8587 if( pOp->p3 ){
8588 newMax = sqlite3BtreeLastPage(pBt);
8589 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
8591 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
8592 break;
8594 #endif
8596 /* Opcode: Function P1 P2 P3 P4 *
8597 ** Synopsis: r[P3]=func(r[P2@NP])
8599 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8600 ** contains a pointer to the function to be run) with arguments taken
8601 ** from register P2 and successors. The number of arguments is in
8602 ** the sqlite3_context object that P4 points to.
8603 ** The result of the function is stored
8604 ** in register P3. Register P3 must not be one of the function inputs.
8606 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8607 ** function was determined to be constant at compile time. If the first
8608 ** argument was constant then bit 0 of P1 is set. This is used to determine
8609 ** whether meta data associated with a user function argument using the
8610 ** sqlite3_set_auxdata() API may be safely retained until the next
8611 ** invocation of this opcode.
8613 ** See also: AggStep, AggFinal, PureFunc
8615 /* Opcode: PureFunc P1 P2 P3 P4 *
8616 ** Synopsis: r[P3]=func(r[P2@NP])
8618 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8619 ** contains a pointer to the function to be run) with arguments taken
8620 ** from register P2 and successors. The number of arguments is in
8621 ** the sqlite3_context object that P4 points to.
8622 ** The result of the function is stored
8623 ** in register P3. Register P3 must not be one of the function inputs.
8625 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8626 ** function was determined to be constant at compile time. If the first
8627 ** argument was constant then bit 0 of P1 is set. This is used to determine
8628 ** whether meta data associated with a user function argument using the
8629 ** sqlite3_set_auxdata() API may be safely retained until the next
8630 ** invocation of this opcode.
8632 ** This opcode works exactly like OP_Function. The only difference is in
8633 ** its name. This opcode is used in places where the function must be
8634 ** purely non-deterministic. Some built-in date/time functions can be
8635 ** either deterministic of non-deterministic, depending on their arguments.
8636 ** When those function are used in a non-deterministic way, they will check
8637 ** to see if they were called using OP_PureFunc instead of OP_Function, and
8638 ** if they were, they throw an error.
8640 ** See also: AggStep, AggFinal, Function
8642 case OP_PureFunc: /* group */
8643 case OP_Function: { /* group */
8644 int i;
8645 sqlite3_context *pCtx;
8647 assert( pOp->p4type==P4_FUNCCTX );
8648 pCtx = pOp->p4.pCtx;
8650 /* If this function is inside of a trigger, the register array in aMem[]
8651 ** might change from one evaluation to the next. The next block of code
8652 ** checks to see if the register array has changed, and if so it
8653 ** reinitializes the relevant parts of the sqlite3_context object */
8654 pOut = &aMem[pOp->p3];
8655 if( pCtx->pOut != pOut ){
8656 pCtx->pVdbe = p;
8657 pCtx->pOut = pOut;
8658 pCtx->enc = encoding;
8659 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
8661 assert( pCtx->pVdbe==p );
8663 memAboutToChange(p, pOut);
8664 #ifdef SQLITE_DEBUG
8665 for(i=0; i<pCtx->argc; i++){
8666 assert( memIsValid(pCtx->argv[i]) );
8667 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
8669 #endif
8670 MemSetTypeFlag(pOut, MEM_Null);
8671 assert( pCtx->isError==0 );
8672 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
8674 /* If the function returned an error, throw an exception */
8675 if( pCtx->isError ){
8676 if( pCtx->isError>0 ){
8677 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
8678 rc = pCtx->isError;
8680 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
8681 pCtx->isError = 0;
8682 if( rc ) goto abort_due_to_error;
8685 assert( (pOut->flags&MEM_Str)==0
8686 || pOut->enc==encoding
8687 || db->mallocFailed );
8688 assert( !sqlite3VdbeMemTooBig(pOut) );
8690 REGISTER_TRACE(pOp->p3, pOut);
8691 UPDATE_MAX_BLOBSIZE(pOut);
8692 break;
8695 /* Opcode: ClrSubtype P1 * * * *
8696 ** Synopsis: r[P1].subtype = 0
8698 ** Clear the subtype from register P1.
8700 case OP_ClrSubtype: { /* in1 */
8701 pIn1 = &aMem[pOp->p1];
8702 pIn1->flags &= ~MEM_Subtype;
8703 break;
8706 /* Opcode: GetSubtype P1 P2 * * *
8707 ** Synopsis: r[P2] = r[P1].subtype
8709 ** Extract the subtype value from register P1 and write that subtype
8710 ** into register P2. If P1 has no subtype, then P1 gets a NULL.
8712 case OP_GetSubtype: { /* in1 out2 */
8713 pIn1 = &aMem[pOp->p1];
8714 pOut = &aMem[pOp->p2];
8715 if( pIn1->flags & MEM_Subtype ){
8716 sqlite3VdbeMemSetInt64(pOut, pIn1->eSubtype);
8717 }else{
8718 sqlite3VdbeMemSetNull(pOut);
8720 break;
8723 /* Opcode: SetSubtype P1 P2 * * *
8724 ** Synopsis: r[P2].subtype = r[P1]
8726 ** Set the subtype value of register P2 to the integer from register P1.
8727 ** If P1 is NULL, clear the subtype from p2.
8729 case OP_SetSubtype: { /* in1 out2 */
8730 pIn1 = &aMem[pOp->p1];
8731 pOut = &aMem[pOp->p2];
8732 if( pIn1->flags & MEM_Null ){
8733 pOut->flags &= ~MEM_Subtype;
8734 }else{
8735 assert( pIn1->flags & MEM_Int );
8736 pOut->flags |= MEM_Subtype;
8737 pOut->eSubtype = (u8)(pIn1->u.i & 0xff);
8739 break;
8742 /* Opcode: FilterAdd P1 * P3 P4 *
8743 ** Synopsis: filter(P1) += key(P3@P4)
8745 ** Compute a hash on the P4 registers starting with r[P3] and
8746 ** add that hash to the bloom filter contained in r[P1].
8748 case OP_FilterAdd: {
8749 u64 h;
8751 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8752 pIn1 = &aMem[pOp->p1];
8753 assert( pIn1->flags & MEM_Blob );
8754 assert( pIn1->n>0 );
8755 h = filterHash(aMem, pOp);
8756 #ifdef SQLITE_DEBUG
8757 if( db->flags&SQLITE_VdbeTrace ){
8758 int ii;
8759 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8760 registerTrace(ii, &aMem[ii]);
8762 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8764 #endif
8765 h %= (pIn1->n*8);
8766 pIn1->z[h/8] |= 1<<(h&7);
8767 break;
8770 /* Opcode: Filter P1 P2 P3 P4 *
8771 ** Synopsis: if key(P3@P4) not in filter(P1) goto P2
8773 ** Compute a hash on the key contained in the P4 registers starting
8774 ** with r[P3]. Check to see if that hash is found in the
8775 ** bloom filter hosted by register P1. If it is not present then
8776 ** maybe jump to P2. Otherwise fall through.
8778 ** False negatives are harmless. It is always safe to fall through,
8779 ** even if the value is in the bloom filter. A false negative causes
8780 ** more CPU cycles to be used, but it should still yield the correct
8781 ** answer. However, an incorrect answer may well arise from a
8782 ** false positive - if the jump is taken when it should fall through.
8784 case OP_Filter: { /* jump */
8785 u64 h;
8787 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8788 pIn1 = &aMem[pOp->p1];
8789 assert( (pIn1->flags & MEM_Blob)!=0 );
8790 assert( pIn1->n >= 1 );
8791 h = filterHash(aMem, pOp);
8792 #ifdef SQLITE_DEBUG
8793 if( db->flags&SQLITE_VdbeTrace ){
8794 int ii;
8795 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8796 registerTrace(ii, &aMem[ii]);
8798 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8800 #endif
8801 h %= (pIn1->n*8);
8802 if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
8803 VdbeBranchTaken(1, 2);
8804 p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
8805 goto jump_to_p2;
8806 }else{
8807 p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
8808 VdbeBranchTaken(0, 2);
8810 break;
8813 /* Opcode: Trace P1 P2 * P4 *
8815 ** Write P4 on the statement trace output if statement tracing is
8816 ** enabled.
8818 ** Operand P1 must be 0x7fffffff and P2 must positive.
8820 /* Opcode: Init P1 P2 P3 P4 *
8821 ** Synopsis: Start at P2
8823 ** Programs contain a single instance of this opcode as the very first
8824 ** opcode.
8826 ** If tracing is enabled (by the sqlite3_trace()) interface, then
8827 ** the UTF-8 string contained in P4 is emitted on the trace callback.
8828 ** Or if P4 is blank, use the string returned by sqlite3_sql().
8830 ** If P2 is not zero, jump to instruction P2.
8832 ** Increment the value of P1 so that OP_Once opcodes will jump the
8833 ** first time they are evaluated for this run.
8835 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
8836 ** error is encountered.
8838 case OP_Trace:
8839 case OP_Init: { /* jump */
8840 int i;
8841 #ifndef SQLITE_OMIT_TRACE
8842 char *zTrace;
8843 #endif
8845 /* If the P4 argument is not NULL, then it must be an SQL comment string.
8846 ** The "--" string is broken up to prevent false-positives with srcck1.c.
8848 ** This assert() provides evidence for:
8849 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
8850 ** would have been returned by the legacy sqlite3_trace() interface by
8851 ** using the X argument when X begins with "--" and invoking
8852 ** sqlite3_expanded_sql(P) otherwise.
8854 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
8856 /* OP_Init is always instruction 0 */
8857 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
8859 #ifndef SQLITE_OMIT_TRACE
8860 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
8861 && p->minWriteFileFormat!=254 /* tag-20220401a */
8862 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8864 #ifndef SQLITE_OMIT_DEPRECATED
8865 if( db->mTrace & SQLITE_TRACE_LEGACY ){
8866 char *z = sqlite3VdbeExpandSql(p, zTrace);
8867 db->trace.xLegacy(db->pTraceArg, z);
8868 sqlite3_free(z);
8869 }else
8870 #endif
8871 if( db->nVdbeExec>1 ){
8872 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
8873 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
8874 sqlite3DbFree(db, z);
8875 }else{
8876 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
8879 #ifdef SQLITE_USE_FCNTL_TRACE
8880 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
8881 if( zTrace ){
8882 int j;
8883 for(j=0; j<db->nDb; j++){
8884 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
8885 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
8888 #endif /* SQLITE_USE_FCNTL_TRACE */
8889 #ifdef SQLITE_DEBUG
8890 if( (db->flags & SQLITE_SqlTrace)!=0
8891 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8893 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8895 #endif /* SQLITE_DEBUG */
8896 #endif /* SQLITE_OMIT_TRACE */
8897 assert( pOp->p2>0 );
8898 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8899 if( pOp->opcode==OP_Trace ) break;
8900 for(i=1; i<p->nOp; i++){
8901 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8903 pOp->p1 = 0;
8905 pOp->p1++;
8906 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8907 goto jump_to_p2;
8910 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8911 /* Opcode: CursorHint P1 * * P4 *
8913 ** Provide a hint to cursor P1 that it only needs to return rows that
8914 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
8915 ** to values currently held in registers. TK_COLUMN terms in the P4
8916 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8918 case OP_CursorHint: {
8919 VdbeCursor *pC;
8921 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8922 assert( pOp->p4type==P4_EXPR );
8923 pC = p->apCsr[pOp->p1];
8924 if( pC ){
8925 assert( pC->eCurType==CURTYPE_BTREE );
8926 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8927 pOp->p4.pExpr, aMem);
8929 break;
8931 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8933 #ifdef SQLITE_DEBUG
8934 /* Opcode: Abortable * * * * *
8936 ** Verify that an Abort can happen. Assert if an Abort at this point
8937 ** might cause database corruption. This opcode only appears in debugging
8938 ** builds.
8940 ** An Abort is safe if either there have been no writes, or if there is
8941 ** an active statement journal.
8943 case OP_Abortable: {
8944 sqlite3VdbeAssertAbortable(p);
8945 break;
8947 #endif
8949 #ifdef SQLITE_DEBUG
8950 /* Opcode: ReleaseReg P1 P2 P3 * P5
8951 ** Synopsis: release r[P1@P2] mask P3
8953 ** Release registers from service. Any content that was in the
8954 ** the registers is unreliable after this opcode completes.
8956 ** The registers released will be the P2 registers starting at P1,
8957 ** except if bit ii of P3 set, then do not release register P1+ii.
8958 ** In other words, P3 is a mask of registers to preserve.
8960 ** Releasing a register clears the Mem.pScopyFrom pointer. That means
8961 ** that if the content of the released register was set using OP_SCopy,
8962 ** a change to the value of the source register for the OP_SCopy will no longer
8963 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8965 ** If P5 is set, then all released registers have their type set
8966 ** to MEM_Undefined so that any subsequent attempt to read the released
8967 ** register (before it is reinitialized) will generate an assertion fault.
8969 ** P5 ought to be set on every call to this opcode.
8970 ** However, there are places in the code generator will release registers
8971 ** before their are used, under the (valid) assumption that the registers
8972 ** will not be reallocated for some other purpose before they are used and
8973 ** hence are safe to release.
8975 ** This opcode is only available in testing and debugging builds. It is
8976 ** not generated for release builds. The purpose of this opcode is to help
8977 ** validate the generated bytecode. This opcode does not actually contribute
8978 ** to computing an answer.
8980 case OP_ReleaseReg: {
8981 Mem *pMem;
8982 int i;
8983 u32 constMask;
8984 assert( pOp->p1>0 );
8985 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8986 pMem = &aMem[pOp->p1];
8987 constMask = pOp->p3;
8988 for(i=0; i<pOp->p2; i++, pMem++){
8989 if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8990 pMem->pScopyFrom = 0;
8991 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
8994 break;
8996 #endif
8998 /* Opcode: Noop * * * * *
9000 ** Do nothing. This instruction is often useful as a jump
9001 ** destination.
9004 ** The magic Explain opcode are only inserted when explain==2 (which
9005 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
9006 ** This opcode records information from the optimizer. It is the
9007 ** the same as a no-op. This opcodesnever appears in a real VM program.
9009 default: { /* This is really OP_Noop, OP_Explain */
9010 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
9012 break;
9015 /*****************************************************************************
9016 ** The cases of the switch statement above this line should all be indented
9017 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
9018 ** readability. From this point on down, the normal indentation rules are
9019 ** restored.
9020 *****************************************************************************/
9023 #if defined(VDBE_PROFILE)
9024 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
9025 pnCycle = 0;
9026 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9027 if( pnCycle ){
9028 *pnCycle += sqlite3Hwtime();
9029 pnCycle = 0;
9031 #endif
9033 /* The following code adds nothing to the actual functionality
9034 ** of the program. It is only here for testing and debugging.
9035 ** On the other hand, it does burn CPU cycles every time through
9036 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
9038 #ifndef NDEBUG
9039 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
9041 #ifdef SQLITE_DEBUG
9042 if( db->flags & SQLITE_VdbeTrace ){
9043 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
9044 if( rc!=0 ) printf("rc=%d\n",rc);
9045 if( opProperty & (OPFLG_OUT2) ){
9046 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
9048 if( opProperty & OPFLG_OUT3 ){
9049 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
9051 if( opProperty==0xff ){
9052 /* Never happens. This code exists to avoid a harmless linkage
9053 ** warning about sqlite3VdbeRegisterDump() being defined but not
9054 ** used. */
9055 sqlite3VdbeRegisterDump(p);
9058 #endif /* SQLITE_DEBUG */
9059 #endif /* NDEBUG */
9060 } /* The end of the for(;;) loop the loops through opcodes */
9062 /* If we reach this point, it means that execution is finished with
9063 ** an error of some kind.
9065 abort_due_to_error:
9066 if( db->mallocFailed ){
9067 rc = SQLITE_NOMEM_BKPT;
9068 }else if( rc==SQLITE_IOERR_CORRUPTFS ){
9069 rc = SQLITE_CORRUPT_BKPT;
9071 assert( rc );
9072 #ifdef SQLITE_DEBUG
9073 if( db->flags & SQLITE_VdbeTrace ){
9074 const char *zTrace = p->zSql;
9075 if( zTrace==0 ){
9076 if( aOp[0].opcode==OP_Trace ){
9077 zTrace = aOp[0].p4.z;
9079 if( zTrace==0 ) zTrace = "???";
9081 printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
9083 #endif
9084 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
9085 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
9087 p->rc = rc;
9088 sqlite3SystemError(db, rc);
9089 testcase( sqlite3GlobalConfig.xLog!=0 );
9090 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
9091 (int)(pOp - aOp), p->zSql, p->zErrMsg);
9092 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
9093 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
9094 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
9095 db->flags |= SQLITE_CorruptRdOnly;
9097 rc = SQLITE_ERROR;
9098 if( resetSchemaOnFault>0 ){
9099 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
9102 /* This is the only way out of this procedure. We have to
9103 ** release the mutexes on btrees that were acquired at the
9104 ** top. */
9105 vdbe_return:
9106 #if defined(VDBE_PROFILE)
9107 if( pnCycle ){
9108 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
9109 pnCycle = 0;
9111 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9112 if( pnCycle ){
9113 *pnCycle += sqlite3Hwtime();
9114 pnCycle = 0;
9116 #endif
9118 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9119 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
9120 nProgressLimit += db->nProgressOps;
9121 if( db->xProgress(db->pProgressArg) ){
9122 nProgressLimit = LARGEST_UINT64;
9123 rc = SQLITE_INTERRUPT;
9124 goto abort_due_to_error;
9127 #endif
9128 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
9129 if( DbMaskNonZero(p->lockMask) ){
9130 sqlite3VdbeLeave(p);
9132 assert( rc!=SQLITE_OK || nExtraDelete==0
9133 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
9135 return rc;
9137 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
9138 ** is encountered.
9140 too_big:
9141 sqlite3VdbeError(p, "string or blob too big");
9142 rc = SQLITE_TOOBIG;
9143 goto abort_due_to_error;
9145 /* Jump to here if a malloc() fails.
9147 no_mem:
9148 sqlite3OomFault(db);
9149 sqlite3VdbeError(p, "out of memory");
9150 rc = SQLITE_NOMEM_BKPT;
9151 goto abort_due_to_error;
9153 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
9154 ** flag.
9156 abort_due_to_interrupt:
9157 assert( AtomicLoad(&db->u1.isInterrupted) );
9158 rc = SQLITE_INTERRUPT;
9159 goto abort_due_to_error;