Replaces use of deprecated WINAPI_FAMILY_APP macro with WINAPI_FAMILY_PC_APP
[sqlcipher.git] / src / vdbe.c
blobd8b471de2e27565431b64cb0224a785ea7262e67
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: { /* jump0 */
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, the value register P1 is left with a value
1156 ** such that subsequent OP_Yields go back to the this same
1157 ** OP_EndCoroutine instruction.
1159 ** See also: InitCoroutine
1161 case OP_EndCoroutine: { /* in1 */
1162 VdbeOp *pCaller;
1163 pIn1 = &aMem[pOp->p1];
1164 assert( pIn1->flags==MEM_Int );
1165 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
1166 pCaller = &aOp[pIn1->u.i];
1167 assert( pCaller->opcode==OP_Yield );
1168 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
1169 pIn1->u.i = (int)(pOp - p->aOp) - 1;
1170 pOp = &aOp[pCaller->p2 - 1];
1171 break;
1174 /* Opcode: Yield P1 P2 * * *
1176 ** Swap the program counter with the value in register P1. This
1177 ** has the effect of yielding to a coroutine.
1179 ** If the coroutine that is launched by this instruction ends with
1180 ** Yield or Return then continue to the next instruction. But if
1181 ** the coroutine launched by this instruction ends with
1182 ** EndCoroutine, then jump to P2 rather than continuing with the
1183 ** next instruction.
1185 ** See also: InitCoroutine
1187 case OP_Yield: { /* in1, jump0 */
1188 int pcDest;
1189 pIn1 = &aMem[pOp->p1];
1190 assert( VdbeMemDynamic(pIn1)==0 );
1191 pIn1->flags = MEM_Int;
1192 pcDest = (int)pIn1->u.i;
1193 pIn1->u.i = (int)(pOp - aOp);
1194 REGISTER_TRACE(pOp->p1, pIn1);
1195 pOp = &aOp[pcDest];
1196 break;
1199 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
1200 ** Synopsis: if r[P3]=null halt
1202 ** Check the value in register P3. If it is NULL then Halt using
1203 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
1204 ** value in register P3 is not NULL, then this routine is a no-op.
1205 ** The P5 parameter should be 1.
1207 case OP_HaltIfNull: { /* in3 */
1208 pIn3 = &aMem[pOp->p3];
1209 #ifdef SQLITE_DEBUG
1210 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1211 #endif
1212 if( (pIn3->flags & MEM_Null)==0 ) break;
1213 /* Fall through into OP_Halt */
1214 /* no break */ deliberate_fall_through
1217 /* Opcode: Halt P1 P2 * P4 P5
1219 ** Exit immediately. All open cursors, etc are closed
1220 ** automatically.
1222 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
1223 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
1224 ** For errors, it can be some other value. If P1!=0 then P2 will determine
1225 ** whether or not to rollback the current transaction. Do not rollback
1226 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
1227 ** then back out all changes that have occurred during this execution of the
1228 ** VDBE, but do not rollback the transaction.
1230 ** If P4 is not null then it is an error message string.
1232 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
1234 ** 0: (no change)
1235 ** 1: NOT NULL constraint failed: P4
1236 ** 2: UNIQUE constraint failed: P4
1237 ** 3: CHECK constraint failed: P4
1238 ** 4: FOREIGN KEY constraint failed: P4
1240 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
1241 ** omitted.
1243 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
1244 ** every program. So a jump past the last instruction of the program
1245 ** is the same as executing Halt.
1247 case OP_Halt: {
1248 VdbeFrame *pFrame;
1249 int pcx;
1251 #ifdef SQLITE_DEBUG
1252 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1253 #endif
1255 /* A deliberately coded "OP_Halt SQLITE_INTERNAL * * * *" opcode indicates
1256 ** something is wrong with the code generator. Raise an assertion in order
1257 ** to bring this to the attention of fuzzers and other testing tools. */
1258 assert( pOp->p1!=SQLITE_INTERNAL );
1260 if( p->pFrame && pOp->p1==SQLITE_OK ){
1261 /* Halt the sub-program. Return control to the parent frame. */
1262 pFrame = p->pFrame;
1263 p->pFrame = pFrame->pParent;
1264 p->nFrame--;
1265 sqlite3VdbeSetChanges(db, p->nChange);
1266 pcx = sqlite3VdbeFrameRestore(pFrame);
1267 if( pOp->p2==OE_Ignore ){
1268 /* Instruction pcx is the OP_Program that invoked the sub-program
1269 ** currently being halted. If the p2 instruction of this OP_Halt
1270 ** instruction is set to OE_Ignore, then the sub-program is throwing
1271 ** an IGNORE exception. In this case jump to the address specified
1272 ** as the p2 of the calling OP_Program. */
1273 pcx = p->aOp[pcx].p2-1;
1275 aOp = p->aOp;
1276 aMem = p->aMem;
1277 pOp = &aOp[pcx];
1278 break;
1280 p->rc = pOp->p1;
1281 p->errorAction = (u8)pOp->p2;
1282 assert( pOp->p5<=4 );
1283 if( p->rc ){
1284 if( pOp->p5 ){
1285 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
1286 "FOREIGN KEY" };
1287 testcase( pOp->p5==1 );
1288 testcase( pOp->p5==2 );
1289 testcase( pOp->p5==3 );
1290 testcase( pOp->p5==4 );
1291 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
1292 if( pOp->p4.z ){
1293 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
1295 }else{
1296 sqlite3VdbeError(p, "%s", pOp->p4.z);
1298 pcx = (int)(pOp - aOp);
1299 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
1301 rc = sqlite3VdbeHalt(p);
1302 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1303 if( rc==SQLITE_BUSY ){
1304 p->rc = SQLITE_BUSY;
1305 }else{
1306 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1307 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1308 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1310 goto vdbe_return;
1313 /* Opcode: Integer P1 P2 * * *
1314 ** Synopsis: r[P2]=P1
1316 ** The 32-bit integer value P1 is written into register P2.
1318 case OP_Integer: { /* out2 */
1319 pOut = out2Prerelease(p, pOp);
1320 pOut->u.i = pOp->p1;
1321 break;
1324 /* Opcode: Int64 * P2 * P4 *
1325 ** Synopsis: r[P2]=P4
1327 ** P4 is a pointer to a 64-bit integer value.
1328 ** Write that value into register P2.
1330 case OP_Int64: { /* out2 */
1331 pOut = out2Prerelease(p, pOp);
1332 assert( pOp->p4.pI64!=0 );
1333 pOut->u.i = *pOp->p4.pI64;
1334 break;
1337 #ifndef SQLITE_OMIT_FLOATING_POINT
1338 /* Opcode: Real * P2 * P4 *
1339 ** Synopsis: r[P2]=P4
1341 ** P4 is a pointer to a 64-bit floating point value.
1342 ** Write that value into register P2.
1344 case OP_Real: { /* same as TK_FLOAT, out2 */
1345 pOut = out2Prerelease(p, pOp);
1346 pOut->flags = MEM_Real;
1347 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1348 pOut->u.r = *pOp->p4.pReal;
1349 break;
1351 #endif
1353 /* Opcode: String8 * P2 * P4 *
1354 ** Synopsis: r[P2]='P4'
1356 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1357 ** into a String opcode before it is executed for the first time. During
1358 ** this transformation, the length of string P4 is computed and stored
1359 ** as the P1 parameter.
1361 case OP_String8: { /* same as TK_STRING, out2 */
1362 assert( pOp->p4.z!=0 );
1363 pOut = out2Prerelease(p, pOp);
1364 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1366 #ifndef SQLITE_OMIT_UTF16
1367 if( encoding!=SQLITE_UTF8 ){
1368 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1369 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1370 if( rc ) goto too_big;
1371 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1372 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1373 assert( VdbeMemDynamic(pOut)==0 );
1374 pOut->szMalloc = 0;
1375 pOut->flags |= MEM_Static;
1376 if( pOp->p4type==P4_DYNAMIC ){
1377 sqlite3DbFree(db, pOp->p4.z);
1379 pOp->p4type = P4_DYNAMIC;
1380 pOp->p4.z = pOut->z;
1381 pOp->p1 = pOut->n;
1383 #endif
1384 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1385 goto too_big;
1387 pOp->opcode = OP_String;
1388 assert( rc==SQLITE_OK );
1389 /* Fall through to the next case, OP_String */
1390 /* no break */ deliberate_fall_through
1393 /* Opcode: String P1 P2 P3 P4 P5
1394 ** Synopsis: r[P2]='P4' (len=P1)
1396 ** The string value P4 of length P1 (bytes) is stored in register P2.
1398 ** If P3 is not zero and the content of register P3 is equal to P5, then
1399 ** the datatype of the register P2 is converted to BLOB. The content is
1400 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1401 ** of a string, as if it had been CAST. In other words:
1403 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1405 case OP_String: { /* out2 */
1406 assert( pOp->p4.z!=0 );
1407 pOut = out2Prerelease(p, pOp);
1408 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1409 pOut->z = pOp->p4.z;
1410 pOut->n = pOp->p1;
1411 pOut->enc = encoding;
1412 UPDATE_MAX_BLOBSIZE(pOut);
1413 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1414 if( pOp->p3>0 ){
1415 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1416 pIn3 = &aMem[pOp->p3];
1417 assert( pIn3->flags & MEM_Int );
1418 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1420 #endif
1421 break;
1424 /* Opcode: BeginSubrtn * P2 * * *
1425 ** Synopsis: r[P2]=NULL
1427 ** Mark the beginning of a subroutine that can be entered in-line
1428 ** or that can be called using OP_Gosub. The subroutine should
1429 ** be terminated by an OP_Return instruction that has a P1 operand that
1430 ** is the same as the P2 operand to this opcode and that has P3 set to 1.
1431 ** If the subroutine is entered in-line, then the OP_Return will simply
1432 ** fall through. But if the subroutine is entered using OP_Gosub, then
1433 ** the OP_Return will jump back to the first instruction after the OP_Gosub.
1435 ** This routine works by loading a NULL into the P2 register. When the
1436 ** return address register contains a NULL, the OP_Return instruction is
1437 ** a no-op that simply falls through to the next instruction (assuming that
1438 ** the OP_Return opcode has a P3 value of 1). Thus if the subroutine is
1439 ** entered in-line, then the OP_Return will cause in-line execution to
1440 ** continue. But if the subroutine is entered via OP_Gosub, then the
1441 ** OP_Return will cause a return to the address following the OP_Gosub.
1443 ** This opcode is identical to OP_Null. It has a different name
1444 ** only to make the byte code easier to read and verify.
1446 /* Opcode: Null P1 P2 P3 * *
1447 ** Synopsis: r[P2..P3]=NULL
1449 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1450 ** NULL into register P3 and every register in between P2 and P3. If P3
1451 ** is less than P2 (typically P3 is zero) then only register P2 is
1452 ** set to NULL.
1454 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1455 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1456 ** OP_Ne or OP_Eq.
1458 case OP_BeginSubrtn:
1459 case OP_Null: { /* out2 */
1460 int cnt;
1461 u16 nullFlag;
1462 pOut = out2Prerelease(p, pOp);
1463 cnt = pOp->p3-pOp->p2;
1464 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1465 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1466 pOut->n = 0;
1467 #ifdef SQLITE_DEBUG
1468 pOut->uTemp = 0;
1469 #endif
1470 while( cnt>0 ){
1471 pOut++;
1472 memAboutToChange(p, pOut);
1473 sqlite3VdbeMemSetNull(pOut);
1474 pOut->flags = nullFlag;
1475 pOut->n = 0;
1476 cnt--;
1478 break;
1481 /* Opcode: SoftNull P1 * * * *
1482 ** Synopsis: r[P1]=NULL
1484 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1485 ** instruction, but do not free any string or blob memory associated with
1486 ** the register, so that if the value was a string or blob that was
1487 ** previously copied using OP_SCopy, the copies will continue to be valid.
1489 case OP_SoftNull: {
1490 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1491 pOut = &aMem[pOp->p1];
1492 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1493 break;
1496 /* Opcode: Blob P1 P2 * P4 *
1497 ** Synopsis: r[P2]=P4 (len=P1)
1499 ** P4 points to a blob of data P1 bytes long. Store this
1500 ** blob in register P2. If P4 is a NULL pointer, then construct
1501 ** a zero-filled blob that is P1 bytes long in P2.
1503 case OP_Blob: { /* out2 */
1504 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1505 pOut = out2Prerelease(p, pOp);
1506 if( pOp->p4.z==0 ){
1507 sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
1508 if( sqlite3VdbeMemExpandBlob(pOut) ) goto no_mem;
1509 }else{
1510 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1512 pOut->enc = encoding;
1513 UPDATE_MAX_BLOBSIZE(pOut);
1514 break;
1517 /* Opcode: Variable P1 P2 * * *
1518 ** Synopsis: r[P2]=parameter(P1)
1520 ** Transfer the values of bound parameter P1 into register P2
1522 case OP_Variable: { /* out2 */
1523 Mem *pVar; /* Value being transferred */
1525 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1526 pVar = &p->aVar[pOp->p1 - 1];
1527 if( sqlite3VdbeMemTooBig(pVar) ){
1528 goto too_big;
1530 pOut = &aMem[pOp->p2];
1531 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
1532 memcpy(pOut, pVar, MEMCELLSIZE);
1533 pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
1534 pOut->flags |= MEM_Static|MEM_FromBind;
1535 UPDATE_MAX_BLOBSIZE(pOut);
1536 break;
1539 /* Opcode: Move P1 P2 P3 * *
1540 ** Synopsis: r[P2@P3]=r[P1@P3]
1542 ** Move the P3 values in register P1..P1+P3-1 over into
1543 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1544 ** left holding a NULL. It is an error for register ranges
1545 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1546 ** for P3 to be less than 1.
1548 case OP_Move: {
1549 int n; /* Number of registers left to copy */
1550 int p1; /* Register to copy from */
1551 int p2; /* Register to copy to */
1553 n = pOp->p3;
1554 p1 = pOp->p1;
1555 p2 = pOp->p2;
1556 assert( n>0 && p1>0 && p2>0 );
1557 assert( p1+n<=p2 || p2+n<=p1 );
1559 pIn1 = &aMem[p1];
1560 pOut = &aMem[p2];
1562 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1563 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1564 assert( memIsValid(pIn1) );
1565 memAboutToChange(p, pOut);
1566 sqlite3VdbeMemMove(pOut, pIn1);
1567 #ifdef SQLITE_DEBUG
1568 pIn1->pScopyFrom = 0;
1569 { int i;
1570 for(i=1; i<p->nMem; i++){
1571 if( aMem[i].pScopyFrom==pIn1 ){
1572 aMem[i].pScopyFrom = pOut;
1576 #endif
1577 Deephemeralize(pOut);
1578 REGISTER_TRACE(p2++, pOut);
1579 pIn1++;
1580 pOut++;
1581 }while( --n );
1582 break;
1585 /* Opcode: Copy P1 P2 P3 * P5
1586 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1588 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1590 ** If the 0x0002 bit of P5 is set then also clear the MEM_Subtype flag in the
1591 ** destination. The 0x0001 bit of P5 indicates that this Copy opcode cannot
1592 ** be merged. The 0x0001 bit is used by the query planner and does not
1593 ** come into play during query execution.
1595 ** This instruction makes a deep copy of the value. A duplicate
1596 ** is made of any string or blob constant. See also OP_SCopy.
1598 case OP_Copy: {
1599 int n;
1601 n = pOp->p3;
1602 pIn1 = &aMem[pOp->p1];
1603 pOut = &aMem[pOp->p2];
1604 assert( pOut!=pIn1 );
1605 while( 1 ){
1606 memAboutToChange(p, pOut);
1607 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1608 Deephemeralize(pOut);
1609 if( (pOut->flags & MEM_Subtype)!=0 && (pOp->p5 & 0x0002)!=0 ){
1610 pOut->flags &= ~MEM_Subtype;
1612 #ifdef SQLITE_DEBUG
1613 pOut->pScopyFrom = 0;
1614 #endif
1615 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1616 if( (n--)==0 ) break;
1617 pOut++;
1618 pIn1++;
1620 break;
1623 /* Opcode: SCopy P1 P2 * * *
1624 ** Synopsis: r[P2]=r[P1]
1626 ** Make a shallow copy of register P1 into register P2.
1628 ** This instruction makes a shallow copy of the value. If the value
1629 ** is a string or blob, then the copy is only a pointer to the
1630 ** original and hence if the original changes so will the copy.
1631 ** Worse, if the original is deallocated, the copy becomes invalid.
1632 ** Thus the program must guarantee that the original will not change
1633 ** during the lifetime of the copy. Use OP_Copy to make a complete
1634 ** copy.
1636 case OP_SCopy: { /* out2 */
1637 pIn1 = &aMem[pOp->p1];
1638 pOut = &aMem[pOp->p2];
1639 assert( pOut!=pIn1 );
1640 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1641 #ifdef SQLITE_DEBUG
1642 pOut->pScopyFrom = pIn1;
1643 pOut->mScopyFlags = pIn1->flags;
1644 #endif
1645 break;
1648 /* Opcode: IntCopy P1 P2 * * *
1649 ** Synopsis: r[P2]=r[P1]
1651 ** Transfer the integer value held in register P1 into register P2.
1653 ** This is an optimized version of SCopy that works only for integer
1654 ** values.
1656 case OP_IntCopy: { /* out2 */
1657 pIn1 = &aMem[pOp->p1];
1658 assert( (pIn1->flags & MEM_Int)!=0 );
1659 pOut = &aMem[pOp->p2];
1660 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1661 break;
1664 /* Opcode: FkCheck * * * * *
1666 ** Halt with an SQLITE_CONSTRAINT error if there are any unresolved
1667 ** foreign key constraint violations. If there are no foreign key
1668 ** constraint violations, this is a no-op.
1670 ** FK constraint violations are also checked when the prepared statement
1671 ** exits. This opcode is used to raise foreign key constraint errors prior
1672 ** to returning results such as a row change count or the result of a
1673 ** RETURNING clause.
1675 case OP_FkCheck: {
1676 if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){
1677 goto abort_due_to_error;
1679 break;
1682 /* Opcode: ResultRow P1 P2 * * *
1683 ** Synopsis: output=r[P1@P2]
1685 ** The registers P1 through P1+P2-1 contain a single row of
1686 ** results. This opcode causes the sqlite3_step() call to terminate
1687 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1688 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1689 ** the result row.
1691 case OP_ResultRow: {
1692 assert( p->nResColumn==pOp->p2 );
1693 assert( pOp->p1>0 || CORRUPT_DB );
1694 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1696 p->cacheCtr = (p->cacheCtr + 2)|1;
1697 p->pResultRow = &aMem[pOp->p1];
1698 #ifdef SQLITE_DEBUG
1700 Mem *pMem = p->pResultRow;
1701 int i;
1702 for(i=0; i<pOp->p2; i++){
1703 assert( memIsValid(&pMem[i]) );
1704 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1705 /* The registers in the result will not be used again when the
1706 ** prepared statement restarts. This is because sqlite3_column()
1707 ** APIs might have caused type conversions of made other changes to
1708 ** the register values. Therefore, we can go ahead and break any
1709 ** OP_SCopy dependencies. */
1710 pMem[i].pScopyFrom = 0;
1713 #endif
1714 if( db->mallocFailed ) goto no_mem;
1715 if( db->mTrace & SQLITE_TRACE_ROW ){
1716 db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1718 p->pc = (int)(pOp - aOp) + 1;
1719 rc = SQLITE_ROW;
1720 goto vdbe_return;
1723 /* Opcode: Concat P1 P2 P3 * *
1724 ** Synopsis: r[P3]=r[P2]+r[P1]
1726 ** Add the text in register P1 onto the end of the text in
1727 ** register P2 and store the result in register P3.
1728 ** If either the P1 or P2 text are NULL then store NULL in P3.
1730 ** P3 = P2 || P1
1732 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1733 ** if P3 is the same register as P2, the implementation is able
1734 ** to avoid a memcpy().
1736 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1737 i64 nByte; /* Total size of the output string or blob */
1738 u16 flags1; /* Initial flags for P1 */
1739 u16 flags2; /* Initial flags for P2 */
1741 pIn1 = &aMem[pOp->p1];
1742 pIn2 = &aMem[pOp->p2];
1743 pOut = &aMem[pOp->p3];
1744 testcase( pOut==pIn2 );
1745 assert( pIn1!=pOut );
1746 flags1 = pIn1->flags;
1747 testcase( flags1 & MEM_Null );
1748 testcase( pIn2->flags & MEM_Null );
1749 if( (flags1 | pIn2->flags) & MEM_Null ){
1750 sqlite3VdbeMemSetNull(pOut);
1751 break;
1753 if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
1754 if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
1755 flags1 = pIn1->flags & ~MEM_Str;
1756 }else if( (flags1 & MEM_Zero)!=0 ){
1757 if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
1758 flags1 = pIn1->flags & ~MEM_Str;
1760 flags2 = pIn2->flags;
1761 if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
1762 if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
1763 flags2 = pIn2->flags & ~MEM_Str;
1764 }else if( (flags2 & MEM_Zero)!=0 ){
1765 if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
1766 flags2 = pIn2->flags & ~MEM_Str;
1768 nByte = pIn1->n + pIn2->n;
1769 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1770 goto too_big;
1772 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1773 goto no_mem;
1775 MemSetTypeFlag(pOut, MEM_Str);
1776 if( pOut!=pIn2 ){
1777 memcpy(pOut->z, pIn2->z, pIn2->n);
1778 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
1779 pIn2->flags = flags2;
1781 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1782 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1783 pIn1->flags = flags1;
1784 if( encoding>SQLITE_UTF8 ) nByte &= ~1;
1785 pOut->z[nByte]=0;
1786 pOut->z[nByte+1] = 0;
1787 pOut->flags |= MEM_Term;
1788 pOut->n = (int)nByte;
1789 pOut->enc = encoding;
1790 UPDATE_MAX_BLOBSIZE(pOut);
1791 break;
1794 /* Opcode: Add P1 P2 P3 * *
1795 ** Synopsis: r[P3]=r[P1]+r[P2]
1797 ** Add the value in register P1 to the value in register P2
1798 ** and store the result in register P3.
1799 ** If either input is NULL, the result is NULL.
1801 /* Opcode: Multiply P1 P2 P3 * *
1802 ** Synopsis: r[P3]=r[P1]*r[P2]
1805 ** Multiply the value in register P1 by the value in register P2
1806 ** and store the result in register P3.
1807 ** If either input is NULL, the result is NULL.
1809 /* Opcode: Subtract P1 P2 P3 * *
1810 ** Synopsis: r[P3]=r[P2]-r[P1]
1812 ** Subtract the value in register P1 from the value in register P2
1813 ** and store the result in register P3.
1814 ** If either input is NULL, the result is NULL.
1816 /* Opcode: Divide P1 P2 P3 * *
1817 ** Synopsis: r[P3]=r[P2]/r[P1]
1819 ** Divide the value in register P1 by the value in register P2
1820 ** and store the result in register P3 (P3=P2/P1). If the value in
1821 ** register P1 is zero, then the result is NULL. If either input is
1822 ** NULL, the result is NULL.
1824 /* Opcode: Remainder P1 P2 P3 * *
1825 ** Synopsis: r[P3]=r[P2]%r[P1]
1827 ** Compute the remainder after integer register P2 is divided by
1828 ** register P1 and store the result in register P3.
1829 ** If the value in register P1 is zero the result is NULL.
1830 ** If either operand is NULL, the result is NULL.
1832 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1833 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1834 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1835 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1836 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1837 u16 type1; /* Numeric type of left operand */
1838 u16 type2; /* Numeric type of right operand */
1839 i64 iA; /* Integer value of left operand */
1840 i64 iB; /* Integer value of right operand */
1841 double rA; /* Real value of left operand */
1842 double rB; /* Real value of right operand */
1844 pIn1 = &aMem[pOp->p1];
1845 type1 = pIn1->flags;
1846 pIn2 = &aMem[pOp->p2];
1847 type2 = pIn2->flags;
1848 pOut = &aMem[pOp->p3];
1849 if( (type1 & type2 & MEM_Int)!=0 ){
1850 int_math:
1851 iA = pIn1->u.i;
1852 iB = pIn2->u.i;
1853 switch( pOp->opcode ){
1854 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1855 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1856 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1857 case OP_Divide: {
1858 if( iA==0 ) goto arithmetic_result_is_null;
1859 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1860 iB /= iA;
1861 break;
1863 default: {
1864 if( iA==0 ) goto arithmetic_result_is_null;
1865 if( iA==-1 ) iA = 1;
1866 iB %= iA;
1867 break;
1870 pOut->u.i = iB;
1871 MemSetTypeFlag(pOut, MEM_Int);
1872 }else if( ((type1 | type2) & MEM_Null)!=0 ){
1873 goto arithmetic_result_is_null;
1874 }else{
1875 type1 = numericType(pIn1);
1876 type2 = numericType(pIn2);
1877 if( (type1 & type2 & MEM_Int)!=0 ) goto int_math;
1878 fp_math:
1879 rA = sqlite3VdbeRealValue(pIn1);
1880 rB = sqlite3VdbeRealValue(pIn2);
1881 switch( pOp->opcode ){
1882 case OP_Add: rB += rA; break;
1883 case OP_Subtract: rB -= rA; break;
1884 case OP_Multiply: rB *= rA; break;
1885 case OP_Divide: {
1886 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1887 if( rA==(double)0 ) goto arithmetic_result_is_null;
1888 rB /= rA;
1889 break;
1891 default: {
1892 iA = sqlite3VdbeIntValue(pIn1);
1893 iB = sqlite3VdbeIntValue(pIn2);
1894 if( iA==0 ) goto arithmetic_result_is_null;
1895 if( iA==-1 ) iA = 1;
1896 rB = (double)(iB % iA);
1897 break;
1900 #ifdef SQLITE_OMIT_FLOATING_POINT
1901 pOut->u.i = rB;
1902 MemSetTypeFlag(pOut, MEM_Int);
1903 #else
1904 if( sqlite3IsNaN(rB) ){
1905 goto arithmetic_result_is_null;
1907 pOut->u.r = rB;
1908 MemSetTypeFlag(pOut, MEM_Real);
1909 #endif
1911 break;
1913 arithmetic_result_is_null:
1914 sqlite3VdbeMemSetNull(pOut);
1915 break;
1918 /* Opcode: CollSeq P1 * * P4
1920 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1921 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1922 ** be returned. This is used by the built-in min(), max() and nullif()
1923 ** functions.
1925 ** If P1 is not zero, then it is a register that a subsequent min() or
1926 ** max() aggregate will set to 1 if the current row is not the minimum or
1927 ** maximum. The P1 register is initialized to 0 by this instruction.
1929 ** The interface used by the implementation of the aforementioned functions
1930 ** to retrieve the collation sequence set by this opcode is not available
1931 ** publicly. Only built-in functions have access to this feature.
1933 case OP_CollSeq: {
1934 assert( pOp->p4type==P4_COLLSEQ );
1935 if( pOp->p1 ){
1936 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1938 break;
1941 /* Opcode: BitAnd P1 P2 P3 * *
1942 ** Synopsis: r[P3]=r[P1]&r[P2]
1944 ** Take the bit-wise AND of the values in register P1 and P2 and
1945 ** store the result in register P3.
1946 ** If either input is NULL, the result is NULL.
1948 /* Opcode: BitOr P1 P2 P3 * *
1949 ** Synopsis: r[P3]=r[P1]|r[P2]
1951 ** Take the bit-wise OR of the values in register P1 and P2 and
1952 ** store the result in register P3.
1953 ** If either input is NULL, the result is NULL.
1955 /* Opcode: ShiftLeft P1 P2 P3 * *
1956 ** Synopsis: r[P3]=r[P2]<<r[P1]
1958 ** Shift the integer value in register P2 to the left by the
1959 ** number of bits specified by the integer in register P1.
1960 ** Store the result in register P3.
1961 ** If either input is NULL, the result is NULL.
1963 /* Opcode: ShiftRight P1 P2 P3 * *
1964 ** Synopsis: r[P3]=r[P2]>>r[P1]
1966 ** Shift the integer value in register P2 to the right by the
1967 ** number of bits specified by the integer in register P1.
1968 ** Store the result in register P3.
1969 ** If either input is NULL, the result is NULL.
1971 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1972 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1973 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1974 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1975 i64 iA;
1976 u64 uA;
1977 i64 iB;
1978 u8 op;
1980 pIn1 = &aMem[pOp->p1];
1981 pIn2 = &aMem[pOp->p2];
1982 pOut = &aMem[pOp->p3];
1983 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1984 sqlite3VdbeMemSetNull(pOut);
1985 break;
1987 iA = sqlite3VdbeIntValue(pIn2);
1988 iB = sqlite3VdbeIntValue(pIn1);
1989 op = pOp->opcode;
1990 if( op==OP_BitAnd ){
1991 iA &= iB;
1992 }else if( op==OP_BitOr ){
1993 iA |= iB;
1994 }else if( iB!=0 ){
1995 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1997 /* If shifting by a negative amount, shift in the other direction */
1998 if( iB<0 ){
1999 assert( OP_ShiftRight==OP_ShiftLeft+1 );
2000 op = 2*OP_ShiftLeft + 1 - op;
2001 iB = iB>(-64) ? -iB : 64;
2004 if( iB>=64 ){
2005 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
2006 }else{
2007 memcpy(&uA, &iA, sizeof(uA));
2008 if( op==OP_ShiftLeft ){
2009 uA <<= iB;
2010 }else{
2011 uA >>= iB;
2012 /* Sign-extend on a right shift of a negative number */
2013 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
2015 memcpy(&iA, &uA, sizeof(iA));
2018 pOut->u.i = iA;
2019 MemSetTypeFlag(pOut, MEM_Int);
2020 break;
2023 /* Opcode: AddImm P1 P2 * * *
2024 ** Synopsis: r[P1]=r[P1]+P2
2026 ** Add the constant P2 to the value in register P1.
2027 ** The result is always an integer.
2029 ** To force any register to be an integer, just add 0.
2031 case OP_AddImm: { /* in1 */
2032 pIn1 = &aMem[pOp->p1];
2033 memAboutToChange(p, pIn1);
2034 sqlite3VdbeMemIntegerify(pIn1);
2035 *(u64*)&pIn1->u.i += (u64)pOp->p2;
2036 break;
2039 /* Opcode: MustBeInt P1 P2 * * *
2041 ** Force the value in register P1 to be an integer. If the value
2042 ** in P1 is not an integer and cannot be converted into an integer
2043 ** without data loss, then jump immediately to P2, or if P2==0
2044 ** raise an SQLITE_MISMATCH exception.
2046 case OP_MustBeInt: { /* jump0, in1 */
2047 pIn1 = &aMem[pOp->p1];
2048 if( (pIn1->flags & MEM_Int)==0 ){
2049 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
2050 if( (pIn1->flags & MEM_Int)==0 ){
2051 VdbeBranchTaken(1, 2);
2052 if( pOp->p2==0 ){
2053 rc = SQLITE_MISMATCH;
2054 goto abort_due_to_error;
2055 }else{
2056 goto jump_to_p2;
2060 VdbeBranchTaken(0, 2);
2061 MemSetTypeFlag(pIn1, MEM_Int);
2062 break;
2065 #ifndef SQLITE_OMIT_FLOATING_POINT
2066 /* Opcode: RealAffinity P1 * * * *
2068 ** If register P1 holds an integer convert it to a real value.
2070 ** This opcode is used when extracting information from a column that
2071 ** has REAL affinity. Such column values may still be stored as
2072 ** integers, for space efficiency, but after extraction we want them
2073 ** to have only a real value.
2075 case OP_RealAffinity: { /* in1 */
2076 pIn1 = &aMem[pOp->p1];
2077 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
2078 testcase( pIn1->flags & MEM_Int );
2079 testcase( pIn1->flags & MEM_IntReal );
2080 sqlite3VdbeMemRealify(pIn1);
2081 REGISTER_TRACE(pOp->p1, pIn1);
2083 break;
2085 #endif
2087 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_ANALYZE)
2088 /* Opcode: Cast P1 P2 * * *
2089 ** Synopsis: affinity(r[P1])
2091 ** Force the value in register P1 to be the type defined by P2.
2093 ** <ul>
2094 ** <li> P2=='A' &rarr; BLOB
2095 ** <li> P2=='B' &rarr; TEXT
2096 ** <li> P2=='C' &rarr; NUMERIC
2097 ** <li> P2=='D' &rarr; INTEGER
2098 ** <li> P2=='E' &rarr; REAL
2099 ** </ul>
2101 ** A NULL value is not changed by this routine. It remains NULL.
2103 case OP_Cast: { /* in1 */
2104 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
2105 testcase( pOp->p2==SQLITE_AFF_TEXT );
2106 testcase( pOp->p2==SQLITE_AFF_BLOB );
2107 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
2108 testcase( pOp->p2==SQLITE_AFF_INTEGER );
2109 testcase( pOp->p2==SQLITE_AFF_REAL );
2110 pIn1 = &aMem[pOp->p1];
2111 memAboutToChange(p, pIn1);
2112 rc = ExpandBlob(pIn1);
2113 if( rc ) goto abort_due_to_error;
2114 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
2115 if( rc ) goto abort_due_to_error;
2116 UPDATE_MAX_BLOBSIZE(pIn1);
2117 REGISTER_TRACE(pOp->p1, pIn1);
2118 break;
2120 #endif /* SQLITE_OMIT_CAST */
2122 /* Opcode: Eq P1 P2 P3 P4 P5
2123 ** Synopsis: IF r[P3]==r[P1]
2125 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
2126 ** jump to address P2.
2128 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2129 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2130 ** to coerce both inputs according to this affinity before the
2131 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2132 ** affinity is used. Note that the affinity conversions are stored
2133 ** back into the input registers P1 and P3. So this opcode can cause
2134 ** persistent changes to registers P1 and P3.
2136 ** Once any conversions have taken place, and neither value is NULL,
2137 ** the values are compared. If both values are blobs then memcmp() is
2138 ** used to determine the results of the comparison. If both values
2139 ** are text, then the appropriate collating function specified in
2140 ** P4 is used to do the comparison. If P4 is not specified then
2141 ** memcmp() is used to compare text string. If both values are
2142 ** numeric, then a numeric comparison is used. If the two values
2143 ** are of different types, then numbers are considered less than
2144 ** strings and strings are considered less than blobs.
2146 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
2147 ** true or false and is never NULL. If both operands are NULL then the result
2148 ** of comparison is true. If either operand is NULL then the result is false.
2149 ** If neither operand is NULL the result is the same as it would be if
2150 ** the SQLITE_NULLEQ flag were omitted from P5.
2152 ** This opcode saves the result of comparison for use by the new
2153 ** OP_Jump opcode.
2155 /* Opcode: Ne P1 P2 P3 P4 P5
2156 ** Synopsis: IF r[P3]!=r[P1]
2158 ** This works just like the Eq opcode except that the jump is taken if
2159 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
2160 ** additional information.
2162 /* Opcode: Lt P1 P2 P3 P4 P5
2163 ** Synopsis: IF r[P3]<r[P1]
2165 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
2166 ** jump to address P2.
2168 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
2169 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
2170 ** bit is clear then fall through if either operand is NULL.
2172 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
2173 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
2174 ** to coerce both inputs according to this affinity before the
2175 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
2176 ** affinity is used. Note that the affinity conversions are stored
2177 ** back into the input registers P1 and P3. So this opcode can cause
2178 ** persistent changes to registers P1 and P3.
2180 ** Once any conversions have taken place, and neither value is NULL,
2181 ** the values are compared. If both values are blobs then memcmp() is
2182 ** used to determine the results of the comparison. If both values
2183 ** are text, then the appropriate collating function specified in
2184 ** P4 is used to do the comparison. If P4 is not specified then
2185 ** memcmp() is used to compare text string. If both values are
2186 ** numeric, then a numeric comparison is used. If the two values
2187 ** are of different types, then numbers are considered less than
2188 ** strings and strings are considered less than blobs.
2190 ** This opcode saves the result of comparison for use by the new
2191 ** OP_Jump opcode.
2193 /* Opcode: Le P1 P2 P3 P4 P5
2194 ** Synopsis: IF r[P3]<=r[P1]
2196 ** This works just like the Lt opcode except that the jump is taken if
2197 ** the content of register P3 is less than or equal to the content of
2198 ** register P1. See the Lt opcode for additional information.
2200 /* Opcode: Gt P1 P2 P3 P4 P5
2201 ** Synopsis: IF r[P3]>r[P1]
2203 ** This works just like the Lt opcode except that the jump is taken if
2204 ** the content of register P3 is greater than the content of
2205 ** register P1. See the Lt opcode for additional information.
2207 /* Opcode: Ge P1 P2 P3 P4 P5
2208 ** Synopsis: IF r[P3]>=r[P1]
2210 ** This works just like the Lt opcode except that the jump is taken if
2211 ** the content of register P3 is greater than or equal to the content of
2212 ** register P1. See the Lt opcode for additional information.
2214 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
2215 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
2216 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
2217 case OP_Le: /* same as TK_LE, jump, in1, in3 */
2218 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
2219 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
2220 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
2221 char affinity; /* Affinity to use for comparison */
2222 u16 flags1; /* Copy of initial value of pIn1->flags */
2223 u16 flags3; /* Copy of initial value of pIn3->flags */
2225 pIn1 = &aMem[pOp->p1];
2226 pIn3 = &aMem[pOp->p3];
2227 flags1 = pIn1->flags;
2228 flags3 = pIn3->flags;
2229 if( (flags1 & flags3 & MEM_Int)!=0 ){
2230 /* Common case of comparison of two integers */
2231 if( pIn3->u.i > pIn1->u.i ){
2232 if( sqlite3aGTb[pOp->opcode] ){
2233 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2234 goto jump_to_p2;
2236 iCompare = +1;
2237 VVA_ONLY( iCompareIsInit = 1; )
2238 }else if( pIn3->u.i < pIn1->u.i ){
2239 if( sqlite3aLTb[pOp->opcode] ){
2240 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2241 goto jump_to_p2;
2243 iCompare = -1;
2244 VVA_ONLY( iCompareIsInit = 1; )
2245 }else{
2246 if( sqlite3aEQb[pOp->opcode] ){
2247 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2248 goto jump_to_p2;
2250 iCompare = 0;
2251 VVA_ONLY( iCompareIsInit = 1; )
2253 VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2254 break;
2256 if( (flags1 | flags3)&MEM_Null ){
2257 /* One or both operands are NULL */
2258 if( pOp->p5 & SQLITE_NULLEQ ){
2259 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
2260 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
2261 ** or not both operands are null.
2263 assert( (flags1 & MEM_Cleared)==0 );
2264 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
2265 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
2266 if( (flags1&flags3&MEM_Null)!=0
2267 && (flags3&MEM_Cleared)==0
2269 res = 0; /* Operands are equal */
2270 }else{
2271 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
2273 }else{
2274 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
2275 ** then the result is always NULL.
2276 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
2278 VdbeBranchTaken(2,3);
2279 if( pOp->p5 & SQLITE_JUMPIFNULL ){
2280 goto jump_to_p2;
2282 iCompare = 1; /* Operands are not equal */
2283 VVA_ONLY( iCompareIsInit = 1; )
2284 break;
2286 }else{
2287 /* Neither operand is NULL and we couldn't do the special high-speed
2288 ** integer comparison case. So do a general-case comparison. */
2289 affinity = pOp->p5 & SQLITE_AFF_MASK;
2290 if( affinity>=SQLITE_AFF_NUMERIC ){
2291 if( (flags1 | flags3)&MEM_Str ){
2292 if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2293 applyNumericAffinity(pIn1,0);
2294 assert( flags3==pIn3->flags || CORRUPT_DB );
2295 flags3 = pIn3->flags;
2297 if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2298 applyNumericAffinity(pIn3,0);
2301 }else if( affinity==SQLITE_AFF_TEXT && ((flags1 | flags3) & MEM_Str)!=0 ){
2302 if( (flags1 & MEM_Str)!=0 ){
2303 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
2304 }else if( (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2305 testcase( pIn1->flags & MEM_Int );
2306 testcase( pIn1->flags & MEM_Real );
2307 testcase( pIn1->flags & MEM_IntReal );
2308 sqlite3VdbeMemStringify(pIn1, encoding, 1);
2309 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
2310 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
2311 if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
2313 if( (flags3 & MEM_Str)!=0 ){
2314 pIn3->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
2315 }else if( (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2316 testcase( pIn3->flags & MEM_Int );
2317 testcase( pIn3->flags & MEM_Real );
2318 testcase( pIn3->flags & MEM_IntReal );
2319 sqlite3VdbeMemStringify(pIn3, encoding, 1);
2320 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
2321 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
2324 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
2325 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
2328 /* At this point, res is negative, zero, or positive if reg[P1] is
2329 ** less than, equal to, or greater than reg[P3], respectively. Compute
2330 ** the answer to this operator in res2, depending on what the comparison
2331 ** operator actually is. The next block of code depends on the fact
2332 ** that the 6 comparison operators are consecutive integers in this
2333 ** order: NE, EQ, GT, LE, LT, GE */
2334 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
2335 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
2336 if( res<0 ){
2337 res2 = sqlite3aLTb[pOp->opcode];
2338 }else if( res==0 ){
2339 res2 = sqlite3aEQb[pOp->opcode];
2340 }else{
2341 res2 = sqlite3aGTb[pOp->opcode];
2343 iCompare = res;
2344 VVA_ONLY( iCompareIsInit = 1; )
2346 /* Undo any changes made by applyAffinity() to the input registers. */
2347 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
2348 pIn3->flags = flags3;
2349 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
2350 pIn1->flags = flags1;
2352 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2353 if( res2 ){
2354 goto jump_to_p2;
2356 break;
2359 /* Opcode: ElseEq * P2 * * *
2361 ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
2362 ** can be zero or more OP_ReleaseReg opcodes intervening, but no other
2363 ** opcodes are allowed to occur between this instruction and the previous
2364 ** OP_Lt or OP_Gt.
2366 ** If the result of an OP_Eq comparison on the same two operands as
2367 ** the prior OP_Lt or OP_Gt would have been true, then jump to P2. If
2368 ** the result of an OP_Eq comparison on the two previous operands
2369 ** would have been false or NULL, then fall through.
2371 case OP_ElseEq: { /* same as TK_ESCAPE, jump */
2373 #ifdef SQLITE_DEBUG
2374 /* Verify the preconditions of this opcode - that it follows an OP_Lt or
2375 ** OP_Gt with zero or more intervening OP_ReleaseReg opcodes */
2376 int iAddr;
2377 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
2378 if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
2379 assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
2380 break;
2382 #endif /* SQLITE_DEBUG */
2383 assert( iCompareIsInit );
2384 VdbeBranchTaken(iCompare==0, 2);
2385 if( iCompare==0 ) goto jump_to_p2;
2386 break;
2390 /* Opcode: Permutation * * * P4 *
2392 ** Set the permutation used by the OP_Compare operator in the next
2393 ** instruction. The permutation is stored in the P4 operand.
2395 ** The permutation is only valid for the next opcode which must be
2396 ** an OP_Compare that has the OPFLAG_PERMUTE bit set in P5.
2398 ** The first integer in the P4 integer array is the length of the array
2399 ** and does not become part of the permutation.
2401 case OP_Permutation: {
2402 assert( pOp->p4type==P4_INTARRAY );
2403 assert( pOp->p4.ai );
2404 assert( pOp[1].opcode==OP_Compare );
2405 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2406 break;
2409 /* Opcode: Compare P1 P2 P3 P4 P5
2410 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2412 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2413 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2414 ** the comparison for use by the next OP_Jump instruct.
2416 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2417 ** determined by the most recent OP_Permutation operator. If the
2418 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2419 ** order.
2421 ** P4 is a KeyInfo structure that defines collating sequences and sort
2422 ** orders for the comparison. The permutation applies to registers
2423 ** only. The KeyInfo elements are used sequentially.
2425 ** The comparison is a sort comparison, so NULLs compare equal,
2426 ** NULLs are less than numbers, numbers are less than strings,
2427 ** and strings are less than blobs.
2429 ** This opcode must be immediately followed by an OP_Jump opcode.
2431 case OP_Compare: {
2432 int n;
2433 int i;
2434 int p1;
2435 int p2;
2436 const KeyInfo *pKeyInfo;
2437 u32 idx;
2438 CollSeq *pColl; /* Collating sequence to use on this term */
2439 int bRev; /* True for DESCENDING sort order */
2440 u32 *aPermute; /* The permutation */
2442 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2443 aPermute = 0;
2444 }else{
2445 assert( pOp>aOp );
2446 assert( pOp[-1].opcode==OP_Permutation );
2447 assert( pOp[-1].p4type==P4_INTARRAY );
2448 aPermute = pOp[-1].p4.ai + 1;
2449 assert( aPermute!=0 );
2451 n = pOp->p3;
2452 pKeyInfo = pOp->p4.pKeyInfo;
2453 assert( n>0 );
2454 assert( pKeyInfo!=0 );
2455 p1 = pOp->p1;
2456 p2 = pOp->p2;
2457 #ifdef SQLITE_DEBUG
2458 if( aPermute ){
2459 int k, mx = 0;
2460 for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
2461 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2462 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2463 }else{
2464 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2465 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2467 #endif /* SQLITE_DEBUG */
2468 for(i=0; i<n; i++){
2469 idx = aPermute ? aPermute[i] : (u32)i;
2470 assert( memIsValid(&aMem[p1+idx]) );
2471 assert( memIsValid(&aMem[p2+idx]) );
2472 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2473 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2474 assert( i<pKeyInfo->nKeyField );
2475 pColl = pKeyInfo->aColl[i];
2476 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
2477 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2478 VVA_ONLY( iCompareIsInit = 1; )
2479 if( iCompare ){
2480 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
2481 && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
2483 iCompare = -iCompare;
2485 if( bRev ) iCompare = -iCompare;
2486 break;
2489 assert( pOp[1].opcode==OP_Jump );
2490 break;
2493 /* Opcode: Jump P1 P2 P3 * *
2495 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2496 ** in the most recent OP_Compare instruction the P1 vector was less than,
2497 ** equal to, or greater than the P2 vector, respectively.
2499 ** This opcode must immediately follow an OP_Compare opcode.
2501 case OP_Jump: { /* jump */
2502 assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
2503 assert( iCompareIsInit );
2504 if( iCompare<0 ){
2505 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
2506 }else if( iCompare==0 ){
2507 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
2508 }else{
2509 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
2511 break;
2514 /* Opcode: And P1 P2 P3 * *
2515 ** Synopsis: r[P3]=(r[P1] && r[P2])
2517 ** Take the logical AND of the values in registers P1 and P2 and
2518 ** write the result into register P3.
2520 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2521 ** the other input is NULL. A NULL and true or two NULLs give
2522 ** a NULL output.
2524 /* Opcode: Or P1 P2 P3 * *
2525 ** Synopsis: r[P3]=(r[P1] || r[P2])
2527 ** Take the logical OR of the values in register P1 and P2 and
2528 ** store the answer in register P3.
2530 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2531 ** even if the other input is NULL. A NULL and false or two NULLs
2532 ** give a NULL output.
2534 case OP_And: /* same as TK_AND, in1, in2, out3 */
2535 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2536 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2537 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2539 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2540 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2541 if( pOp->opcode==OP_And ){
2542 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2543 v1 = and_logic[v1*3+v2];
2544 }else{
2545 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2546 v1 = or_logic[v1*3+v2];
2548 pOut = &aMem[pOp->p3];
2549 if( v1==2 ){
2550 MemSetTypeFlag(pOut, MEM_Null);
2551 }else{
2552 pOut->u.i = v1;
2553 MemSetTypeFlag(pOut, MEM_Int);
2555 break;
2558 /* Opcode: IsTrue P1 P2 P3 P4 *
2559 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2561 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2562 ** IS NOT FALSE operators.
2564 ** Interpret the value in register P1 as a boolean value. Store that
2565 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2566 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2567 ** is 1.
2569 ** The logic is summarized like this:
2571 ** <ul>
2572 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2573 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2574 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2575 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2576 ** </ul>
2578 case OP_IsTrue: { /* in1, out2 */
2579 assert( pOp->p4type==P4_INT32 );
2580 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2581 assert( pOp->p3==0 || pOp->p3==1 );
2582 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2583 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2584 break;
2587 /* Opcode: Not P1 P2 * * *
2588 ** Synopsis: r[P2]= !r[P1]
2590 ** Interpret the value in register P1 as a boolean value. Store the
2591 ** boolean complement in register P2. If the value in register P1 is
2592 ** NULL, then a NULL is stored in P2.
2594 case OP_Not: { /* same as TK_NOT, in1, out2 */
2595 pIn1 = &aMem[pOp->p1];
2596 pOut = &aMem[pOp->p2];
2597 if( (pIn1->flags & MEM_Null)==0 ){
2598 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2599 }else{
2600 sqlite3VdbeMemSetNull(pOut);
2602 break;
2605 /* Opcode: BitNot P1 P2 * * *
2606 ** Synopsis: r[P2]= ~r[P1]
2608 ** Interpret the content of register P1 as an integer. Store the
2609 ** ones-complement of the P1 value into register P2. If P1 holds
2610 ** a NULL then store a NULL in P2.
2612 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2613 pIn1 = &aMem[pOp->p1];
2614 pOut = &aMem[pOp->p2];
2615 sqlite3VdbeMemSetNull(pOut);
2616 if( (pIn1->flags & MEM_Null)==0 ){
2617 pOut->flags = MEM_Int;
2618 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2620 break;
2623 /* Opcode: Once P1 P2 * * *
2625 ** Fall through to the next instruction the first time this opcode is
2626 ** encountered on each invocation of the byte-code program. Jump to P2
2627 ** on the second and all subsequent encounters during the same invocation.
2629 ** Top-level programs determine first invocation by comparing the P1
2630 ** operand against the P1 operand on the OP_Init opcode at the beginning
2631 ** of the program. If the P1 values differ, then fall through and make
2632 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2633 ** the same then take the jump.
2635 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2636 ** whether or not the jump should be taken. The bitmask is necessary
2637 ** because the self-altering code trick does not work for recursive
2638 ** triggers.
2640 case OP_Once: { /* jump */
2641 u32 iAddr; /* Address of this instruction */
2642 assert( p->aOp[0].opcode==OP_Init );
2643 if( p->pFrame ){
2644 iAddr = (int)(pOp - p->aOp);
2645 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2646 VdbeBranchTaken(1, 2);
2647 goto jump_to_p2;
2649 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2650 }else{
2651 if( p->aOp[0].p1==pOp->p1 ){
2652 VdbeBranchTaken(1, 2);
2653 goto jump_to_p2;
2656 VdbeBranchTaken(0, 2);
2657 pOp->p1 = p->aOp[0].p1;
2658 break;
2661 /* Opcode: If P1 P2 P3 * *
2663 ** Jump to P2 if the value in register P1 is true. The value
2664 ** is considered true if it is numeric and non-zero. If the value
2665 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2667 case OP_If: { /* jump, in1 */
2668 int c;
2669 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2670 VdbeBranchTaken(c!=0, 2);
2671 if( c ) goto jump_to_p2;
2672 break;
2675 /* Opcode: IfNot P1 P2 P3 * *
2677 ** Jump to P2 if the value in register P1 is False. The value
2678 ** is considered false if it has a numeric value of zero. If the value
2679 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2681 case OP_IfNot: { /* jump, in1 */
2682 int c;
2683 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2684 VdbeBranchTaken(c!=0, 2);
2685 if( c ) goto jump_to_p2;
2686 break;
2689 /* Opcode: IsNull P1 P2 * * *
2690 ** Synopsis: if r[P1]==NULL goto P2
2692 ** Jump to P2 if the value in register P1 is NULL.
2694 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2695 pIn1 = &aMem[pOp->p1];
2696 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2697 if( (pIn1->flags & MEM_Null)!=0 ){
2698 goto jump_to_p2;
2700 break;
2703 /* Opcode: IsType P1 P2 P3 P4 P5
2704 ** Synopsis: if typeof(P1.P3) in P5 goto P2
2706 ** Jump to P2 if the type of a column in a btree is one of the types specified
2707 ** by the P5 bitmask.
2709 ** P1 is normally a cursor on a btree for which the row decode cache is
2710 ** valid through at least column P3. In other words, there should have been
2711 ** a prior OP_Column for column P3 or greater. If the cursor is not valid,
2712 ** then this opcode might give spurious results.
2713 ** The the btree row has fewer than P3 columns, then use P4 as the
2714 ** datatype.
2716 ** If P1 is -1, then P3 is a register number and the datatype is taken
2717 ** from the value in that register.
2719 ** P5 is a bitmask of data types. SQLITE_INTEGER is the least significant
2720 ** (0x01) bit. SQLITE_FLOAT is the 0x02 bit. SQLITE_TEXT is 0x04.
2721 ** SQLITE_BLOB is 0x08. SQLITE_NULL is 0x10.
2723 ** WARNING: This opcode does not reliably distinguish between NULL and REAL
2724 ** when P1>=0. If the database contains a NaN value, this opcode will think
2725 ** that the datatype is REAL when it should be NULL. When P1<0 and the value
2726 ** is already stored in register P3, then this opcode does reliably
2727 ** distinguish between NULL and REAL. The problem only arises then P1>=0.
2729 ** Take the jump to address P2 if and only if the datatype of the
2730 ** value determined by P1 and P3 corresponds to one of the bits in the
2731 ** P5 bitmask.
2734 case OP_IsType: { /* jump */
2735 VdbeCursor *pC;
2736 u16 typeMask;
2737 u32 serialType;
2739 assert( pOp->p1>=(-1) && pOp->p1<p->nCursor );
2740 assert( pOp->p1>=0 || (pOp->p3>=0 && pOp->p3<=(p->nMem+1 - p->nCursor)) );
2741 if( pOp->p1>=0 ){
2742 pC = p->apCsr[pOp->p1];
2743 assert( pC!=0 );
2744 assert( pOp->p3>=0 );
2745 if( pOp->p3<pC->nHdrParsed ){
2746 serialType = pC->aType[pOp->p3];
2747 if( serialType>=12 ){
2748 if( serialType&1 ){
2749 typeMask = 0x04; /* SQLITE_TEXT */
2750 }else{
2751 typeMask = 0x08; /* SQLITE_BLOB */
2753 }else{
2754 static const unsigned char aMask[] = {
2755 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2,
2756 0x01, 0x01, 0x10, 0x10
2758 testcase( serialType==0 );
2759 testcase( serialType==1 );
2760 testcase( serialType==2 );
2761 testcase( serialType==3 );
2762 testcase( serialType==4 );
2763 testcase( serialType==5 );
2764 testcase( serialType==6 );
2765 testcase( serialType==7 );
2766 testcase( serialType==8 );
2767 testcase( serialType==9 );
2768 testcase( serialType==10 );
2769 testcase( serialType==11 );
2770 typeMask = aMask[serialType];
2772 }else{
2773 typeMask = 1 << (pOp->p4.i - 1);
2774 testcase( typeMask==0x01 );
2775 testcase( typeMask==0x02 );
2776 testcase( typeMask==0x04 );
2777 testcase( typeMask==0x08 );
2778 testcase( typeMask==0x10 );
2780 }else{
2781 assert( memIsValid(&aMem[pOp->p3]) );
2782 typeMask = 1 << (sqlite3_value_type((sqlite3_value*)&aMem[pOp->p3])-1);
2783 testcase( typeMask==0x01 );
2784 testcase( typeMask==0x02 );
2785 testcase( typeMask==0x04 );
2786 testcase( typeMask==0x08 );
2787 testcase( typeMask==0x10 );
2789 VdbeBranchTaken( (typeMask & pOp->p5)!=0, 2);
2790 if( typeMask & pOp->p5 ){
2791 goto jump_to_p2;
2793 break;
2796 /* Opcode: ZeroOrNull P1 P2 P3 * *
2797 ** Synopsis: r[P2] = 0 OR NULL
2799 ** If both registers P1 and P3 are NOT NULL, then store a zero in
2800 ** register P2. If either registers P1 or P3 are NULL then put
2801 ** a NULL in register P2.
2803 case OP_ZeroOrNull: { /* in1, in2, out2, in3 */
2804 if( (aMem[pOp->p1].flags & MEM_Null)!=0
2805 || (aMem[pOp->p3].flags & MEM_Null)!=0
2807 sqlite3VdbeMemSetNull(aMem + pOp->p2);
2808 }else{
2809 sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
2811 break;
2814 /* Opcode: NotNull P1 P2 * * *
2815 ** Synopsis: if r[P1]!=NULL goto P2
2817 ** Jump to P2 if the value in register P1 is not NULL.
2819 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2820 pIn1 = &aMem[pOp->p1];
2821 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2822 if( (pIn1->flags & MEM_Null)==0 ){
2823 goto jump_to_p2;
2825 break;
2828 /* Opcode: IfNullRow P1 P2 P3 * *
2829 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2831 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2832 ** If it is, then set register P3 to NULL and jump immediately to P2.
2833 ** If P1 is not on a NULL row, then fall through without making any
2834 ** changes.
2836 ** If P1 is not an open cursor, then this opcode is a no-op.
2838 case OP_IfNullRow: { /* jump */
2839 VdbeCursor *pC;
2840 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2841 pC = p->apCsr[pOp->p1];
2842 if( pC && pC->nullRow ){
2843 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2844 goto jump_to_p2;
2846 break;
2849 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2850 /* Opcode: Offset P1 P2 P3 * *
2851 ** Synopsis: r[P3] = sqlite_offset(P1)
2853 ** Store in register r[P3] the byte offset into the database file that is the
2854 ** start of the payload for the record at which that cursor P1 is currently
2855 ** pointing.
2857 ** P2 is the column number for the argument to the sqlite_offset() function.
2858 ** This opcode does not use P2 itself, but the P2 value is used by the
2859 ** code generator. The P1, P2, and P3 operands to this opcode are the
2860 ** same as for OP_Column.
2862 ** This opcode is only available if SQLite is compiled with the
2863 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2865 case OP_Offset: { /* out3 */
2866 VdbeCursor *pC; /* The VDBE cursor */
2867 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2868 pC = p->apCsr[pOp->p1];
2869 pOut = &p->aMem[pOp->p3];
2870 if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
2871 sqlite3VdbeMemSetNull(pOut);
2872 }else{
2873 if( pC->deferredMoveto ){
2874 rc = sqlite3VdbeFinishMoveto(pC);
2875 if( rc ) goto abort_due_to_error;
2877 if( sqlite3BtreeEof(pC->uc.pCursor) ){
2878 sqlite3VdbeMemSetNull(pOut);
2879 }else{
2880 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2883 break;
2885 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2887 /* Opcode: Column P1 P2 P3 P4 P5
2888 ** Synopsis: r[P3]=PX cursor P1 column P2
2890 ** Interpret the data that cursor P1 points to as a structure built using
2891 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2892 ** information about the format of the data.) Extract the P2-th column
2893 ** from this record. If there are less than (P2+1)
2894 ** values in the record, extract a NULL.
2896 ** The value extracted is stored in register P3.
2898 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2899 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2900 ** the result.
2902 ** If the OPFLAG_LENGTHARG bit is set in P5 then the result is guaranteed
2903 ** to only be used by the length() function or the equivalent. The content
2904 ** of large blobs is not loaded, thus saving CPU cycles. If the
2905 ** OPFLAG_TYPEOFARG bit is set then the result will only be used by the
2906 ** typeof() function or the IS NULL or IS NOT NULL operators or the
2907 ** equivalent. In this case, all content loading can be omitted.
2909 case OP_Column: { /* ncycle */
2910 u32 p2; /* column number to retrieve */
2911 VdbeCursor *pC; /* The VDBE cursor */
2912 BtCursor *pCrsr; /* The B-Tree cursor corresponding to pC */
2913 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2914 int len; /* The length of the serialized data for the column */
2915 int i; /* Loop counter */
2916 Mem *pDest; /* Where to write the extracted value */
2917 Mem sMem; /* For storing the record being decoded */
2918 const u8 *zData; /* Part of the record being decoded */
2919 const u8 *zHdr; /* Next unparsed byte of the header */
2920 const u8 *zEndHdr; /* Pointer to first byte after the header */
2921 u64 offset64; /* 64-bit offset */
2922 u32 t; /* A type code from the record header */
2923 Mem *pReg; /* PseudoTable input register */
2925 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2926 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2927 pC = p->apCsr[pOp->p1];
2928 p2 = (u32)pOp->p2;
2930 op_column_restart:
2931 assert( pC!=0 );
2932 assert( p2<(u32)pC->nField
2933 || (pC->eCurType==CURTYPE_PSEUDO && pC->seekResult==0) );
2934 aOffset = pC->aOffset;
2935 assert( aOffset==pC->aType+pC->nField );
2936 assert( pC->eCurType!=CURTYPE_VTAB );
2937 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2938 assert( pC->eCurType!=CURTYPE_SORTER );
2940 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2941 if( pC->nullRow ){
2942 if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
2943 /* For the special case of as pseudo-cursor, the seekResult field
2944 ** identifies the register that holds the record */
2945 pReg = &aMem[pC->seekResult];
2946 assert( pReg->flags & MEM_Blob );
2947 assert( memIsValid(pReg) );
2948 pC->payloadSize = pC->szRow = pReg->n;
2949 pC->aRow = (u8*)pReg->z;
2950 }else{
2951 pDest = &aMem[pOp->p3];
2952 memAboutToChange(p, pDest);
2953 sqlite3VdbeMemSetNull(pDest);
2954 goto op_column_out;
2956 }else{
2957 pCrsr = pC->uc.pCursor;
2958 if( pC->deferredMoveto ){
2959 u32 iMap;
2960 assert( !pC->isEphemeral );
2961 if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0 ){
2962 pC = pC->pAltCursor;
2963 p2 = iMap - 1;
2964 goto op_column_restart;
2966 rc = sqlite3VdbeFinishMoveto(pC);
2967 if( rc ) goto abort_due_to_error;
2968 }else if( sqlite3BtreeCursorHasMoved(pCrsr) ){
2969 rc = sqlite3VdbeHandleMovedCursor(pC);
2970 if( rc ) goto abort_due_to_error;
2971 goto op_column_restart;
2973 assert( pC->eCurType==CURTYPE_BTREE );
2974 assert( pCrsr );
2975 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2976 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2977 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2978 assert( pC->szRow<=pC->payloadSize );
2979 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2981 pC->cacheStatus = p->cacheCtr;
2982 if( (aOffset[0] = pC->aRow[0])<0x80 ){
2983 pC->iHdrOffset = 1;
2984 }else{
2985 pC->iHdrOffset = sqlite3GetVarint32(pC->aRow, aOffset);
2987 pC->nHdrParsed = 0;
2989 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2990 /* pC->aRow does not have to hold the entire row, but it does at least
2991 ** need to cover the header of the record. If pC->aRow does not contain
2992 ** the complete header, then set it to zero, forcing the header to be
2993 ** dynamically allocated. */
2994 pC->aRow = 0;
2995 pC->szRow = 0;
2997 /* Make sure a corrupt database has not given us an oversize header.
2998 ** Do this now to avoid an oversize memory allocation.
3000 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
3001 ** types use so much data space that there can only be 4096 and 32 of
3002 ** them, respectively. So the maximum header length results from a
3003 ** 3-byte type for each of the maximum of 32768 columns plus three
3004 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
3006 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
3007 goto op_column_corrupt;
3009 }else{
3010 /* This is an optimization. By skipping over the first few tests
3011 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
3012 ** measurable performance gain.
3014 ** This branch is taken even if aOffset[0]==0. Such a record is never
3015 ** generated by SQLite, and could be considered corruption, but we
3016 ** accept it for historical reasons. When aOffset[0]==0, the code this
3017 ** branch jumps to reads past the end of the record, but never more
3018 ** than a few bytes. Even if the record occurs at the end of the page
3019 ** content area, the "page header" comes after the page content and so
3020 ** this overread is harmless. Similar overreads can occur for a corrupt
3021 ** database file.
3023 zData = pC->aRow;
3024 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
3025 testcase( aOffset[0]==0 );
3026 goto op_column_read_header;
3028 }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
3029 rc = sqlite3VdbeHandleMovedCursor(pC);
3030 if( rc ) goto abort_due_to_error;
3031 goto op_column_restart;
3034 /* Make sure at least the first p2+1 entries of the header have been
3035 ** parsed and valid information is in aOffset[] and pC->aType[].
3037 if( pC->nHdrParsed<=p2 ){
3038 /* If there is more header available for parsing in the record, try
3039 ** to extract additional fields up through the p2+1-th field
3041 if( pC->iHdrOffset<aOffset[0] ){
3042 /* Make sure zData points to enough of the record to cover the header. */
3043 if( pC->aRow==0 ){
3044 memset(&sMem, 0, sizeof(sMem));
3045 rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
3046 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3047 zData = (u8*)sMem.z;
3048 }else{
3049 zData = pC->aRow;
3052 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
3053 op_column_read_header:
3054 i = pC->nHdrParsed;
3055 offset64 = aOffset[i];
3056 zHdr = zData + pC->iHdrOffset;
3057 zEndHdr = zData + aOffset[0];
3058 testcase( zHdr>=zEndHdr );
3060 if( (pC->aType[i] = t = zHdr[0])<0x80 ){
3061 zHdr++;
3062 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
3063 }else{
3064 zHdr += sqlite3GetVarint32(zHdr, &t);
3065 pC->aType[i] = t;
3066 offset64 += sqlite3VdbeSerialTypeLen(t);
3068 aOffset[++i] = (u32)(offset64 & 0xffffffff);
3069 }while( (u32)i<=p2 && zHdr<zEndHdr );
3071 /* The record is corrupt if any of the following are true:
3072 ** (1) the bytes of the header extend past the declared header size
3073 ** (2) the entire header was used but not all data was used
3074 ** (3) the end of the data extends beyond the end of the record.
3076 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
3077 || (offset64 > pC->payloadSize)
3079 if( aOffset[0]==0 ){
3080 i = 0;
3081 zHdr = zEndHdr;
3082 }else{
3083 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
3084 goto op_column_corrupt;
3088 pC->nHdrParsed = i;
3089 pC->iHdrOffset = (u32)(zHdr - zData);
3090 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
3091 }else{
3092 t = 0;
3095 /* If after trying to extract new entries from the header, nHdrParsed is
3096 ** still not up to p2, that means that the record has fewer than p2
3097 ** columns. So the result will be either the default value or a NULL.
3099 if( pC->nHdrParsed<=p2 ){
3100 pDest = &aMem[pOp->p3];
3101 memAboutToChange(p, pDest);
3102 if( pOp->p4type==P4_MEM ){
3103 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
3104 }else{
3105 sqlite3VdbeMemSetNull(pDest);
3107 goto op_column_out;
3109 }else{
3110 t = pC->aType[p2];
3113 /* Extract the content for the p2+1-th column. Control can only
3114 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
3115 ** all valid.
3117 assert( p2<pC->nHdrParsed );
3118 assert( rc==SQLITE_OK );
3119 pDest = &aMem[pOp->p3];
3120 memAboutToChange(p, pDest);
3121 assert( sqlite3VdbeCheckMemInvariants(pDest) );
3122 if( VdbeMemDynamic(pDest) ){
3123 sqlite3VdbeMemSetNull(pDest);
3125 assert( t==pC->aType[p2] );
3126 if( pC->szRow>=aOffset[p2+1] ){
3127 /* This is the common case where the desired content fits on the original
3128 ** page - where the content is not on an overflow page */
3129 zData = pC->aRow + aOffset[p2];
3130 if( t<12 ){
3131 sqlite3VdbeSerialGet(zData, t, pDest);
3132 }else{
3133 /* If the column value is a string, we need a persistent value, not
3134 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
3135 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
3137 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
3138 pDest->n = len = (t-12)/2;
3139 pDest->enc = encoding;
3140 if( pDest->szMalloc < len+2 ){
3141 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
3142 pDest->flags = MEM_Null;
3143 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
3144 }else{
3145 pDest->z = pDest->zMalloc;
3147 memcpy(pDest->z, zData, len);
3148 pDest->z[len] = 0;
3149 pDest->z[len+1] = 0;
3150 pDest->flags = aFlag[t&1];
3152 }else{
3153 u8 p5;
3154 pDest->enc = encoding;
3155 assert( pDest->db==db );
3156 /* This branch happens only when content is on overflow pages */
3157 if( ((p5 = (pOp->p5 & OPFLAG_BYTELENARG))!=0
3158 && (p5==OPFLAG_TYPEOFARG
3159 || (t>=12 && ((t&1)==0 || p5==OPFLAG_BYTELENARG))
3162 || sqlite3VdbeSerialTypeLen(t)==0
3164 /* Content is irrelevant for
3165 ** 1. the typeof() function,
3166 ** 2. the length(X) function if X is a blob, and
3167 ** 3. if the content length is zero.
3168 ** So we might as well use bogus content rather than reading
3169 ** content from disk.
3171 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
3172 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
3173 ** read more. Use the global constant sqlite3CtypeMap[] as the array,
3174 ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
3175 ** and it begins with a bunch of zeros.
3177 sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
3178 }else{
3179 rc = vdbeColumnFromOverflow(pC, p2, t, aOffset[p2],
3180 p->cacheCtr, colCacheCtr, pDest);
3181 if( rc ){
3182 if( rc==SQLITE_NOMEM ) goto no_mem;
3183 if( rc==SQLITE_TOOBIG ) goto too_big;
3184 goto abort_due_to_error;
3189 op_column_out:
3190 UPDATE_MAX_BLOBSIZE(pDest);
3191 REGISTER_TRACE(pOp->p3, pDest);
3192 break;
3194 op_column_corrupt:
3195 if( aOp[0].p3>0 ){
3196 pOp = &aOp[aOp[0].p3-1];
3197 break;
3198 }else{
3199 rc = SQLITE_CORRUPT_BKPT;
3200 goto abort_due_to_error;
3204 /* Opcode: TypeCheck P1 P2 P3 P4 *
3205 ** Synopsis: typecheck(r[P1@P2])
3207 ** Apply affinities to the range of P2 registers beginning with P1.
3208 ** Take the affinities from the Table object in P4. If any value
3209 ** cannot be coerced into the correct type, then raise an error.
3211 ** This opcode is similar to OP_Affinity except that this opcode
3212 ** forces the register type to the Table column type. This is used
3213 ** to implement "strict affinity".
3215 ** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
3216 ** is zero. When P3 is non-zero, no type checking occurs for
3217 ** static generated columns. Virtual columns are computed at query time
3218 ** and so they are never checked.
3220 ** Preconditions:
3222 ** <ul>
3223 ** <li> P2 should be the number of non-virtual columns in the
3224 ** table of P4.
3225 ** <li> Table P4 should be a STRICT table.
3226 ** </ul>
3228 ** If any precondition is false, an assertion fault occurs.
3230 case OP_TypeCheck: {
3231 Table *pTab;
3232 Column *aCol;
3233 int i;
3235 assert( pOp->p4type==P4_TABLE );
3236 pTab = pOp->p4.pTab;
3237 assert( pTab->tabFlags & TF_Strict );
3238 assert( pTab->nNVCol==pOp->p2 );
3239 aCol = pTab->aCol;
3240 pIn1 = &aMem[pOp->p1];
3241 for(i=0; i<pTab->nCol; i++){
3242 if( aCol[i].colFlags & COLFLAG_GENERATED ){
3243 if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
3244 if( pOp->p3 ){ pIn1++; continue; }
3246 assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
3247 applyAffinity(pIn1, aCol[i].affinity, encoding);
3248 if( (pIn1->flags & MEM_Null)==0 ){
3249 switch( aCol[i].eCType ){
3250 case COLTYPE_BLOB: {
3251 if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
3252 break;
3254 case COLTYPE_INTEGER:
3255 case COLTYPE_INT: {
3256 if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
3257 break;
3259 case COLTYPE_TEXT: {
3260 if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
3261 break;
3263 case COLTYPE_REAL: {
3264 testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
3265 assert( (pIn1->flags & MEM_IntReal)==0 );
3266 if( pIn1->flags & MEM_Int ){
3267 /* When applying REAL affinity, if the result is still an MEM_Int
3268 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3269 ** so that we keep the high-resolution integer value but know that
3270 ** the type really wants to be REAL. */
3271 testcase( pIn1->u.i==140737488355328LL );
3272 testcase( pIn1->u.i==140737488355327LL );
3273 testcase( pIn1->u.i==-140737488355328LL );
3274 testcase( pIn1->u.i==-140737488355329LL );
3275 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
3276 pIn1->flags |= MEM_IntReal;
3277 pIn1->flags &= ~MEM_Int;
3278 }else{
3279 pIn1->u.r = (double)pIn1->u.i;
3280 pIn1->flags |= MEM_Real;
3281 pIn1->flags &= ~MEM_Int;
3283 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
3284 goto vdbe_type_error;
3286 break;
3288 default: {
3289 /* COLTYPE_ANY. Accept anything. */
3290 break;
3294 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3295 pIn1++;
3297 assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
3298 break;
3300 vdbe_type_error:
3301 sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
3302 vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
3303 pTab->zName, aCol[i].zCnName);
3304 rc = SQLITE_CONSTRAINT_DATATYPE;
3305 goto abort_due_to_error;
3308 /* Opcode: Affinity P1 P2 * P4 *
3309 ** Synopsis: affinity(r[P1@P2])
3311 ** Apply affinities to a range of P2 registers starting with P1.
3313 ** P4 is a string that is P2 characters long. The N-th character of the
3314 ** string indicates the column affinity that should be used for the N-th
3315 ** memory cell in the range.
3317 case OP_Affinity: {
3318 const char *zAffinity; /* The affinity to be applied */
3320 zAffinity = pOp->p4.z;
3321 assert( zAffinity!=0 );
3322 assert( pOp->p2>0 );
3323 assert( zAffinity[pOp->p2]==0 );
3324 pIn1 = &aMem[pOp->p1];
3325 while( 1 /*exit-by-break*/ ){
3326 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
3327 assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
3328 applyAffinity(pIn1, zAffinity[0], encoding);
3329 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
3330 /* When applying REAL affinity, if the result is still an MEM_Int
3331 ** that will fit in 6 bytes, then change the type to MEM_IntReal
3332 ** so that we keep the high-resolution integer value but know that
3333 ** the type really wants to be REAL. */
3334 testcase( pIn1->u.i==140737488355328LL );
3335 testcase( pIn1->u.i==140737488355327LL );
3336 testcase( pIn1->u.i==-140737488355328LL );
3337 testcase( pIn1->u.i==-140737488355329LL );
3338 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
3339 pIn1->flags |= MEM_IntReal;
3340 pIn1->flags &= ~MEM_Int;
3341 }else{
3342 pIn1->u.r = (double)pIn1->u.i;
3343 pIn1->flags |= MEM_Real;
3344 pIn1->flags &= ~(MEM_Int|MEM_Str);
3347 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3348 zAffinity++;
3349 if( zAffinity[0]==0 ) break;
3350 pIn1++;
3352 break;
3355 /* Opcode: MakeRecord P1 P2 P3 P4 *
3356 ** Synopsis: r[P3]=mkrec(r[P1@P2])
3358 ** Convert P2 registers beginning with P1 into the [record format]
3359 ** use as a data record in a database table or as a key
3360 ** in an index. The OP_Column opcode can decode the record later.
3362 ** P4 may be a string that is P2 characters long. The N-th character of the
3363 ** string indicates the column affinity that should be used for the N-th
3364 ** field of the index key.
3366 ** The mapping from character to affinity is given by the SQLITE_AFF_
3367 ** macros defined in sqliteInt.h.
3369 ** If P4 is NULL then all index fields have the affinity BLOB.
3371 ** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
3372 ** compile-time option is enabled:
3374 ** * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
3375 ** of the right-most table that can be null-trimmed.
3377 ** * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
3378 ** OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
3379 ** accept no-change records with serial_type 10. This value is
3380 ** only used inside an assert() and does not affect the end result.
3382 case OP_MakeRecord: {
3383 Mem *pRec; /* The new record */
3384 u64 nData; /* Number of bytes of data space */
3385 int nHdr; /* Number of bytes of header space */
3386 i64 nByte; /* Data space required for this record */
3387 i64 nZero; /* Number of zero bytes at the end of the record */
3388 int nVarint; /* Number of bytes in a varint */
3389 u32 serial_type; /* Type field */
3390 Mem *pData0; /* First field to be combined into the record */
3391 Mem *pLast; /* Last field of the record */
3392 int nField; /* Number of fields in the record */
3393 char *zAffinity; /* The affinity string for the record */
3394 u32 len; /* Length of a field */
3395 u8 *zHdr; /* Where to write next byte of the header */
3396 u8 *zPayload; /* Where to write next byte of the payload */
3398 /* Assuming the record contains N fields, the record format looks
3399 ** like this:
3401 ** ------------------------------------------------------------------------
3402 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
3403 ** ------------------------------------------------------------------------
3405 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
3406 ** and so forth.
3408 ** Each type field is a varint representing the serial type of the
3409 ** corresponding data element (see sqlite3VdbeSerialType()). The
3410 ** hdr-size field is also a varint which is the offset from the beginning
3411 ** of the record to data0.
3413 nData = 0; /* Number of bytes of data space */
3414 nHdr = 0; /* Number of bytes of header space */
3415 nZero = 0; /* Number of zero bytes at the end of the record */
3416 nField = pOp->p1;
3417 zAffinity = pOp->p4.z;
3418 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
3419 pData0 = &aMem[nField];
3420 nField = pOp->p2;
3421 pLast = &pData0[nField-1];
3423 /* Identify the output register */
3424 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
3425 pOut = &aMem[pOp->p3];
3426 memAboutToChange(p, pOut);
3428 /* Apply the requested affinity to all inputs
3430 assert( pData0<=pLast );
3431 if( zAffinity ){
3432 pRec = pData0;
3434 applyAffinity(pRec, zAffinity[0], encoding);
3435 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
3436 pRec->flags |= MEM_IntReal;
3437 pRec->flags &= ~(MEM_Int);
3439 REGISTER_TRACE((int)(pRec-aMem), pRec);
3440 zAffinity++;
3441 pRec++;
3442 assert( zAffinity[0]==0 || pRec<=pLast );
3443 }while( zAffinity[0] );
3446 #ifdef SQLITE_ENABLE_NULL_TRIM
3447 /* NULLs can be safely trimmed from the end of the record, as long as
3448 ** as the schema format is 2 or more and none of the omitted columns
3449 ** have a non-NULL default value. Also, the record must be left with
3450 ** at least one field. If P5>0 then it will be one more than the
3451 ** index of the right-most column with a non-NULL default value */
3452 if( pOp->p5 ){
3453 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
3454 pLast--;
3455 nField--;
3458 #endif
3460 /* Loop through the elements that will make up the record to figure
3461 ** out how much space is required for the new record. After this loop,
3462 ** the Mem.uTemp field of each term should hold the serial-type that will
3463 ** be used for that term in the generated record:
3465 ** Mem.uTemp value type
3466 ** --------------- ---------------
3467 ** 0 NULL
3468 ** 1 1-byte signed integer
3469 ** 2 2-byte signed integer
3470 ** 3 3-byte signed integer
3471 ** 4 4-byte signed integer
3472 ** 5 6-byte signed integer
3473 ** 6 8-byte signed integer
3474 ** 7 IEEE float
3475 ** 8 Integer constant 0
3476 ** 9 Integer constant 1
3477 ** 10,11 reserved for expansion
3478 ** N>=12 and even BLOB
3479 ** N>=13 and odd text
3481 ** The following additional values are computed:
3482 ** nHdr Number of bytes needed for the record header
3483 ** nData Number of bytes of data space needed for the record
3484 ** nZero Zero bytes at the end of the record
3486 pRec = pLast;
3488 assert( memIsValid(pRec) );
3489 if( pRec->flags & MEM_Null ){
3490 if( pRec->flags & MEM_Zero ){
3491 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
3492 ** table methods that never invoke sqlite3_result_xxxxx() while
3493 ** computing an unchanging column value in an UPDATE statement.
3494 ** Give such values a special internal-use-only serial-type of 10
3495 ** so that they can be passed through to xUpdate and have
3496 ** a true sqlite3_value_nochange(). */
3497 #ifndef SQLITE_ENABLE_NULL_TRIM
3498 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
3499 #endif
3500 pRec->uTemp = 10;
3501 }else{
3502 pRec->uTemp = 0;
3504 nHdr++;
3505 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
3506 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3507 i64 i = pRec->u.i;
3508 u64 uu;
3509 testcase( pRec->flags & MEM_Int );
3510 testcase( pRec->flags & MEM_IntReal );
3511 if( i<0 ){
3512 uu = ~i;
3513 }else{
3514 uu = i;
3516 nHdr++;
3517 testcase( uu==127 ); testcase( uu==128 );
3518 testcase( uu==32767 ); testcase( uu==32768 );
3519 testcase( uu==8388607 ); testcase( uu==8388608 );
3520 testcase( uu==2147483647 ); testcase( uu==2147483648LL );
3521 testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
3522 if( uu<=127 ){
3523 if( (i&1)==i && p->minWriteFileFormat>=4 ){
3524 pRec->uTemp = 8+(u32)uu;
3525 }else{
3526 nData++;
3527 pRec->uTemp = 1;
3529 }else if( uu<=32767 ){
3530 nData += 2;
3531 pRec->uTemp = 2;
3532 }else if( uu<=8388607 ){
3533 nData += 3;
3534 pRec->uTemp = 3;
3535 }else if( uu<=2147483647 ){
3536 nData += 4;
3537 pRec->uTemp = 4;
3538 }else if( uu<=140737488355327LL ){
3539 nData += 6;
3540 pRec->uTemp = 5;
3541 }else{
3542 nData += 8;
3543 if( pRec->flags & MEM_IntReal ){
3544 /* If the value is IntReal and is going to take up 8 bytes to store
3545 ** as an integer, then we might as well make it an 8-byte floating
3546 ** point value */
3547 pRec->u.r = (double)pRec->u.i;
3548 pRec->flags &= ~MEM_IntReal;
3549 pRec->flags |= MEM_Real;
3550 pRec->uTemp = 7;
3551 }else{
3552 pRec->uTemp = 6;
3555 }else if( pRec->flags & MEM_Real ){
3556 nHdr++;
3557 nData += 8;
3558 pRec->uTemp = 7;
3559 }else{
3560 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
3561 assert( pRec->n>=0 );
3562 len = (u32)pRec->n;
3563 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
3564 if( pRec->flags & MEM_Zero ){
3565 serial_type += pRec->u.nZero*2;
3566 if( nData ){
3567 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
3568 len += pRec->u.nZero;
3569 }else{
3570 nZero += pRec->u.nZero;
3573 nData += len;
3574 nHdr += sqlite3VarintLen(serial_type);
3575 pRec->uTemp = serial_type;
3577 if( pRec==pData0 ) break;
3578 pRec--;
3579 }while(1);
3581 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
3582 ** which determines the total number of bytes in the header. The varint
3583 ** value is the size of the header in bytes including the size varint
3584 ** itself. */
3585 testcase( nHdr==126 );
3586 testcase( nHdr==127 );
3587 if( nHdr<=126 ){
3588 /* The common case */
3589 nHdr += 1;
3590 }else{
3591 /* Rare case of a really large header */
3592 nVarint = sqlite3VarintLen(nHdr);
3593 nHdr += nVarint;
3594 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
3596 nByte = nHdr+nData;
3598 /* Make sure the output register has a buffer large enough to store
3599 ** the new record. The output register (pOp->p3) is not allowed to
3600 ** be one of the input registers (because the following call to
3601 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
3603 if( nByte+nZero<=pOut->szMalloc ){
3604 /* The output register is already large enough to hold the record.
3605 ** No error checks or buffer enlargement is required */
3606 pOut->z = pOut->zMalloc;
3607 }else{
3608 /* Need to make sure that the output is not too big and then enlarge
3609 ** the output register to hold the full result */
3610 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3611 goto too_big;
3613 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
3614 goto no_mem;
3617 pOut->n = (int)nByte;
3618 pOut->flags = MEM_Blob;
3619 if( nZero ){
3620 pOut->u.nZero = nZero;
3621 pOut->flags |= MEM_Zero;
3623 UPDATE_MAX_BLOBSIZE(pOut);
3624 zHdr = (u8 *)pOut->z;
3625 zPayload = zHdr + nHdr;
3627 /* Write the record */
3628 if( nHdr<0x80 ){
3629 *(zHdr++) = nHdr;
3630 }else{
3631 zHdr += sqlite3PutVarint(zHdr,nHdr);
3633 assert( pData0<=pLast );
3634 pRec = pData0;
3635 while( 1 /*exit-by-break*/ ){
3636 serial_type = pRec->uTemp;
3637 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
3638 ** additional varints, one per column.
3639 ** EVIDENCE-OF: R-64536-51728 The values for each column in the record
3640 ** immediately follow the header. */
3641 if( serial_type<=7 ){
3642 *(zHdr++) = serial_type;
3643 if( serial_type==0 ){
3644 /* NULL value. No change in zPayload */
3645 }else{
3646 u64 v;
3647 if( serial_type==7 ){
3648 assert( sizeof(v)==sizeof(pRec->u.r) );
3649 memcpy(&v, &pRec->u.r, sizeof(v));
3650 swapMixedEndianFloat(v);
3651 }else{
3652 v = pRec->u.i;
3654 len = sqlite3SmallTypeSizes[serial_type];
3655 assert( len>=1 && len<=8 && len!=5 && len!=7 );
3656 switch( len ){
3657 default: zPayload[7] = (u8)(v&0xff); v >>= 8;
3658 zPayload[6] = (u8)(v&0xff); v >>= 8;
3659 /* no break */ deliberate_fall_through
3660 case 6: zPayload[5] = (u8)(v&0xff); v >>= 8;
3661 zPayload[4] = (u8)(v&0xff); v >>= 8;
3662 /* no break */ deliberate_fall_through
3663 case 4: zPayload[3] = (u8)(v&0xff); v >>= 8;
3664 /* no break */ deliberate_fall_through
3665 case 3: zPayload[2] = (u8)(v&0xff); v >>= 8;
3666 /* no break */ deliberate_fall_through
3667 case 2: zPayload[1] = (u8)(v&0xff); v >>= 8;
3668 /* no break */ deliberate_fall_through
3669 case 1: zPayload[0] = (u8)(v&0xff);
3671 zPayload += len;
3673 }else if( serial_type<0x80 ){
3674 *(zHdr++) = serial_type;
3675 if( serial_type>=14 && pRec->n>0 ){
3676 assert( pRec->z!=0 );
3677 memcpy(zPayload, pRec->z, pRec->n);
3678 zPayload += pRec->n;
3680 }else{
3681 zHdr += sqlite3PutVarint(zHdr, serial_type);
3682 if( pRec->n ){
3683 assert( pRec->z!=0 );
3684 memcpy(zPayload, pRec->z, pRec->n);
3685 zPayload += pRec->n;
3688 if( pRec==pLast ) break;
3689 pRec++;
3691 assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
3692 assert( nByte==(int)(zPayload - (u8*)pOut->z) );
3694 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
3695 REGISTER_TRACE(pOp->p3, pOut);
3696 break;
3699 /* Opcode: Count P1 P2 P3 * *
3700 ** Synopsis: r[P2]=count()
3702 ** Store the number of entries (an integer value) in the table or index
3703 ** opened by cursor P1 in register P2.
3705 ** If P3==0, then an exact count is obtained, which involves visiting
3706 ** every btree page of the table. But if P3 is non-zero, an estimate
3707 ** is returned based on the current cursor position.
3709 case OP_Count: { /* out2 */
3710 i64 nEntry;
3711 BtCursor *pCrsr;
3713 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
3714 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
3715 assert( pCrsr );
3716 if( pOp->p3 ){
3717 nEntry = sqlite3BtreeRowCountEst(pCrsr);
3718 }else{
3719 nEntry = 0; /* Not needed. Only used to silence a warning. */
3720 rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
3721 if( rc ) goto abort_due_to_error;
3723 pOut = out2Prerelease(p, pOp);
3724 pOut->u.i = nEntry;
3725 goto check_for_interrupt;
3728 /* Opcode: Savepoint P1 * * P4 *
3730 ** Open, release or rollback the savepoint named by parameter P4, depending
3731 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
3732 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
3733 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
3735 case OP_Savepoint: {
3736 int p1; /* Value of P1 operand */
3737 char *zName; /* Name of savepoint */
3738 int nName;
3739 Savepoint *pNew;
3740 Savepoint *pSavepoint;
3741 Savepoint *pTmp;
3742 int iSavepoint;
3743 int ii;
3745 p1 = pOp->p1;
3746 zName = pOp->p4.z;
3748 /* Assert that the p1 parameter is valid. Also that if there is no open
3749 ** transaction, then there cannot be any savepoints.
3751 assert( db->pSavepoint==0 || db->autoCommit==0 );
3752 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
3753 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
3754 assert( checkSavepointCount(db) );
3755 assert( p->bIsReader );
3757 if( p1==SAVEPOINT_BEGIN ){
3758 if( db->nVdbeWrite>0 ){
3759 /* A new savepoint cannot be created if there are active write
3760 ** statements (i.e. open read/write incremental blob handles).
3762 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
3763 rc = SQLITE_BUSY;
3764 }else{
3765 nName = sqlite3Strlen30(zName);
3767 #ifndef SQLITE_OMIT_VIRTUALTABLE
3768 /* This call is Ok even if this savepoint is actually a transaction
3769 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3770 ** If this is a transaction savepoint being opened, it is guaranteed
3771 ** that the db->aVTrans[] array is empty. */
3772 assert( db->autoCommit==0 || db->nVTrans==0 );
3773 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
3774 db->nStatement+db->nSavepoint);
3775 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3776 #endif
3778 /* Create a new savepoint structure. */
3779 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
3780 if( pNew ){
3781 pNew->zName = (char *)&pNew[1];
3782 memcpy(pNew->zName, zName, nName+1);
3784 /* If there is no open transaction, then mark this as a special
3785 ** "transaction savepoint". */
3786 if( db->autoCommit ){
3787 db->autoCommit = 0;
3788 db->isTransactionSavepoint = 1;
3789 }else{
3790 db->nSavepoint++;
3793 /* Link the new savepoint into the database handle's list. */
3794 pNew->pNext = db->pSavepoint;
3795 db->pSavepoint = pNew;
3796 pNew->nDeferredCons = db->nDeferredCons;
3797 pNew->nDeferredImmCons = db->nDeferredImmCons;
3800 }else{
3801 assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
3802 iSavepoint = 0;
3804 /* Find the named savepoint. If there is no such savepoint, then an
3805 ** an error is returned to the user. */
3806 for(
3807 pSavepoint = db->pSavepoint;
3808 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3809 pSavepoint = pSavepoint->pNext
3811 iSavepoint++;
3813 if( !pSavepoint ){
3814 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3815 rc = SQLITE_ERROR;
3816 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3817 /* It is not possible to release (commit) a savepoint if there are
3818 ** active write statements.
3820 sqlite3VdbeError(p, "cannot release savepoint - "
3821 "SQL statements in progress");
3822 rc = SQLITE_BUSY;
3823 }else{
3825 /* Determine whether or not this is a transaction savepoint. If so,
3826 ** and this is a RELEASE command, then the current transaction
3827 ** is committed.
3829 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3830 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3831 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3832 goto vdbe_return;
3834 db->autoCommit = 1;
3835 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3836 p->pc = (int)(pOp - aOp);
3837 db->autoCommit = 0;
3838 p->rc = rc = SQLITE_BUSY;
3839 goto vdbe_return;
3841 rc = p->rc;
3842 if( rc ){
3843 db->autoCommit = 0;
3844 }else{
3845 db->isTransactionSavepoint = 0;
3847 }else{
3848 int isSchemaChange;
3849 iSavepoint = db->nSavepoint - iSavepoint - 1;
3850 if( p1==SAVEPOINT_ROLLBACK ){
3851 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3852 for(ii=0; ii<db->nDb; ii++){
3853 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3854 SQLITE_ABORT_ROLLBACK,
3855 isSchemaChange==0);
3856 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3858 }else{
3859 assert( p1==SAVEPOINT_RELEASE );
3860 isSchemaChange = 0;
3862 for(ii=0; ii<db->nDb; ii++){
3863 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3864 if( rc!=SQLITE_OK ){
3865 goto abort_due_to_error;
3868 if( isSchemaChange ){
3869 sqlite3ExpirePreparedStatements(db, 0);
3870 sqlite3ResetAllSchemasOfConnection(db);
3871 db->mDbFlags |= DBFLAG_SchemaChange;
3874 if( rc ) goto abort_due_to_error;
3876 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3877 ** savepoints nested inside of the savepoint being operated on. */
3878 while( db->pSavepoint!=pSavepoint ){
3879 pTmp = db->pSavepoint;
3880 db->pSavepoint = pTmp->pNext;
3881 sqlite3DbFree(db, pTmp);
3882 db->nSavepoint--;
3885 /* If it is a RELEASE, then destroy the savepoint being operated on
3886 ** too. If it is a ROLLBACK TO, then set the number of deferred
3887 ** constraint violations present in the database to the value stored
3888 ** when the savepoint was created. */
3889 if( p1==SAVEPOINT_RELEASE ){
3890 assert( pSavepoint==db->pSavepoint );
3891 db->pSavepoint = pSavepoint->pNext;
3892 sqlite3DbFree(db, pSavepoint);
3893 if( !isTransaction ){
3894 db->nSavepoint--;
3896 }else{
3897 assert( p1==SAVEPOINT_ROLLBACK );
3898 db->nDeferredCons = pSavepoint->nDeferredCons;
3899 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3902 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3903 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3904 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3908 if( rc ) goto abort_due_to_error;
3909 if( p->eVdbeState==VDBE_HALT_STATE ){
3910 rc = SQLITE_DONE;
3911 goto vdbe_return;
3913 break;
3916 /* Opcode: AutoCommit P1 P2 * * *
3918 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3919 ** back any currently active btree transactions. If there are any active
3920 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3921 ** there are active writing VMs or active VMs that use shared cache.
3923 ** This instruction causes the VM to halt.
3925 case OP_AutoCommit: {
3926 int desiredAutoCommit;
3927 int iRollback;
3929 desiredAutoCommit = pOp->p1;
3930 iRollback = pOp->p2;
3931 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3932 assert( desiredAutoCommit==1 || iRollback==0 );
3933 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3934 assert( p->bIsReader );
3936 if( desiredAutoCommit!=db->autoCommit ){
3937 if( iRollback ){
3938 assert( desiredAutoCommit==1 );
3939 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3940 db->autoCommit = 1;
3941 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3942 /* If this instruction implements a COMMIT and other VMs are writing
3943 ** return an error indicating that the other VMs must complete first.
3945 sqlite3VdbeError(p, "cannot commit transaction - "
3946 "SQL statements in progress");
3947 rc = SQLITE_BUSY;
3948 goto abort_due_to_error;
3949 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3950 goto vdbe_return;
3951 }else{
3952 db->autoCommit = (u8)desiredAutoCommit;
3954 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3955 p->pc = (int)(pOp - aOp);
3956 db->autoCommit = (u8)(1-desiredAutoCommit);
3957 p->rc = rc = SQLITE_BUSY;
3958 goto vdbe_return;
3960 sqlite3CloseSavepoints(db);
3961 if( p->rc==SQLITE_OK ){
3962 rc = SQLITE_DONE;
3963 }else{
3964 rc = SQLITE_ERROR;
3966 goto vdbe_return;
3967 }else{
3968 sqlite3VdbeError(p,
3969 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3970 (iRollback)?"cannot rollback - no transaction is active":
3971 "cannot commit - no transaction is active"));
3973 rc = SQLITE_ERROR;
3974 goto abort_due_to_error;
3976 /*NOTREACHED*/ assert(0);
3979 /* Opcode: Transaction P1 P2 P3 P4 P5
3981 ** Begin a transaction on database P1 if a transaction is not already
3982 ** active.
3983 ** If P2 is non-zero, then a write-transaction is started, or if a
3984 ** read-transaction is already active, it is upgraded to a write-transaction.
3985 ** If P2 is zero, then a read-transaction is started. If P2 is 2 or more
3986 ** then an exclusive transaction is started.
3988 ** P1 is the index of the database file on which the transaction is
3989 ** started. Index 0 is the main database file and index 1 is the
3990 ** file used for temporary tables. Indices of 2 or more are used for
3991 ** attached databases.
3993 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3994 ** true (this flag is set if the Vdbe may modify more than one row and may
3995 ** throw an ABORT exception), a statement transaction may also be opened.
3996 ** More specifically, a statement transaction is opened iff the database
3997 ** connection is currently not in autocommit mode, or if there are other
3998 ** active statements. A statement transaction allows the changes made by this
3999 ** VDBE to be rolled back after an error without having to roll back the
4000 ** entire transaction. If no error is encountered, the statement transaction
4001 ** will automatically commit when the VDBE halts.
4003 ** If P5!=0 then this opcode also checks the schema cookie against P3
4004 ** and the schema generation counter against P4.
4005 ** The cookie changes its value whenever the database schema changes.
4006 ** This operation is used to detect when that the cookie has changed
4007 ** and that the current process needs to reread the schema. If the schema
4008 ** cookie in P3 differs from the schema cookie in the database header or
4009 ** if the schema generation counter in P4 differs from the current
4010 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
4011 ** halts. The sqlite3_step() wrapper function might then reprepare the
4012 ** statement and rerun it from the beginning.
4014 case OP_Transaction: {
4015 Btree *pBt;
4016 Db *pDb;
4017 int iMeta = 0;
4019 assert( p->bIsReader );
4020 assert( p->readOnly==0 || pOp->p2==0 );
4021 assert( pOp->p2>=0 && pOp->p2<=2 );
4022 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4023 assert( DbMaskTest(p->btreeMask, pOp->p1) );
4024 assert( rc==SQLITE_OK );
4025 if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
4026 if( db->flags & SQLITE_QueryOnly ){
4027 /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
4028 rc = SQLITE_READONLY;
4029 }else{
4030 /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
4031 ** transaction */
4032 rc = SQLITE_CORRUPT;
4034 goto abort_due_to_error;
4036 pDb = &db->aDb[pOp->p1];
4037 pBt = pDb->pBt;
4039 if( pBt ){
4040 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
4041 testcase( rc==SQLITE_BUSY_SNAPSHOT );
4042 testcase( rc==SQLITE_BUSY_RECOVERY );
4043 if( rc!=SQLITE_OK ){
4044 if( (rc&0xff)==SQLITE_BUSY ){
4045 p->pc = (int)(pOp - aOp);
4046 p->rc = rc;
4047 goto vdbe_return;
4049 goto abort_due_to_error;
4052 if( p->usesStmtJournal
4053 && pOp->p2
4054 && (db->autoCommit==0 || db->nVdbeRead>1)
4056 assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
4057 if( p->iStatement==0 ){
4058 assert( db->nStatement>=0 && db->nSavepoint>=0 );
4059 db->nStatement++;
4060 p->iStatement = db->nSavepoint + db->nStatement;
4063 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
4064 if( rc==SQLITE_OK ){
4065 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
4068 /* Store the current value of the database handles deferred constraint
4069 ** counter. If the statement transaction needs to be rolled back,
4070 ** the value of this counter needs to be restored too. */
4071 p->nStmtDefCons = db->nDeferredCons;
4072 p->nStmtDefImmCons = db->nDeferredImmCons;
4075 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
4076 if( rc==SQLITE_OK
4077 && pOp->p5
4078 && (iMeta!=pOp->p3 || pDb->pSchema->iGeneration!=pOp->p4.i)
4081 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
4082 ** version is checked to ensure that the schema has not changed since the
4083 ** SQL statement was prepared.
4085 sqlite3DbFree(db, p->zErrMsg);
4086 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
4087 /* If the schema-cookie from the database file matches the cookie
4088 ** stored with the in-memory representation of the schema, do
4089 ** not reload the schema from the database file.
4091 ** If virtual-tables are in use, this is not just an optimization.
4092 ** Often, v-tables store their data in other SQLite tables, which
4093 ** are queried from within xNext() and other v-table methods using
4094 ** prepared queries. If such a query is out-of-date, we do not want to
4095 ** discard the database schema, as the user code implementing the
4096 ** v-table would have to be ready for the sqlite3_vtab structure itself
4097 ** to be invalidated whenever sqlite3_step() is called from within
4098 ** a v-table method.
4100 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
4101 sqlite3ResetOneSchema(db, pOp->p1);
4103 p->expired = 1;
4104 rc = SQLITE_SCHEMA;
4106 /* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
4107 ** from being modified in sqlite3VdbeHalt(). If this statement is
4108 ** reprepared, changeCntOn will be set again. */
4109 p->changeCntOn = 0;
4111 if( rc ) goto abort_due_to_error;
4112 break;
4115 /* Opcode: ReadCookie P1 P2 P3 * *
4117 ** Read cookie number P3 from database P1 and write it into register P2.
4118 ** P3==1 is the schema version. P3==2 is the database format.
4119 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
4120 ** the main database file and P1==1 is the database file used to store
4121 ** temporary tables.
4123 ** There must be a read-lock on the database (either a transaction
4124 ** must be started or there must be an open cursor) before
4125 ** executing this instruction.
4127 case OP_ReadCookie: { /* out2 */
4128 int iMeta;
4129 int iDb;
4130 int iCookie;
4132 assert( p->bIsReader );
4133 iDb = pOp->p1;
4134 iCookie = pOp->p3;
4135 assert( pOp->p3<SQLITE_N_BTREE_META );
4136 assert( iDb>=0 && iDb<db->nDb );
4137 assert( db->aDb[iDb].pBt!=0 );
4138 assert( DbMaskTest(p->btreeMask, iDb) );
4140 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
4141 pOut = out2Prerelease(p, pOp);
4142 pOut->u.i = iMeta;
4143 break;
4146 /* Opcode: SetCookie P1 P2 P3 * P5
4148 ** Write the integer value P3 into cookie number P2 of database P1.
4149 ** P2==1 is the schema version. P2==2 is the database format.
4150 ** P2==3 is the recommended pager cache
4151 ** size, and so forth. P1==0 is the main database file and P1==1 is the
4152 ** database file used to store temporary tables.
4154 ** A transaction must be started before executing this opcode.
4156 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
4157 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
4158 ** has P5 set to 1, so that the internal schema version will be different
4159 ** from the database schema version, resulting in a schema reset.
4161 case OP_SetCookie: {
4162 Db *pDb;
4164 sqlite3VdbeIncrWriteCounter(p, 0);
4165 assert( pOp->p2<SQLITE_N_BTREE_META );
4166 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4167 assert( DbMaskTest(p->btreeMask, pOp->p1) );
4168 assert( p->readOnly==0 );
4169 pDb = &db->aDb[pOp->p1];
4170 assert( pDb->pBt!=0 );
4171 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
4172 /* See note about index shifting on OP_ReadCookie */
4173 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
4174 if( pOp->p2==BTREE_SCHEMA_VERSION ){
4175 /* When the schema cookie changes, record the new cookie internally */
4176 *(u32*)&pDb->pSchema->schema_cookie = *(u32*)&pOp->p3 - pOp->p5;
4177 db->mDbFlags |= DBFLAG_SchemaChange;
4178 sqlite3FkClearTriggerCache(db, pOp->p1);
4179 }else if( pOp->p2==BTREE_FILE_FORMAT ){
4180 /* Record changes in the file format */
4181 pDb->pSchema->file_format = pOp->p3;
4183 if( pOp->p1==1 ){
4184 /* Invalidate all prepared statements whenever the TEMP database
4185 ** schema is changed. Ticket #1644 */
4186 sqlite3ExpirePreparedStatements(db, 0);
4187 p->expired = 0;
4189 if( rc ) goto abort_due_to_error;
4190 break;
4193 /* Opcode: OpenRead P1 P2 P3 P4 P5
4194 ** Synopsis: root=P2 iDb=P3
4196 ** Open a read-only cursor for the database table whose root page is
4197 ** P2 in a database file. The database file is determined by P3.
4198 ** P3==0 means the main database, P3==1 means the database used for
4199 ** temporary tables, and P3>1 means used the corresponding attached
4200 ** database. Give the new cursor an identifier of P1. The P1
4201 ** values need not be contiguous but all P1 values should be small integers.
4202 ** It is an error for P1 to be negative.
4204 ** Allowed P5 bits:
4205 ** <ul>
4206 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4207 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4208 ** of OP_SeekLE/OP_IdxLT)
4209 ** </ul>
4211 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4212 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4213 ** object, then table being opened must be an [index b-tree] where the
4214 ** KeyInfo object defines the content and collating
4215 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4216 ** value, then the table being opened must be a [table b-tree] with a
4217 ** number of columns no less than the value of P4.
4219 ** See also: OpenWrite, ReopenIdx
4221 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
4222 ** Synopsis: root=P2 iDb=P3
4224 ** The ReopenIdx opcode works like OP_OpenRead except that it first
4225 ** checks to see if the cursor on P1 is already open on the same
4226 ** b-tree and if it is this opcode becomes a no-op. In other words,
4227 ** if the cursor is already open, do not reopen it.
4229 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
4230 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
4231 ** be the same as every other ReopenIdx or OpenRead for the same cursor
4232 ** number.
4234 ** Allowed P5 bits:
4235 ** <ul>
4236 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4237 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4238 ** of OP_SeekLE/OP_IdxLT)
4239 ** </ul>
4241 ** See also: OP_OpenRead, OP_OpenWrite
4243 /* Opcode: OpenWrite P1 P2 P3 P4 P5
4244 ** Synopsis: root=P2 iDb=P3
4246 ** Open a read/write cursor named P1 on the table or index whose root
4247 ** page is P2 (or whose root page is held in register P2 if the
4248 ** OPFLAG_P2ISREG bit is set in P5 - see below).
4250 ** The P4 value may be either an integer (P4_INT32) or a pointer to
4251 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
4252 ** object, then table being opened must be an [index b-tree] where the
4253 ** KeyInfo object defines the content and collating
4254 ** sequence of that index b-tree. Otherwise, if P4 is an integer
4255 ** value, then the table being opened must be a [table b-tree] with a
4256 ** number of columns no less than the value of P4.
4258 ** Allowed P5 bits:
4259 ** <ul>
4260 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
4261 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
4262 ** of OP_SeekLE/OP_IdxLT)
4263 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
4264 ** and subsequently delete entries in an index btree. This is a
4265 ** hint to the storage engine that the storage engine is allowed to
4266 ** ignore. The hint is not used by the official SQLite b*tree storage
4267 ** engine, but is used by COMDB2.
4268 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
4269 ** as the root page, not the value of P2 itself.
4270 ** </ul>
4272 ** This instruction works like OpenRead except that it opens the cursor
4273 ** in read/write mode.
4275 ** See also: OP_OpenRead, OP_ReopenIdx
4277 case OP_ReopenIdx: { /* ncycle */
4278 int nField;
4279 KeyInfo *pKeyInfo;
4280 u32 p2;
4281 int iDb;
4282 int wrFlag;
4283 Btree *pX;
4284 VdbeCursor *pCur;
4285 Db *pDb;
4287 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4288 assert( pOp->p4type==P4_KEYINFO );
4289 pCur = p->apCsr[pOp->p1];
4290 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
4291 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
4292 assert( pCur->eCurType==CURTYPE_BTREE );
4293 sqlite3BtreeClearCursor(pCur->uc.pCursor);
4294 goto open_cursor_set_hints;
4296 /* If the cursor is not currently open or is open on a different
4297 ** index, then fall through into OP_OpenRead to force a reopen */
4298 case OP_OpenRead: /* ncycle */
4299 case OP_OpenWrite:
4301 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
4302 assert( p->bIsReader );
4303 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
4304 || p->readOnly==0 );
4306 if( p->expired==1 ){
4307 rc = SQLITE_ABORT_ROLLBACK;
4308 goto abort_due_to_error;
4311 nField = 0;
4312 pKeyInfo = 0;
4313 p2 = (u32)pOp->p2;
4314 iDb = pOp->p3;
4315 assert( iDb>=0 && iDb<db->nDb );
4316 assert( DbMaskTest(p->btreeMask, iDb) );
4317 pDb = &db->aDb[iDb];
4318 pX = pDb->pBt;
4319 assert( pX!=0 );
4320 if( pOp->opcode==OP_OpenWrite ){
4321 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
4322 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
4323 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4324 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
4325 p->minWriteFileFormat = pDb->pSchema->file_format;
4327 }else{
4328 wrFlag = 0;
4330 if( pOp->p5 & OPFLAG_P2ISREG ){
4331 assert( p2>0 );
4332 assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
4333 assert( pOp->opcode==OP_OpenWrite );
4334 pIn2 = &aMem[p2];
4335 assert( memIsValid(pIn2) );
4336 assert( (pIn2->flags & MEM_Int)!=0 );
4337 sqlite3VdbeMemIntegerify(pIn2);
4338 p2 = (int)pIn2->u.i;
4339 /* The p2 value always comes from a prior OP_CreateBtree opcode and
4340 ** that opcode will always set the p2 value to 2 or more or else fail.
4341 ** If there were a failure, the prepared statement would have halted
4342 ** before reaching this instruction. */
4343 assert( p2>=2 );
4345 if( pOp->p4type==P4_KEYINFO ){
4346 pKeyInfo = pOp->p4.pKeyInfo;
4347 assert( pKeyInfo->enc==ENC(db) );
4348 assert( pKeyInfo->db==db );
4349 nField = pKeyInfo->nAllField;
4350 }else if( pOp->p4type==P4_INT32 ){
4351 nField = pOp->p4.i;
4353 assert( pOp->p1>=0 );
4354 assert( nField>=0 );
4355 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
4356 pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
4357 if( pCur==0 ) goto no_mem;
4358 pCur->iDb = iDb;
4359 pCur->nullRow = 1;
4360 pCur->isOrdered = 1;
4361 pCur->pgnoRoot = p2;
4362 #ifdef SQLITE_DEBUG
4363 pCur->wrFlag = wrFlag;
4364 #endif
4365 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
4366 pCur->pKeyInfo = pKeyInfo;
4367 /* Set the VdbeCursor.isTable variable. Previous versions of
4368 ** SQLite used to check if the root-page flags were sane at this point
4369 ** and report database corruption if they were not, but this check has
4370 ** since moved into the btree layer. */
4371 pCur->isTable = pOp->p4type!=P4_KEYINFO;
4373 open_cursor_set_hints:
4374 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
4375 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
4376 testcase( pOp->p5 & OPFLAG_BULKCSR );
4377 testcase( pOp->p2 & OPFLAG_SEEKEQ );
4378 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
4379 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
4380 if( rc ) goto abort_due_to_error;
4381 break;
4384 /* Opcode: OpenDup P1 P2 * * *
4386 ** Open a new cursor P1 that points to the same ephemeral table as
4387 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
4388 ** opcode. Only ephemeral cursors may be duplicated.
4390 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
4392 case OP_OpenDup: { /* ncycle */
4393 VdbeCursor *pOrig; /* The original cursor to be duplicated */
4394 VdbeCursor *pCx; /* The new cursor */
4396 pOrig = p->apCsr[pOp->p2];
4397 assert( pOrig );
4398 assert( pOrig->isEphemeral ); /* Only ephemeral cursors can be duplicated */
4400 pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
4401 if( pCx==0 ) goto no_mem;
4402 pCx->nullRow = 1;
4403 pCx->isEphemeral = 1;
4404 pCx->pKeyInfo = pOrig->pKeyInfo;
4405 pCx->isTable = pOrig->isTable;
4406 pCx->pgnoRoot = pOrig->pgnoRoot;
4407 pCx->isOrdered = pOrig->isOrdered;
4408 pCx->ub.pBtx = pOrig->ub.pBtx;
4409 pCx->noReuse = 1;
4410 pOrig->noReuse = 1;
4411 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4412 pCx->pKeyInfo, pCx->uc.pCursor);
4413 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
4414 ** opened for a database. Since there is already an open cursor when this
4415 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
4416 assert( rc==SQLITE_OK );
4417 break;
4421 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5
4422 ** Synopsis: nColumn=P2
4424 ** Open a new cursor P1 to a transient table.
4425 ** The cursor is always opened read/write even if
4426 ** the main database is read-only. The ephemeral
4427 ** table is deleted automatically when the cursor is closed.
4429 ** If the cursor P1 is already opened on an ephemeral table, the table
4430 ** is cleared (all content is erased).
4432 ** P2 is the number of columns in the ephemeral table.
4433 ** The cursor points to a BTree table if P4==0 and to a BTree index
4434 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
4435 ** that defines the format of keys in the index.
4437 ** The P5 parameter can be a mask of the BTREE_* flags defined
4438 ** in btree.h. These flags control aspects of the operation of
4439 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
4440 ** added automatically.
4442 ** If P3 is positive, then reg[P3] is modified slightly so that it
4443 ** can be used as zero-length data for OP_Insert. This is an optimization
4444 ** that avoids an extra OP_Blob opcode to initialize that register.
4446 /* Opcode: OpenAutoindex P1 P2 * P4 *
4447 ** Synopsis: nColumn=P2
4449 ** This opcode works the same as OP_OpenEphemeral. It has a
4450 ** different name to distinguish its use. Tables created using
4451 ** by this opcode will be used for automatically created transient
4452 ** indices in joins.
4454 case OP_OpenAutoindex: /* ncycle */
4455 case OP_OpenEphemeral: { /* ncycle */
4456 VdbeCursor *pCx;
4457 KeyInfo *pKeyInfo;
4459 static const int vfsFlags =
4460 SQLITE_OPEN_READWRITE |
4461 SQLITE_OPEN_CREATE |
4462 SQLITE_OPEN_EXCLUSIVE |
4463 SQLITE_OPEN_DELETEONCLOSE |
4464 SQLITE_OPEN_TRANSIENT_DB;
4465 assert( pOp->p1>=0 );
4466 assert( pOp->p2>=0 );
4467 if( pOp->p3>0 ){
4468 /* Make register reg[P3] into a value that can be used as the data
4469 ** form sqlite3BtreeInsert() where the length of the data is zero. */
4470 assert( pOp->p2==0 ); /* Only used when number of columns is zero */
4471 assert( pOp->opcode==OP_OpenEphemeral );
4472 assert( aMem[pOp->p3].flags & MEM_Null );
4473 aMem[pOp->p3].n = 0;
4474 aMem[pOp->p3].z = "";
4476 pCx = p->apCsr[pOp->p1];
4477 if( pCx && !pCx->noReuse && ALWAYS(pOp->p2<=pCx->nField) ){
4478 /* If the ephemeral table is already open and has no duplicates from
4479 ** OP_OpenDup, then erase all existing content so that the table is
4480 ** empty again, rather than creating a new table. */
4481 assert( pCx->isEphemeral );
4482 pCx->seqCount = 0;
4483 pCx->cacheStatus = CACHE_STALE;
4484 rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
4485 }else{
4486 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
4487 if( pCx==0 ) goto no_mem;
4488 pCx->isEphemeral = 1;
4489 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
4490 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
4491 vfsFlags);
4492 if( rc==SQLITE_OK ){
4493 rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
4494 if( rc==SQLITE_OK ){
4495 /* If a transient index is required, create it by calling
4496 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
4497 ** opening it. If a transient table is required, just use the
4498 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
4500 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
4501 assert( pOp->p4type==P4_KEYINFO );
4502 rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
4503 BTREE_BLOBKEY | pOp->p5);
4504 if( rc==SQLITE_OK ){
4505 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
4506 assert( pKeyInfo->db==db );
4507 assert( pKeyInfo->enc==ENC(db) );
4508 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4509 pKeyInfo, pCx->uc.pCursor);
4511 pCx->isTable = 0;
4512 }else{
4513 pCx->pgnoRoot = SCHEMA_ROOT;
4514 rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
4515 0, pCx->uc.pCursor);
4516 pCx->isTable = 1;
4519 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
4520 if( rc ){
4521 sqlite3BtreeClose(pCx->ub.pBtx);
4525 if( rc ) goto abort_due_to_error;
4526 pCx->nullRow = 1;
4527 break;
4530 /* Opcode: SorterOpen P1 P2 P3 P4 *
4532 ** This opcode works like OP_OpenEphemeral except that it opens
4533 ** a transient index that is specifically designed to sort large
4534 ** tables using an external merge-sort algorithm.
4536 ** If argument P3 is non-zero, then it indicates that the sorter may
4537 ** assume that a stable sort considering the first P3 fields of each
4538 ** key is sufficient to produce the required results.
4540 case OP_SorterOpen: {
4541 VdbeCursor *pCx;
4543 assert( pOp->p1>=0 );
4544 assert( pOp->p2>=0 );
4545 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
4546 if( pCx==0 ) goto no_mem;
4547 pCx->pKeyInfo = pOp->p4.pKeyInfo;
4548 assert( pCx->pKeyInfo->db==db );
4549 assert( pCx->pKeyInfo->enc==ENC(db) );
4550 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4551 if( rc ) goto abort_due_to_error;
4552 break;
4555 /* Opcode: SequenceTest P1 P2 * * *
4556 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4558 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4559 ** to P2. Regardless of whether or not the jump is taken, increment the
4560 ** the sequence value.
4562 case OP_SequenceTest: {
4563 VdbeCursor *pC;
4564 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4565 pC = p->apCsr[pOp->p1];
4566 assert( isSorter(pC) );
4567 if( (pC->seqCount++)==0 ){
4568 goto jump_to_p2;
4570 break;
4573 /* Opcode: OpenPseudo P1 P2 P3 * *
4574 ** Synopsis: P3 columns in r[P2]
4576 ** Open a new cursor that points to a fake table that contains a single
4577 ** row of data. The content of that one row is the content of memory
4578 ** register P2. In other words, cursor P1 becomes an alias for the
4579 ** MEM_Blob content contained in register P2.
4581 ** A pseudo-table created by this opcode is used to hold a single
4582 ** row output from the sorter so that the row can be decomposed into
4583 ** individual columns using the OP_Column opcode. The OP_Column opcode
4584 ** is the only cursor opcode that works with a pseudo-table.
4586 ** P3 is the number of fields in the records that will be stored by
4587 ** the pseudo-table. If P2 is 0 or negative then the pseudo-cursor
4588 ** will return NULL for every column.
4590 case OP_OpenPseudo: {
4591 VdbeCursor *pCx;
4593 assert( pOp->p1>=0 );
4594 assert( pOp->p3>=0 );
4595 pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
4596 if( pCx==0 ) goto no_mem;
4597 pCx->nullRow = 1;
4598 pCx->seekResult = pOp->p2;
4599 pCx->isTable = 1;
4600 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4601 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
4602 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4603 ** which is a performance optimization */
4604 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4605 assert( pOp->p5==0 );
4606 break;
4609 /* Opcode: Close P1 * * * *
4611 ** Close a cursor previously opened as P1. If P1 is not
4612 ** currently open, this instruction is a no-op.
4614 case OP_Close: { /* ncycle */
4615 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4616 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4617 p->apCsr[pOp->p1] = 0;
4618 break;
4621 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4622 /* Opcode: ColumnsUsed P1 * * P4 *
4624 ** This opcode (which only exists if SQLite was compiled with
4625 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4626 ** table or index for cursor P1 are used. P4 is a 64-bit integer
4627 ** (P4_INT64) in which the first 63 bits are one for each of the
4628 ** first 63 columns of the table or index that are actually used
4629 ** by the cursor. The high-order bit is set if any column after
4630 ** the 64th is used.
4632 case OP_ColumnsUsed: {
4633 VdbeCursor *pC;
4634 pC = p->apCsr[pOp->p1];
4635 assert( pC->eCurType==CURTYPE_BTREE );
4636 pC->maskUsed = *(u64*)pOp->p4.pI64;
4637 break;
4639 #endif
4641 /* Opcode: SeekGE P1 P2 P3 P4 *
4642 ** Synopsis: key=r[P3@P4]
4644 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4645 ** use the value in register P3 as the key. If cursor P1 refers
4646 ** to an SQL index, then P3 is the first in an array of P4 registers
4647 ** that are used as an unpacked index key.
4649 ** Reposition cursor P1 so that it points to the smallest entry that
4650 ** is greater than or equal to the key value. If there are no records
4651 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4653 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4654 ** opcode will either land on a record that exactly matches the key, or
4655 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4656 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4657 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4658 ** IdxGT opcode will be used on subsequent loop iterations. The
4659 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4660 ** is an equality search.
4662 ** This opcode leaves the cursor configured to move in forward order,
4663 ** from the beginning toward the end. In other words, the cursor is
4664 ** configured to use Next, not Prev.
4666 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4668 /* Opcode: SeekGT P1 P2 P3 P4 *
4669 ** Synopsis: key=r[P3@P4]
4671 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4672 ** use the value in register P3 as a key. If cursor P1 refers
4673 ** to an SQL index, then P3 is the first in an array of P4 registers
4674 ** that are used as an unpacked index key.
4676 ** Reposition cursor P1 so that it points to the smallest entry that
4677 ** is greater than the key value. If there are no records greater than
4678 ** the key and P2 is not zero, then jump to P2.
4680 ** This opcode leaves the cursor configured to move in forward order,
4681 ** from the beginning toward the end. In other words, the cursor is
4682 ** configured to use Next, not Prev.
4684 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4686 /* Opcode: SeekLT P1 P2 P3 P4 *
4687 ** Synopsis: key=r[P3@P4]
4689 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4690 ** use the value in register P3 as a key. If cursor P1 refers
4691 ** to an SQL index, then P3 is the first in an array of P4 registers
4692 ** that are used as an unpacked index key.
4694 ** Reposition cursor P1 so that it points to the largest entry that
4695 ** is less than the key value. If there are no records less than
4696 ** the key and P2 is not zero, then jump to P2.
4698 ** This opcode leaves the cursor configured to move in reverse order,
4699 ** from the end toward the beginning. In other words, the cursor is
4700 ** configured to use Prev, not Next.
4702 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4704 /* Opcode: SeekLE P1 P2 P3 P4 *
4705 ** Synopsis: key=r[P3@P4]
4707 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4708 ** use the value in register P3 as a key. If cursor P1 refers
4709 ** to an SQL index, then P3 is the first in an array of P4 registers
4710 ** that are used as an unpacked index key.
4712 ** Reposition cursor P1 so that it points to the largest entry that
4713 ** is less than or equal to the key value. If there are no records
4714 ** less than or equal to the key and P2 is not zero, then jump to P2.
4716 ** This opcode leaves the cursor configured to move in reverse order,
4717 ** from the end toward the beginning. In other words, the cursor is
4718 ** configured to use Prev, not Next.
4720 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4721 ** opcode will either land on a record that exactly matches the key, or
4722 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4723 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4724 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4725 ** IdxGE opcode will be used on subsequent loop iterations. The
4726 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4727 ** is an equality search.
4729 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4731 case OP_SeekLT: /* jump0, in3, group, ncycle */
4732 case OP_SeekLE: /* jump0, in3, group, ncycle */
4733 case OP_SeekGE: /* jump0, in3, group, ncycle */
4734 case OP_SeekGT: { /* jump0, in3, group, ncycle */
4735 int res; /* Comparison result */
4736 int oc; /* Opcode */
4737 VdbeCursor *pC; /* The cursor to seek */
4738 UnpackedRecord r; /* The key to seek for */
4739 int nField; /* Number of columns or fields in the key */
4740 i64 iKey; /* The rowid we are to seek to */
4741 int eqOnly; /* Only interested in == results */
4743 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4744 assert( pOp->p2!=0 );
4745 pC = p->apCsr[pOp->p1];
4746 assert( pC!=0 );
4747 assert( pC->eCurType==CURTYPE_BTREE );
4748 assert( OP_SeekLE == OP_SeekLT+1 );
4749 assert( OP_SeekGE == OP_SeekLT+2 );
4750 assert( OP_SeekGT == OP_SeekLT+3 );
4751 assert( pC->isOrdered );
4752 assert( pC->uc.pCursor!=0 );
4753 oc = pOp->opcode;
4754 eqOnly = 0;
4755 pC->nullRow = 0;
4756 #ifdef SQLITE_DEBUG
4757 pC->seekOp = pOp->opcode;
4758 #endif
4760 pC->deferredMoveto = 0;
4761 pC->cacheStatus = CACHE_STALE;
4762 if( pC->isTable ){
4763 u16 flags3, newType;
4764 /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4765 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4766 || CORRUPT_DB );
4768 /* The input value in P3 might be of any type: integer, real, string,
4769 ** blob, or NULL. But it needs to be an integer before we can do
4770 ** the seek, so convert it. */
4771 pIn3 = &aMem[pOp->p3];
4772 flags3 = pIn3->flags;
4773 if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4774 applyNumericAffinity(pIn3, 0);
4776 iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4777 newType = pIn3->flags; /* Record the type after applying numeric affinity */
4778 pIn3->flags = flags3; /* But convert the type back to its original */
4780 /* If the P3 value could not be converted into an integer without
4781 ** loss of information, then special processing is required... */
4782 if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4783 int c;
4784 if( (newType & MEM_Real)==0 ){
4785 if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4786 VdbeBranchTaken(1,2);
4787 goto jump_to_p2;
4788 }else{
4789 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4790 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4791 goto seek_not_found;
4794 c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
4796 /* If the approximation iKey is larger than the actual real search
4797 ** term, substitute >= for > and < for <=. e.g. if the search term
4798 ** is 4.9 and the integer approximation 5:
4800 ** (x > 4.9) -> (x >= 5)
4801 ** (x <= 4.9) -> (x < 5)
4803 if( c>0 ){
4804 assert( OP_SeekGE==(OP_SeekGT-1) );
4805 assert( OP_SeekLT==(OP_SeekLE-1) );
4806 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4807 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4810 /* If the approximation iKey is smaller than the actual real search
4811 ** term, substitute <= for < and > for >=. */
4812 else if( c<0 ){
4813 assert( OP_SeekLE==(OP_SeekLT+1) );
4814 assert( OP_SeekGT==(OP_SeekGE+1) );
4815 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4816 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4819 rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
4820 pC->movetoTarget = iKey; /* Used by OP_Delete */
4821 if( rc!=SQLITE_OK ){
4822 goto abort_due_to_error;
4824 }else{
4825 /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4826 ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4827 ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4828 ** with the same key.
4830 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4831 eqOnly = 1;
4832 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4833 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4834 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4835 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4836 assert( pOp[1].p1==pOp[0].p1 );
4837 assert( pOp[1].p2==pOp[0].p2 );
4838 assert( pOp[1].p3==pOp[0].p3 );
4839 assert( pOp[1].p4.i==pOp[0].p4.i );
4842 nField = pOp->p4.i;
4843 assert( pOp->p4type==P4_INT32 );
4844 assert( nField>0 );
4845 r.pKeyInfo = pC->pKeyInfo;
4846 r.nField = (u16)nField;
4848 /* The next line of code computes as follows, only faster:
4849 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
4850 ** r.default_rc = -1;
4851 ** }else{
4852 ** r.default_rc = +1;
4853 ** }
4855 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4856 assert( oc!=OP_SeekGT || r.default_rc==-1 );
4857 assert( oc!=OP_SeekLE || r.default_rc==-1 );
4858 assert( oc!=OP_SeekGE || r.default_rc==+1 );
4859 assert( oc!=OP_SeekLT || r.default_rc==+1 );
4861 r.aMem = &aMem[pOp->p3];
4862 #ifdef SQLITE_DEBUG
4864 int i;
4865 for(i=0; i<r.nField; i++){
4866 assert( memIsValid(&r.aMem[i]) );
4867 if( i>0 ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
4870 #endif
4871 r.eqSeen = 0;
4872 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
4873 if( rc!=SQLITE_OK ){
4874 goto abort_due_to_error;
4876 if( eqOnly && r.eqSeen==0 ){
4877 assert( res!=0 );
4878 goto seek_not_found;
4881 #ifdef SQLITE_TEST
4882 sqlite3_search_count++;
4883 #endif
4884 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
4885 if( res<0 || (res==0 && oc==OP_SeekGT) ){
4886 res = 0;
4887 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4888 if( rc!=SQLITE_OK ){
4889 if( rc==SQLITE_DONE ){
4890 rc = SQLITE_OK;
4891 res = 1;
4892 }else{
4893 goto abort_due_to_error;
4896 }else{
4897 res = 0;
4899 }else{
4900 assert( oc==OP_SeekLT || oc==OP_SeekLE );
4901 if( res>0 || (res==0 && oc==OP_SeekLT) ){
4902 res = 0;
4903 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4904 if( rc!=SQLITE_OK ){
4905 if( rc==SQLITE_DONE ){
4906 rc = SQLITE_OK;
4907 res = 1;
4908 }else{
4909 goto abort_due_to_error;
4912 }else{
4913 /* res might be negative because the table is empty. Check to
4914 ** see if this is the case.
4916 res = sqlite3BtreeEof(pC->uc.pCursor);
4919 seek_not_found:
4920 assert( pOp->p2>0 );
4921 VdbeBranchTaken(res!=0,2);
4922 if( res ){
4923 goto jump_to_p2;
4924 }else if( eqOnly ){
4925 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4926 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4928 break;
4932 /* Opcode: SeekScan P1 P2 * * P5
4933 ** Synopsis: Scan-ahead up to P1 rows
4935 ** This opcode is a prefix opcode to OP_SeekGE. In other words, this
4936 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4937 ** checked by assert() statements.
4939 ** This opcode uses the P1 through P4 operands of the subsequent
4940 ** OP_SeekGE. In the text that follows, the operands of the subsequent
4941 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4. Only
4942 ** the P1, P2 and P5 operands of this opcode are also used, and are called
4943 ** This.P1, This.P2 and This.P5.
4945 ** This opcode helps to optimize IN operators on a multi-column index
4946 ** where the IN operator is on the later terms of the index by avoiding
4947 ** unnecessary seeks on the btree, substituting steps to the next row
4948 ** of the b-tree instead. A correct answer is obtained if this opcode
4949 ** is omitted or is a no-op.
4951 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4952 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4953 ** to. Call this SeekGE.P3/P4 row the "target".
4955 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4956 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4958 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4959 ** might be the target row, or it might be near and slightly before the
4960 ** target row, or it might be after the target row. If the cursor is
4961 ** currently before the target row, then this opcode attempts to position
4962 ** the cursor on or after the target row by invoking sqlite3BtreeStep()
4963 ** on the cursor between 1 and This.P1 times.
4965 ** The This.P5 parameter is a flag that indicates what to do if the
4966 ** cursor ends up pointing at a valid row that is past the target
4967 ** row. If This.P5 is false (0) then a jump is made to SeekGE.P2. If
4968 ** This.P5 is true (non-zero) then a jump is made to This.P2. The P5==0
4969 ** case occurs when there are no inequality constraints to the right of
4970 ** the IN constraint. The jump to SeekGE.P2 ends the loop. The P5!=0 case
4971 ** occurs when there are inequality constraints to the right of the IN
4972 ** operator. In that case, the This.P2 will point either directly to or
4973 ** to setup code prior to the OP_IdxGT or OP_IdxGE opcode that checks for
4974 ** loop terminate.
4976 ** Possible outcomes from this opcode:<ol>
4978 ** <li> If the cursor is initially not pointed to any valid row, then
4979 ** fall through into the subsequent OP_SeekGE opcode.
4981 ** <li> If the cursor is left pointing to a row that is before the target
4982 ** row, even after making as many as This.P1 calls to
4983 ** sqlite3BtreeNext(), then also fall through into OP_SeekGE.
4985 ** <li> If the cursor is left pointing at the target row, either because it
4986 ** was at the target row to begin with or because one or more
4987 ** sqlite3BtreeNext() calls moved the cursor to the target row,
4988 ** then jump to This.P2..,
4990 ** <li> If the cursor started out before the target row and a call to
4991 ** to sqlite3BtreeNext() moved the cursor off the end of the index
4992 ** (indicating that the target row definitely does not exist in the
4993 ** btree) then jump to SeekGE.P2, ending the loop.
4995 ** <li> If the cursor ends up on a valid row that is past the target row
4996 ** (indicating that the target row does not exist in the btree) then
4997 ** jump to SeekOP.P2 if This.P5==0 or to This.P2 if This.P5>0.
4998 ** </ol>
5000 case OP_SeekScan: { /* ncycle */
5001 VdbeCursor *pC;
5002 int res;
5003 int nStep;
5004 UnpackedRecord r;
5006 assert( pOp[1].opcode==OP_SeekGE );
5008 /* If pOp->p5 is clear, then pOp->p2 points to the first instruction past the
5009 ** OP_IdxGT that follows the OP_SeekGE. Otherwise, it points to the first
5010 ** opcode past the OP_SeekGE itself. */
5011 assert( pOp->p2>=(int)(pOp-aOp)+2 );
5012 #ifdef SQLITE_DEBUG
5013 if( pOp->p5==0 ){
5014 /* There are no inequality constraints following the IN constraint. */
5015 assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
5016 assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
5017 assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
5018 assert( aOp[pOp->p2-1].opcode==OP_IdxGT
5019 || aOp[pOp->p2-1].opcode==OP_IdxGE );
5020 testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
5021 }else{
5022 /* There are inequality constraints. */
5023 assert( pOp->p2==(int)(pOp-aOp)+2 );
5024 assert( aOp[pOp->p2-1].opcode==OP_SeekGE );
5026 #endif
5028 assert( pOp->p1>0 );
5029 pC = p->apCsr[pOp[1].p1];
5030 assert( pC!=0 );
5031 assert( pC->eCurType==CURTYPE_BTREE );
5032 assert( !pC->isTable );
5033 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
5034 #ifdef SQLITE_DEBUG
5035 if( db->flags&SQLITE_VdbeTrace ){
5036 printf("... cursor not valid - fall through\n");
5038 #endif
5039 break;
5041 nStep = pOp->p1;
5042 assert( nStep>=1 );
5043 r.pKeyInfo = pC->pKeyInfo;
5044 r.nField = (u16)pOp[1].p4.i;
5045 r.default_rc = 0;
5046 r.aMem = &aMem[pOp[1].p3];
5047 #ifdef SQLITE_DEBUG
5049 int i;
5050 for(i=0; i<r.nField; i++){
5051 assert( memIsValid(&r.aMem[i]) );
5052 REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
5055 #endif
5056 res = 0; /* Not needed. Only used to silence a warning. */
5057 while(1){
5058 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
5059 if( rc ) goto abort_due_to_error;
5060 if( res>0 && pOp->p5==0 ){
5061 seekscan_search_fail:
5062 /* Jump to SeekGE.P2, ending the loop */
5063 #ifdef SQLITE_DEBUG
5064 if( db->flags&SQLITE_VdbeTrace ){
5065 printf("... %d steps and then skip\n", pOp->p1 - nStep);
5067 #endif
5068 VdbeBranchTaken(1,3);
5069 pOp++;
5070 goto jump_to_p2;
5072 if( res>=0 ){
5073 /* Jump to This.P2, bypassing the OP_SeekGE opcode */
5074 #ifdef SQLITE_DEBUG
5075 if( db->flags&SQLITE_VdbeTrace ){
5076 printf("... %d steps and then success\n", pOp->p1 - nStep);
5078 #endif
5079 VdbeBranchTaken(2,3);
5080 goto jump_to_p2;
5081 break;
5083 if( nStep<=0 ){
5084 #ifdef SQLITE_DEBUG
5085 if( db->flags&SQLITE_VdbeTrace ){
5086 printf("... fall through after %d steps\n", pOp->p1);
5088 #endif
5089 VdbeBranchTaken(0,3);
5090 break;
5092 nStep--;
5093 pC->cacheStatus = CACHE_STALE;
5094 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
5095 if( rc ){
5096 if( rc==SQLITE_DONE ){
5097 rc = SQLITE_OK;
5098 goto seekscan_search_fail;
5099 }else{
5100 goto abort_due_to_error;
5105 break;
5109 /* Opcode: SeekHit P1 P2 P3 * *
5110 ** Synopsis: set P2<=seekHit<=P3
5112 ** Increase or decrease the seekHit value for cursor P1, if necessary,
5113 ** so that it is no less than P2 and no greater than P3.
5115 ** The seekHit integer represents the maximum of terms in an index for which
5116 ** there is known to be at least one match. If the seekHit value is smaller
5117 ** than the total number of equality terms in an index lookup, then the
5118 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
5119 ** early, thus saving work. This is part of the IN-early-out optimization.
5121 ** P1 must be a valid b-tree cursor.
5123 case OP_SeekHit: { /* ncycle */
5124 VdbeCursor *pC;
5125 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5126 pC = p->apCsr[pOp->p1];
5127 assert( pC!=0 );
5128 assert( pOp->p3>=pOp->p2 );
5129 if( pC->seekHit<pOp->p2 ){
5130 #ifdef SQLITE_DEBUG
5131 if( db->flags&SQLITE_VdbeTrace ){
5132 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
5134 #endif
5135 pC->seekHit = pOp->p2;
5136 }else if( pC->seekHit>pOp->p3 ){
5137 #ifdef SQLITE_DEBUG
5138 if( db->flags&SQLITE_VdbeTrace ){
5139 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
5141 #endif
5142 pC->seekHit = pOp->p3;
5144 break;
5147 /* Opcode: IfNotOpen P1 P2 * * *
5148 ** Synopsis: if( !csr[P1] ) goto P2
5150 ** If cursor P1 is not open or if P1 is set to a NULL row using the
5151 ** OP_NullRow opcode, then jump to instruction P2. Otherwise, fall through.
5153 case OP_IfNotOpen: { /* jump */
5154 VdbeCursor *pCur;
5156 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5157 pCur = p->apCsr[pOp->p1];
5158 VdbeBranchTaken(pCur==0 || pCur->nullRow, 2);
5159 if( pCur==0 || pCur->nullRow ){
5160 goto jump_to_p2_and_check_for_interrupt;
5162 break;
5165 /* Opcode: Found P1 P2 P3 P4 *
5166 ** Synopsis: key=r[P3@P4]
5168 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5169 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5170 ** record.
5172 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5173 ** is a prefix of any entry in P1 then a jump is made to P2 and
5174 ** P1 is left pointing at the matching entry.
5176 ** This operation leaves the cursor in a state where it can be
5177 ** advanced in the forward direction. The Next instruction will work,
5178 ** but not the Prev instruction.
5180 ** See also: NotFound, NoConflict, NotExists. SeekGe
5182 /* Opcode: NotFound P1 P2 P3 P4 *
5183 ** Synopsis: key=r[P3@P4]
5185 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5186 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5187 ** record.
5189 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5190 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
5191 ** does contain an entry whose prefix matches the P3/P4 record then control
5192 ** falls through to the next instruction and P1 is left pointing at the
5193 ** matching entry.
5195 ** This operation leaves the cursor in a state where it cannot be
5196 ** advanced in either direction. In other words, the Next and Prev
5197 ** opcodes do not work after this operation.
5199 ** See also: Found, NotExists, NoConflict, IfNoHope
5201 /* Opcode: IfNoHope P1 P2 P3 P4 *
5202 ** Synopsis: key=r[P3@P4]
5204 ** Register P3 is the first of P4 registers that form an unpacked
5205 ** record. Cursor P1 is an index btree. P2 is a jump destination.
5206 ** In other words, the operands to this opcode are the same as the
5207 ** operands to OP_NotFound and OP_IdxGT.
5209 ** This opcode is an optimization attempt only. If this opcode always
5210 ** falls through, the correct answer is still obtained, but extra work
5211 ** is performed.
5213 ** A value of N in the seekHit flag of cursor P1 means that there exists
5214 ** a key P3:N that will match some record in the index. We want to know
5215 ** if it is possible for a record P3:P4 to match some record in the
5216 ** index. If it is not possible, we can skip some work. So if seekHit
5217 ** is less than P4, attempt to find out if a match is possible by running
5218 ** OP_NotFound.
5220 ** This opcode is used in IN clause processing for a multi-column key.
5221 ** If an IN clause is attached to an element of the key other than the
5222 ** left-most element, and if there are no matches on the most recent
5223 ** seek over the whole key, then it might be that one of the key element
5224 ** to the left is prohibiting a match, and hence there is "no hope" of
5225 ** any match regardless of how many IN clause elements are checked.
5226 ** In such a case, we abandon the IN clause search early, using this
5227 ** opcode. The opcode name comes from the fact that the
5228 ** jump is taken if there is "no hope" of achieving a match.
5230 ** See also: NotFound, SeekHit
5232 /* Opcode: NoConflict P1 P2 P3 P4 *
5233 ** Synopsis: key=r[P3@P4]
5235 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
5236 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
5237 ** record.
5239 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
5240 ** contains any NULL value, jump immediately to P2. If all terms of the
5241 ** record are not-NULL then a check is done to determine if any row in the
5242 ** P1 index btree has a matching key prefix. If there are no matches, jump
5243 ** immediately to P2. If there is a match, fall through and leave the P1
5244 ** cursor pointing to the matching row.
5246 ** This opcode is similar to OP_NotFound with the exceptions that the
5247 ** branch is always taken if any part of the search key input is NULL.
5249 ** This operation leaves the cursor in a state where it cannot be
5250 ** advanced in either direction. In other words, the Next and Prev
5251 ** opcodes do not work after this operation.
5253 ** See also: NotFound, Found, NotExists
5255 case OP_IfNoHope: { /* jump, in3, ncycle */
5256 VdbeCursor *pC;
5257 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5258 pC = p->apCsr[pOp->p1];
5259 assert( pC!=0 );
5260 #ifdef SQLITE_DEBUG
5261 if( db->flags&SQLITE_VdbeTrace ){
5262 printf("seekHit is %d\n", pC->seekHit);
5264 #endif
5265 if( pC->seekHit>=pOp->p4.i ) break;
5266 /* Fall through into OP_NotFound */
5267 /* no break */ deliberate_fall_through
5269 case OP_NoConflict: /* jump, in3, ncycle */
5270 case OP_NotFound: /* jump, in3, ncycle */
5271 case OP_Found: { /* jump, in3, ncycle */
5272 int alreadyExists;
5273 int ii;
5274 VdbeCursor *pC;
5275 UnpackedRecord *pIdxKey;
5276 UnpackedRecord r;
5278 #ifdef SQLITE_TEST
5279 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
5280 #endif
5282 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5283 assert( pOp->p4type==P4_INT32 );
5284 pC = p->apCsr[pOp->p1];
5285 assert( pC!=0 );
5286 #ifdef SQLITE_DEBUG
5287 pC->seekOp = pOp->opcode;
5288 #endif
5289 r.aMem = &aMem[pOp->p3];
5290 assert( pC->eCurType==CURTYPE_BTREE );
5291 assert( pC->uc.pCursor!=0 );
5292 assert( pC->isTable==0 );
5293 r.nField = (u16)pOp->p4.i;
5294 if( r.nField>0 ){
5295 /* Key values in an array of registers */
5296 r.pKeyInfo = pC->pKeyInfo;
5297 r.default_rc = 0;
5298 #ifdef SQLITE_DEBUG
5299 for(ii=0; ii<r.nField; ii++){
5300 assert( memIsValid(&r.aMem[ii]) );
5301 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
5302 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
5304 #endif
5305 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &pC->seekResult);
5306 }else{
5307 /* Composite key generated by OP_MakeRecord */
5308 assert( r.aMem->flags & MEM_Blob );
5309 assert( pOp->opcode!=OP_NoConflict );
5310 rc = ExpandBlob(r.aMem);
5311 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
5312 if( rc ) goto no_mem;
5313 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
5314 if( pIdxKey==0 ) goto no_mem;
5315 sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);
5316 pIdxKey->default_rc = 0;
5317 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);
5318 sqlite3DbFreeNN(db, pIdxKey);
5320 if( rc!=SQLITE_OK ){
5321 goto abort_due_to_error;
5323 alreadyExists = (pC->seekResult==0);
5324 pC->nullRow = 1-alreadyExists;
5325 pC->deferredMoveto = 0;
5326 pC->cacheStatus = CACHE_STALE;
5327 if( pOp->opcode==OP_Found ){
5328 VdbeBranchTaken(alreadyExists!=0,2);
5329 if( alreadyExists ) goto jump_to_p2;
5330 }else{
5331 if( !alreadyExists ){
5332 VdbeBranchTaken(1,2);
5333 goto jump_to_p2;
5335 if( pOp->opcode==OP_NoConflict ){
5336 /* For the OP_NoConflict opcode, take the jump if any of the
5337 ** input fields are NULL, since any key with a NULL will not
5338 ** conflict */
5339 for(ii=0; ii<r.nField; ii++){
5340 if( r.aMem[ii].flags & MEM_Null ){
5341 VdbeBranchTaken(1,2);
5342 goto jump_to_p2;
5346 VdbeBranchTaken(0,2);
5347 if( pOp->opcode==OP_IfNoHope ){
5348 pC->seekHit = pOp->p4.i;
5351 break;
5354 /* Opcode: SeekRowid P1 P2 P3 * *
5355 ** Synopsis: intkey=r[P3]
5357 ** P1 is the index of a cursor open on an SQL table btree (with integer
5358 ** keys). If register P3 does not contain an integer or if P1 does not
5359 ** contain a record with rowid P3 then jump immediately to P2.
5360 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
5361 ** a record with rowid P3 then
5362 ** leave the cursor pointing at that record and fall through to the next
5363 ** instruction.
5365 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
5366 ** the P3 register must be guaranteed to contain an integer value. With this
5367 ** opcode, register P3 might not contain an integer.
5369 ** The OP_NotFound opcode performs the same operation on index btrees
5370 ** (with arbitrary multi-value keys).
5372 ** This opcode leaves the cursor in a state where it cannot be advanced
5373 ** in either direction. In other words, the Next and Prev opcodes will
5374 ** not work following this opcode.
5376 ** See also: Found, NotFound, NoConflict, SeekRowid
5378 /* Opcode: NotExists P1 P2 P3 * *
5379 ** Synopsis: intkey=r[P3]
5381 ** P1 is the index of a cursor open on an SQL table btree (with integer
5382 ** keys). P3 is an integer rowid. If P1 does not contain a record with
5383 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
5384 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
5385 ** leave the cursor pointing at that record and fall through to the next
5386 ** instruction.
5388 ** The OP_SeekRowid opcode performs the same operation but also allows the
5389 ** P3 register to contain a non-integer value, in which case the jump is
5390 ** always taken. This opcode requires that P3 always contain an integer.
5392 ** The OP_NotFound opcode performs the same operation on index btrees
5393 ** (with arbitrary multi-value keys).
5395 ** This opcode leaves the cursor in a state where it cannot be advanced
5396 ** in either direction. In other words, the Next and Prev opcodes will
5397 ** not work following this opcode.
5399 ** See also: Found, NotFound, NoConflict, SeekRowid
5401 case OP_SeekRowid: { /* jump0, in3, ncycle */
5402 VdbeCursor *pC;
5403 BtCursor *pCrsr;
5404 int res;
5405 u64 iKey;
5407 pIn3 = &aMem[pOp->p3];
5408 testcase( pIn3->flags & MEM_Int );
5409 testcase( pIn3->flags & MEM_IntReal );
5410 testcase( pIn3->flags & MEM_Real );
5411 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
5412 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
5413 /* If pIn3->u.i does not contain an integer, compute iKey as the
5414 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
5415 ** into an integer without loss of information. Take care to avoid
5416 ** changing the datatype of pIn3, however, as it is used by other
5417 ** parts of the prepared statement. */
5418 Mem x = pIn3[0];
5419 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
5420 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
5421 iKey = x.u.i;
5422 goto notExistsWithKey;
5424 /* Fall through into OP_NotExists */
5425 /* no break */ deliberate_fall_through
5426 case OP_NotExists: /* jump, in3, ncycle */
5427 pIn3 = &aMem[pOp->p3];
5428 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
5429 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5430 iKey = pIn3->u.i;
5431 notExistsWithKey:
5432 pC = p->apCsr[pOp->p1];
5433 assert( pC!=0 );
5434 #ifdef SQLITE_DEBUG
5435 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
5436 #endif
5437 assert( pC->isTable );
5438 assert( pC->eCurType==CURTYPE_BTREE );
5439 pCrsr = pC->uc.pCursor;
5440 assert( pCrsr!=0 );
5441 res = 0;
5442 rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
5443 assert( rc==SQLITE_OK || res==0 );
5444 pC->movetoTarget = iKey; /* Used by OP_Delete */
5445 pC->nullRow = 0;
5446 pC->cacheStatus = CACHE_STALE;
5447 pC->deferredMoveto = 0;
5448 VdbeBranchTaken(res!=0,2);
5449 pC->seekResult = res;
5450 if( res!=0 ){
5451 assert( rc==SQLITE_OK );
5452 if( pOp->p2==0 ){
5453 rc = SQLITE_CORRUPT_BKPT;
5454 }else{
5455 goto jump_to_p2;
5458 if( rc ) goto abort_due_to_error;
5459 break;
5462 /* Opcode: Sequence P1 P2 * * *
5463 ** Synopsis: r[P2]=cursor[P1].ctr++
5465 ** Find the next available sequence number for cursor P1.
5466 ** Write the sequence number into register P2.
5467 ** The sequence number on the cursor is incremented after this
5468 ** instruction.
5470 case OP_Sequence: { /* out2 */
5471 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5472 assert( p->apCsr[pOp->p1]!=0 );
5473 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
5474 pOut = out2Prerelease(p, pOp);
5475 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
5476 break;
5480 /* Opcode: NewRowid P1 P2 P3 * *
5481 ** Synopsis: r[P2]=rowid
5483 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
5484 ** The record number is not previously used as a key in the database
5485 ** table that cursor P1 points to. The new record number is written
5486 ** written to register P2.
5488 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
5489 ** the largest previously generated record number. No new record numbers are
5490 ** allowed to be less than this value. When this value reaches its maximum,
5491 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
5492 ** generated record number. This P3 mechanism is used to help implement the
5493 ** AUTOINCREMENT feature.
5495 case OP_NewRowid: { /* out2 */
5496 i64 v; /* The new rowid */
5497 VdbeCursor *pC; /* Cursor of table to get the new rowid */
5498 int res; /* Result of an sqlite3BtreeLast() */
5499 int cnt; /* Counter to limit the number of searches */
5500 #ifndef SQLITE_OMIT_AUTOINCREMENT
5501 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
5502 VdbeFrame *pFrame; /* Root frame of VDBE */
5503 #endif
5505 v = 0;
5506 res = 0;
5507 pOut = out2Prerelease(p, pOp);
5508 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5509 pC = p->apCsr[pOp->p1];
5510 assert( pC!=0 );
5511 assert( pC->isTable );
5512 assert( pC->eCurType==CURTYPE_BTREE );
5513 assert( pC->uc.pCursor!=0 );
5515 /* The next rowid or record number (different terms for the same
5516 ** thing) is obtained in a two-step algorithm.
5518 ** First we attempt to find the largest existing rowid and add one
5519 ** to that. But if the largest existing rowid is already the maximum
5520 ** positive integer, we have to fall through to the second
5521 ** probabilistic algorithm
5523 ** The second algorithm is to select a rowid at random and see if
5524 ** it already exists in the table. If it does not exist, we have
5525 ** succeeded. If the random rowid does exist, we select a new one
5526 ** and try again, up to 100 times.
5528 assert( pC->isTable );
5530 #ifdef SQLITE_32BIT_ROWID
5531 # define MAX_ROWID 0x7fffffff
5532 #else
5533 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
5534 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
5535 ** to provide the constant while making all compilers happy.
5537 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
5538 #endif
5540 if( !pC->useRandomRowid ){
5541 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
5542 if( rc!=SQLITE_OK ){
5543 goto abort_due_to_error;
5545 if( res ){
5546 v = 1; /* IMP: R-61914-48074 */
5547 }else{
5548 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
5549 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5550 if( v>=MAX_ROWID ){
5551 pC->useRandomRowid = 1;
5552 }else{
5553 v++; /* IMP: R-29538-34987 */
5558 #ifndef SQLITE_OMIT_AUTOINCREMENT
5559 if( pOp->p3 ){
5560 /* Assert that P3 is a valid memory cell. */
5561 assert( pOp->p3>0 );
5562 if( p->pFrame ){
5563 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5564 /* Assert that P3 is a valid memory cell. */
5565 assert( pOp->p3<=pFrame->nMem );
5566 pMem = &pFrame->aMem[pOp->p3];
5567 }else{
5568 /* Assert that P3 is a valid memory cell. */
5569 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
5570 pMem = &aMem[pOp->p3];
5571 memAboutToChange(p, pMem);
5573 assert( memIsValid(pMem) );
5575 REGISTER_TRACE(pOp->p3, pMem);
5576 sqlite3VdbeMemIntegerify(pMem);
5577 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
5578 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
5579 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
5580 goto abort_due_to_error;
5582 if( v<pMem->u.i+1 ){
5583 v = pMem->u.i + 1;
5585 pMem->u.i = v;
5587 #endif
5588 if( pC->useRandomRowid ){
5589 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
5590 ** largest possible integer (9223372036854775807) then the database
5591 ** engine starts picking positive candidate ROWIDs at random until
5592 ** it finds one that is not previously used. */
5593 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
5594 ** an AUTOINCREMENT table. */
5595 cnt = 0;
5597 sqlite3_randomness(sizeof(v), &v);
5598 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
5599 }while( ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
5600 0, &res))==SQLITE_OK)
5601 && (res==0)
5602 && (++cnt<100));
5603 if( rc ) goto abort_due_to_error;
5604 if( res==0 ){
5605 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
5606 goto abort_due_to_error;
5608 assert( v>0 ); /* EV: R-40812-03570 */
5610 pC->deferredMoveto = 0;
5611 pC->cacheStatus = CACHE_STALE;
5613 pOut->u.i = v;
5614 break;
5617 /* Opcode: Insert P1 P2 P3 P4 P5
5618 ** Synopsis: intkey=r[P3] data=r[P2]
5620 ** Write an entry into the table of cursor P1. A new entry is
5621 ** created if it doesn't already exist or the data for an existing
5622 ** entry is overwritten. The data is the value MEM_Blob stored in register
5623 ** number P2. The key is stored in register P3. The key must
5624 ** be a MEM_Int.
5626 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5627 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
5628 ** then rowid is stored for subsequent return by the
5629 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5631 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5632 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5633 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5634 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5636 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5637 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
5638 ** is part of an INSERT operation. The difference is only important to
5639 ** the update hook.
5641 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5642 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5643 ** following a successful insert.
5645 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5646 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5647 ** and register P2 becomes ephemeral. If the cursor is changed, the
5648 ** value of register P2 will then change. Make sure this does not
5649 ** cause any problems.)
5651 ** This instruction only works on tables. The equivalent instruction
5652 ** for indices is OP_IdxInsert.
5654 case OP_Insert: {
5655 Mem *pData; /* MEM cell holding data for the record to be inserted */
5656 Mem *pKey; /* MEM cell holding key for the record */
5657 VdbeCursor *pC; /* Cursor to table into which insert is written */
5658 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
5659 const char *zDb; /* database name - used by the update hook */
5660 Table *pTab; /* Table structure - used by update and pre-update hooks */
5661 BtreePayload x; /* Payload to be inserted */
5663 pData = &aMem[pOp->p2];
5664 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5665 assert( memIsValid(pData) );
5666 pC = p->apCsr[pOp->p1];
5667 assert( pC!=0 );
5668 assert( pC->eCurType==CURTYPE_BTREE );
5669 assert( pC->deferredMoveto==0 );
5670 assert( pC->uc.pCursor!=0 );
5671 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5672 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5673 REGISTER_TRACE(pOp->p2, pData);
5674 sqlite3VdbeIncrWriteCounter(p, pC);
5676 pKey = &aMem[pOp->p3];
5677 assert( pKey->flags & MEM_Int );
5678 assert( memIsValid(pKey) );
5679 REGISTER_TRACE(pOp->p3, pKey);
5680 x.nKey = pKey->u.i;
5682 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5683 assert( pC->iDb>=0 );
5684 zDb = db->aDb[pC->iDb].zDbSName;
5685 pTab = pOp->p4.pTab;
5686 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5687 }else{
5688 pTab = 0;
5689 zDb = 0;
5692 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5693 /* Invoke the pre-update hook, if any */
5694 if( pTab ){
5695 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5696 sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
5698 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5699 /* Prevent post-update hook from running in cases when it should not */
5700 pTab = 0;
5703 if( pOp->p5 & OPFLAG_ISNOOP ) break;
5704 #endif
5706 assert( (pOp->p5 & OPFLAG_LASTROWID)==0 || (pOp->p5 & OPFLAG_NCHANGE)!=0 );
5707 if( pOp->p5 & OPFLAG_NCHANGE ){
5708 p->nChange++;
5709 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5711 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5712 x.pData = pData->z;
5713 x.nData = pData->n;
5714 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5715 if( pData->flags & MEM_Zero ){
5716 x.nZero = pData->u.nZero;
5717 }else{
5718 x.nZero = 0;
5720 x.pKey = 0;
5721 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
5722 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5723 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5724 seekResult
5726 pC->deferredMoveto = 0;
5727 pC->cacheStatus = CACHE_STALE;
5728 colCacheCtr++;
5730 /* Invoke the update-hook if required. */
5731 if( rc ) goto abort_due_to_error;
5732 if( pTab ){
5733 assert( db->xUpdateCallback!=0 );
5734 assert( pTab->aCol!=0 );
5735 db->xUpdateCallback(db->pUpdateArg,
5736 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5737 zDb, pTab->zName, x.nKey);
5739 break;
5742 /* Opcode: RowCell P1 P2 P3 * *
5744 ** P1 and P2 are both open cursors. Both must be opened on the same type
5745 ** of table - intkey or index. This opcode is used as part of copying
5746 ** the current row from P2 into P1. If the cursors are opened on intkey
5747 ** tables, register P3 contains the rowid to use with the new record in
5748 ** P1. If they are opened on index tables, P3 is not used.
5750 ** This opcode must be followed by either an Insert or InsertIdx opcode
5751 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
5753 case OP_RowCell: {
5754 VdbeCursor *pDest; /* Cursor to write to */
5755 VdbeCursor *pSrc; /* Cursor to read from */
5756 i64 iKey; /* Rowid value to insert with */
5757 assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
5758 assert( pOp[1].opcode==OP_Insert || pOp->p3==0 );
5759 assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
5760 assert( pOp[1].p5 & OPFLAG_PREFORMAT );
5761 pDest = p->apCsr[pOp->p1];
5762 pSrc = p->apCsr[pOp->p2];
5763 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
5764 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
5765 if( rc!=SQLITE_OK ) goto abort_due_to_error;
5766 break;
5769 /* Opcode: Delete P1 P2 P3 P4 P5
5771 ** Delete the record at which the P1 cursor is currently pointing.
5773 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5774 ** the cursor will be left pointing at either the next or the previous
5775 ** record in the table. If it is left pointing at the next record, then
5776 ** the next Next instruction will be a no-op. As a result, in this case
5777 ** it is ok to delete a record from within a Next loop. If
5778 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5779 ** left in an undefined state.
5781 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5782 ** delete is one of several associated with deleting a table row and
5783 ** all its associated index entries. Exactly one of those deletes is
5784 ** the "primary" delete. The others are all on OPFLAG_FORDELETE
5785 ** cursors or else are marked with the AUXDELETE flag.
5787 ** If the OPFLAG_NCHANGE (0x01) flag of P2 (NB: P2 not P5) is set, then
5788 ** the row change count is incremented (otherwise not).
5790 ** If the OPFLAG_ISNOOP (0x40) flag of P2 (not P5!) is set, then the
5791 ** pre-update-hook for deletes is run, but the btree is otherwise unchanged.
5792 ** This happens when the OP_Delete is to be shortly followed by an OP_Insert
5793 ** with the same key, causing the btree entry to be overwritten.
5795 ** P1 must not be pseudo-table. It has to be a real table with
5796 ** multiple rows.
5798 ** If P4 is not NULL then it points to a Table object. In this case either
5799 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5800 ** have been positioned using OP_NotFound prior to invoking this opcode in
5801 ** this case. Specifically, if one is configured, the pre-update hook is
5802 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5803 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5805 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5806 ** of the memory cell that contains the value that the rowid of the row will
5807 ** be set to by the update.
5809 case OP_Delete: {
5810 VdbeCursor *pC;
5811 const char *zDb;
5812 Table *pTab;
5813 int opflags;
5815 opflags = pOp->p2;
5816 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5817 pC = p->apCsr[pOp->p1];
5818 assert( pC!=0 );
5819 assert( pC->eCurType==CURTYPE_BTREE );
5820 assert( pC->uc.pCursor!=0 );
5821 assert( pC->deferredMoveto==0 );
5822 sqlite3VdbeIncrWriteCounter(p, pC);
5824 #ifdef SQLITE_DEBUG
5825 if( pOp->p4type==P4_TABLE
5826 && HasRowid(pOp->p4.pTab)
5827 && pOp->p5==0
5828 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5830 /* If p5 is zero, the seek operation that positioned the cursor prior to
5831 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5832 ** the row that is being deleted */
5833 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5834 assert( CORRUPT_DB || pC->movetoTarget==iKey );
5836 #endif
5838 /* If the update-hook or pre-update-hook will be invoked, set zDb to
5839 ** the name of the db to pass as to it. Also set local pTab to a copy
5840 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5841 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5842 ** VdbeCursor.movetoTarget to the current rowid. */
5843 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5844 assert( pC->iDb>=0 );
5845 assert( pOp->p4.pTab!=0 );
5846 zDb = db->aDb[pC->iDb].zDbSName;
5847 pTab = pOp->p4.pTab;
5848 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5849 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5851 }else{
5852 zDb = 0;
5853 pTab = 0;
5856 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5857 /* Invoke the pre-update-hook if required. */
5858 assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
5859 if( db->xPreUpdateCallback && pTab ){
5860 assert( !(opflags & OPFLAG_ISUPDATE)
5861 || HasRowid(pTab)==0
5862 || (aMem[pOp->p3].flags & MEM_Int)
5864 sqlite3VdbePreUpdateHook(p, pC,
5865 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5866 zDb, pTab, pC->movetoTarget,
5867 pOp->p3, -1
5870 if( opflags & OPFLAG_ISNOOP ) break;
5871 #endif
5873 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5874 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5875 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5876 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5878 #ifdef SQLITE_DEBUG
5879 if( p->pFrame==0 ){
5880 if( pC->isEphemeral==0
5881 && (pOp->p5 & OPFLAG_AUXDELETE)==0
5882 && (pC->wrFlag & OPFLAG_FORDELETE)==0
5884 nExtraDelete++;
5886 if( pOp->p2 & OPFLAG_NCHANGE ){
5887 nExtraDelete--;
5890 #endif
5892 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5893 pC->cacheStatus = CACHE_STALE;
5894 colCacheCtr++;
5895 pC->seekResult = 0;
5896 if( rc ) goto abort_due_to_error;
5898 /* Invoke the update-hook if required. */
5899 if( opflags & OPFLAG_NCHANGE ){
5900 p->nChange++;
5901 if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
5902 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5903 pC->movetoTarget);
5904 assert( pC->iDb>=0 );
5908 break;
5910 /* Opcode: ResetCount * * * * *
5912 ** The value of the change counter is copied to the database handle
5913 ** change counter (returned by subsequent calls to sqlite3_changes()).
5914 ** Then the VMs internal change counter resets to 0.
5915 ** This is used by trigger programs.
5917 case OP_ResetCount: {
5918 sqlite3VdbeSetChanges(db, p->nChange);
5919 p->nChange = 0;
5920 break;
5923 /* Opcode: SorterCompare P1 P2 P3 P4
5924 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5926 ** P1 is a sorter cursor. This instruction compares a prefix of the
5927 ** record blob in register P3 against a prefix of the entry that
5928 ** the sorter cursor currently points to. Only the first P4 fields
5929 ** of r[P3] and the sorter record are compared.
5931 ** If either P3 or the sorter contains a NULL in one of their significant
5932 ** fields (not counting the P4 fields at the end which are ignored) then
5933 ** the comparison is assumed to be equal.
5935 ** Fall through to next instruction if the two records compare equal to
5936 ** each other. Jump to P2 if they are different.
5938 case OP_SorterCompare: {
5939 VdbeCursor *pC;
5940 int res;
5941 int nKeyCol;
5943 pC = p->apCsr[pOp->p1];
5944 assert( isSorter(pC) );
5945 assert( pOp->p4type==P4_INT32 );
5946 pIn3 = &aMem[pOp->p3];
5947 nKeyCol = pOp->p4.i;
5948 res = 0;
5949 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5950 VdbeBranchTaken(res!=0,2);
5951 if( rc ) goto abort_due_to_error;
5952 if( res ) goto jump_to_p2;
5953 break;
5956 /* Opcode: SorterData P1 P2 P3 * *
5957 ** Synopsis: r[P2]=data
5959 ** Write into register P2 the current sorter data for sorter cursor P1.
5960 ** Then clear the column header cache on cursor P3.
5962 ** This opcode is normally used to move a record out of the sorter and into
5963 ** a register that is the source for a pseudo-table cursor created using
5964 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
5965 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
5966 ** us from having to issue a separate NullRow instruction to clear that cache.
5968 case OP_SorterData: { /* ncycle */
5969 VdbeCursor *pC;
5971 pOut = &aMem[pOp->p2];
5972 pC = p->apCsr[pOp->p1];
5973 assert( isSorter(pC) );
5974 rc = sqlite3VdbeSorterRowkey(pC, pOut);
5975 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5976 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5977 if( rc ) goto abort_due_to_error;
5978 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5979 break;
5982 /* Opcode: RowData P1 P2 P3 * *
5983 ** Synopsis: r[P2]=data
5985 ** Write into register P2 the complete row content for the row at
5986 ** which cursor P1 is currently pointing.
5987 ** There is no interpretation of the data.
5988 ** It is just copied onto the P2 register exactly as
5989 ** it is found in the database file.
5991 ** If cursor P1 is an index, then the content is the key of the row.
5992 ** If cursor P2 is a table, then the content extracted is the data.
5994 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5995 ** of a real table, not a pseudo-table.
5997 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5998 ** into the database page. That means that the content of the output
5999 ** register will be invalidated as soon as the cursor moves - including
6000 ** moves caused by other cursors that "save" the current cursors
6001 ** position in order that they can write to the same table. If P3==0
6002 ** then a copy of the data is made into memory. P3!=0 is faster, but
6003 ** P3==0 is safer.
6005 ** If P3!=0 then the content of the P2 register is unsuitable for use
6006 ** in OP_Result and any OP_Result will invalidate the P2 register content.
6007 ** The P2 register content is invalidated by opcodes like OP_Function or
6008 ** by any use of another cursor pointing to the same table.
6010 case OP_RowData: {
6011 VdbeCursor *pC;
6012 BtCursor *pCrsr;
6013 u32 n;
6015 pOut = out2Prerelease(p, pOp);
6017 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6018 pC = p->apCsr[pOp->p1];
6019 assert( pC!=0 );
6020 assert( pC->eCurType==CURTYPE_BTREE );
6021 assert( isSorter(pC)==0 );
6022 assert( pC->nullRow==0 );
6023 assert( pC->uc.pCursor!=0 );
6024 pCrsr = pC->uc.pCursor;
6026 /* The OP_RowData opcodes always follow OP_NotExists or
6027 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
6028 ** that might invalidate the cursor.
6029 ** If this where not the case, on of the following assert()s
6030 ** would fail. Should this ever change (because of changes in the code
6031 ** generator) then the fix would be to insert a call to
6032 ** sqlite3VdbeCursorMoveto().
6034 assert( pC->deferredMoveto==0 );
6035 assert( sqlite3BtreeCursorIsValid(pCrsr) );
6037 n = sqlite3BtreePayloadSize(pCrsr);
6038 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
6039 goto too_big;
6041 testcase( n==0 );
6042 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
6043 if( rc ) goto abort_due_to_error;
6044 if( !pOp->p3 ) Deephemeralize(pOut);
6045 UPDATE_MAX_BLOBSIZE(pOut);
6046 REGISTER_TRACE(pOp->p2, pOut);
6047 break;
6050 /* Opcode: Rowid P1 P2 * * *
6051 ** Synopsis: r[P2]=PX rowid of P1
6053 ** Store in register P2 an integer which is the key of the table entry that
6054 ** P1 is currently point to.
6056 ** P1 can be either an ordinary table or a virtual table. There used to
6057 ** be a separate OP_VRowid opcode for use with virtual tables, but this
6058 ** one opcode now works for both table types.
6060 case OP_Rowid: { /* out2, ncycle */
6061 VdbeCursor *pC;
6062 i64 v;
6063 sqlite3_vtab *pVtab;
6064 const sqlite3_module *pModule;
6066 pOut = out2Prerelease(p, pOp);
6067 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6068 pC = p->apCsr[pOp->p1];
6069 assert( pC!=0 );
6070 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
6071 if( pC->nullRow ){
6072 pOut->flags = MEM_Null;
6073 break;
6074 }else if( pC->deferredMoveto ){
6075 v = pC->movetoTarget;
6076 #ifndef SQLITE_OMIT_VIRTUALTABLE
6077 }else if( pC->eCurType==CURTYPE_VTAB ){
6078 assert( pC->uc.pVCur!=0 );
6079 pVtab = pC->uc.pVCur->pVtab;
6080 pModule = pVtab->pModule;
6081 assert( pModule->xRowid );
6082 rc = pModule->xRowid(pC->uc.pVCur, &v);
6083 sqlite3VtabImportErrmsg(p, pVtab);
6084 if( rc ) goto abort_due_to_error;
6085 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6086 }else{
6087 assert( pC->eCurType==CURTYPE_BTREE );
6088 assert( pC->uc.pCursor!=0 );
6089 rc = sqlite3VdbeCursorRestore(pC);
6090 if( rc ) goto abort_due_to_error;
6091 if( pC->nullRow ){
6092 pOut->flags = MEM_Null;
6093 break;
6095 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
6097 pOut->u.i = v;
6098 break;
6101 /* Opcode: NullRow P1 * * * *
6103 ** Move the cursor P1 to a null row. Any OP_Column operations
6104 ** that occur while the cursor is on the null row will always
6105 ** write a NULL.
6107 ** If cursor P1 is not previously opened, open it now to a special
6108 ** pseudo-cursor that always returns NULL for every column.
6110 case OP_NullRow: {
6111 VdbeCursor *pC;
6113 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6114 pC = p->apCsr[pOp->p1];
6115 if( pC==0 ){
6116 /* If the cursor is not already open, create a special kind of
6117 ** pseudo-cursor that always gives null rows. */
6118 pC = allocateCursor(p, pOp->p1, 1, CURTYPE_PSEUDO);
6119 if( pC==0 ) goto no_mem;
6120 pC->seekResult = 0;
6121 pC->isTable = 1;
6122 pC->noReuse = 1;
6123 pC->uc.pCursor = sqlite3BtreeFakeValidCursor();
6125 pC->nullRow = 1;
6126 pC->cacheStatus = CACHE_STALE;
6127 if( pC->eCurType==CURTYPE_BTREE ){
6128 assert( pC->uc.pCursor!=0 );
6129 sqlite3BtreeClearCursor(pC->uc.pCursor);
6131 #ifdef SQLITE_DEBUG
6132 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
6133 #endif
6134 break;
6137 /* Opcode: SeekEnd P1 * * * *
6139 ** Position cursor P1 at the end of the btree for the purpose of
6140 ** appending a new entry onto the btree.
6142 ** It is assumed that the cursor is used only for appending and so
6143 ** if the cursor is valid, then the cursor must already be pointing
6144 ** at the end of the btree and so no changes are made to
6145 ** the cursor.
6147 /* Opcode: Last P1 P2 * * *
6149 ** The next use of the Rowid or Column or Prev instruction for P1
6150 ** will refer to the last entry in the database table or index.
6151 ** If the table or index is empty and P2>0, then jump immediately to P2.
6152 ** If P2 is 0 or if the table or index is not empty, fall through
6153 ** to the following instruction.
6155 ** This opcode leaves the cursor configured to move in reverse order,
6156 ** from the end toward the beginning. In other words, the cursor is
6157 ** configured to use Prev, not Next.
6159 case OP_SeekEnd: /* ncycle */
6160 case OP_Last: { /* jump0, ncycle */
6161 VdbeCursor *pC;
6162 BtCursor *pCrsr;
6163 int res;
6165 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6166 pC = p->apCsr[pOp->p1];
6167 assert( pC!=0 );
6168 assert( pC->eCurType==CURTYPE_BTREE );
6169 pCrsr = pC->uc.pCursor;
6170 res = 0;
6171 assert( pCrsr!=0 );
6172 #ifdef SQLITE_DEBUG
6173 pC->seekOp = pOp->opcode;
6174 #endif
6175 if( pOp->opcode==OP_SeekEnd ){
6176 assert( pOp->p2==0 );
6177 pC->seekResult = -1;
6178 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
6179 break;
6182 rc = sqlite3BtreeLast(pCrsr, &res);
6183 pC->nullRow = (u8)res;
6184 pC->deferredMoveto = 0;
6185 pC->cacheStatus = CACHE_STALE;
6186 if( rc ) goto abort_due_to_error;
6187 if( pOp->p2>0 ){
6188 VdbeBranchTaken(res!=0,2);
6189 if( res ) goto jump_to_p2;
6191 break;
6194 /* Opcode: IfSizeBetween P1 P2 P3 P4 *
6196 ** Let N be the approximate number of rows in the table or index
6197 ** with cursor P1 and let X be 10*log2(N) if N is positive or -1
6198 ** if N is zero.
6200 ** Jump to P2 if X is in between P3 and P4, inclusive.
6202 case OP_IfSizeBetween: { /* jump */
6203 VdbeCursor *pC;
6204 BtCursor *pCrsr;
6205 int res;
6206 i64 sz;
6208 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6209 assert( pOp->p4type==P4_INT32 );
6210 assert( pOp->p3>=-1 && pOp->p3<=640*2 );
6211 assert( pOp->p4.i>=-1 && pOp->p4.i<=640*2 );
6212 pC = p->apCsr[pOp->p1];
6213 assert( pC!=0 );
6214 pCrsr = pC->uc.pCursor;
6215 assert( pCrsr );
6216 rc = sqlite3BtreeFirst(pCrsr, &res);
6217 if( rc ) goto abort_due_to_error;
6218 if( res!=0 ){
6219 sz = -1; /* -Infinity encoding */
6220 }else{
6221 sz = sqlite3BtreeRowCountEst(pCrsr);
6222 assert( sz>0 );
6223 sz = sqlite3LogEst((u64)sz);
6225 res = sz>=pOp->p3 && sz<=pOp->p4.i;
6226 VdbeBranchTaken(res!=0,2);
6227 if( res ) goto jump_to_p2;
6228 break;
6232 /* Opcode: SorterSort P1 P2 * * *
6234 ** After all records have been inserted into the Sorter object
6235 ** identified by P1, invoke this opcode to actually do the sorting.
6236 ** Jump to P2 if there are no records to be sorted.
6238 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
6239 ** for Sorter objects.
6241 /* Opcode: Sort P1 P2 * * *
6243 ** This opcode does exactly the same thing as OP_Rewind except that
6244 ** it increments an undocumented global variable used for testing.
6246 ** Sorting is accomplished by writing records into a sorting index,
6247 ** then rewinding that index and playing it back from beginning to
6248 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
6249 ** rewinding so that the global variable will be incremented and
6250 ** regression tests can determine whether or not the optimizer is
6251 ** correctly optimizing out sorts.
6253 case OP_SorterSort: /* jump ncycle */
6254 case OP_Sort: { /* jump ncycle */
6255 #ifdef SQLITE_TEST
6256 sqlite3_sort_count++;
6257 sqlite3_search_count--;
6258 #endif
6259 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
6260 /* Fall through into OP_Rewind */
6261 /* no break */ deliberate_fall_through
6263 /* Opcode: Rewind P1 P2 * * *
6265 ** The next use of the Rowid or Column or Next instruction for P1
6266 ** will refer to the first entry in the database table or index.
6267 ** If the table or index is empty, jump immediately to P2.
6268 ** If the table or index is not empty, fall through to the following
6269 ** instruction.
6271 ** If P2 is zero, that is an assertion that the P1 table is never
6272 ** empty and hence the jump will never be taken.
6274 ** This opcode leaves the cursor configured to move in forward order,
6275 ** from the beginning toward the end. In other words, the cursor is
6276 ** configured to use Next, not Prev.
6278 case OP_Rewind: { /* jump0, ncycle */
6279 VdbeCursor *pC;
6280 BtCursor *pCrsr;
6281 int res;
6283 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6284 assert( pOp->p5==0 );
6285 assert( pOp->p2>=0 && pOp->p2<p->nOp );
6287 pC = p->apCsr[pOp->p1];
6288 assert( pC!=0 );
6289 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
6290 res = 1;
6291 #ifdef SQLITE_DEBUG
6292 pC->seekOp = OP_Rewind;
6293 #endif
6294 if( isSorter(pC) ){
6295 rc = sqlite3VdbeSorterRewind(pC, &res);
6296 }else{
6297 assert( pC->eCurType==CURTYPE_BTREE );
6298 pCrsr = pC->uc.pCursor;
6299 assert( pCrsr );
6300 rc = sqlite3BtreeFirst(pCrsr, &res);
6301 pC->deferredMoveto = 0;
6302 pC->cacheStatus = CACHE_STALE;
6304 if( rc ) goto abort_due_to_error;
6305 pC->nullRow = (u8)res;
6306 if( pOp->p2>0 ){
6307 VdbeBranchTaken(res!=0,2);
6308 if( res ) goto jump_to_p2;
6310 break;
6313 /* Opcode: Next P1 P2 P3 * P5
6315 ** Advance cursor P1 so that it points to the next key/data pair in its
6316 ** table or index. If there are no more key/value pairs then fall through
6317 ** to the following instruction. But if the cursor advance was successful,
6318 ** jump immediately to P2.
6320 ** The Next opcode is only valid following an SeekGT, SeekGE, or
6321 ** OP_Rewind opcode used to position the cursor. Next is not allowed
6322 ** to follow SeekLT, SeekLE, or OP_Last.
6324 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
6325 ** been opened prior to this opcode or the program will segfault.
6327 ** The P3 value is a hint to the btree implementation. If P3==1, that
6328 ** means P1 is an SQL index and that this instruction could have been
6329 ** omitted if that index had been unique. P3 is usually 0. P3 is
6330 ** always either 0 or 1.
6332 ** If P5 is positive and the jump is taken, then event counter
6333 ** number P5-1 in the prepared statement is incremented.
6335 ** See also: Prev
6337 /* Opcode: Prev P1 P2 P3 * P5
6339 ** Back up cursor P1 so that it points to the previous key/data pair in its
6340 ** table or index. If there is no previous key/value pairs then fall through
6341 ** to the following instruction. But if the cursor backup was successful,
6342 ** jump immediately to P2.
6345 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
6346 ** OP_Last opcode used to position the cursor. Prev is not allowed
6347 ** to follow SeekGT, SeekGE, or OP_Rewind.
6349 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
6350 ** not open then the behavior is undefined.
6352 ** The P3 value is a hint to the btree implementation. If P3==1, that
6353 ** means P1 is an SQL index and that this instruction could have been
6354 ** omitted if that index had been unique. P3 is usually 0. P3 is
6355 ** always either 0 or 1.
6357 ** If P5 is positive and the jump is taken, then event counter
6358 ** number P5-1 in the prepared statement is incremented.
6360 /* Opcode: SorterNext P1 P2 * * P5
6362 ** This opcode works just like OP_Next except that P1 must be a
6363 ** sorter object for which the OP_SorterSort opcode has been
6364 ** invoked. This opcode advances the cursor to the next sorted
6365 ** record, or jumps to P2 if there are no more sorted records.
6367 case OP_SorterNext: { /* jump */
6368 VdbeCursor *pC;
6370 pC = p->apCsr[pOp->p1];
6371 assert( isSorter(pC) );
6372 rc = sqlite3VdbeSorterNext(db, pC);
6373 goto next_tail;
6375 case OP_Prev: /* jump, ncycle */
6376 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6377 assert( pOp->p5==0
6378 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6379 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6380 pC = p->apCsr[pOp->p1];
6381 assert( pC!=0 );
6382 assert( pC->deferredMoveto==0 );
6383 assert( pC->eCurType==CURTYPE_BTREE );
6384 assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
6385 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
6386 || pC->seekOp==OP_NullRow);
6387 rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
6388 goto next_tail;
6390 case OP_Next: /* jump, ncycle */
6391 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6392 assert( pOp->p5==0
6393 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
6394 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
6395 pC = p->apCsr[pOp->p1];
6396 assert( pC!=0 );
6397 assert( pC->deferredMoveto==0 );
6398 assert( pC->eCurType==CURTYPE_BTREE );
6399 assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
6400 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
6401 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
6402 || pC->seekOp==OP_IfNoHope);
6403 rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
6405 next_tail:
6406 pC->cacheStatus = CACHE_STALE;
6407 VdbeBranchTaken(rc==SQLITE_OK,2);
6408 if( rc==SQLITE_OK ){
6409 pC->nullRow = 0;
6410 p->aCounter[pOp->p5]++;
6411 #ifdef SQLITE_TEST
6412 sqlite3_search_count++;
6413 #endif
6414 goto jump_to_p2_and_check_for_interrupt;
6416 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6417 rc = SQLITE_OK;
6418 pC->nullRow = 1;
6419 goto check_for_interrupt;
6422 /* Opcode: IdxInsert P1 P2 P3 P4 P5
6423 ** Synopsis: key=r[P2]
6425 ** Register P2 holds an SQL index key made using the
6426 ** MakeRecord instructions. This opcode writes that key
6427 ** into the index P1. Data for the entry is nil.
6429 ** If P4 is not zero, then it is the number of values in the unpacked
6430 ** key of reg(P2). In that case, P3 is the index of the first register
6431 ** for the unpacked key. The availability of the unpacked key can sometimes
6432 ** be an optimization.
6434 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
6435 ** that this insert is likely to be an append.
6437 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
6438 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
6439 ** then the change counter is unchanged.
6441 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
6442 ** run faster by avoiding an unnecessary seek on cursor P1. However,
6443 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
6444 ** seeks on the cursor or if the most recent seek used a key equivalent
6445 ** to P2.
6447 ** This instruction only works for indices. The equivalent instruction
6448 ** for tables is OP_Insert.
6450 case OP_IdxInsert: { /* in2 */
6451 VdbeCursor *pC;
6452 BtreePayload x;
6454 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6455 pC = p->apCsr[pOp->p1];
6456 sqlite3VdbeIncrWriteCounter(p, pC);
6457 assert( pC!=0 );
6458 assert( !isSorter(pC) );
6459 pIn2 = &aMem[pOp->p2];
6460 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
6461 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
6462 assert( pC->eCurType==CURTYPE_BTREE );
6463 assert( pC->isTable==0 );
6464 rc = ExpandBlob(pIn2);
6465 if( rc ) goto abort_due_to_error;
6466 x.nKey = pIn2->n;
6467 x.pKey = pIn2->z;
6468 x.aMem = aMem + pOp->p3;
6469 x.nMem = (u16)pOp->p4.i;
6470 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
6471 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
6472 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
6474 assert( pC->deferredMoveto==0 );
6475 pC->cacheStatus = CACHE_STALE;
6476 if( rc) goto abort_due_to_error;
6477 break;
6480 /* Opcode: SorterInsert P1 P2 * * *
6481 ** Synopsis: key=r[P2]
6483 ** Register P2 holds an SQL index key made using the
6484 ** MakeRecord instructions. This opcode writes that key
6485 ** into the sorter P1. Data for the entry is nil.
6487 case OP_SorterInsert: { /* in2 */
6488 VdbeCursor *pC;
6490 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6491 pC = p->apCsr[pOp->p1];
6492 sqlite3VdbeIncrWriteCounter(p, pC);
6493 assert( pC!=0 );
6494 assert( isSorter(pC) );
6495 pIn2 = &aMem[pOp->p2];
6496 assert( pIn2->flags & MEM_Blob );
6497 assert( pC->isTable==0 );
6498 rc = ExpandBlob(pIn2);
6499 if( rc ) goto abort_due_to_error;
6500 rc = sqlite3VdbeSorterWrite(pC, pIn2);
6501 if( rc) goto abort_due_to_error;
6502 break;
6505 /* Opcode: IdxDelete P1 P2 P3 * P5
6506 ** Synopsis: key=r[P2@P3]
6508 ** The content of P3 registers starting at register P2 form
6509 ** an unpacked index key. This opcode removes that entry from the
6510 ** index opened by cursor P1.
6512 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
6513 ** if no matching index entry is found. This happens when running
6514 ** an UPDATE or DELETE statement and the index entry to be updated
6515 ** or deleted is not found. For some uses of IdxDelete
6516 ** (example: the EXCEPT operator) it does not matter that no matching
6517 ** entry is found. For those cases, P5 is zero. Also, do not raise
6518 ** this (self-correcting and non-critical) error if in writable_schema mode.
6520 case OP_IdxDelete: {
6521 VdbeCursor *pC;
6522 BtCursor *pCrsr;
6523 int res;
6524 UnpackedRecord r;
6526 assert( pOp->p3>0 );
6527 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
6528 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6529 pC = p->apCsr[pOp->p1];
6530 assert( pC!=0 );
6531 assert( pC->eCurType==CURTYPE_BTREE );
6532 sqlite3VdbeIncrWriteCounter(p, pC);
6533 pCrsr = pC->uc.pCursor;
6534 assert( pCrsr!=0 );
6535 r.pKeyInfo = pC->pKeyInfo;
6536 r.nField = (u16)pOp->p3;
6537 r.default_rc = 0;
6538 r.aMem = &aMem[pOp->p2];
6539 rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
6540 if( rc ) goto abort_due_to_error;
6541 if( res==0 ){
6542 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
6543 if( rc ) goto abort_due_to_error;
6544 }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
6545 rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
6546 goto abort_due_to_error;
6548 assert( pC->deferredMoveto==0 );
6549 pC->cacheStatus = CACHE_STALE;
6550 pC->seekResult = 0;
6551 break;
6554 /* Opcode: DeferredSeek P1 * P3 P4 *
6555 ** Synopsis: Move P3 to P1.rowid if needed
6557 ** P1 is an open index cursor and P3 is a cursor on the corresponding
6558 ** table. This opcode does a deferred seek of the P3 table cursor
6559 ** to the row that corresponds to the current row of P1.
6561 ** This is a deferred seek. Nothing actually happens until
6562 ** the cursor is used to read a record. That way, if no reads
6563 ** occur, no unnecessary I/O happens.
6565 ** P4 may be an array of integers (type P4_INTARRAY) containing
6566 ** one entry for each column in the P3 table. If array entry a(i)
6567 ** is non-zero, then reading column a(i)-1 from cursor P3 is
6568 ** equivalent to performing the deferred seek and then reading column i
6569 ** from P1. This information is stored in P3 and used to redirect
6570 ** reads against P3 over to P1, thus possibly avoiding the need to
6571 ** seek and read cursor P3.
6573 /* Opcode: IdxRowid P1 P2 * * *
6574 ** Synopsis: r[P2]=rowid
6576 ** Write into register P2 an integer which is the last entry in the record at
6577 ** the end of the index key pointed to by cursor P1. This integer should be
6578 ** the rowid of the table entry to which this index entry points.
6580 ** See also: Rowid, MakeRecord.
6582 case OP_DeferredSeek: /* ncycle */
6583 case OP_IdxRowid: { /* out2, ncycle */
6584 VdbeCursor *pC; /* The P1 index cursor */
6585 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
6586 i64 rowid; /* Rowid that P1 current points to */
6588 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6589 pC = p->apCsr[pOp->p1];
6590 assert( pC!=0 );
6591 assert( pC->eCurType==CURTYPE_BTREE || IsNullCursor(pC) );
6592 assert( pC->uc.pCursor!=0 );
6593 assert( pC->isTable==0 || IsNullCursor(pC) );
6594 assert( pC->deferredMoveto==0 );
6595 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
6597 /* The IdxRowid and Seek opcodes are combined because of the commonality
6598 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
6599 rc = sqlite3VdbeCursorRestore(pC);
6601 /* sqlite3VdbeCursorRestore() may fail if the cursor has been disturbed
6602 ** since it was last positioned and an error (e.g. OOM or an IO error)
6603 ** occurs while trying to reposition it. */
6604 if( rc!=SQLITE_OK ) goto abort_due_to_error;
6606 if( !pC->nullRow ){
6607 rowid = 0; /* Not needed. Only used to silence a warning. */
6608 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
6609 if( rc!=SQLITE_OK ){
6610 goto abort_due_to_error;
6612 if( pOp->opcode==OP_DeferredSeek ){
6613 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
6614 pTabCur = p->apCsr[pOp->p3];
6615 assert( pTabCur!=0 );
6616 assert( pTabCur->eCurType==CURTYPE_BTREE );
6617 assert( pTabCur->uc.pCursor!=0 );
6618 assert( pTabCur->isTable );
6619 pTabCur->nullRow = 0;
6620 pTabCur->movetoTarget = rowid;
6621 pTabCur->deferredMoveto = 1;
6622 pTabCur->cacheStatus = CACHE_STALE;
6623 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
6624 assert( !pTabCur->isEphemeral );
6625 pTabCur->ub.aAltMap = pOp->p4.ai;
6626 assert( !pC->isEphemeral );
6627 pTabCur->pAltCursor = pC;
6628 }else{
6629 pOut = out2Prerelease(p, pOp);
6630 pOut->u.i = rowid;
6632 }else{
6633 assert( pOp->opcode==OP_IdxRowid );
6634 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
6636 break;
6639 /* Opcode: FinishSeek P1 * * * *
6641 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
6642 ** seek operation now, without further delay. If the cursor seek has
6643 ** already occurred, this instruction is a no-op.
6645 case OP_FinishSeek: { /* ncycle */
6646 VdbeCursor *pC; /* The P1 index cursor */
6648 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6649 pC = p->apCsr[pOp->p1];
6650 if( pC->deferredMoveto ){
6651 rc = sqlite3VdbeFinishMoveto(pC);
6652 if( rc ) goto abort_due_to_error;
6654 break;
6657 /* Opcode: IdxGE P1 P2 P3 P4 *
6658 ** Synopsis: key=r[P3@P4]
6660 ** The P4 register values beginning with P3 form an unpacked index
6661 ** key that omits the PRIMARY KEY. Compare this key value against the index
6662 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6663 ** fields at the end.
6665 ** If the P1 index entry is greater than or equal to the key value
6666 ** then jump to P2. Otherwise fall through to the next instruction.
6668 /* Opcode: IdxGT P1 P2 P3 P4 *
6669 ** Synopsis: key=r[P3@P4]
6671 ** The P4 register values beginning with P3 form an unpacked index
6672 ** key that omits the PRIMARY KEY. Compare this key value against the index
6673 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6674 ** fields at the end.
6676 ** If the P1 index entry is greater than the key value
6677 ** then jump to P2. Otherwise fall through to the next instruction.
6679 /* Opcode: IdxLT P1 P2 P3 P4 *
6680 ** Synopsis: key=r[P3@P4]
6682 ** The P4 register values beginning with P3 form an unpacked index
6683 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6684 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6685 ** ROWID on the P1 index.
6687 ** If the P1 index entry is less than the key value then jump to P2.
6688 ** Otherwise fall through to the next instruction.
6690 /* Opcode: IdxLE P1 P2 P3 P4 *
6691 ** Synopsis: key=r[P3@P4]
6693 ** The P4 register values beginning with P3 form an unpacked index
6694 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6695 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6696 ** ROWID on the P1 index.
6698 ** If the P1 index entry is less than or equal to the key value then jump
6699 ** to P2. Otherwise fall through to the next instruction.
6701 case OP_IdxLE: /* jump, ncycle */
6702 case OP_IdxGT: /* jump, ncycle */
6703 case OP_IdxLT: /* jump, ncycle */
6704 case OP_IdxGE: { /* jump, ncycle */
6705 VdbeCursor *pC;
6706 int res;
6707 UnpackedRecord r;
6709 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6710 pC = p->apCsr[pOp->p1];
6711 assert( pC!=0 );
6712 assert( pC->isOrdered );
6713 assert( pC->eCurType==CURTYPE_BTREE );
6714 assert( pC->uc.pCursor!=0);
6715 assert( pC->deferredMoveto==0 );
6716 assert( pOp->p4type==P4_INT32 );
6717 r.pKeyInfo = pC->pKeyInfo;
6718 r.nField = (u16)pOp->p4.i;
6719 if( pOp->opcode<OP_IdxLT ){
6720 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6721 r.default_rc = -1;
6722 }else{
6723 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6724 r.default_rc = 0;
6726 r.aMem = &aMem[pOp->p3];
6727 #ifdef SQLITE_DEBUG
6729 int i;
6730 for(i=0; i<r.nField; i++){
6731 assert( memIsValid(&r.aMem[i]) );
6732 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6735 #endif
6737 /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6739 i64 nCellKey = 0;
6740 BtCursor *pCur;
6741 Mem m;
6743 assert( pC->eCurType==CURTYPE_BTREE );
6744 pCur = pC->uc.pCursor;
6745 assert( sqlite3BtreeCursorIsValid(pCur) );
6746 nCellKey = sqlite3BtreePayloadSize(pCur);
6747 /* nCellKey will always be between 0 and 0xffffffff because of the way
6748 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6749 if( nCellKey<=0 || nCellKey>0x7fffffff ){
6750 rc = SQLITE_CORRUPT_BKPT;
6751 goto abort_due_to_error;
6753 sqlite3VdbeMemInit(&m, db, 0);
6754 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6755 if( rc ) goto abort_due_to_error;
6756 res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6757 sqlite3VdbeMemReleaseMalloc(&m);
6759 /* End of inlined sqlite3VdbeIdxKeyCompare() */
6761 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6762 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6763 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6764 res = -res;
6765 }else{
6766 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6767 res++;
6769 VdbeBranchTaken(res>0,2);
6770 assert( rc==SQLITE_OK );
6771 if( res>0 ) goto jump_to_p2;
6772 break;
6775 /* Opcode: Destroy P1 P2 P3 * *
6777 ** Delete an entire database table or index whose root page in the database
6778 ** file is given by P1.
6780 ** The table being destroyed is in the main database file if P3==0. If
6781 ** P3==1 then the table to be destroyed is in the auxiliary database file
6782 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6784 ** If AUTOVACUUM is enabled then it is possible that another root page
6785 ** might be moved into the newly deleted root page in order to keep all
6786 ** root pages contiguous at the beginning of the database. The former
6787 ** value of the root page that moved - its value before the move occurred -
6788 ** is stored in register P2. If no page movement was required (because the
6789 ** table being dropped was already the last one in the database) then a
6790 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
6791 ** is stored in register P2.
6793 ** This opcode throws an error if there are any active reader VMs when
6794 ** it is invoked. This is done to avoid the difficulty associated with
6795 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6796 ** database. This error is thrown even if the database is not an AUTOVACUUM
6797 ** db in order to avoid introducing an incompatibility between autovacuum
6798 ** and non-autovacuum modes.
6800 ** See also: Clear
6802 case OP_Destroy: { /* out2 */
6803 int iMoved;
6804 int iDb;
6806 sqlite3VdbeIncrWriteCounter(p, 0);
6807 assert( p->readOnly==0 );
6808 assert( pOp->p1>1 );
6809 pOut = out2Prerelease(p, pOp);
6810 pOut->flags = MEM_Null;
6811 if( db->nVdbeRead > db->nVDestroy+1 ){
6812 rc = SQLITE_LOCKED;
6813 p->errorAction = OE_Abort;
6814 goto abort_due_to_error;
6815 }else{
6816 iDb = pOp->p3;
6817 assert( DbMaskTest(p->btreeMask, iDb) );
6818 iMoved = 0; /* Not needed. Only to silence a warning. */
6819 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6820 pOut->flags = MEM_Int;
6821 pOut->u.i = iMoved;
6822 if( rc ) goto abort_due_to_error;
6823 #ifndef SQLITE_OMIT_AUTOVACUUM
6824 if( iMoved!=0 ){
6825 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6826 /* All OP_Destroy operations occur on the same btree */
6827 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6828 resetSchemaOnFault = iDb+1;
6830 #endif
6832 break;
6835 /* Opcode: Clear P1 P2 P3
6837 ** Delete all contents of the database table or index whose root page
6838 ** in the database file is given by P1. But, unlike Destroy, do not
6839 ** remove the table or index from the database file.
6841 ** The table being cleared is in the main database file if P2==0. If
6842 ** P2==1 then the table to be cleared is in the auxiliary database file
6843 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6845 ** If the P3 value is non-zero, then the row change count is incremented
6846 ** by the number of rows in the table being cleared. If P3 is greater
6847 ** than zero, then the value stored in register P3 is also incremented
6848 ** by the number of rows in the table being cleared.
6850 ** See also: Destroy
6852 case OP_Clear: {
6853 i64 nChange;
6855 sqlite3VdbeIncrWriteCounter(p, 0);
6856 nChange = 0;
6857 assert( p->readOnly==0 );
6858 assert( DbMaskTest(p->btreeMask, pOp->p2) );
6859 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
6860 if( pOp->p3 ){
6861 p->nChange += nChange;
6862 if( pOp->p3>0 ){
6863 assert( memIsValid(&aMem[pOp->p3]) );
6864 memAboutToChange(p, &aMem[pOp->p3]);
6865 aMem[pOp->p3].u.i += nChange;
6868 if( rc ) goto abort_due_to_error;
6869 break;
6872 /* Opcode: ResetSorter P1 * * * *
6874 ** Delete all contents from the ephemeral table or sorter
6875 ** that is open on cursor P1.
6877 ** This opcode only works for cursors used for sorting and
6878 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6880 case OP_ResetSorter: {
6881 VdbeCursor *pC;
6883 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6884 pC = p->apCsr[pOp->p1];
6885 assert( pC!=0 );
6886 if( isSorter(pC) ){
6887 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6888 }else{
6889 assert( pC->eCurType==CURTYPE_BTREE );
6890 assert( pC->isEphemeral );
6891 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6892 if( rc ) goto abort_due_to_error;
6894 break;
6897 /* Opcode: CreateBtree P1 P2 P3 * *
6898 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6900 ** Allocate a new b-tree in the main database file if P1==0 or in the
6901 ** TEMP database file if P1==1 or in an attached database if
6902 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6903 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6904 ** The root page number of the new b-tree is stored in register P2.
6906 case OP_CreateBtree: { /* out2 */
6907 Pgno pgno;
6908 Db *pDb;
6910 sqlite3VdbeIncrWriteCounter(p, 0);
6911 pOut = out2Prerelease(p, pOp);
6912 pgno = 0;
6913 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6914 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6915 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6916 assert( p->readOnly==0 );
6917 pDb = &db->aDb[pOp->p1];
6918 assert( pDb->pBt!=0 );
6919 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6920 if( rc ) goto abort_due_to_error;
6921 pOut->u.i = pgno;
6922 break;
6925 /* Opcode: SqlExec P1 P2 * P4 *
6927 ** Run the SQL statement or statements specified in the P4 string.
6929 ** The P1 parameter is a bitmask of options:
6931 ** 0x0001 Disable Auth and Trace callbacks while the statements
6932 ** in P4 are running.
6934 ** 0x0002 Set db->nAnalysisLimit to P2 while the statements in
6935 ** P4 are running.
6938 case OP_SqlExec: {
6939 char *zErr;
6940 #ifndef SQLITE_OMIT_AUTHORIZATION
6941 sqlite3_xauth xAuth;
6942 #endif
6943 u8 mTrace;
6944 int savedAnalysisLimit;
6946 sqlite3VdbeIncrWriteCounter(p, 0);
6947 db->nSqlExec++;
6948 zErr = 0;
6949 #ifndef SQLITE_OMIT_AUTHORIZATION
6950 xAuth = db->xAuth;
6951 #endif
6952 mTrace = db->mTrace;
6953 savedAnalysisLimit = db->nAnalysisLimit;
6954 if( pOp->p1 & 0x0001 ){
6955 #ifndef SQLITE_OMIT_AUTHORIZATION
6956 db->xAuth = 0;
6957 #endif
6958 db->mTrace = 0;
6960 if( pOp->p1 & 0x0002 ){
6961 db->nAnalysisLimit = pOp->p2;
6963 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, &zErr);
6964 db->nSqlExec--;
6965 #ifndef SQLITE_OMIT_AUTHORIZATION
6966 db->xAuth = xAuth;
6967 #endif
6968 db->mTrace = mTrace;
6969 db->nAnalysisLimit = savedAnalysisLimit;
6970 if( zErr || rc ){
6971 sqlite3VdbeError(p, "%s", zErr);
6972 sqlite3_free(zErr);
6973 if( rc==SQLITE_NOMEM ) goto no_mem;
6974 goto abort_due_to_error;
6976 break;
6979 /* Opcode: ParseSchema P1 * * P4 *
6981 ** Read and parse all entries from the schema table of database P1
6982 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
6983 ** entire schema for P1 is reparsed.
6985 ** This opcode invokes the parser to create a new virtual machine,
6986 ** then runs the new virtual machine. It is thus a re-entrant opcode.
6988 case OP_ParseSchema: {
6989 int iDb;
6990 const char *zSchema;
6991 char *zSql;
6992 InitData initData;
6994 /* Any prepared statement that invokes this opcode will hold mutexes
6995 ** on every btree. This is a prerequisite for invoking
6996 ** sqlite3InitCallback().
6998 #ifdef SQLITE_DEBUG
6999 for(iDb=0; iDb<db->nDb; iDb++){
7000 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
7002 #endif
7004 iDb = pOp->p1;
7005 assert( iDb>=0 && iDb<db->nDb );
7006 assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
7007 || db->mallocFailed
7008 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
7010 #ifndef SQLITE_OMIT_ALTERTABLE
7011 if( pOp->p4.z==0 ){
7012 sqlite3SchemaClear(db->aDb[iDb].pSchema);
7013 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
7014 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
7015 db->mDbFlags |= DBFLAG_SchemaChange;
7016 p->expired = 0;
7017 }else
7018 #endif
7020 zSchema = LEGACY_SCHEMA_TABLE;
7021 initData.db = db;
7022 initData.iDb = iDb;
7023 initData.pzErrMsg = &p->zErrMsg;
7024 initData.mInitFlags = 0;
7025 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
7026 zSql = sqlite3MPrintf(db,
7027 "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
7028 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
7029 if( zSql==0 ){
7030 rc = SQLITE_NOMEM_BKPT;
7031 }else{
7032 assert( db->init.busy==0 );
7033 db->init.busy = 1;
7034 initData.rc = SQLITE_OK;
7035 initData.nInitRow = 0;
7036 assert( !db->mallocFailed );
7037 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
7038 if( rc==SQLITE_OK ) rc = initData.rc;
7039 if( rc==SQLITE_OK && initData.nInitRow==0 ){
7040 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
7041 ** at least one SQL statement. Any less than that indicates that
7042 ** the sqlite_schema table is corrupt. */
7043 rc = SQLITE_CORRUPT_BKPT;
7045 sqlite3DbFreeNN(db, zSql);
7046 db->init.busy = 0;
7049 if( rc ){
7050 sqlite3ResetAllSchemasOfConnection(db);
7051 if( rc==SQLITE_NOMEM ){
7052 goto no_mem;
7054 goto abort_due_to_error;
7056 break;
7059 #if !defined(SQLITE_OMIT_ANALYZE)
7060 /* Opcode: LoadAnalysis P1 * * * *
7062 ** Read the sqlite_stat1 table for database P1 and load the content
7063 ** of that table into the internal index hash table. This will cause
7064 ** the analysis to be used when preparing all subsequent queries.
7066 case OP_LoadAnalysis: {
7067 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7068 rc = sqlite3AnalysisLoad(db, pOp->p1);
7069 if( rc ) goto abort_due_to_error;
7070 break;
7072 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
7074 /* Opcode: DropTable P1 * * P4 *
7076 ** Remove the internal (in-memory) data structures that describe
7077 ** the table named P4 in database P1. This is called after a table
7078 ** is dropped from disk (using the Destroy opcode) in order to keep
7079 ** the internal representation of the
7080 ** schema consistent with what is on disk.
7082 case OP_DropTable: {
7083 sqlite3VdbeIncrWriteCounter(p, 0);
7084 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
7085 break;
7088 /* Opcode: DropIndex P1 * * P4 *
7090 ** Remove the internal (in-memory) data structures that describe
7091 ** the index named P4 in database P1. This is called after an index
7092 ** is dropped from disk (using the Destroy opcode)
7093 ** in order to keep the internal representation of the
7094 ** schema consistent with what is on disk.
7096 case OP_DropIndex: {
7097 sqlite3VdbeIncrWriteCounter(p, 0);
7098 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
7099 break;
7102 /* Opcode: DropTrigger P1 * * P4 *
7104 ** Remove the internal (in-memory) data structures that describe
7105 ** the trigger named P4 in database P1. This is called after a trigger
7106 ** is dropped from disk (using the Destroy opcode) in order to keep
7107 ** the internal representation of the
7108 ** schema consistent with what is on disk.
7110 case OP_DropTrigger: {
7111 sqlite3VdbeIncrWriteCounter(p, 0);
7112 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
7113 break;
7117 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
7118 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
7120 ** Do an analysis of the currently open database. Store in
7121 ** register (P1+1) the text of an error message describing any problems.
7122 ** If no problems are found, store a NULL in register (P1+1).
7124 ** The register (P1) contains one less than the maximum number of allowed
7125 ** errors. At most reg(P1) errors will be reported.
7126 ** In other words, the analysis stops as soon as reg(P1) errors are
7127 ** seen. Reg(P1) is updated with the number of errors remaining.
7129 ** The root page numbers of all tables in the database are integers
7130 ** stored in P4_INTARRAY argument.
7132 ** If P5 is not zero, the check is done on the auxiliary database
7133 ** file, not the main database file.
7135 ** This opcode is used to implement the integrity_check pragma.
7137 case OP_IntegrityCk: {
7138 int nRoot; /* Number of tables to check. (Number of root pages.) */
7139 Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */
7140 int nErr; /* Number of errors reported */
7141 char *z; /* Text of the error report */
7142 Mem *pnErr; /* Register keeping track of errors remaining */
7144 assert( p->bIsReader );
7145 assert( pOp->p4type==P4_INTARRAY );
7146 nRoot = pOp->p2;
7147 aRoot = pOp->p4.ai;
7148 assert( nRoot>0 );
7149 assert( aRoot!=0 );
7150 assert( aRoot[0]==(Pgno)nRoot );
7151 assert( pOp->p1>0 && (pOp->p1+1)<=(p->nMem+1 - p->nCursor) );
7152 pnErr = &aMem[pOp->p1];
7153 assert( (pnErr->flags & MEM_Int)!=0 );
7154 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
7155 pIn1 = &aMem[pOp->p1+1];
7156 assert( pOp->p5<db->nDb );
7157 assert( DbMaskTest(p->btreeMask, pOp->p5) );
7158 rc = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1],
7159 &aMem[pOp->p3], nRoot, (int)pnErr->u.i+1, &nErr, &z);
7160 sqlite3VdbeMemSetNull(pIn1);
7161 if( nErr==0 ){
7162 assert( z==0 );
7163 }else if( rc ){
7164 sqlite3_free(z);
7165 goto abort_due_to_error;
7166 }else{
7167 pnErr->u.i -= nErr-1;
7168 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
7170 UPDATE_MAX_BLOBSIZE(pIn1);
7171 sqlite3VdbeChangeEncoding(pIn1, encoding);
7172 goto check_for_interrupt;
7174 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
7176 /* Opcode: RowSetAdd P1 P2 * * *
7177 ** Synopsis: rowset(P1)=r[P2]
7179 ** Insert the integer value held by register P2 into a RowSet object
7180 ** held in register P1.
7182 ** An assertion fails if P2 is not an integer.
7184 case OP_RowSetAdd: { /* in1, in2 */
7185 pIn1 = &aMem[pOp->p1];
7186 pIn2 = &aMem[pOp->p2];
7187 assert( (pIn2->flags & MEM_Int)!=0 );
7188 if( (pIn1->flags & MEM_Blob)==0 ){
7189 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7191 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7192 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
7193 break;
7196 /* Opcode: RowSetRead P1 P2 P3 * *
7197 ** Synopsis: r[P3]=rowset(P1)
7199 ** Extract the smallest value from the RowSet object in P1
7200 ** and put that value into register P3.
7201 ** Or, if RowSet object P1 is initially empty, leave P3
7202 ** unchanged and jump to instruction P2.
7204 case OP_RowSetRead: { /* jump, in1, out3 */
7205 i64 val;
7207 pIn1 = &aMem[pOp->p1];
7208 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
7209 if( (pIn1->flags & MEM_Blob)==0
7210 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
7212 /* The boolean index is empty */
7213 sqlite3VdbeMemSetNull(pIn1);
7214 VdbeBranchTaken(1,2);
7215 goto jump_to_p2_and_check_for_interrupt;
7216 }else{
7217 /* A value was pulled from the index */
7218 VdbeBranchTaken(0,2);
7219 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
7221 goto check_for_interrupt;
7224 /* Opcode: RowSetTest P1 P2 P3 P4
7225 ** Synopsis: if r[P3] in rowset(P1) goto P2
7227 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
7228 ** contains a RowSet object and that RowSet object contains
7229 ** the value held in P3, jump to register P2. Otherwise, insert the
7230 ** integer in P3 into the RowSet and continue on to the
7231 ** next opcode.
7233 ** The RowSet object is optimized for the case where sets of integers
7234 ** are inserted in distinct phases, which each set contains no duplicates.
7235 ** Each set is identified by a unique P4 value. The first set
7236 ** must have P4==0, the final set must have P4==-1, and for all other sets
7237 ** must have P4>0.
7239 ** This allows optimizations: (a) when P4==0 there is no need to test
7240 ** the RowSet object for P3, as it is guaranteed not to contain it,
7241 ** (b) when P4==-1 there is no need to insert the value, as it will
7242 ** never be tested for, and (c) when a value that is part of set X is
7243 ** inserted, there is no need to search to see if the same value was
7244 ** previously inserted as part of set X (only if it was previously
7245 ** inserted as part of some other set).
7247 case OP_RowSetTest: { /* jump, in1, in3 */
7248 int iSet;
7249 int exists;
7251 pIn1 = &aMem[pOp->p1];
7252 pIn3 = &aMem[pOp->p3];
7253 iSet = pOp->p4.i;
7254 assert( pIn3->flags&MEM_Int );
7256 /* If there is anything other than a rowset object in memory cell P1,
7257 ** delete it now and initialize P1 with an empty rowset
7259 if( (pIn1->flags & MEM_Blob)==0 ){
7260 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
7262 assert( sqlite3VdbeMemIsRowSet(pIn1) );
7263 assert( pOp->p4type==P4_INT32 );
7264 assert( iSet==-1 || iSet>=0 );
7265 if( iSet ){
7266 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
7267 VdbeBranchTaken(exists!=0,2);
7268 if( exists ) goto jump_to_p2;
7270 if( iSet>=0 ){
7271 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
7273 break;
7277 #ifndef SQLITE_OMIT_TRIGGER
7279 /* Opcode: Program P1 P2 P3 P4 P5
7281 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
7283 ** P1 contains the address of the memory cell that contains the first memory
7284 ** cell in an array of values used as arguments to the sub-program. P2
7285 ** contains the address to jump to if the sub-program throws an IGNORE
7286 ** exception using the RAISE() function. P2 might be zero, if there is
7287 ** no possibility that an IGNORE exception will be raised.
7288 ** Register P3 contains the address
7289 ** of a memory cell in this (the parent) VM that is used to allocate the
7290 ** memory required by the sub-vdbe at runtime.
7292 ** P4 is a pointer to the VM containing the trigger program.
7294 ** If P5 is non-zero, then recursive program invocation is enabled.
7296 case OP_Program: { /* jump0 */
7297 int nMem; /* Number of memory registers for sub-program */
7298 int nByte; /* Bytes of runtime space required for sub-program */
7299 Mem *pRt; /* Register to allocate runtime space */
7300 Mem *pMem; /* Used to iterate through memory cells */
7301 Mem *pEnd; /* Last memory cell in new array */
7302 VdbeFrame *pFrame; /* New vdbe frame to execute in */
7303 SubProgram *pProgram; /* Sub-program to execute */
7304 void *t; /* Token identifying trigger */
7306 pProgram = pOp->p4.pProgram;
7307 pRt = &aMem[pOp->p3];
7308 assert( pProgram->nOp>0 );
7310 /* If the p5 flag is clear, then recursive invocation of triggers is
7311 ** disabled for backwards compatibility (p5 is set if this sub-program
7312 ** is really a trigger, not a foreign key action, and the flag set
7313 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
7315 ** It is recursive invocation of triggers, at the SQL level, that is
7316 ** disabled. In some cases a single trigger may generate more than one
7317 ** SubProgram (if the trigger may be executed with more than one different
7318 ** ON CONFLICT algorithm). SubProgram structures associated with a
7319 ** single trigger all have the same value for the SubProgram.token
7320 ** variable. */
7321 if( pOp->p5 ){
7322 t = pProgram->token;
7323 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
7324 if( pFrame ) break;
7327 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
7328 rc = SQLITE_ERROR;
7329 sqlite3VdbeError(p, "too many levels of trigger recursion");
7330 goto abort_due_to_error;
7333 /* Register pRt is used to store the memory required to save the state
7334 ** of the current program, and the memory required at runtime to execute
7335 ** the trigger program. If this trigger has been fired before, then pRt
7336 ** is already allocated. Otherwise, it must be initialized. */
7337 if( (pRt->flags&MEM_Blob)==0 ){
7338 /* SubProgram.nMem is set to the number of memory cells used by the
7339 ** program stored in SubProgram.aOp. As well as these, one memory
7340 ** cell is required for each cursor used by the program. Set local
7341 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
7343 nMem = pProgram->nMem + pProgram->nCsr;
7344 assert( nMem>0 );
7345 if( pProgram->nCsr==0 ) nMem++;
7346 nByte = ROUND8(sizeof(VdbeFrame))
7347 + nMem * sizeof(Mem)
7348 + pProgram->nCsr * sizeof(VdbeCursor*)
7349 + (pProgram->nOp + 7)/8;
7350 pFrame = sqlite3DbMallocZero(db, nByte);
7351 if( !pFrame ){
7352 goto no_mem;
7354 sqlite3VdbeMemRelease(pRt);
7355 pRt->flags = MEM_Blob|MEM_Dyn;
7356 pRt->z = (char*)pFrame;
7357 pRt->n = nByte;
7358 pRt->xDel = sqlite3VdbeFrameMemDel;
7360 pFrame->v = p;
7361 pFrame->nChildMem = nMem;
7362 pFrame->nChildCsr = pProgram->nCsr;
7363 pFrame->pc = (int)(pOp - aOp);
7364 pFrame->aMem = p->aMem;
7365 pFrame->nMem = p->nMem;
7366 pFrame->apCsr = p->apCsr;
7367 pFrame->nCursor = p->nCursor;
7368 pFrame->aOp = p->aOp;
7369 pFrame->nOp = p->nOp;
7370 pFrame->token = pProgram->token;
7371 #ifdef SQLITE_DEBUG
7372 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
7373 #endif
7375 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
7376 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
7377 pMem->flags = MEM_Undefined;
7378 pMem->db = db;
7380 }else{
7381 pFrame = (VdbeFrame*)pRt->z;
7382 assert( pRt->xDel==sqlite3VdbeFrameMemDel );
7383 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
7384 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
7385 assert( pProgram->nCsr==pFrame->nChildCsr );
7386 assert( (int)(pOp - aOp)==pFrame->pc );
7389 p->nFrame++;
7390 pFrame->pParent = p->pFrame;
7391 pFrame->lastRowid = db->lastRowid;
7392 pFrame->nChange = p->nChange;
7393 pFrame->nDbChange = p->db->nChange;
7394 assert( pFrame->pAuxData==0 );
7395 pFrame->pAuxData = p->pAuxData;
7396 p->pAuxData = 0;
7397 p->nChange = 0;
7398 p->pFrame = pFrame;
7399 p->aMem = aMem = VdbeFrameMem(pFrame);
7400 p->nMem = pFrame->nChildMem;
7401 p->nCursor = (u16)pFrame->nChildCsr;
7402 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
7403 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
7404 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
7405 p->aOp = aOp = pProgram->aOp;
7406 p->nOp = pProgram->nOp;
7407 #ifdef SQLITE_DEBUG
7408 /* Verify that second and subsequent executions of the same trigger do not
7409 ** try to reuse register values from the first use. */
7411 int i;
7412 for(i=0; i<p->nMem; i++){
7413 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
7414 MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
7417 #endif
7418 pOp = &aOp[-1];
7419 goto check_for_interrupt;
7422 /* Opcode: Param P1 P2 * * *
7424 ** This opcode is only ever present in sub-programs called via the
7425 ** OP_Program instruction. Copy a value currently stored in a memory
7426 ** cell of the calling (parent) frame to cell P2 in the current frames
7427 ** address space. This is used by trigger programs to access the new.*
7428 ** and old.* values.
7430 ** The address of the cell in the parent frame is determined by adding
7431 ** the value of the P1 argument to the value of the P1 argument to the
7432 ** calling OP_Program instruction.
7434 case OP_Param: { /* out2 */
7435 VdbeFrame *pFrame;
7436 Mem *pIn;
7437 pOut = out2Prerelease(p, pOp);
7438 pFrame = p->pFrame;
7439 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
7440 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
7441 break;
7444 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
7446 #ifndef SQLITE_OMIT_FOREIGN_KEY
7447 /* Opcode: FkCounter P1 P2 * * *
7448 ** Synopsis: fkctr[P1]+=P2
7450 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
7451 ** If P1 is non-zero, the database constraint counter is incremented
7452 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
7453 ** statement counter is incremented (immediate foreign key constraints).
7455 case OP_FkCounter: {
7456 if( db->flags & SQLITE_DeferFKs ){
7457 db->nDeferredImmCons += pOp->p2;
7458 }else if( pOp->p1 ){
7459 db->nDeferredCons += pOp->p2;
7460 }else{
7461 p->nFkConstraint += pOp->p2;
7463 break;
7466 /* Opcode: FkIfZero P1 P2 * * *
7467 ** Synopsis: if fkctr[P1]==0 goto P2
7469 ** This opcode tests if a foreign key constraint-counter is currently zero.
7470 ** If so, jump to instruction P2. Otherwise, fall through to the next
7471 ** instruction.
7473 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
7474 ** is zero (the one that counts deferred constraint violations). If P1 is
7475 ** zero, the jump is taken if the statement constraint-counter is zero
7476 ** (immediate foreign key constraint violations).
7478 case OP_FkIfZero: { /* jump */
7479 if( pOp->p1 ){
7480 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
7481 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7482 }else{
7483 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
7484 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7486 break;
7488 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
7490 #ifndef SQLITE_OMIT_AUTOINCREMENT
7491 /* Opcode: MemMax P1 P2 * * *
7492 ** Synopsis: r[P1]=max(r[P1],r[P2])
7494 ** P1 is a register in the root frame of this VM (the root frame is
7495 ** different from the current frame if this instruction is being executed
7496 ** within a sub-program). Set the value of register P1 to the maximum of
7497 ** its current value and the value in register P2.
7499 ** This instruction throws an error if the memory cell is not initially
7500 ** an integer.
7502 case OP_MemMax: { /* in2 */
7503 VdbeFrame *pFrame;
7504 if( p->pFrame ){
7505 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
7506 pIn1 = &pFrame->aMem[pOp->p1];
7507 }else{
7508 pIn1 = &aMem[pOp->p1];
7510 assert( memIsValid(pIn1) );
7511 sqlite3VdbeMemIntegerify(pIn1);
7512 pIn2 = &aMem[pOp->p2];
7513 sqlite3VdbeMemIntegerify(pIn2);
7514 if( pIn1->u.i<pIn2->u.i){
7515 pIn1->u.i = pIn2->u.i;
7517 break;
7519 #endif /* SQLITE_OMIT_AUTOINCREMENT */
7521 /* Opcode: IfPos P1 P2 P3 * *
7522 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
7524 ** Register P1 must contain an integer.
7525 ** If the value of register P1 is 1 or greater, subtract P3 from the
7526 ** value in P1 and jump to P2.
7528 ** If the initial value of register P1 is less than 1, then the
7529 ** value is unchanged and control passes through to the next instruction.
7531 case OP_IfPos: { /* jump, in1 */
7532 pIn1 = &aMem[pOp->p1];
7533 assert( pIn1->flags&MEM_Int );
7534 VdbeBranchTaken( pIn1->u.i>0, 2);
7535 if( pIn1->u.i>0 ){
7536 pIn1->u.i -= pOp->p3;
7537 goto jump_to_p2;
7539 break;
7542 /* Opcode: OffsetLimit P1 P2 P3 * *
7543 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
7545 ** This opcode performs a commonly used computation associated with
7546 ** LIMIT and OFFSET processing. r[P1] holds the limit counter. r[P3]
7547 ** holds the offset counter. The opcode computes the combined value
7548 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
7549 ** value computed is the total number of rows that will need to be
7550 ** visited in order to complete the query.
7552 ** If r[P3] is zero or negative, that means there is no OFFSET
7553 ** and r[P2] is set to be the value of the LIMIT, r[P1].
7555 ** if r[P1] is zero or negative, that means there is no LIMIT
7556 ** and r[P2] is set to -1.
7558 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
7560 case OP_OffsetLimit: { /* in1, out2, in3 */
7561 i64 x;
7562 pIn1 = &aMem[pOp->p1];
7563 pIn3 = &aMem[pOp->p3];
7564 pOut = out2Prerelease(p, pOp);
7565 assert( pIn1->flags & MEM_Int );
7566 assert( pIn3->flags & MEM_Int );
7567 x = pIn1->u.i;
7568 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
7569 /* If the LIMIT is less than or equal to zero, loop forever. This
7570 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
7571 ** also loop forever. This is undocumented. In fact, one could argue
7572 ** that the loop should terminate. But assuming 1 billion iterations
7573 ** per second (far exceeding the capabilities of any current hardware)
7574 ** it would take nearly 300 years to actually reach the limit. So
7575 ** looping forever is a reasonable approximation. */
7576 pOut->u.i = -1;
7577 }else{
7578 pOut->u.i = x;
7580 break;
7583 /* Opcode: IfNotZero P1 P2 * * *
7584 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
7586 ** Register P1 must contain an integer. If the content of register P1 is
7587 ** initially greater than zero, then decrement the value in register P1.
7588 ** If it is non-zero (negative or positive) and then also jump to P2.
7589 ** If register P1 is initially zero, leave it unchanged and fall through.
7591 case OP_IfNotZero: { /* jump, in1 */
7592 pIn1 = &aMem[pOp->p1];
7593 assert( pIn1->flags&MEM_Int );
7594 VdbeBranchTaken(pIn1->u.i<0, 2);
7595 if( pIn1->u.i ){
7596 if( pIn1->u.i>0 ) pIn1->u.i--;
7597 goto jump_to_p2;
7599 break;
7602 /* Opcode: DecrJumpZero P1 P2 * * *
7603 ** Synopsis: if (--r[P1])==0 goto P2
7605 ** Register P1 must hold an integer. Decrement the value in P1
7606 ** and jump to P2 if the new value is exactly zero.
7608 case OP_DecrJumpZero: { /* jump, in1 */
7609 pIn1 = &aMem[pOp->p1];
7610 assert( pIn1->flags&MEM_Int );
7611 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
7612 VdbeBranchTaken(pIn1->u.i==0, 2);
7613 if( pIn1->u.i==0 ) goto jump_to_p2;
7614 break;
7618 /* Opcode: AggStep * P2 P3 P4 P5
7619 ** Synopsis: accum=r[P3] step(r[P2@P5])
7621 ** Execute the xStep function for an aggregate.
7622 ** The function has P5 arguments. P4 is a pointer to the
7623 ** FuncDef structure that specifies the function. Register P3 is the
7624 ** accumulator.
7626 ** The P5 arguments are taken from register P2 and its
7627 ** successors.
7629 /* Opcode: AggInverse * P2 P3 P4 P5
7630 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
7632 ** Execute the xInverse function for an aggregate.
7633 ** The function has P5 arguments. P4 is a pointer to the
7634 ** FuncDef structure that specifies the function. Register P3 is the
7635 ** accumulator.
7637 ** The P5 arguments are taken from register P2 and its
7638 ** successors.
7640 /* Opcode: AggStep1 P1 P2 P3 P4 P5
7641 ** Synopsis: accum=r[P3] step(r[P2@P5])
7643 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
7644 ** aggregate. The function has P5 arguments. P4 is a pointer to the
7645 ** FuncDef structure that specifies the function. Register P3 is the
7646 ** accumulator.
7648 ** The P5 arguments are taken from register P2 and its
7649 ** successors.
7651 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
7652 ** the FuncDef stored in P4 is converted into an sqlite3_context and
7653 ** the opcode is changed. In this way, the initialization of the
7654 ** sqlite3_context only happens once, instead of on each call to the
7655 ** step function.
7657 case OP_AggInverse:
7658 case OP_AggStep: {
7659 int n;
7660 sqlite3_context *pCtx;
7662 assert( pOp->p4type==P4_FUNCDEF );
7663 n = pOp->p5;
7664 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7665 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7666 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7667 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
7668 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
7669 if( pCtx==0 ) goto no_mem;
7670 pCtx->pMem = 0;
7671 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
7672 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
7673 pCtx->pFunc = pOp->p4.pFunc;
7674 pCtx->iOp = (int)(pOp - aOp);
7675 pCtx->pVdbe = p;
7676 pCtx->skipFlag = 0;
7677 pCtx->isError = 0;
7678 pCtx->enc = encoding;
7679 pCtx->argc = n;
7680 pOp->p4type = P4_FUNCCTX;
7681 pOp->p4.pCtx = pCtx;
7683 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
7684 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
7686 pOp->opcode = OP_AggStep1;
7687 /* Fall through into OP_AggStep */
7688 /* no break */ deliberate_fall_through
7690 case OP_AggStep1: {
7691 int i;
7692 sqlite3_context *pCtx;
7693 Mem *pMem;
7695 assert( pOp->p4type==P4_FUNCCTX );
7696 pCtx = pOp->p4.pCtx;
7697 pMem = &aMem[pOp->p3];
7699 #ifdef SQLITE_DEBUG
7700 if( pOp->p1 ){
7701 /* This is an OP_AggInverse call. Verify that xStep has always
7702 ** been called at least once prior to any xInverse call. */
7703 assert( pMem->uTemp==0x1122e0e3 );
7704 }else{
7705 /* This is an OP_AggStep call. Mark it as such. */
7706 pMem->uTemp = 0x1122e0e3;
7708 #endif
7710 /* If this function is inside of a trigger, the register array in aMem[]
7711 ** might change from one evaluation to the next. The next block of code
7712 ** checks to see if the register array has changed, and if so it
7713 ** reinitializes the relevant parts of the sqlite3_context object */
7714 if( pCtx->pMem != pMem ){
7715 pCtx->pMem = pMem;
7716 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7719 #ifdef SQLITE_DEBUG
7720 for(i=0; i<pCtx->argc; i++){
7721 assert( memIsValid(pCtx->argv[i]) );
7722 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7724 #endif
7726 pMem->n++;
7727 assert( pCtx->pOut->flags==MEM_Null );
7728 assert( pCtx->isError==0 );
7729 assert( pCtx->skipFlag==0 );
7730 #ifndef SQLITE_OMIT_WINDOWFUNC
7731 if( pOp->p1 ){
7732 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7733 }else
7734 #endif
7735 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7737 if( pCtx->isError ){
7738 if( pCtx->isError>0 ){
7739 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7740 rc = pCtx->isError;
7742 if( pCtx->skipFlag ){
7743 assert( pOp[-1].opcode==OP_CollSeq );
7744 i = pOp[-1].p1;
7745 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7746 pCtx->skipFlag = 0;
7748 sqlite3VdbeMemRelease(pCtx->pOut);
7749 pCtx->pOut->flags = MEM_Null;
7750 pCtx->isError = 0;
7751 if( rc ) goto abort_due_to_error;
7753 assert( pCtx->pOut->flags==MEM_Null );
7754 assert( pCtx->skipFlag==0 );
7755 break;
7758 /* Opcode: AggFinal P1 P2 * P4 *
7759 ** Synopsis: accum=r[P1] N=P2
7761 ** P1 is the memory location that is the accumulator for an aggregate
7762 ** or window function. Execute the finalizer function
7763 ** for an aggregate and store the result in P1.
7765 ** P2 is the number of arguments that the step function takes and
7766 ** P4 is a pointer to the FuncDef for this function. The P2
7767 ** argument is not used by this opcode. It is only there to disambiguate
7768 ** functions that can take varying numbers of arguments. The
7769 ** P4 argument is only needed for the case where
7770 ** the step function was not previously called.
7772 /* Opcode: AggValue * P2 P3 P4 *
7773 ** Synopsis: r[P3]=value N=P2
7775 ** Invoke the xValue() function and store the result in register P3.
7777 ** P2 is the number of arguments that the step function takes and
7778 ** P4 is a pointer to the FuncDef for this function. The P2
7779 ** argument is not used by this opcode. It is only there to disambiguate
7780 ** functions that can take varying numbers of arguments. The
7781 ** P4 argument is only needed for the case where
7782 ** the step function was not previously called.
7784 case OP_AggValue:
7785 case OP_AggFinal: {
7786 Mem *pMem;
7787 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7788 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7789 pMem = &aMem[pOp->p1];
7790 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7791 #ifndef SQLITE_OMIT_WINDOWFUNC
7792 if( pOp->p3 ){
7793 memAboutToChange(p, &aMem[pOp->p3]);
7794 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7795 pMem = &aMem[pOp->p3];
7796 }else
7797 #endif
7799 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7802 if( rc ){
7803 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7804 goto abort_due_to_error;
7806 sqlite3VdbeChangeEncoding(pMem, encoding);
7807 UPDATE_MAX_BLOBSIZE(pMem);
7808 REGISTER_TRACE((int)(pMem-aMem), pMem);
7809 break;
7812 #ifndef SQLITE_OMIT_WAL
7813 /* Opcode: Checkpoint P1 P2 P3 * *
7815 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7816 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7817 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
7818 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
7819 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7820 ** in the WAL that have been checkpointed after the checkpoint
7821 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
7822 ** mem[P3+2] are initialized to -1.
7824 case OP_Checkpoint: {
7825 int i; /* Loop counter */
7826 int aRes[3]; /* Results */
7827 Mem *pMem; /* Write results here */
7829 assert( p->readOnly==0 );
7830 aRes[0] = 0;
7831 aRes[1] = aRes[2] = -1;
7832 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7833 || pOp->p2==SQLITE_CHECKPOINT_FULL
7834 || pOp->p2==SQLITE_CHECKPOINT_RESTART
7835 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7837 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7838 if( rc ){
7839 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7840 rc = SQLITE_OK;
7841 aRes[0] = 1;
7843 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7844 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7846 break;
7848 #endif
7850 #ifndef SQLITE_OMIT_PRAGMA
7851 /* Opcode: JournalMode P1 P2 P3 * *
7853 ** Change the journal mode of database P1 to P3. P3 must be one of the
7854 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7855 ** modes (delete, truncate, persist, off and memory), this is a simple
7856 ** operation. No IO is required.
7858 ** If changing into or out of WAL mode the procedure is more complicated.
7860 ** Write a string containing the final journal-mode to register P2.
7862 case OP_JournalMode: { /* out2 */
7863 Btree *pBt; /* Btree to change journal mode of */
7864 Pager *pPager; /* Pager associated with pBt */
7865 int eNew; /* New journal mode */
7866 int eOld; /* The old journal mode */
7867 #ifndef SQLITE_OMIT_WAL
7868 const char *zFilename; /* Name of database file for pPager */
7869 #endif
7871 pOut = out2Prerelease(p, pOp);
7872 eNew = pOp->p3;
7873 assert( eNew==PAGER_JOURNALMODE_DELETE
7874 || eNew==PAGER_JOURNALMODE_TRUNCATE
7875 || eNew==PAGER_JOURNALMODE_PERSIST
7876 || eNew==PAGER_JOURNALMODE_OFF
7877 || eNew==PAGER_JOURNALMODE_MEMORY
7878 || eNew==PAGER_JOURNALMODE_WAL
7879 || eNew==PAGER_JOURNALMODE_QUERY
7881 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7882 assert( p->readOnly==0 );
7884 pBt = db->aDb[pOp->p1].pBt;
7885 pPager = sqlite3BtreePager(pBt);
7886 eOld = sqlite3PagerGetJournalMode(pPager);
7887 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7888 assert( sqlite3BtreeHoldsMutex(pBt) );
7889 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7891 #ifndef SQLITE_OMIT_WAL
7892 zFilename = sqlite3PagerFilename(pPager, 1);
7894 /* Do not allow a transition to journal_mode=WAL for a database
7895 ** in temporary storage or if the VFS does not support shared memory
7897 if( eNew==PAGER_JOURNALMODE_WAL
7898 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
7899 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
7901 eNew = eOld;
7904 if( (eNew!=eOld)
7905 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7907 if( !db->autoCommit || db->nVdbeRead>1 ){
7908 rc = SQLITE_ERROR;
7909 sqlite3VdbeError(p,
7910 "cannot change %s wal mode from within a transaction",
7911 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7913 goto abort_due_to_error;
7914 }else{
7916 if( eOld==PAGER_JOURNALMODE_WAL ){
7917 /* If leaving WAL mode, close the log file. If successful, the call
7918 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7919 ** file. An EXCLUSIVE lock may still be held on the database file
7920 ** after a successful return.
7922 rc = sqlite3PagerCloseWal(pPager, db);
7923 if( rc==SQLITE_OK ){
7924 sqlite3PagerSetJournalMode(pPager, eNew);
7926 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7927 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
7928 ** as an intermediate */
7929 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7932 /* Open a transaction on the database file. Regardless of the journal
7933 ** mode, this transaction always uses a rollback journal.
7935 assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7936 if( rc==SQLITE_OK ){
7937 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7941 #endif /* ifndef SQLITE_OMIT_WAL */
7943 if( rc ) eNew = eOld;
7944 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7946 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7947 pOut->z = (char *)sqlite3JournalModename(eNew);
7948 pOut->n = sqlite3Strlen30(pOut->z);
7949 pOut->enc = SQLITE_UTF8;
7950 sqlite3VdbeChangeEncoding(pOut, encoding);
7951 if( rc ) goto abort_due_to_error;
7952 break;
7954 #endif /* SQLITE_OMIT_PRAGMA */
7956 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7957 /* Opcode: Vacuum P1 P2 * * *
7959 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
7960 ** for an attached database. The "temp" database may not be vacuumed.
7962 ** If P2 is not zero, then it is a register holding a string which is
7963 ** the file into which the result of vacuum should be written. When
7964 ** P2 is zero, the vacuum overwrites the original database.
7966 case OP_Vacuum: {
7967 assert( p->readOnly==0 );
7968 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7969 pOp->p2 ? &aMem[pOp->p2] : 0);
7970 if( rc ) goto abort_due_to_error;
7971 break;
7973 #endif
7975 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7976 /* Opcode: IncrVacuum P1 P2 * * *
7978 ** Perform a single step of the incremental vacuum procedure on
7979 ** the P1 database. If the vacuum has finished, jump to instruction
7980 ** P2. Otherwise, fall through to the next instruction.
7982 case OP_IncrVacuum: { /* jump */
7983 Btree *pBt;
7985 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7986 assert( DbMaskTest(p->btreeMask, pOp->p1) );
7987 assert( p->readOnly==0 );
7988 pBt = db->aDb[pOp->p1].pBt;
7989 rc = sqlite3BtreeIncrVacuum(pBt);
7990 VdbeBranchTaken(rc==SQLITE_DONE,2);
7991 if( rc ){
7992 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7993 rc = SQLITE_OK;
7994 goto jump_to_p2;
7996 break;
7998 #endif
8000 /* Opcode: Expire P1 P2 * * *
8002 ** Cause precompiled statements to expire. When an expired statement
8003 ** is executed using sqlite3_step() it will either automatically
8004 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
8005 ** or it will fail with SQLITE_SCHEMA.
8007 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
8008 ** then only the currently executing statement is expired.
8010 ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
8011 ** then running SQL statements are allowed to continue to run to completion.
8012 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
8013 ** that might help the statement run faster but which does not affect the
8014 ** correctness of operation.
8016 case OP_Expire: {
8017 assert( pOp->p2==0 || pOp->p2==1 );
8018 if( !pOp->p1 ){
8019 sqlite3ExpirePreparedStatements(db, pOp->p2);
8020 }else{
8021 p->expired = pOp->p2+1;
8023 break;
8026 /* Opcode: CursorLock P1 * * * *
8028 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
8029 ** written by an other cursor.
8031 case OP_CursorLock: {
8032 VdbeCursor *pC;
8033 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8034 pC = p->apCsr[pOp->p1];
8035 assert( pC!=0 );
8036 assert( pC->eCurType==CURTYPE_BTREE );
8037 sqlite3BtreeCursorPin(pC->uc.pCursor);
8038 break;
8041 /* Opcode: CursorUnlock P1 * * * *
8043 ** Unlock the btree to which cursor P1 is pointing so that it can be
8044 ** written by other cursors.
8046 case OP_CursorUnlock: {
8047 VdbeCursor *pC;
8048 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8049 pC = p->apCsr[pOp->p1];
8050 assert( pC!=0 );
8051 assert( pC->eCurType==CURTYPE_BTREE );
8052 sqlite3BtreeCursorUnpin(pC->uc.pCursor);
8053 break;
8056 #ifndef SQLITE_OMIT_SHARED_CACHE
8057 /* Opcode: TableLock P1 P2 P3 P4 *
8058 ** Synopsis: iDb=P1 root=P2 write=P3
8060 ** Obtain a lock on a particular table. This instruction is only used when
8061 ** the shared-cache feature is enabled.
8063 ** P1 is the index of the database in sqlite3.aDb[] of the database
8064 ** on which the lock is acquired. A readlock is obtained if P3==0 or
8065 ** a write lock if P3==1.
8067 ** P2 contains the root-page of the table to lock.
8069 ** P4 contains a pointer to the name of the table being locked. This is only
8070 ** used to generate an error message if the lock cannot be obtained.
8072 case OP_TableLock: {
8073 u8 isWriteLock = (u8)pOp->p3;
8074 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
8075 int p1 = pOp->p1;
8076 assert( p1>=0 && p1<db->nDb );
8077 assert( DbMaskTest(p->btreeMask, p1) );
8078 assert( isWriteLock==0 || isWriteLock==1 );
8079 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
8080 if( rc ){
8081 if( (rc&0xFF)==SQLITE_LOCKED ){
8082 const char *z = pOp->p4.z;
8083 sqlite3VdbeError(p, "database table is locked: %s", z);
8085 goto abort_due_to_error;
8088 break;
8090 #endif /* SQLITE_OMIT_SHARED_CACHE */
8092 #ifndef SQLITE_OMIT_VIRTUALTABLE
8093 /* Opcode: VBegin * * * P4 *
8095 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
8096 ** xBegin method for that table.
8098 ** Also, whether or not P4 is set, check that this is not being called from
8099 ** within a callback to a virtual table xSync() method. If it is, the error
8100 ** code will be set to SQLITE_LOCKED.
8102 case OP_VBegin: {
8103 VTable *pVTab;
8104 pVTab = pOp->p4.pVtab;
8105 rc = sqlite3VtabBegin(db, pVTab);
8106 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
8107 if( rc ) goto abort_due_to_error;
8108 break;
8110 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8112 #ifndef SQLITE_OMIT_VIRTUALTABLE
8113 /* Opcode: VCreate P1 P2 * * *
8115 ** P2 is a register that holds the name of a virtual table in database
8116 ** P1. Call the xCreate method for that table.
8118 case OP_VCreate: {
8119 Mem sMem; /* For storing the record being decoded */
8120 const char *zTab; /* Name of the virtual table */
8122 memset(&sMem, 0, sizeof(sMem));
8123 sMem.db = db;
8124 /* Because P2 is always a static string, it is impossible for the
8125 ** sqlite3VdbeMemCopy() to fail */
8126 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
8127 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
8128 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
8129 assert( rc==SQLITE_OK );
8130 zTab = (const char*)sqlite3_value_text(&sMem);
8131 assert( zTab || db->mallocFailed );
8132 if( zTab ){
8133 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
8135 sqlite3VdbeMemRelease(&sMem);
8136 if( rc ) goto abort_due_to_error;
8137 break;
8139 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8141 #ifndef SQLITE_OMIT_VIRTUALTABLE
8142 /* Opcode: VDestroy P1 * * P4 *
8144 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
8145 ** of that table.
8147 case OP_VDestroy: {
8148 db->nVDestroy++;
8149 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
8150 db->nVDestroy--;
8151 assert( p->errorAction==OE_Abort && p->usesStmtJournal );
8152 if( rc ) goto abort_due_to_error;
8153 break;
8155 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8157 #ifndef SQLITE_OMIT_VIRTUALTABLE
8158 /* Opcode: VOpen P1 * * P4 *
8160 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8161 ** P1 is a cursor number. This opcode opens a cursor to the virtual
8162 ** table and stores that cursor in P1.
8164 case OP_VOpen: { /* ncycle */
8165 VdbeCursor *pCur;
8166 sqlite3_vtab_cursor *pVCur;
8167 sqlite3_vtab *pVtab;
8168 const sqlite3_module *pModule;
8170 assert( p->bIsReader );
8171 pCur = 0;
8172 pVCur = 0;
8173 pVtab = pOp->p4.pVtab->pVtab;
8174 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8175 rc = SQLITE_LOCKED;
8176 goto abort_due_to_error;
8178 pModule = pVtab->pModule;
8179 rc = pModule->xOpen(pVtab, &pVCur);
8180 sqlite3VtabImportErrmsg(p, pVtab);
8181 if( rc ) goto abort_due_to_error;
8183 /* Initialize sqlite3_vtab_cursor base class */
8184 pVCur->pVtab = pVtab;
8186 /* Initialize vdbe cursor object */
8187 pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
8188 if( pCur ){
8189 pCur->uc.pVCur = pVCur;
8190 pVtab->nRef++;
8191 }else{
8192 assert( db->mallocFailed );
8193 pModule->xClose(pVCur);
8194 goto no_mem;
8196 break;
8198 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8200 #ifndef SQLITE_OMIT_VIRTUALTABLE
8201 /* Opcode: VCheck P1 P2 P3 P4 *
8203 ** P4 is a pointer to a Table object that is a virtual table in schema P1
8204 ** that supports the xIntegrity() method. This opcode runs the xIntegrity()
8205 ** method for that virtual table, using P3 as the integer argument. If
8206 ** an error is reported back, the table name is prepended to the error
8207 ** message and that message is stored in P2. If no errors are seen,
8208 ** register P2 is set to NULL.
8210 case OP_VCheck: { /* out2 */
8211 Table *pTab;
8212 sqlite3_vtab *pVtab;
8213 const sqlite3_module *pModule;
8214 char *zErr = 0;
8216 pOut = &aMem[pOp->p2];
8217 sqlite3VdbeMemSetNull(pOut); /* Innocent until proven guilty */
8218 assert( pOp->p4type==P4_TABLEREF );
8219 pTab = pOp->p4.pTab;
8220 assert( pTab!=0 );
8221 assert( pTab->nTabRef>0 );
8222 assert( IsVirtual(pTab) );
8223 if( pTab->u.vtab.p==0 ) break;
8224 pVtab = pTab->u.vtab.p->pVtab;
8225 assert( pVtab!=0 );
8226 pModule = pVtab->pModule;
8227 assert( pModule!=0 );
8228 assert( pModule->iVersion>=4 );
8229 assert( pModule->xIntegrity!=0 );
8230 sqlite3VtabLock(pTab->u.vtab.p);
8231 assert( pOp->p1>=0 && pOp->p1<db->nDb );
8232 rc = pModule->xIntegrity(pVtab, db->aDb[pOp->p1].zDbSName, pTab->zName,
8233 pOp->p3, &zErr);
8234 sqlite3VtabUnlock(pTab->u.vtab.p);
8235 if( rc ){
8236 sqlite3_free(zErr);
8237 goto abort_due_to_error;
8239 if( zErr ){
8240 sqlite3VdbeMemSetStr(pOut, zErr, -1, SQLITE_UTF8, sqlite3_free);
8242 break;
8244 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8246 #ifndef SQLITE_OMIT_VIRTUALTABLE
8247 /* Opcode: VInitIn P1 P2 P3 * *
8248 ** Synopsis: r[P2]=ValueList(P1,P3)
8250 ** Set register P2 to be a pointer to a ValueList object for cursor P1
8251 ** with cache register P3 and output register P3+1. This ValueList object
8252 ** can be used as the first argument to sqlite3_vtab_in_first() and
8253 ** sqlite3_vtab_in_next() to extract all of the values stored in the P1
8254 ** cursor. Register P3 is used to hold the values returned by
8255 ** sqlite3_vtab_in_first() and sqlite3_vtab_in_next().
8257 case OP_VInitIn: { /* out2, ncycle */
8258 VdbeCursor *pC; /* The cursor containing the RHS values */
8259 ValueList *pRhs; /* New ValueList object to put in reg[P2] */
8261 pC = p->apCsr[pOp->p1];
8262 pRhs = sqlite3_malloc64( sizeof(*pRhs) );
8263 if( pRhs==0 ) goto no_mem;
8264 pRhs->pCsr = pC->uc.pCursor;
8265 pRhs->pOut = &aMem[pOp->p3];
8266 pOut = out2Prerelease(p, pOp);
8267 pOut->flags = MEM_Null;
8268 sqlite3VdbeMemSetPointer(pOut, pRhs, "ValueList", sqlite3VdbeValueListFree);
8269 break;
8271 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8274 #ifndef SQLITE_OMIT_VIRTUALTABLE
8275 /* Opcode: VFilter P1 P2 P3 P4 *
8276 ** Synopsis: iplan=r[P3] zplan='P4'
8278 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
8279 ** the filtered result set is empty.
8281 ** P4 is either NULL or a string that was generated by the xBestIndex
8282 ** method of the module. The interpretation of the P4 string is left
8283 ** to the module implementation.
8285 ** This opcode invokes the xFilter method on the virtual table specified
8286 ** by P1. The integer query plan parameter to xFilter is stored in register
8287 ** P3. Register P3+1 stores the argc parameter to be passed to the
8288 ** xFilter method. Registers P3+2..P3+1+argc are the argc
8289 ** additional parameters which are passed to
8290 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
8292 ** A jump is made to P2 if the result set after filtering would be empty.
8294 case OP_VFilter: { /* jump, ncycle */
8295 int nArg;
8296 int iQuery;
8297 const sqlite3_module *pModule;
8298 Mem *pQuery;
8299 Mem *pArgc;
8300 sqlite3_vtab_cursor *pVCur;
8301 sqlite3_vtab *pVtab;
8302 VdbeCursor *pCur;
8303 int res;
8304 int i;
8305 Mem **apArg;
8307 pQuery = &aMem[pOp->p3];
8308 pArgc = &pQuery[1];
8309 pCur = p->apCsr[pOp->p1];
8310 assert( memIsValid(pQuery) );
8311 REGISTER_TRACE(pOp->p3, pQuery);
8312 assert( pCur!=0 );
8313 assert( pCur->eCurType==CURTYPE_VTAB );
8314 pVCur = pCur->uc.pVCur;
8315 pVtab = pVCur->pVtab;
8316 pModule = pVtab->pModule;
8318 /* Grab the index number and argc parameters */
8319 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
8320 nArg = (int)pArgc->u.i;
8321 iQuery = (int)pQuery->u.i;
8323 /* Invoke the xFilter method */
8324 apArg = p->apArg;
8325 for(i = 0; i<nArg; i++){
8326 apArg[i] = &pArgc[i+1];
8328 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
8329 sqlite3VtabImportErrmsg(p, pVtab);
8330 if( rc ) goto abort_due_to_error;
8331 res = pModule->xEof(pVCur);
8332 pCur->nullRow = 0;
8333 VdbeBranchTaken(res!=0,2);
8334 if( res ) goto jump_to_p2;
8335 break;
8337 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8339 #ifndef SQLITE_OMIT_VIRTUALTABLE
8340 /* Opcode: VColumn P1 P2 P3 * P5
8341 ** Synopsis: r[P3]=vcolumn(P2)
8343 ** Store in register P3 the value of the P2-th column of
8344 ** the current row of the virtual-table of cursor P1.
8346 ** If the VColumn opcode is being used to fetch the value of
8347 ** an unchanging column during an UPDATE operation, then the P5
8348 ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
8349 ** function to return true inside the xColumn method of the virtual
8350 ** table implementation. The P5 column might also contain other
8351 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
8352 ** unused by OP_VColumn.
8354 case OP_VColumn: { /* ncycle */
8355 sqlite3_vtab *pVtab;
8356 const sqlite3_module *pModule;
8357 Mem *pDest;
8358 sqlite3_context sContext;
8359 FuncDef nullFunc;
8361 VdbeCursor *pCur = p->apCsr[pOp->p1];
8362 assert( pCur!=0 );
8363 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
8364 pDest = &aMem[pOp->p3];
8365 memAboutToChange(p, pDest);
8366 if( pCur->nullRow ){
8367 sqlite3VdbeMemSetNull(pDest);
8368 break;
8370 assert( pCur->eCurType==CURTYPE_VTAB );
8371 pVtab = pCur->uc.pVCur->pVtab;
8372 pModule = pVtab->pModule;
8373 assert( pModule->xColumn );
8374 memset(&sContext, 0, sizeof(sContext));
8375 sContext.pOut = pDest;
8376 sContext.enc = encoding;
8377 nullFunc.pUserData = 0;
8378 nullFunc.funcFlags = SQLITE_RESULT_SUBTYPE;
8379 sContext.pFunc = &nullFunc;
8380 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
8381 if( pOp->p5 & OPFLAG_NOCHNG ){
8382 sqlite3VdbeMemSetNull(pDest);
8383 pDest->flags = MEM_Null|MEM_Zero;
8384 pDest->u.nZero = 0;
8385 }else{
8386 MemSetTypeFlag(pDest, MEM_Null);
8388 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
8389 sqlite3VtabImportErrmsg(p, pVtab);
8390 if( sContext.isError>0 ){
8391 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
8392 rc = sContext.isError;
8394 sqlite3VdbeChangeEncoding(pDest, encoding);
8395 REGISTER_TRACE(pOp->p3, pDest);
8396 UPDATE_MAX_BLOBSIZE(pDest);
8398 if( rc ) goto abort_due_to_error;
8399 break;
8401 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8403 #ifndef SQLITE_OMIT_VIRTUALTABLE
8404 /* Opcode: VNext P1 P2 * * *
8406 ** Advance virtual table P1 to the next row in its result set and
8407 ** jump to instruction P2. Or, if the virtual table has reached
8408 ** the end of its result set, then fall through to the next instruction.
8410 case OP_VNext: { /* jump, ncycle */
8411 sqlite3_vtab *pVtab;
8412 const sqlite3_module *pModule;
8413 int res;
8414 VdbeCursor *pCur;
8416 pCur = p->apCsr[pOp->p1];
8417 assert( pCur!=0 );
8418 assert( pCur->eCurType==CURTYPE_VTAB );
8419 if( pCur->nullRow ){
8420 break;
8422 pVtab = pCur->uc.pVCur->pVtab;
8423 pModule = pVtab->pModule;
8424 assert( pModule->xNext );
8426 /* Invoke the xNext() method of the module. There is no way for the
8427 ** underlying implementation to return an error if one occurs during
8428 ** xNext(). Instead, if an error occurs, true is returned (indicating that
8429 ** data is available) and the error code returned when xColumn or
8430 ** some other method is next invoked on the save virtual table cursor.
8432 rc = pModule->xNext(pCur->uc.pVCur);
8433 sqlite3VtabImportErrmsg(p, pVtab);
8434 if( rc ) goto abort_due_to_error;
8435 res = pModule->xEof(pCur->uc.pVCur);
8436 VdbeBranchTaken(!res,2);
8437 if( !res ){
8438 /* If there is data, jump to P2 */
8439 goto jump_to_p2_and_check_for_interrupt;
8441 goto check_for_interrupt;
8443 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8445 #ifndef SQLITE_OMIT_VIRTUALTABLE
8446 /* Opcode: VRename P1 * * P4 *
8448 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8449 ** This opcode invokes the corresponding xRename method. The value
8450 ** in register P1 is passed as the zName argument to the xRename method.
8452 case OP_VRename: {
8453 sqlite3_vtab *pVtab;
8454 Mem *pName;
8455 int isLegacy;
8457 isLegacy = (db->flags & SQLITE_LegacyAlter);
8458 db->flags |= SQLITE_LegacyAlter;
8459 pVtab = pOp->p4.pVtab->pVtab;
8460 pName = &aMem[pOp->p1];
8461 assert( pVtab->pModule->xRename );
8462 assert( memIsValid(pName) );
8463 assert( p->readOnly==0 );
8464 REGISTER_TRACE(pOp->p1, pName);
8465 assert( pName->flags & MEM_Str );
8466 testcase( pName->enc==SQLITE_UTF8 );
8467 testcase( pName->enc==SQLITE_UTF16BE );
8468 testcase( pName->enc==SQLITE_UTF16LE );
8469 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
8470 if( rc ) goto abort_due_to_error;
8471 rc = pVtab->pModule->xRename(pVtab, pName->z);
8472 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
8473 sqlite3VtabImportErrmsg(p, pVtab);
8474 p->expired = 0;
8475 if( rc ) goto abort_due_to_error;
8476 break;
8478 #endif
8480 #ifndef SQLITE_OMIT_VIRTUALTABLE
8481 /* Opcode: VUpdate P1 P2 P3 P4 P5
8482 ** Synopsis: data=r[P3@P2]
8484 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8485 ** This opcode invokes the corresponding xUpdate method. P2 values
8486 ** are contiguous memory cells starting at P3 to pass to the xUpdate
8487 ** invocation. The value in register (P3+P2-1) corresponds to the
8488 ** p2th element of the argv array passed to xUpdate.
8490 ** The xUpdate method will do a DELETE or an INSERT or both.
8491 ** The argv[0] element (which corresponds to memory cell P3)
8492 ** is the rowid of a row to delete. If argv[0] is NULL then no
8493 ** deletion occurs. The argv[1] element is the rowid of the new
8494 ** row. This can be NULL to have the virtual table select the new
8495 ** rowid for itself. The subsequent elements in the array are
8496 ** the values of columns in the new row.
8498 ** If P2==1 then no insert is performed. argv[0] is the rowid of
8499 ** a row to delete.
8501 ** P1 is a boolean flag. If it is set to true and the xUpdate call
8502 ** is successful, then the value returned by sqlite3_last_insert_rowid()
8503 ** is set to the value of the rowid for the row just inserted.
8505 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
8506 ** apply in the case of a constraint failure on an insert or update.
8508 case OP_VUpdate: {
8509 sqlite3_vtab *pVtab;
8510 const sqlite3_module *pModule;
8511 int nArg;
8512 int i;
8513 sqlite_int64 rowid = 0;
8514 Mem **apArg;
8515 Mem *pX;
8517 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
8518 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
8520 assert( p->readOnly==0 );
8521 if( db->mallocFailed ) goto no_mem;
8522 sqlite3VdbeIncrWriteCounter(p, 0);
8523 pVtab = pOp->p4.pVtab->pVtab;
8524 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8525 rc = SQLITE_LOCKED;
8526 goto abort_due_to_error;
8528 pModule = pVtab->pModule;
8529 nArg = pOp->p2;
8530 assert( pOp->p4type==P4_VTAB );
8531 if( ALWAYS(pModule->xUpdate) ){
8532 u8 vtabOnConflict = db->vtabOnConflict;
8533 apArg = p->apArg;
8534 pX = &aMem[pOp->p3];
8535 for(i=0; i<nArg; i++){
8536 assert( memIsValid(pX) );
8537 memAboutToChange(p, pX);
8538 apArg[i] = pX;
8539 pX++;
8541 db->vtabOnConflict = pOp->p5;
8542 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
8543 db->vtabOnConflict = vtabOnConflict;
8544 sqlite3VtabImportErrmsg(p, pVtab);
8545 if( rc==SQLITE_OK && pOp->p1 ){
8546 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
8547 db->lastRowid = rowid;
8549 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
8550 if( pOp->p5==OE_Ignore ){
8551 rc = SQLITE_OK;
8552 }else{
8553 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
8555 }else{
8556 p->nChange++;
8558 if( rc ) goto abort_due_to_error;
8560 break;
8562 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8564 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8565 /* Opcode: Pagecount P1 P2 * * *
8567 ** Write the current number of pages in database P1 to memory cell P2.
8569 case OP_Pagecount: { /* out2 */
8570 pOut = out2Prerelease(p, pOp);
8571 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
8572 break;
8574 #endif
8577 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
8578 /* Opcode: MaxPgcnt P1 P2 P3 * *
8580 ** Try to set the maximum page count for database P1 to the value in P3.
8581 ** Do not let the maximum page count fall below the current page count and
8582 ** do not change the maximum page count value if P3==0.
8584 ** Store the maximum page count after the change in register P2.
8586 case OP_MaxPgcnt: { /* out2 */
8587 unsigned int newMax;
8588 Btree *pBt;
8590 pOut = out2Prerelease(p, pOp);
8591 pBt = db->aDb[pOp->p1].pBt;
8592 newMax = 0;
8593 if( pOp->p3 ){
8594 newMax = sqlite3BtreeLastPage(pBt);
8595 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
8597 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
8598 break;
8600 #endif
8602 /* Opcode: Function P1 P2 P3 P4 *
8603 ** Synopsis: r[P3]=func(r[P2@NP])
8605 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8606 ** contains a pointer to the function to be run) with arguments taken
8607 ** from register P2 and successors. The number of arguments is in
8608 ** the sqlite3_context object that P4 points to.
8609 ** The result of the function is stored
8610 ** in register P3. Register P3 must not be one of the function inputs.
8612 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8613 ** function was determined to be constant at compile time. If the first
8614 ** argument was constant then bit 0 of P1 is set. This is used to determine
8615 ** whether meta data associated with a user function argument using the
8616 ** sqlite3_set_auxdata() API may be safely retained until the next
8617 ** invocation of this opcode.
8619 ** See also: AggStep, AggFinal, PureFunc
8621 /* Opcode: PureFunc P1 P2 P3 P4 *
8622 ** Synopsis: r[P3]=func(r[P2@NP])
8624 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8625 ** contains a pointer to the function to be run) with arguments taken
8626 ** from register P2 and successors. The number of arguments is in
8627 ** the sqlite3_context object that P4 points to.
8628 ** The result of the function is stored
8629 ** in register P3. Register P3 must not be one of the function inputs.
8631 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8632 ** function was determined to be constant at compile time. If the first
8633 ** argument was constant then bit 0 of P1 is set. This is used to determine
8634 ** whether meta data associated with a user function argument using the
8635 ** sqlite3_set_auxdata() API may be safely retained until the next
8636 ** invocation of this opcode.
8638 ** This opcode works exactly like OP_Function. The only difference is in
8639 ** its name. This opcode is used in places where the function must be
8640 ** purely non-deterministic. Some built-in date/time functions can be
8641 ** either deterministic of non-deterministic, depending on their arguments.
8642 ** When those function are used in a non-deterministic way, they will check
8643 ** to see if they were called using OP_PureFunc instead of OP_Function, and
8644 ** if they were, they throw an error.
8646 ** See also: AggStep, AggFinal, Function
8648 case OP_PureFunc: /* group */
8649 case OP_Function: { /* group */
8650 int i;
8651 sqlite3_context *pCtx;
8653 assert( pOp->p4type==P4_FUNCCTX );
8654 pCtx = pOp->p4.pCtx;
8656 /* If this function is inside of a trigger, the register array in aMem[]
8657 ** might change from one evaluation to the next. The next block of code
8658 ** checks to see if the register array has changed, and if so it
8659 ** reinitializes the relevant parts of the sqlite3_context object */
8660 pOut = &aMem[pOp->p3];
8661 if( pCtx->pOut != pOut ){
8662 pCtx->pVdbe = p;
8663 pCtx->pOut = pOut;
8664 pCtx->enc = encoding;
8665 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
8667 assert( pCtx->pVdbe==p );
8669 memAboutToChange(p, pOut);
8670 #ifdef SQLITE_DEBUG
8671 for(i=0; i<pCtx->argc; i++){
8672 assert( memIsValid(pCtx->argv[i]) );
8673 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
8675 #endif
8676 MemSetTypeFlag(pOut, MEM_Null);
8677 assert( pCtx->isError==0 );
8678 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
8680 /* If the function returned an error, throw an exception */
8681 if( pCtx->isError ){
8682 if( pCtx->isError>0 ){
8683 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
8684 rc = pCtx->isError;
8686 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
8687 pCtx->isError = 0;
8688 if( rc ) goto abort_due_to_error;
8691 assert( (pOut->flags&MEM_Str)==0
8692 || pOut->enc==encoding
8693 || db->mallocFailed );
8694 assert( !sqlite3VdbeMemTooBig(pOut) );
8696 REGISTER_TRACE(pOp->p3, pOut);
8697 UPDATE_MAX_BLOBSIZE(pOut);
8698 break;
8701 /* Opcode: ClrSubtype P1 * * * *
8702 ** Synopsis: r[P1].subtype = 0
8704 ** Clear the subtype from register P1.
8706 case OP_ClrSubtype: { /* in1 */
8707 pIn1 = &aMem[pOp->p1];
8708 pIn1->flags &= ~MEM_Subtype;
8709 break;
8712 /* Opcode: GetSubtype P1 P2 * * *
8713 ** Synopsis: r[P2] = r[P1].subtype
8715 ** Extract the subtype value from register P1 and write that subtype
8716 ** into register P2. If P1 has no subtype, then P1 gets a NULL.
8718 case OP_GetSubtype: { /* in1 out2 */
8719 pIn1 = &aMem[pOp->p1];
8720 pOut = &aMem[pOp->p2];
8721 if( pIn1->flags & MEM_Subtype ){
8722 sqlite3VdbeMemSetInt64(pOut, pIn1->eSubtype);
8723 }else{
8724 sqlite3VdbeMemSetNull(pOut);
8726 break;
8729 /* Opcode: SetSubtype P1 P2 * * *
8730 ** Synopsis: r[P2].subtype = r[P1]
8732 ** Set the subtype value of register P2 to the integer from register P1.
8733 ** If P1 is NULL, clear the subtype from p2.
8735 case OP_SetSubtype: { /* in1 out2 */
8736 pIn1 = &aMem[pOp->p1];
8737 pOut = &aMem[pOp->p2];
8738 if( pIn1->flags & MEM_Null ){
8739 pOut->flags &= ~MEM_Subtype;
8740 }else{
8741 assert( pIn1->flags & MEM_Int );
8742 pOut->flags |= MEM_Subtype;
8743 pOut->eSubtype = (u8)(pIn1->u.i & 0xff);
8745 break;
8748 /* Opcode: FilterAdd P1 * P3 P4 *
8749 ** Synopsis: filter(P1) += key(P3@P4)
8751 ** Compute a hash on the P4 registers starting with r[P3] and
8752 ** add that hash to the bloom filter contained in r[P1].
8754 case OP_FilterAdd: {
8755 u64 h;
8757 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8758 pIn1 = &aMem[pOp->p1];
8759 assert( pIn1->flags & MEM_Blob );
8760 assert( pIn1->n>0 );
8761 h = filterHash(aMem, pOp);
8762 #ifdef SQLITE_DEBUG
8763 if( db->flags&SQLITE_VdbeTrace ){
8764 int ii;
8765 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8766 registerTrace(ii, &aMem[ii]);
8768 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8770 #endif
8771 h %= (pIn1->n*8);
8772 pIn1->z[h/8] |= 1<<(h&7);
8773 break;
8776 /* Opcode: Filter P1 P2 P3 P4 *
8777 ** Synopsis: if key(P3@P4) not in filter(P1) goto P2
8779 ** Compute a hash on the key contained in the P4 registers starting
8780 ** with r[P3]. Check to see if that hash is found in the
8781 ** bloom filter hosted by register P1. If it is not present then
8782 ** maybe jump to P2. Otherwise fall through.
8784 ** False negatives are harmless. It is always safe to fall through,
8785 ** even if the value is in the bloom filter. A false negative causes
8786 ** more CPU cycles to be used, but it should still yield the correct
8787 ** answer. However, an incorrect answer may well arise from a
8788 ** false positive - if the jump is taken when it should fall through.
8790 case OP_Filter: { /* jump */
8791 u64 h;
8793 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8794 pIn1 = &aMem[pOp->p1];
8795 assert( (pIn1->flags & MEM_Blob)!=0 );
8796 assert( pIn1->n >= 1 );
8797 h = filterHash(aMem, pOp);
8798 #ifdef SQLITE_DEBUG
8799 if( db->flags&SQLITE_VdbeTrace ){
8800 int ii;
8801 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8802 registerTrace(ii, &aMem[ii]);
8804 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8806 #endif
8807 h %= (pIn1->n*8);
8808 if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
8809 VdbeBranchTaken(1, 2);
8810 p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
8811 goto jump_to_p2;
8812 }else{
8813 p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
8814 VdbeBranchTaken(0, 2);
8816 break;
8819 /* Opcode: Trace P1 P2 * P4 *
8821 ** Write P4 on the statement trace output if statement tracing is
8822 ** enabled.
8824 ** Operand P1 must be 0x7fffffff and P2 must positive.
8826 /* Opcode: Init P1 P2 P3 P4 *
8827 ** Synopsis: Start at P2
8829 ** Programs contain a single instance of this opcode as the very first
8830 ** opcode.
8832 ** If tracing is enabled (by the sqlite3_trace()) interface, then
8833 ** the UTF-8 string contained in P4 is emitted on the trace callback.
8834 ** Or if P4 is blank, use the string returned by sqlite3_sql().
8836 ** If P2 is not zero, jump to instruction P2.
8838 ** Increment the value of P1 so that OP_Once opcodes will jump the
8839 ** first time they are evaluated for this run.
8841 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
8842 ** error is encountered.
8844 case OP_Trace:
8845 case OP_Init: { /* jump0 */
8846 int i;
8847 #ifndef SQLITE_OMIT_TRACE
8848 char *zTrace;
8849 #endif
8851 /* If the P4 argument is not NULL, then it must be an SQL comment string.
8852 ** The "--" string is broken up to prevent false-positives with srcck1.c.
8854 ** This assert() provides evidence for:
8855 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
8856 ** would have been returned by the legacy sqlite3_trace() interface by
8857 ** using the X argument when X begins with "--" and invoking
8858 ** sqlite3_expanded_sql(P) otherwise.
8860 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
8862 /* OP_Init is always instruction 0 */
8863 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
8865 #ifndef SQLITE_OMIT_TRACE
8866 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
8867 && p->minWriteFileFormat!=254 /* tag-20220401a */
8868 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8870 #ifndef SQLITE_OMIT_DEPRECATED
8871 if( db->mTrace & SQLITE_TRACE_LEGACY ){
8872 char *z = sqlite3VdbeExpandSql(p, zTrace);
8873 db->trace.xLegacy(db->pTraceArg, z);
8874 sqlite3_free(z);
8875 }else
8876 #endif
8877 if( db->nVdbeExec>1 ){
8878 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
8879 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
8880 sqlite3DbFree(db, z);
8881 }else{
8882 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
8885 #ifdef SQLITE_USE_FCNTL_TRACE
8886 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
8887 if( zTrace ){
8888 int j;
8889 for(j=0; j<db->nDb; j++){
8890 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
8891 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
8894 #endif /* SQLITE_USE_FCNTL_TRACE */
8895 #ifdef SQLITE_DEBUG
8896 if( (db->flags & SQLITE_SqlTrace)!=0
8897 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8899 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8901 #endif /* SQLITE_DEBUG */
8902 #endif /* SQLITE_OMIT_TRACE */
8903 assert( pOp->p2>0 );
8904 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8905 if( pOp->opcode==OP_Trace ) break;
8906 for(i=1; i<p->nOp; i++){
8907 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8909 pOp->p1 = 0;
8911 pOp->p1++;
8912 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8913 goto jump_to_p2;
8916 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8917 /* Opcode: CursorHint P1 * * P4 *
8919 ** Provide a hint to cursor P1 that it only needs to return rows that
8920 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
8921 ** to values currently held in registers. TK_COLUMN terms in the P4
8922 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8924 case OP_CursorHint: {
8925 VdbeCursor *pC;
8927 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8928 assert( pOp->p4type==P4_EXPR );
8929 pC = p->apCsr[pOp->p1];
8930 if( pC ){
8931 assert( pC->eCurType==CURTYPE_BTREE );
8932 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8933 pOp->p4.pExpr, aMem);
8935 break;
8937 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8939 #ifdef SQLITE_DEBUG
8940 /* Opcode: Abortable * * * * *
8942 ** Verify that an Abort can happen. Assert if an Abort at this point
8943 ** might cause database corruption. This opcode only appears in debugging
8944 ** builds.
8946 ** An Abort is safe if either there have been no writes, or if there is
8947 ** an active statement journal.
8949 case OP_Abortable: {
8950 sqlite3VdbeAssertAbortable(p);
8951 break;
8953 #endif
8955 #ifdef SQLITE_DEBUG
8956 /* Opcode: ReleaseReg P1 P2 P3 * P5
8957 ** Synopsis: release r[P1@P2] mask P3
8959 ** Release registers from service. Any content that was in the
8960 ** the registers is unreliable after this opcode completes.
8962 ** The registers released will be the P2 registers starting at P1,
8963 ** except if bit ii of P3 set, then do not release register P1+ii.
8964 ** In other words, P3 is a mask of registers to preserve.
8966 ** Releasing a register clears the Mem.pScopyFrom pointer. That means
8967 ** that if the content of the released register was set using OP_SCopy,
8968 ** a change to the value of the source register for the OP_SCopy will no longer
8969 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8971 ** If P5 is set, then all released registers have their type set
8972 ** to MEM_Undefined so that any subsequent attempt to read the released
8973 ** register (before it is reinitialized) will generate an assertion fault.
8975 ** P5 ought to be set on every call to this opcode.
8976 ** However, there are places in the code generator will release registers
8977 ** before their are used, under the (valid) assumption that the registers
8978 ** will not be reallocated for some other purpose before they are used and
8979 ** hence are safe to release.
8981 ** This opcode is only available in testing and debugging builds. It is
8982 ** not generated for release builds. The purpose of this opcode is to help
8983 ** validate the generated bytecode. This opcode does not actually contribute
8984 ** to computing an answer.
8986 case OP_ReleaseReg: {
8987 Mem *pMem;
8988 int i;
8989 u32 constMask;
8990 assert( pOp->p1>0 );
8991 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8992 pMem = &aMem[pOp->p1];
8993 constMask = pOp->p3;
8994 for(i=0; i<pOp->p2; i++, pMem++){
8995 if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8996 pMem->pScopyFrom = 0;
8997 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
9000 break;
9002 #endif
9004 /* Opcode: Noop * * * * *
9006 ** Do nothing. This instruction is often useful as a jump
9007 ** destination.
9010 ** The magic Explain opcode are only inserted when explain==2 (which
9011 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
9012 ** This opcode records information from the optimizer. It is the
9013 ** the same as a no-op. This opcodesnever appears in a real VM program.
9015 default: { /* This is really OP_Noop, OP_Explain */
9016 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
9018 break;
9021 /*****************************************************************************
9022 ** The cases of the switch statement above this line should all be indented
9023 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
9024 ** readability. From this point on down, the normal indentation rules are
9025 ** restored.
9026 *****************************************************************************/
9029 #if defined(VDBE_PROFILE)
9030 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
9031 pnCycle = 0;
9032 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9033 if( pnCycle ){
9034 *pnCycle += sqlite3Hwtime();
9035 pnCycle = 0;
9037 #endif
9039 /* The following code adds nothing to the actual functionality
9040 ** of the program. It is only here for testing and debugging.
9041 ** On the other hand, it does burn CPU cycles every time through
9042 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
9044 #ifndef NDEBUG
9045 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
9047 #ifdef SQLITE_DEBUG
9048 if( db->flags & SQLITE_VdbeTrace ){
9049 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
9050 if( rc!=0 ) printf("rc=%d\n",rc);
9051 if( opProperty & (OPFLG_OUT2) ){
9052 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
9054 if( opProperty & OPFLG_OUT3 ){
9055 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
9057 if( opProperty==0xff ){
9058 /* Never happens. This code exists to avoid a harmless linkage
9059 ** warning about sqlite3VdbeRegisterDump() being defined but not
9060 ** used. */
9061 sqlite3VdbeRegisterDump(p);
9064 #endif /* SQLITE_DEBUG */
9065 #endif /* NDEBUG */
9066 } /* The end of the for(;;) loop the loops through opcodes */
9068 /* If we reach this point, it means that execution is finished with
9069 ** an error of some kind.
9071 abort_due_to_error:
9072 if( db->mallocFailed ){
9073 rc = SQLITE_NOMEM_BKPT;
9074 }else if( rc==SQLITE_IOERR_CORRUPTFS ){
9075 rc = SQLITE_CORRUPT_BKPT;
9077 assert( rc );
9078 #ifdef SQLITE_DEBUG
9079 if( db->flags & SQLITE_VdbeTrace ){
9080 const char *zTrace = p->zSql;
9081 if( zTrace==0 ){
9082 if( aOp[0].opcode==OP_Trace ){
9083 zTrace = aOp[0].p4.z;
9085 if( zTrace==0 ) zTrace = "???";
9087 printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
9089 #endif
9090 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
9091 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
9093 p->rc = rc;
9094 sqlite3SystemError(db, rc);
9095 testcase( sqlite3GlobalConfig.xLog!=0 );
9096 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
9097 (int)(pOp - aOp), p->zSql, p->zErrMsg);
9098 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
9099 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
9100 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
9101 db->flags |= SQLITE_CorruptRdOnly;
9103 rc = SQLITE_ERROR;
9104 if( resetSchemaOnFault>0 ){
9105 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
9108 /* This is the only way out of this procedure. We have to
9109 ** release the mutexes on btrees that were acquired at the
9110 ** top. */
9111 vdbe_return:
9112 #if defined(VDBE_PROFILE)
9113 if( pnCycle ){
9114 *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
9115 pnCycle = 0;
9117 #elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9118 if( pnCycle ){
9119 *pnCycle += sqlite3Hwtime();
9120 pnCycle = 0;
9122 #endif
9124 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9125 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
9126 nProgressLimit += db->nProgressOps;
9127 if( db->xProgress(db->pProgressArg) ){
9128 nProgressLimit = LARGEST_UINT64;
9129 rc = SQLITE_INTERRUPT;
9130 goto abort_due_to_error;
9133 #endif
9134 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
9135 if( DbMaskNonZero(p->lockMask) ){
9136 sqlite3VdbeLeave(p);
9138 assert( rc!=SQLITE_OK || nExtraDelete==0
9139 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
9141 return rc;
9143 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
9144 ** is encountered.
9146 too_big:
9147 sqlite3VdbeError(p, "string or blob too big");
9148 rc = SQLITE_TOOBIG;
9149 goto abort_due_to_error;
9151 /* Jump to here if a malloc() fails.
9153 no_mem:
9154 sqlite3OomFault(db);
9155 sqlite3VdbeError(p, "out of memory");
9156 rc = SQLITE_NOMEM_BKPT;
9157 goto abort_due_to_error;
9159 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
9160 ** flag.
9162 abort_due_to_interrupt:
9163 assert( AtomicLoad(&db->u1.isInterrupted) );
9164 rc = SQLITE_INTERRUPT;
9165 goto abort_due_to_error;