4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** The code in this file implements the function that runs the
13 ** bytecode of a prepared statement.
15 ** Various scripts scan this source file in order to generate HTML
16 ** documentation, headers files, or other derived files. The formatting
17 ** of the code in this file is, therefore, important. See other comments
18 ** in this file for details. If in doubt, do not deviate from existing
19 ** commenting and indentation practices when changing or adding code.
21 #include "sqliteInt.h"
25 ** Invoke this macro on memory cells just prior to changing the
26 ** value of the cell. This macro verifies that shallow copies are
27 ** not misused. A shallow copy of a string or blob just copies a
28 ** pointer to the string or blob, not the content. If the original
29 ** is changed while the copy is still in use, the string or blob might
30 ** be changed out from under the copy. This macro verifies that nothing
31 ** like that ever happens.
34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
36 # define memAboutToChange(P,M)
40 ** Given a cursor number and a column for a table or index, compute a
41 ** hash value for use in the Mem.iTabColHash value. The iTabColHash
42 ** column is only used for verification - it is omitted from production
43 ** builds. Collisions are harmless in the sense that the correct answer
44 ** still results. The only harm of collisions is that they can potential
45 ** reduce column-cache error detection during SQLITE_DEBUG builds.
47 ** No valid hash should be 0.
49 #define TableColumnHash(T,C) (((u32)(T)<<16)^(u32)(C+2))
52 ** The following global variable is incremented every time a cursor
53 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
54 ** procedures use this information to make sure that indices are
55 ** working correctly. This variable has no function other than to
56 ** help verify the correct operation of the library.
59 int sqlite3_search_count
= 0;
63 ** When this global variable is positive, it gets decremented once before
64 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
65 ** field of the sqlite3 structure is set in order to simulate an interrupt.
67 ** This facility is used for testing purposes only. It does not function
68 ** in an ordinary build.
71 int sqlite3_interrupt_count
= 0;
75 ** The next global variable is incremented each type the OP_Sort opcode
76 ** is executed. The test procedures use this information to make sure that
77 ** sorting is occurring or not occurring at appropriate times. This variable
78 ** has no function other than to help verify the correct operation of the
82 int sqlite3_sort_count
= 0;
86 ** The next global variable records the size of the largest MEM_Blob
87 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
88 ** use this information to make sure that the zero-blob functionality
89 ** is working correctly. This variable has no function other than to
90 ** help verify the correct operation of the library.
93 int sqlite3_max_blobsize
= 0;
94 static void updateMaxBlobsize(Mem
*p
){
95 if( (p
->flags
& (MEM_Str
|MEM_Blob
))!=0 && p
->n
>sqlite3_max_blobsize
){
96 sqlite3_max_blobsize
= p
->n
;
102 ** This macro evaluates to true if either the update hook or the preupdate
103 ** hook are enabled for database connect DB.
105 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
106 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
108 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
112 ** The next global variable is incremented each time the OP_Found opcode
113 ** is executed. This is used to test whether or not the foreign key
114 ** operation implemented using OP_FkIsZero is working. This variable
115 ** has no function other than to help verify the correct operation of the
119 int sqlite3_found_count
= 0;
123 ** Test a register to see if it exceeds the current maximum blob size.
124 ** If it does, record the new maximum blob size.
126 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
127 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
129 # define UPDATE_MAX_BLOBSIZE(P)
133 ** Invoke the VDBE coverage callback, if that callback is defined. This
134 ** feature is used for test suite validation only and does not appear an
135 ** production builds.
137 ** M is an integer between 2 and 4. 2 indicates a ordinary two-way
138 ** branch (I=0 means fall through and I=1 means taken). 3 indicates
139 ** a 3-way branch where the third way is when one of the operands is
140 ** NULL. 4 indicates the OP_Jump instruction which has three destinations
141 ** depending on whether the first operand is less than, equal to, or greater
144 ** iSrcLine is the source code line (from the __LINE__ macro) that
145 ** generated the VDBE instruction combined with flag bits. The source
146 ** code line number is in the lower 24 bits of iSrcLine and the upper
147 ** 8 bytes are flags. The lower three bits of the flags indicate
148 ** values for I that should never occur. For example, if the branch is
149 ** always taken, the flags should be 0x05 since the fall-through and
150 ** alternate branch are never taken. If a branch is never taken then
151 ** flags should be 0x06 since only the fall-through approach is allowed.
153 ** Bit 0x04 of the flags indicates an OP_Jump opcode that is only
154 ** interested in equal or not-equal. In other words, I==0 and I==2
155 ** should be treated the same.
157 ** Since only a line number is retained, not the filename, this macro
158 ** only works for amalgamation builds. But that is ok, since these macros
159 ** should be no-ops except for special builds used to measure test coverage.
161 #if !defined(SQLITE_VDBE_COVERAGE)
162 # define VdbeBranchTaken(I,M)
164 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
165 static void vdbeTakeBranch(u32 iSrcLine
, u8 I
, u8 M
){
167 assert( I
<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
168 assert( M
<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
169 assert( I
<M
); /* I can only be 2 if M is 3 or 4 */
170 /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
172 /* The upper 8 bits of iSrcLine are flags. The lower three bits of
173 ** the flags indicate directions that the branch can never go. If
174 ** a branch really does go in one of those directions, assert right
176 mNever
= iSrcLine
>> 24;
177 assert( (I
& mNever
)==0 );
178 if( sqlite3GlobalConfig
.xVdbeBranch
==0 ) return; /*NO_TEST*/
180 if( M
==2 ) I
|= 0x04;
183 if( (mNever
&0x08)!=0 && (I
&0x05)!=0) I
|= 0x05; /*NO_TEST*/
185 sqlite3GlobalConfig
.xVdbeBranch(sqlite3GlobalConfig
.pVdbeBranchArg
,
186 iSrcLine
&0xffffff, I
, M
);
191 ** Convert the given register into a string if it isn't one
192 ** already. Return non-zero if a malloc() fails.
194 #define Stringify(P, enc) \
195 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
199 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
200 ** a pointer to a dynamically allocated string where some other entity
201 ** is responsible for deallocating that string. Because the register
202 ** does not control the string, it might be deleted without the register
205 ** This routine converts an ephemeral string into a dynamically allocated
206 ** string that the register itself controls. In other words, it
207 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
209 #define Deephemeralize(P) \
210 if( ((P)->flags&MEM_Ephem)!=0 \
211 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
213 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
214 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
217 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
218 ** if we run out of memory.
220 static VdbeCursor
*allocateCursor(
221 Vdbe
*p
, /* The virtual machine */
222 int iCur
, /* Index of the new VdbeCursor */
223 int nField
, /* Number of fields in the table or index */
224 int iDb
, /* Database the cursor belongs to, or -1 */
225 u8 eCurType
/* Type of the new cursor */
227 /* Find the memory cell that will be used to store the blob of memory
228 ** required for this VdbeCursor structure. It is convenient to use a
229 ** vdbe memory cell to manage the memory allocation required for a
230 ** VdbeCursor structure for the following reasons:
232 ** * Sometimes cursor numbers are used for a couple of different
233 ** purposes in a vdbe program. The different uses might require
234 ** different sized allocations. Memory cells provide growable
237 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
238 ** be freed lazily via the sqlite3_release_memory() API. This
239 ** minimizes the number of malloc calls made by the system.
241 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
242 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
243 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
245 Mem
*pMem
= iCur
>0 ? &p
->aMem
[p
->nMem
-iCur
] : p
->aMem
;
250 ROUND8(sizeof(VdbeCursor
)) + 2*sizeof(u32
)*nField
+
251 (eCurType
==CURTYPE_BTREE
?sqlite3BtreeCursorSize():0);
253 assert( iCur
>=0 && iCur
<p
->nCursor
);
254 if( p
->apCsr
[iCur
] ){ /*OPTIMIZATION-IF-FALSE*/
255 sqlite3VdbeFreeCursor(p
, p
->apCsr
[iCur
]);
258 if( SQLITE_OK
==sqlite3VdbeMemClearAndResize(pMem
, nByte
) ){
259 p
->apCsr
[iCur
] = pCx
= (VdbeCursor
*)pMem
->z
;
260 memset(pCx
, 0, offsetof(VdbeCursor
,pAltCursor
));
261 pCx
->eCurType
= eCurType
;
263 pCx
->nField
= nField
;
264 pCx
->aOffset
= &pCx
->aType
[nField
];
265 if( eCurType
==CURTYPE_BTREE
){
266 pCx
->uc
.pCursor
= (BtCursor
*)
267 &pMem
->z
[ROUND8(sizeof(VdbeCursor
))+2*sizeof(u32
)*nField
];
268 sqlite3BtreeCursorZero(pCx
->uc
.pCursor
);
275 ** Try to convert a value into a numeric representation if we can
276 ** do so without loss of information. In other words, if the string
277 ** looks like a number, convert it into a number. If it does not
278 ** look like a number, leave it alone.
280 ** If the bTryForInt flag is true, then extra effort is made to give
281 ** an integer representation. Strings that look like floating point
282 ** values but which have no fractional component (example: '48.00')
283 ** will have a MEM_Int representation when bTryForInt is true.
285 ** If bTryForInt is false, then if the input string contains a decimal
286 ** point or exponential notation, the result is only MEM_Real, even
287 ** if there is an exact integer representation of the quantity.
289 static void applyNumericAffinity(Mem
*pRec
, int bTryForInt
){
293 assert( (pRec
->flags
& (MEM_Str
|MEM_Int
|MEM_Real
))==MEM_Str
);
294 if( sqlite3AtoF(pRec
->z
, &rValue
, pRec
->n
, enc
)==0 ) return;
295 if( 0==sqlite3Atoi64(pRec
->z
, &iValue
, pRec
->n
, enc
) ){
297 pRec
->flags
|= MEM_Int
;
300 pRec
->flags
|= MEM_Real
;
301 if( bTryForInt
) sqlite3VdbeIntegerAffinity(pRec
);
303 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
304 ** string representation after computing a numeric equivalent, because the
305 ** string representation might not be the canonical representation for the
306 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
307 pRec
->flags
&= ~MEM_Str
;
311 ** Processing is determine by the affinity parameter:
313 ** SQLITE_AFF_INTEGER:
315 ** SQLITE_AFF_NUMERIC:
316 ** Try to convert pRec to an integer representation or a
317 ** floating-point representation if an integer representation
318 ** is not possible. Note that the integer representation is
319 ** always preferred, even if the affinity is REAL, because
320 ** an integer representation is more space efficient on disk.
323 ** Convert pRec to a text representation.
326 ** No-op. pRec is unchanged.
328 static void applyAffinity(
329 Mem
*pRec
, /* The value to apply affinity to */
330 char affinity
, /* The affinity to be applied */
331 u8 enc
/* Use this text encoding */
333 if( affinity
>=SQLITE_AFF_NUMERIC
){
334 assert( affinity
==SQLITE_AFF_INTEGER
|| affinity
==SQLITE_AFF_REAL
335 || affinity
==SQLITE_AFF_NUMERIC
);
336 if( (pRec
->flags
& MEM_Int
)==0 ){ /*OPTIMIZATION-IF-FALSE*/
337 if( (pRec
->flags
& MEM_Real
)==0 ){
338 if( pRec
->flags
& MEM_Str
) applyNumericAffinity(pRec
,1);
340 sqlite3VdbeIntegerAffinity(pRec
);
343 }else if( affinity
==SQLITE_AFF_TEXT
){
344 /* Only attempt the conversion to TEXT if there is an integer or real
345 ** representation (blob and NULL do not get converted) but no string
346 ** representation. It would be harmless to repeat the conversion if
347 ** there is already a string rep, but it is pointless to waste those
349 if( 0==(pRec
->flags
&MEM_Str
) ){ /*OPTIMIZATION-IF-FALSE*/
350 if( (pRec
->flags
&(MEM_Real
|MEM_Int
)) ){
351 sqlite3VdbeMemStringify(pRec
, enc
, 1);
354 pRec
->flags
&= ~(MEM_Real
|MEM_Int
);
359 ** Try to convert the type of a function argument or a result column
360 ** into a numeric representation. Use either INTEGER or REAL whichever
361 ** is appropriate. But only do the conversion if it is possible without
362 ** loss of information and return the revised type of the argument.
364 int sqlite3_value_numeric_type(sqlite3_value
*pVal
){
365 int eType
= sqlite3_value_type(pVal
);
366 if( eType
==SQLITE_TEXT
){
367 Mem
*pMem
= (Mem
*)pVal
;
368 applyNumericAffinity(pMem
, 0);
369 eType
= sqlite3_value_type(pVal
);
375 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
376 ** not the internal Mem* type.
378 void sqlite3ValueApplyAffinity(
383 applyAffinity((Mem
*)pVal
, affinity
, enc
);
387 ** pMem currently only holds a string type (or maybe a BLOB that we can
388 ** interpret as a string if we want to). Compute its corresponding
389 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
392 static u16 SQLITE_NOINLINE
computeNumericType(Mem
*pMem
){
393 assert( (pMem
->flags
& (MEM_Int
|MEM_Real
))==0 );
394 assert( (pMem
->flags
& (MEM_Str
|MEM_Blob
))!=0 );
395 if( sqlite3AtoF(pMem
->z
, &pMem
->u
.r
, pMem
->n
, pMem
->enc
)==0 ){
398 if( sqlite3Atoi64(pMem
->z
, &pMem
->u
.i
, pMem
->n
, pMem
->enc
)==0 ){
405 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
408 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
409 ** But it does set pMem->u.r and pMem->u.i appropriately.
411 static u16
numericType(Mem
*pMem
){
412 if( pMem
->flags
& (MEM_Int
|MEM_Real
) ){
413 return pMem
->flags
& (MEM_Int
|MEM_Real
);
415 if( pMem
->flags
& (MEM_Str
|MEM_Blob
) ){
416 return computeNumericType(pMem
);
423 ** Write a nice string representation of the contents of cell pMem
424 ** into buffer zBuf, length nBuf.
426 void sqlite3VdbeMemPrettyPrint(Mem
*pMem
, char *zBuf
){
430 static const char *const encnames
[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
437 assert( (f
& (MEM_Static
|MEM_Ephem
))==0 );
438 }else if( f
& MEM_Static
){
440 assert( (f
& (MEM_Dyn
|MEM_Ephem
))==0 );
441 }else if( f
& MEM_Ephem
){
443 assert( (f
& (MEM_Static
|MEM_Dyn
))==0 );
448 sqlite3_snprintf(100, zCsr
, "%d[", pMem
->n
);
449 zCsr
+= sqlite3Strlen30(zCsr
);
450 for(i
=0; i
<16 && i
<pMem
->n
; i
++){
451 sqlite3_snprintf(100, zCsr
, "%02X", ((int)pMem
->z
[i
] & 0xFF));
452 zCsr
+= sqlite3Strlen30(zCsr
);
454 for(i
=0; i
<16 && i
<pMem
->n
; i
++){
456 if( z
<32 || z
>126 ) *zCsr
++ = '.';
461 sqlite3_snprintf(100, zCsr
,"+%dz",pMem
->u
.nZero
);
462 zCsr
+= sqlite3Strlen30(zCsr
);
465 }else if( f
& MEM_Str
){
470 assert( (f
& (MEM_Static
|MEM_Ephem
))==0 );
471 }else if( f
& MEM_Static
){
473 assert( (f
& (MEM_Dyn
|MEM_Ephem
))==0 );
474 }else if( f
& MEM_Ephem
){
476 assert( (f
& (MEM_Static
|MEM_Dyn
))==0 );
481 sqlite3_snprintf(100, &zBuf
[k
], "%d", pMem
->n
);
482 k
+= sqlite3Strlen30(&zBuf
[k
]);
484 for(j
=0; j
<15 && j
<pMem
->n
; j
++){
486 if( c
>=0x20 && c
<0x7f ){
493 sqlite3_snprintf(100,&zBuf
[k
], encnames
[pMem
->enc
]);
494 k
+= sqlite3Strlen30(&zBuf
[k
]);
502 ** Print the value of a register for tracing purposes:
504 static void memTracePrint(Mem
*p
){
505 if( p
->flags
& MEM_Undefined
){
506 printf(" undefined");
507 }else if( p
->flags
& MEM_Null
){
508 printf(p
->flags
& MEM_Zero
? " NULL-nochng" : " NULL");
509 }else if( (p
->flags
& (MEM_Int
|MEM_Str
))==(MEM_Int
|MEM_Str
) ){
510 printf(" si:%lld", p
->u
.i
);
511 }else if( p
->flags
& MEM_Int
){
512 printf(" i:%lld", p
->u
.i
);
513 #ifndef SQLITE_OMIT_FLOATING_POINT
514 }else if( p
->flags
& MEM_Real
){
515 printf(" r:%g", p
->u
.r
);
517 }else if( p
->flags
& MEM_RowSet
){
521 sqlite3VdbeMemPrettyPrint(p
, zBuf
);
524 if( p
->flags
& MEM_Subtype
) printf(" subtype=0x%02x", p
->eSubtype
);
526 static void registerTrace(int iReg
, Mem
*p
){
527 printf("REG[%d] = ", iReg
);
530 sqlite3VdbeCheckMemInvariants(p
);
535 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
537 # define REGISTER_TRACE(R,M)
544 ** hwtime.h contains inline assembler code for implementing
545 ** high-performance timing routines.
553 ** This function is only called from within an assert() expression. It
554 ** checks that the sqlite3.nTransaction variable is correctly set to
555 ** the number of non-transaction savepoints currently in the
556 ** linked list starting at sqlite3.pSavepoint.
560 ** assert( checkSavepointCount(db) );
562 static int checkSavepointCount(sqlite3
*db
){
565 for(p
=db
->pSavepoint
; p
; p
=p
->pNext
) n
++;
566 assert( n
==(db
->nSavepoint
+ db
->isTransactionSavepoint
) );
572 ** Return the register of pOp->p2 after first preparing it to be
573 ** overwritten with an integer value.
575 static SQLITE_NOINLINE Mem
*out2PrereleaseWithClear(Mem
*pOut
){
576 sqlite3VdbeMemSetNull(pOut
);
577 pOut
->flags
= MEM_Int
;
580 static Mem
*out2Prerelease(Vdbe
*p
, VdbeOp
*pOp
){
583 assert( pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
) );
584 pOut
= &p
->aMem
[pOp
->p2
];
585 memAboutToChange(p
, pOut
);
586 if( VdbeMemDynamic(pOut
) ){ /*OPTIMIZATION-IF-FALSE*/
587 return out2PrereleaseWithClear(pOut
);
589 pOut
->flags
= MEM_Int
;
596 ** Execute as much of a VDBE program as we can.
597 ** This is the core of sqlite3_step().
600 Vdbe
*p
/* The VDBE */
602 Op
*aOp
= p
->aOp
; /* Copy of p->aOp */
603 Op
*pOp
= aOp
; /* Current operation */
604 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
605 Op
*pOrigOp
; /* Value of pOp at the top of the loop */
608 int nExtraDelete
= 0; /* Verifies FORDELETE and AUXDELETE flags */
610 int rc
= SQLITE_OK
; /* Value to return */
611 sqlite3
*db
= p
->db
; /* The database */
612 u8 resetSchemaOnFault
= 0; /* Reset schema after an error if positive */
613 u8 encoding
= ENC(db
); /* The database encoding */
614 int iCompare
= 0; /* Result of last comparison */
615 unsigned nVmStep
= 0; /* Number of virtual machine steps */
616 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
617 unsigned nProgressLimit
; /* Invoke xProgress() when nVmStep reaches this */
619 Mem
*aMem
= p
->aMem
; /* Copy of p->aMem */
620 Mem
*pIn1
= 0; /* 1st input operand */
621 Mem
*pIn2
= 0; /* 2nd input operand */
622 Mem
*pIn3
= 0; /* 3rd input operand */
623 Mem
*pOut
= 0; /* Output operand */
625 u64 start
; /* CPU clock count at start of opcode */
627 /*** INSERT STACK UNION HERE ***/
629 assert( p
->magic
==VDBE_MAGIC_RUN
); /* sqlite3_step() verifies this */
631 if( p
->rc
==SQLITE_NOMEM
){
632 /* This happens if a malloc() inside a call to sqlite3_column_text() or
633 ** sqlite3_column_text16() failed. */
636 assert( p
->rc
==SQLITE_OK
|| (p
->rc
&0xff)==SQLITE_BUSY
);
637 assert( p
->bIsReader
|| p
->readOnly
!=0 );
639 assert( p
->explain
==0 );
641 db
->busyHandler
.nBusy
= 0;
642 if( db
->u1
.isInterrupted
) goto abort_due_to_interrupt
;
643 sqlite3VdbeIOTraceSql(p
);
644 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
646 u32 iPrior
= p
->aCounter
[SQLITE_STMTSTATUS_VM_STEP
];
647 assert( 0 < db
->nProgressOps
);
648 nProgressLimit
= db
->nProgressOps
- (iPrior
% db
->nProgressOps
);
650 nProgressLimit
= 0xffffffff;
654 sqlite3BeginBenignMalloc();
656 && (p
->db
->flags
& (SQLITE_VdbeListing
|SQLITE_VdbeEQP
|SQLITE_VdbeTrace
))!=0
660 sqlite3VdbePrintSql(p
);
661 if( p
->db
->flags
& SQLITE_VdbeListing
){
662 printf("VDBE Program Listing:\n");
663 for(i
=0; i
<p
->nOp
; i
++){
664 sqlite3VdbePrintOp(stdout
, i
, &aOp
[i
]);
667 if( p
->db
->flags
& SQLITE_VdbeEQP
){
668 for(i
=0; i
<p
->nOp
; i
++){
669 if( aOp
[i
].opcode
==OP_Explain
){
670 if( once
) printf("VDBE Query Plan:\n");
671 printf("%s\n", aOp
[i
].p4
.z
);
676 if( p
->db
->flags
& SQLITE_VdbeTrace
) printf("VDBE Trace:\n");
678 sqlite3EndBenignMalloc();
680 for(pOp
=&aOp
[p
->pc
]; 1; pOp
++){
681 /* Errors are detected by individual opcodes, with an immediate
682 ** jumps to abort_due_to_error. */
683 assert( rc
==SQLITE_OK
);
685 assert( pOp
>=aOp
&& pOp
<&aOp
[p
->nOp
]);
687 start
= sqlite3NProfileCnt
? sqlite3NProfileCnt
: sqlite3Hwtime();
690 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
691 if( p
->anExec
) p
->anExec
[(int)(pOp
-aOp
)]++;
694 /* Only allow tracing if SQLITE_DEBUG is defined.
697 if( db
->flags
& SQLITE_VdbeTrace
){
698 sqlite3VdbePrintOp(stdout
, (int)(pOp
- aOp
), pOp
);
703 /* Check to see if we need to simulate an interrupt. This only happens
704 ** if we have a special test build.
707 if( sqlite3_interrupt_count
>0 ){
708 sqlite3_interrupt_count
--;
709 if( sqlite3_interrupt_count
==0 ){
710 sqlite3_interrupt(db
);
715 /* Sanity checking on other operands */
718 u8 opProperty
= sqlite3OpcodeProperty
[pOp
->opcode
];
719 if( (opProperty
& OPFLG_IN1
)!=0 ){
721 assert( pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
722 assert( memIsValid(&aMem
[pOp
->p1
]) );
723 assert( sqlite3VdbeCheckMemInvariants(&aMem
[pOp
->p1
]) );
724 REGISTER_TRACE(pOp
->p1
, &aMem
[pOp
->p1
]);
726 if( (opProperty
& OPFLG_IN2
)!=0 ){
728 assert( pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
) );
729 assert( memIsValid(&aMem
[pOp
->p2
]) );
730 assert( sqlite3VdbeCheckMemInvariants(&aMem
[pOp
->p2
]) );
731 REGISTER_TRACE(pOp
->p2
, &aMem
[pOp
->p2
]);
733 if( (opProperty
& OPFLG_IN3
)!=0 ){
735 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
736 assert( memIsValid(&aMem
[pOp
->p3
]) );
737 assert( sqlite3VdbeCheckMemInvariants(&aMem
[pOp
->p3
]) );
738 REGISTER_TRACE(pOp
->p3
, &aMem
[pOp
->p3
]);
740 if( (opProperty
& OPFLG_OUT2
)!=0 ){
742 assert( pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
) );
743 memAboutToChange(p
, &aMem
[pOp
->p2
]);
745 if( (opProperty
& OPFLG_OUT3
)!=0 ){
747 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
748 memAboutToChange(p
, &aMem
[pOp
->p3
]);
752 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
756 switch( pOp
->opcode
){
758 /*****************************************************************************
759 ** What follows is a massive switch statement where each case implements a
760 ** separate instruction in the virtual machine. If we follow the usual
761 ** indentation conventions, each case should be indented by 6 spaces. But
762 ** that is a lot of wasted space on the left margin. So the code within
763 ** the switch statement will break with convention and be flush-left. Another
764 ** big comment (similar to this one) will mark the point in the code where
765 ** we transition back to normal indentation.
767 ** The formatting of each case is important. The makefile for SQLite
768 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
769 ** file looking for lines that begin with "case OP_". The opcodes.h files
770 ** will be filled with #defines that give unique integer values to each
771 ** opcode and the opcodes.c file is filled with an array of strings where
772 ** each string is the symbolic name for the corresponding opcode. If the
773 ** case statement is followed by a comment of the form "/# same as ... #/"
774 ** that comment is used to determine the particular value of the opcode.
776 ** Other keywords in the comment that follows each case are used to
777 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
778 ** Keywords include: in1, in2, in3, out2, out3. See
779 ** the mkopcodeh.awk script for additional information.
781 ** Documentation about VDBE opcodes is generated by scanning this file
782 ** for lines of that contain "Opcode:". That line and all subsequent
783 ** comment lines are used in the generation of the opcode.html documentation
788 ** Formatting is important to scripts that scan this file.
789 ** Do not deviate from the formatting style currently in use.
791 *****************************************************************************/
793 /* Opcode: Goto * P2 * * *
795 ** An unconditional jump to address P2.
796 ** The next instruction executed will be
797 ** the one at index P2 from the beginning of
800 ** The P1 parameter is not actually used by this opcode. However, it
801 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
802 ** that this Goto is the bottom of a loop and that the lines from P2 down
803 ** to the current line should be indented for EXPLAIN output.
805 case OP_Goto
: { /* jump */
806 jump_to_p2_and_check_for_interrupt
:
807 pOp
= &aOp
[pOp
->p2
- 1];
809 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
810 ** OP_VNext, or OP_SorterNext) all jump here upon
811 ** completion. Check to see if sqlite3_interrupt() has been called
812 ** or if the progress callback needs to be invoked.
814 ** This code uses unstructured "goto" statements and does not look clean.
815 ** But that is not due to sloppy coding habits. The code is written this
816 ** way for performance, to avoid having to run the interrupt and progress
817 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
818 ** faster according to "valgrind --tool=cachegrind" */
820 if( db
->u1
.isInterrupted
) goto abort_due_to_interrupt
;
821 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
822 /* Call the progress callback if it is configured and the required number
823 ** of VDBE ops have been executed (either since this invocation of
824 ** sqlite3VdbeExec() or since last time the progress callback was called).
825 ** If the progress callback returns non-zero, exit the virtual machine with
826 ** a return code SQLITE_ABORT.
828 if( nVmStep
>=nProgressLimit
&& db
->xProgress
!=0 ){
829 assert( db
->nProgressOps
!=0 );
830 nProgressLimit
= nVmStep
+ db
->nProgressOps
- (nVmStep
%db
->nProgressOps
);
831 if( db
->xProgress(db
->pProgressArg
) ){
832 rc
= SQLITE_INTERRUPT
;
833 goto abort_due_to_error
;
841 /* Opcode: Gosub P1 P2 * * *
843 ** Write the current address onto register P1
844 ** and then jump to address P2.
846 case OP_Gosub
: { /* jump */
847 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
848 pIn1
= &aMem
[pOp
->p1
];
849 assert( VdbeMemDynamic(pIn1
)==0 );
850 memAboutToChange(p
, pIn1
);
851 pIn1
->flags
= MEM_Int
;
852 pIn1
->u
.i
= (int)(pOp
-aOp
);
853 REGISTER_TRACE(pOp
->p1
, pIn1
);
855 /* Most jump operations do a goto to this spot in order to update
856 ** the pOp pointer. */
858 pOp
= &aOp
[pOp
->p2
- 1];
862 /* Opcode: Return P1 * * * *
864 ** Jump to the next instruction after the address in register P1. After
865 ** the jump, register P1 becomes undefined.
867 case OP_Return
: { /* in1 */
868 pIn1
= &aMem
[pOp
->p1
];
869 assert( pIn1
->flags
==MEM_Int
);
870 pOp
= &aOp
[pIn1
->u
.i
];
871 pIn1
->flags
= MEM_Undefined
;
875 /* Opcode: InitCoroutine P1 P2 P3 * *
877 ** Set up register P1 so that it will Yield to the coroutine
878 ** located at address P3.
880 ** If P2!=0 then the coroutine implementation immediately follows
881 ** this opcode. So jump over the coroutine implementation to
884 ** See also: EndCoroutine
886 case OP_InitCoroutine
: { /* jump */
887 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
888 assert( pOp
->p2
>=0 && pOp
->p2
<p
->nOp
);
889 assert( pOp
->p3
>=0 && pOp
->p3
<p
->nOp
);
890 pOut
= &aMem
[pOp
->p1
];
891 assert( !VdbeMemDynamic(pOut
) );
892 pOut
->u
.i
= pOp
->p3
- 1;
893 pOut
->flags
= MEM_Int
;
894 if( pOp
->p2
) goto jump_to_p2
;
898 /* Opcode: EndCoroutine P1 * * * *
900 ** The instruction at the address in register P1 is a Yield.
901 ** Jump to the P2 parameter of that Yield.
902 ** After the jump, register P1 becomes undefined.
904 ** See also: InitCoroutine
906 case OP_EndCoroutine
: { /* in1 */
908 pIn1
= &aMem
[pOp
->p1
];
909 assert( pIn1
->flags
==MEM_Int
);
910 assert( pIn1
->u
.i
>=0 && pIn1
->u
.i
<p
->nOp
);
911 pCaller
= &aOp
[pIn1
->u
.i
];
912 assert( pCaller
->opcode
==OP_Yield
);
913 assert( pCaller
->p2
>=0 && pCaller
->p2
<p
->nOp
);
914 pOp
= &aOp
[pCaller
->p2
- 1];
915 pIn1
->flags
= MEM_Undefined
;
919 /* Opcode: Yield P1 P2 * * *
921 ** Swap the program counter with the value in register P1. This
922 ** has the effect of yielding to a coroutine.
924 ** If the coroutine that is launched by this instruction ends with
925 ** Yield or Return then continue to the next instruction. But if
926 ** the coroutine launched by this instruction ends with
927 ** EndCoroutine, then jump to P2 rather than continuing with the
930 ** See also: InitCoroutine
932 case OP_Yield
: { /* in1, jump */
934 pIn1
= &aMem
[pOp
->p1
];
935 assert( VdbeMemDynamic(pIn1
)==0 );
936 pIn1
->flags
= MEM_Int
;
937 pcDest
= (int)pIn1
->u
.i
;
938 pIn1
->u
.i
= (int)(pOp
- aOp
);
939 REGISTER_TRACE(pOp
->p1
, pIn1
);
944 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
945 ** Synopsis: if r[P3]=null halt
947 ** Check the value in register P3. If it is NULL then Halt using
948 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
949 ** value in register P3 is not NULL, then this routine is a no-op.
950 ** The P5 parameter should be 1.
952 case OP_HaltIfNull
: { /* in3 */
953 pIn3
= &aMem
[pOp
->p3
];
955 if( pOp
->p2
==OE_Abort
){ sqlite3VdbeAssertAbortable(p
); }
957 if( (pIn3
->flags
& MEM_Null
)==0 ) break;
958 /* Fall through into OP_Halt */
961 /* Opcode: Halt P1 P2 * P4 P5
963 ** Exit immediately. All open cursors, etc are closed
966 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
967 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
968 ** For errors, it can be some other value. If P1!=0 then P2 will determine
969 ** whether or not to rollback the current transaction. Do not rollback
970 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
971 ** then back out all changes that have occurred during this execution of the
972 ** VDBE, but do not rollback the transaction.
974 ** If P4 is not null then it is an error message string.
976 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
979 ** 1: NOT NULL contraint failed: P4
980 ** 2: UNIQUE constraint failed: P4
981 ** 3: CHECK constraint failed: P4
982 ** 4: FOREIGN KEY constraint failed: P4
984 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
987 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
988 ** every program. So a jump past the last instruction of the program
989 ** is the same as executing Halt.
995 pcx
= (int)(pOp
- aOp
);
997 if( pOp
->p2
==OE_Abort
){ sqlite3VdbeAssertAbortable(p
); }
999 if( pOp
->p1
==SQLITE_OK
&& p
->pFrame
){
1000 /* Halt the sub-program. Return control to the parent frame. */
1002 p
->pFrame
= pFrame
->pParent
;
1004 sqlite3VdbeSetChanges(db
, p
->nChange
);
1005 pcx
= sqlite3VdbeFrameRestore(pFrame
);
1006 if( pOp
->p2
==OE_Ignore
){
1007 /* Instruction pcx is the OP_Program that invoked the sub-program
1008 ** currently being halted. If the p2 instruction of this OP_Halt
1009 ** instruction is set to OE_Ignore, then the sub-program is throwing
1010 ** an IGNORE exception. In this case jump to the address specified
1011 ** as the p2 of the calling OP_Program. */
1012 pcx
= p
->aOp
[pcx
].p2
-1;
1020 p
->errorAction
= (u8
)pOp
->p2
;
1022 assert( pOp
->p5
<=4 );
1025 static const char * const azType
[] = { "NOT NULL", "UNIQUE", "CHECK",
1027 testcase( pOp
->p5
==1 );
1028 testcase( pOp
->p5
==2 );
1029 testcase( pOp
->p5
==3 );
1030 testcase( pOp
->p5
==4 );
1031 sqlite3VdbeError(p
, "%s constraint failed", azType
[pOp
->p5
-1]);
1033 p
->zErrMsg
= sqlite3MPrintf(db
, "%z: %s", p
->zErrMsg
, pOp
->p4
.z
);
1036 sqlite3VdbeError(p
, "%s", pOp
->p4
.z
);
1038 sqlite3_log(pOp
->p1
, "abort at %d in [%s]: %s", pcx
, p
->zSql
, p
->zErrMsg
);
1040 rc
= sqlite3VdbeHalt(p
);
1041 assert( rc
==SQLITE_BUSY
|| rc
==SQLITE_OK
|| rc
==SQLITE_ERROR
);
1042 if( rc
==SQLITE_BUSY
){
1043 p
->rc
= SQLITE_BUSY
;
1045 assert( rc
==SQLITE_OK
|| (p
->rc
&0xff)==SQLITE_CONSTRAINT
);
1046 assert( rc
==SQLITE_OK
|| db
->nDeferredCons
>0 || db
->nDeferredImmCons
>0 );
1047 rc
= p
->rc
? SQLITE_ERROR
: SQLITE_DONE
;
1052 /* Opcode: Integer P1 P2 * * *
1053 ** Synopsis: r[P2]=P1
1055 ** The 32-bit integer value P1 is written into register P2.
1057 case OP_Integer
: { /* out2 */
1058 pOut
= out2Prerelease(p
, pOp
);
1059 pOut
->u
.i
= pOp
->p1
;
1063 /* Opcode: Int64 * P2 * P4 *
1064 ** Synopsis: r[P2]=P4
1066 ** P4 is a pointer to a 64-bit integer value.
1067 ** Write that value into register P2.
1069 case OP_Int64
: { /* out2 */
1070 pOut
= out2Prerelease(p
, pOp
);
1071 assert( pOp
->p4
.pI64
!=0 );
1072 pOut
->u
.i
= *pOp
->p4
.pI64
;
1076 #ifndef SQLITE_OMIT_FLOATING_POINT
1077 /* Opcode: Real * P2 * P4 *
1078 ** Synopsis: r[P2]=P4
1080 ** P4 is a pointer to a 64-bit floating point value.
1081 ** Write that value into register P2.
1083 case OP_Real
: { /* same as TK_FLOAT, out2 */
1084 pOut
= out2Prerelease(p
, pOp
);
1085 pOut
->flags
= MEM_Real
;
1086 assert( !sqlite3IsNaN(*pOp
->p4
.pReal
) );
1087 pOut
->u
.r
= *pOp
->p4
.pReal
;
1092 /* Opcode: String8 * P2 * P4 *
1093 ** Synopsis: r[P2]='P4'
1095 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1096 ** into a String opcode before it is executed for the first time. During
1097 ** this transformation, the length of string P4 is computed and stored
1098 ** as the P1 parameter.
1100 case OP_String8
: { /* same as TK_STRING, out2 */
1101 assert( pOp
->p4
.z
!=0 );
1102 pOut
= out2Prerelease(p
, pOp
);
1103 pOp
->opcode
= OP_String
;
1104 pOp
->p1
= sqlite3Strlen30(pOp
->p4
.z
);
1106 #ifndef SQLITE_OMIT_UTF16
1107 if( encoding
!=SQLITE_UTF8
){
1108 rc
= sqlite3VdbeMemSetStr(pOut
, pOp
->p4
.z
, -1, SQLITE_UTF8
, SQLITE_STATIC
);
1109 assert( rc
==SQLITE_OK
|| rc
==SQLITE_TOOBIG
);
1110 if( SQLITE_OK
!=sqlite3VdbeChangeEncoding(pOut
, encoding
) ) goto no_mem
;
1111 assert( pOut
->szMalloc
>0 && pOut
->zMalloc
==pOut
->z
);
1112 assert( VdbeMemDynamic(pOut
)==0 );
1114 pOut
->flags
|= MEM_Static
;
1115 if( pOp
->p4type
==P4_DYNAMIC
){
1116 sqlite3DbFree(db
, pOp
->p4
.z
);
1118 pOp
->p4type
= P4_DYNAMIC
;
1119 pOp
->p4
.z
= pOut
->z
;
1122 testcase( rc
==SQLITE_TOOBIG
);
1124 if( pOp
->p1
>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
1127 assert( rc
==SQLITE_OK
);
1128 /* Fall through to the next case, OP_String */
1131 /* Opcode: String P1 P2 P3 P4 P5
1132 ** Synopsis: r[P2]='P4' (len=P1)
1134 ** The string value P4 of length P1 (bytes) is stored in register P2.
1136 ** If P3 is not zero and the content of register P3 is equal to P5, then
1137 ** the datatype of the register P2 is converted to BLOB. The content is
1138 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1139 ** of a string, as if it had been CAST. In other words:
1141 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1143 case OP_String
: { /* out2 */
1144 assert( pOp
->p4
.z
!=0 );
1145 pOut
= out2Prerelease(p
, pOp
);
1146 pOut
->flags
= MEM_Str
|MEM_Static
|MEM_Term
;
1147 pOut
->z
= pOp
->p4
.z
;
1149 pOut
->enc
= encoding
;
1150 UPDATE_MAX_BLOBSIZE(pOut
);
1151 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1153 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
1154 pIn3
= &aMem
[pOp
->p3
];
1155 assert( pIn3
->flags
& MEM_Int
);
1156 if( pIn3
->u
.i
==pOp
->p5
) pOut
->flags
= MEM_Blob
|MEM_Static
|MEM_Term
;
1162 /* Opcode: Null P1 P2 P3 * *
1163 ** Synopsis: r[P2..P3]=NULL
1165 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1166 ** NULL into register P3 and every register in between P2 and P3. If P3
1167 ** is less than P2 (typically P3 is zero) then only register P2 is
1170 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1171 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1174 case OP_Null
: { /* out2 */
1177 pOut
= out2Prerelease(p
, pOp
);
1178 cnt
= pOp
->p3
-pOp
->p2
;
1179 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
1180 pOut
->flags
= nullFlag
= pOp
->p1
? (MEM_Null
|MEM_Cleared
) : MEM_Null
;
1187 memAboutToChange(p
, pOut
);
1188 sqlite3VdbeMemSetNull(pOut
);
1189 pOut
->flags
= nullFlag
;
1196 /* Opcode: SoftNull P1 * * * *
1197 ** Synopsis: r[P1]=NULL
1199 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1200 ** instruction, but do not free any string or blob memory associated with
1201 ** the register, so that if the value was a string or blob that was
1202 ** previously copied using OP_SCopy, the copies will continue to be valid.
1205 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
1206 pOut
= &aMem
[pOp
->p1
];
1207 pOut
->flags
= (pOut
->flags
&~(MEM_Undefined
|MEM_AffMask
))|MEM_Null
;
1211 /* Opcode: Blob P1 P2 * P4 *
1212 ** Synopsis: r[P2]=P4 (len=P1)
1214 ** P4 points to a blob of data P1 bytes long. Store this
1215 ** blob in register P2.
1217 case OP_Blob
: { /* out2 */
1218 assert( pOp
->p1
<= SQLITE_MAX_LENGTH
);
1219 pOut
= out2Prerelease(p
, pOp
);
1220 sqlite3VdbeMemSetStr(pOut
, pOp
->p4
.z
, pOp
->p1
, 0, 0);
1221 pOut
->enc
= encoding
;
1222 UPDATE_MAX_BLOBSIZE(pOut
);
1226 /* Opcode: Variable P1 P2 * P4 *
1227 ** Synopsis: r[P2]=parameter(P1,P4)
1229 ** Transfer the values of bound parameter P1 into register P2
1231 ** If the parameter is named, then its name appears in P4.
1232 ** The P4 value is used by sqlite3_bind_parameter_name().
1234 case OP_Variable
: { /* out2 */
1235 Mem
*pVar
; /* Value being transferred */
1237 assert( pOp
->p1
>0 && pOp
->p1
<=p
->nVar
);
1238 assert( pOp
->p4
.z
==0 || pOp
->p4
.z
==sqlite3VListNumToName(p
->pVList
,pOp
->p1
) );
1239 pVar
= &p
->aVar
[pOp
->p1
- 1];
1240 if( sqlite3VdbeMemTooBig(pVar
) ){
1243 pOut
= &aMem
[pOp
->p2
];
1244 sqlite3VdbeMemShallowCopy(pOut
, pVar
, MEM_Static
);
1245 UPDATE_MAX_BLOBSIZE(pOut
);
1249 /* Opcode: Move P1 P2 P3 * *
1250 ** Synopsis: r[P2@P3]=r[P1@P3]
1252 ** Move the P3 values in register P1..P1+P3-1 over into
1253 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1254 ** left holding a NULL. It is an error for register ranges
1255 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1256 ** for P3 to be less than 1.
1259 int n
; /* Number of registers left to copy */
1260 int p1
; /* Register to copy from */
1261 int p2
; /* Register to copy to */
1266 assert( n
>0 && p1
>0 && p2
>0 );
1267 assert( p1
+n
<=p2
|| p2
+n
<=p1
);
1272 assert( pOut
<=&aMem
[(p
->nMem
+1 - p
->nCursor
)] );
1273 assert( pIn1
<=&aMem
[(p
->nMem
+1 - p
->nCursor
)] );
1274 assert( memIsValid(pIn1
) );
1275 memAboutToChange(p
, pOut
);
1276 sqlite3VdbeMemMove(pOut
, pIn1
);
1278 if( pOut
->pScopyFrom
>=&aMem
[p1
] && pOut
->pScopyFrom
<pOut
){
1279 pOut
->pScopyFrom
+= pOp
->p2
- p1
;
1282 Deephemeralize(pOut
);
1283 REGISTER_TRACE(p2
++, pOut
);
1290 /* Opcode: Copy P1 P2 P3 * *
1291 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1293 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1295 ** This instruction makes a deep copy of the value. A duplicate
1296 ** is made of any string or blob constant. See also OP_SCopy.
1302 pIn1
= &aMem
[pOp
->p1
];
1303 pOut
= &aMem
[pOp
->p2
];
1304 assert( pOut
!=pIn1
);
1306 memAboutToChange(p
, pOut
);
1307 sqlite3VdbeMemShallowCopy(pOut
, pIn1
, MEM_Ephem
);
1308 Deephemeralize(pOut
);
1310 pOut
->pScopyFrom
= 0;
1311 pOut
->iTabColHash
= 0;
1313 REGISTER_TRACE(pOp
->p2
+pOp
->p3
-n
, pOut
);
1314 if( (n
--)==0 ) break;
1321 /* Opcode: SCopy P1 P2 * * *
1322 ** Synopsis: r[P2]=r[P1]
1324 ** Make a shallow copy of register P1 into register P2.
1326 ** This instruction makes a shallow copy of the value. If the value
1327 ** is a string or blob, then the copy is only a pointer to the
1328 ** original and hence if the original changes so will the copy.
1329 ** Worse, if the original is deallocated, the copy becomes invalid.
1330 ** Thus the program must guarantee that the original will not change
1331 ** during the lifetime of the copy. Use OP_Copy to make a complete
1334 case OP_SCopy
: { /* out2 */
1335 pIn1
= &aMem
[pOp
->p1
];
1336 pOut
= &aMem
[pOp
->p2
];
1337 assert( pOut
!=pIn1
);
1338 sqlite3VdbeMemShallowCopy(pOut
, pIn1
, MEM_Ephem
);
1340 pOut
->pScopyFrom
= pIn1
;
1341 pOut
->mScopyFlags
= pIn1
->flags
;
1346 /* Opcode: IntCopy P1 P2 * * *
1347 ** Synopsis: r[P2]=r[P1]
1349 ** Transfer the integer value held in register P1 into register P2.
1351 ** This is an optimized version of SCopy that works only for integer
1354 case OP_IntCopy
: { /* out2 */
1355 pIn1
= &aMem
[pOp
->p1
];
1356 assert( (pIn1
->flags
& MEM_Int
)!=0 );
1357 pOut
= &aMem
[pOp
->p2
];
1358 sqlite3VdbeMemSetInt64(pOut
, pIn1
->u
.i
);
1362 /* Opcode: ResultRow P1 P2 * * *
1363 ** Synopsis: output=r[P1@P2]
1365 ** The registers P1 through P1+P2-1 contain a single row of
1366 ** results. This opcode causes the sqlite3_step() call to terminate
1367 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1368 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1371 case OP_ResultRow
: {
1374 assert( p
->nResColumn
==pOp
->p2
);
1375 assert( pOp
->p1
>0 );
1376 assert( pOp
->p1
+pOp
->p2
<=(p
->nMem
+1 - p
->nCursor
)+1 );
1378 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1379 /* Run the progress counter just before returning.
1381 if( db
->xProgress
!=0
1382 && nVmStep
>=nProgressLimit
1383 && db
->xProgress(db
->pProgressArg
)!=0
1385 rc
= SQLITE_INTERRUPT
;
1386 goto abort_due_to_error
;
1390 /* If this statement has violated immediate foreign key constraints, do
1391 ** not return the number of rows modified. And do not RELEASE the statement
1392 ** transaction. It needs to be rolled back. */
1393 if( SQLITE_OK
!=(rc
= sqlite3VdbeCheckFk(p
, 0)) ){
1394 assert( db
->flags
&SQLITE_CountRows
);
1395 assert( p
->usesStmtJournal
);
1396 goto abort_due_to_error
;
1399 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1400 ** DML statements invoke this opcode to return the number of rows
1401 ** modified to the user. This is the only way that a VM that
1402 ** opens a statement transaction may invoke this opcode.
1404 ** In case this is such a statement, close any statement transaction
1405 ** opened by this VM before returning control to the user. This is to
1406 ** ensure that statement-transactions are always nested, not overlapping.
1407 ** If the open statement-transaction is not closed here, then the user
1408 ** may step another VM that opens its own statement transaction. This
1409 ** may lead to overlapping statement transactions.
1411 ** The statement transaction is never a top-level transaction. Hence
1412 ** the RELEASE call below can never fail.
1414 assert( p
->iStatement
==0 || db
->flags
&SQLITE_CountRows
);
1415 rc
= sqlite3VdbeCloseStatement(p
, SAVEPOINT_RELEASE
);
1416 assert( rc
==SQLITE_OK
);
1418 /* Invalidate all ephemeral cursor row caches */
1419 p
->cacheCtr
= (p
->cacheCtr
+ 2)|1;
1421 /* Make sure the results of the current row are \000 terminated
1422 ** and have an assigned type. The results are de-ephemeralized as
1425 pMem
= p
->pResultSet
= &aMem
[pOp
->p1
];
1426 for(i
=0; i
<pOp
->p2
; i
++){
1427 assert( memIsValid(&pMem
[i
]) );
1428 Deephemeralize(&pMem
[i
]);
1429 assert( (pMem
[i
].flags
& MEM_Ephem
)==0
1430 || (pMem
[i
].flags
& (MEM_Str
|MEM_Blob
))==0 );
1431 sqlite3VdbeMemNulTerminate(&pMem
[i
]);
1432 REGISTER_TRACE(pOp
->p1
+i
, &pMem
[i
]);
1434 if( db
->mallocFailed
) goto no_mem
;
1436 if( db
->mTrace
& SQLITE_TRACE_ROW
){
1437 db
->xTrace(SQLITE_TRACE_ROW
, db
->pTraceArg
, p
, 0);
1440 /* Return SQLITE_ROW
1442 p
->pc
= (int)(pOp
- aOp
) + 1;
1447 /* Opcode: Concat P1 P2 P3 * *
1448 ** Synopsis: r[P3]=r[P2]+r[P1]
1450 ** Add the text in register P1 onto the end of the text in
1451 ** register P2 and store the result in register P3.
1452 ** If either the P1 or P2 text are NULL then store NULL in P3.
1456 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1457 ** if P3 is the same register as P2, the implementation is able
1458 ** to avoid a memcpy().
1460 case OP_Concat
: { /* same as TK_CONCAT, in1, in2, out3 */
1463 pIn1
= &aMem
[pOp
->p1
];
1464 pIn2
= &aMem
[pOp
->p2
];
1465 pOut
= &aMem
[pOp
->p3
];
1466 assert( pIn1
!=pOut
);
1467 if( (pIn1
->flags
| pIn2
->flags
) & MEM_Null
){
1468 sqlite3VdbeMemSetNull(pOut
);
1471 if( ExpandBlob(pIn1
) || ExpandBlob(pIn2
) ) goto no_mem
;
1472 Stringify(pIn1
, encoding
);
1473 Stringify(pIn2
, encoding
);
1474 nByte
= pIn1
->n
+ pIn2
->n
;
1475 if( nByte
>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
1478 if( sqlite3VdbeMemGrow(pOut
, (int)nByte
+2, pOut
==pIn2
) ){
1481 MemSetTypeFlag(pOut
, MEM_Str
);
1483 memcpy(pOut
->z
, pIn2
->z
, pIn2
->n
);
1485 memcpy(&pOut
->z
[pIn2
->n
], pIn1
->z
, pIn1
->n
);
1487 pOut
->z
[nByte
+1] = 0;
1488 pOut
->flags
|= MEM_Term
;
1489 pOut
->n
= (int)nByte
;
1490 pOut
->enc
= encoding
;
1491 UPDATE_MAX_BLOBSIZE(pOut
);
1495 /* Opcode: Add P1 P2 P3 * *
1496 ** Synopsis: r[P3]=r[P1]+r[P2]
1498 ** Add the value in register P1 to the value in register P2
1499 ** and store the result in register P3.
1500 ** If either input is NULL, the result is NULL.
1502 /* Opcode: Multiply P1 P2 P3 * *
1503 ** Synopsis: r[P3]=r[P1]*r[P2]
1506 ** Multiply the value in register P1 by the value in register P2
1507 ** and store the result in register P3.
1508 ** If either input is NULL, the result is NULL.
1510 /* Opcode: Subtract P1 P2 P3 * *
1511 ** Synopsis: r[P3]=r[P2]-r[P1]
1513 ** Subtract the value in register P1 from the value in register P2
1514 ** and store the result in register P3.
1515 ** If either input is NULL, the result is NULL.
1517 /* Opcode: Divide P1 P2 P3 * *
1518 ** Synopsis: r[P3]=r[P2]/r[P1]
1520 ** Divide the value in register P1 by the value in register P2
1521 ** and store the result in register P3 (P3=P2/P1). If the value in
1522 ** register P1 is zero, then the result is NULL. If either input is
1523 ** NULL, the result is NULL.
1525 /* Opcode: Remainder P1 P2 P3 * *
1526 ** Synopsis: r[P3]=r[P2]%r[P1]
1528 ** Compute the remainder after integer register P2 is divided by
1529 ** register P1 and store the result in register P3.
1530 ** If the value in register P1 is zero the result is NULL.
1531 ** If either operand is NULL, the result is NULL.
1533 case OP_Add
: /* same as TK_PLUS, in1, in2, out3 */
1534 case OP_Subtract
: /* same as TK_MINUS, in1, in2, out3 */
1535 case OP_Multiply
: /* same as TK_STAR, in1, in2, out3 */
1536 case OP_Divide
: /* same as TK_SLASH, in1, in2, out3 */
1537 case OP_Remainder
: { /* same as TK_REM, in1, in2, out3 */
1538 char bIntint
; /* Started out as two integer operands */
1539 u16 flags
; /* Combined MEM_* flags from both inputs */
1540 u16 type1
; /* Numeric type of left operand */
1541 u16 type2
; /* Numeric type of right operand */
1542 i64 iA
; /* Integer value of left operand */
1543 i64 iB
; /* Integer value of right operand */
1544 double rA
; /* Real value of left operand */
1545 double rB
; /* Real value of right operand */
1547 pIn1
= &aMem
[pOp
->p1
];
1548 type1
= numericType(pIn1
);
1549 pIn2
= &aMem
[pOp
->p2
];
1550 type2
= numericType(pIn2
);
1551 pOut
= &aMem
[pOp
->p3
];
1552 flags
= pIn1
->flags
| pIn2
->flags
;
1553 if( (type1
& type2
& MEM_Int
)!=0 ){
1557 switch( pOp
->opcode
){
1558 case OP_Add
: if( sqlite3AddInt64(&iB
,iA
) ) goto fp_math
; break;
1559 case OP_Subtract
: if( sqlite3SubInt64(&iB
,iA
) ) goto fp_math
; break;
1560 case OP_Multiply
: if( sqlite3MulInt64(&iB
,iA
) ) goto fp_math
; break;
1562 if( iA
==0 ) goto arithmetic_result_is_null
;
1563 if( iA
==-1 && iB
==SMALLEST_INT64
) goto fp_math
;
1568 if( iA
==0 ) goto arithmetic_result_is_null
;
1569 if( iA
==-1 ) iA
= 1;
1575 MemSetTypeFlag(pOut
, MEM_Int
);
1576 }else if( (flags
& MEM_Null
)!=0 ){
1577 goto arithmetic_result_is_null
;
1581 rA
= sqlite3VdbeRealValue(pIn1
);
1582 rB
= sqlite3VdbeRealValue(pIn2
);
1583 switch( pOp
->opcode
){
1584 case OP_Add
: rB
+= rA
; break;
1585 case OP_Subtract
: rB
-= rA
; break;
1586 case OP_Multiply
: rB
*= rA
; break;
1588 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1589 if( rA
==(double)0 ) goto arithmetic_result_is_null
;
1596 if( iA
==0 ) goto arithmetic_result_is_null
;
1597 if( iA
==-1 ) iA
= 1;
1598 rB
= (double)(iB
% iA
);
1602 #ifdef SQLITE_OMIT_FLOATING_POINT
1604 MemSetTypeFlag(pOut
, MEM_Int
);
1606 if( sqlite3IsNaN(rB
) ){
1607 goto arithmetic_result_is_null
;
1610 MemSetTypeFlag(pOut
, MEM_Real
);
1611 if( ((type1
|type2
)&MEM_Real
)==0 && !bIntint
){
1612 sqlite3VdbeIntegerAffinity(pOut
);
1618 arithmetic_result_is_null
:
1619 sqlite3VdbeMemSetNull(pOut
);
1623 /* Opcode: CollSeq P1 * * P4
1625 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1626 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1627 ** be returned. This is used by the built-in min(), max() and nullif()
1630 ** If P1 is not zero, then it is a register that a subsequent min() or
1631 ** max() aggregate will set to 1 if the current row is not the minimum or
1632 ** maximum. The P1 register is initialized to 0 by this instruction.
1634 ** The interface used by the implementation of the aforementioned functions
1635 ** to retrieve the collation sequence set by this opcode is not available
1636 ** publicly. Only built-in functions have access to this feature.
1639 assert( pOp
->p4type
==P4_COLLSEQ
);
1641 sqlite3VdbeMemSetInt64(&aMem
[pOp
->p1
], 0);
1646 /* Opcode: BitAnd P1 P2 P3 * *
1647 ** Synopsis: r[P3]=r[P1]&r[P2]
1649 ** Take the bit-wise AND of the values in register P1 and P2 and
1650 ** store the result in register P3.
1651 ** If either input is NULL, the result is NULL.
1653 /* Opcode: BitOr P1 P2 P3 * *
1654 ** Synopsis: r[P3]=r[P1]|r[P2]
1656 ** Take the bit-wise OR of the values in register P1 and P2 and
1657 ** store the result in register P3.
1658 ** If either input is NULL, the result is NULL.
1660 /* Opcode: ShiftLeft P1 P2 P3 * *
1661 ** Synopsis: r[P3]=r[P2]<<r[P1]
1663 ** Shift the integer value in register P2 to the left by the
1664 ** number of bits specified by the integer in register P1.
1665 ** Store the result in register P3.
1666 ** If either input is NULL, the result is NULL.
1668 /* Opcode: ShiftRight P1 P2 P3 * *
1669 ** Synopsis: r[P3]=r[P2]>>r[P1]
1671 ** Shift the integer value in register P2 to the right by the
1672 ** number of bits specified by the integer in register P1.
1673 ** Store the result in register P3.
1674 ** If either input is NULL, the result is NULL.
1676 case OP_BitAnd
: /* same as TK_BITAND, in1, in2, out3 */
1677 case OP_BitOr
: /* same as TK_BITOR, in1, in2, out3 */
1678 case OP_ShiftLeft
: /* same as TK_LSHIFT, in1, in2, out3 */
1679 case OP_ShiftRight
: { /* same as TK_RSHIFT, in1, in2, out3 */
1685 pIn1
= &aMem
[pOp
->p1
];
1686 pIn2
= &aMem
[pOp
->p2
];
1687 pOut
= &aMem
[pOp
->p3
];
1688 if( (pIn1
->flags
| pIn2
->flags
) & MEM_Null
){
1689 sqlite3VdbeMemSetNull(pOut
);
1692 iA
= sqlite3VdbeIntValue(pIn2
);
1693 iB
= sqlite3VdbeIntValue(pIn1
);
1695 if( op
==OP_BitAnd
){
1697 }else if( op
==OP_BitOr
){
1700 assert( op
==OP_ShiftRight
|| op
==OP_ShiftLeft
);
1702 /* If shifting by a negative amount, shift in the other direction */
1704 assert( OP_ShiftRight
==OP_ShiftLeft
+1 );
1705 op
= 2*OP_ShiftLeft
+ 1 - op
;
1706 iB
= iB
>(-64) ? -iB
: 64;
1710 iA
= (iA
>=0 || op
==OP_ShiftLeft
) ? 0 : -1;
1712 memcpy(&uA
, &iA
, sizeof(uA
));
1713 if( op
==OP_ShiftLeft
){
1717 /* Sign-extend on a right shift of a negative number */
1718 if( iA
<0 ) uA
|= ((((u64
)0xffffffff)<<32)|0xffffffff) << (64-iB
);
1720 memcpy(&iA
, &uA
, sizeof(iA
));
1724 MemSetTypeFlag(pOut
, MEM_Int
);
1728 /* Opcode: AddImm P1 P2 * * *
1729 ** Synopsis: r[P1]=r[P1]+P2
1731 ** Add the constant P2 to the value in register P1.
1732 ** The result is always an integer.
1734 ** To force any register to be an integer, just add 0.
1736 case OP_AddImm
: { /* in1 */
1737 pIn1
= &aMem
[pOp
->p1
];
1738 memAboutToChange(p
, pIn1
);
1739 sqlite3VdbeMemIntegerify(pIn1
);
1740 pIn1
->u
.i
+= pOp
->p2
;
1744 /* Opcode: MustBeInt P1 P2 * * *
1746 ** Force the value in register P1 to be an integer. If the value
1747 ** in P1 is not an integer and cannot be converted into an integer
1748 ** without data loss, then jump immediately to P2, or if P2==0
1749 ** raise an SQLITE_MISMATCH exception.
1751 case OP_MustBeInt
: { /* jump, in1 */
1752 pIn1
= &aMem
[pOp
->p1
];
1753 if( (pIn1
->flags
& MEM_Int
)==0 ){
1754 applyAffinity(pIn1
, SQLITE_AFF_NUMERIC
, encoding
);
1755 VdbeBranchTaken((pIn1
->flags
&MEM_Int
)==0, 2);
1756 if( (pIn1
->flags
& MEM_Int
)==0 ){
1758 rc
= SQLITE_MISMATCH
;
1759 goto abort_due_to_error
;
1765 MemSetTypeFlag(pIn1
, MEM_Int
);
1769 #ifndef SQLITE_OMIT_FLOATING_POINT
1770 /* Opcode: RealAffinity P1 * * * *
1772 ** If register P1 holds an integer convert it to a real value.
1774 ** This opcode is used when extracting information from a column that
1775 ** has REAL affinity. Such column values may still be stored as
1776 ** integers, for space efficiency, but after extraction we want them
1777 ** to have only a real value.
1779 case OP_RealAffinity
: { /* in1 */
1780 pIn1
= &aMem
[pOp
->p1
];
1781 if( pIn1
->flags
& MEM_Int
){
1782 sqlite3VdbeMemRealify(pIn1
);
1788 #ifndef SQLITE_OMIT_CAST
1789 /* Opcode: Cast P1 P2 * * *
1790 ** Synopsis: affinity(r[P1])
1792 ** Force the value in register P1 to be the type defined by P2.
1795 ** <li> P2=='A' → BLOB
1796 ** <li> P2=='B' → TEXT
1797 ** <li> P2=='C' → NUMERIC
1798 ** <li> P2=='D' → INTEGER
1799 ** <li> P2=='E' → REAL
1802 ** A NULL value is not changed by this routine. It remains NULL.
1804 case OP_Cast
: { /* in1 */
1805 assert( pOp
->p2
>=SQLITE_AFF_BLOB
&& pOp
->p2
<=SQLITE_AFF_REAL
);
1806 testcase( pOp
->p2
==SQLITE_AFF_TEXT
);
1807 testcase( pOp
->p2
==SQLITE_AFF_BLOB
);
1808 testcase( pOp
->p2
==SQLITE_AFF_NUMERIC
);
1809 testcase( pOp
->p2
==SQLITE_AFF_INTEGER
);
1810 testcase( pOp
->p2
==SQLITE_AFF_REAL
);
1811 pIn1
= &aMem
[pOp
->p1
];
1812 memAboutToChange(p
, pIn1
);
1813 rc
= ExpandBlob(pIn1
);
1814 sqlite3VdbeMemCast(pIn1
, pOp
->p2
, encoding
);
1815 UPDATE_MAX_BLOBSIZE(pIn1
);
1816 if( rc
) goto abort_due_to_error
;
1819 #endif /* SQLITE_OMIT_CAST */
1821 /* Opcode: Eq P1 P2 P3 P4 P5
1822 ** Synopsis: IF r[P3]==r[P1]
1824 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
1825 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
1826 ** store the result of comparison in register P2.
1828 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1829 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1830 ** to coerce both inputs according to this affinity before the
1831 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1832 ** affinity is used. Note that the affinity conversions are stored
1833 ** back into the input registers P1 and P3. So this opcode can cause
1834 ** persistent changes to registers P1 and P3.
1836 ** Once any conversions have taken place, and neither value is NULL,
1837 ** the values are compared. If both values are blobs then memcmp() is
1838 ** used to determine the results of the comparison. If both values
1839 ** are text, then the appropriate collating function specified in
1840 ** P4 is used to do the comparison. If P4 is not specified then
1841 ** memcmp() is used to compare text string. If both values are
1842 ** numeric, then a numeric comparison is used. If the two values
1843 ** are of different types, then numbers are considered less than
1844 ** strings and strings are considered less than blobs.
1846 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1847 ** true or false and is never NULL. If both operands are NULL then the result
1848 ** of comparison is true. If either operand is NULL then the result is false.
1849 ** If neither operand is NULL the result is the same as it would be if
1850 ** the SQLITE_NULLEQ flag were omitted from P5.
1852 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1853 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
1854 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
1856 /* Opcode: Ne P1 P2 P3 P4 P5
1857 ** Synopsis: IF r[P3]!=r[P1]
1859 ** This works just like the Eq opcode except that the jump is taken if
1860 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
1861 ** additional information.
1863 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1864 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
1865 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
1867 /* Opcode: Lt P1 P2 P3 P4 P5
1868 ** Synopsis: IF r[P3]<r[P1]
1870 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1871 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
1872 ** the result of comparison (0 or 1 or NULL) into register P2.
1874 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1875 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
1876 ** bit is clear then fall through if either operand is NULL.
1878 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1879 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1880 ** to coerce both inputs according to this affinity before the
1881 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1882 ** affinity is used. Note that the affinity conversions are stored
1883 ** back into the input registers P1 and P3. So this opcode can cause
1884 ** persistent changes to registers P1 and P3.
1886 ** Once any conversions have taken place, and neither value is NULL,
1887 ** the values are compared. If both values are blobs then memcmp() is
1888 ** used to determine the results of the comparison. If both values
1889 ** are text, then the appropriate collating function specified in
1890 ** P4 is used to do the comparison. If P4 is not specified then
1891 ** memcmp() is used to compare text string. If both values are
1892 ** numeric, then a numeric comparison is used. If the two values
1893 ** are of different types, then numbers are considered less than
1894 ** strings and strings are considered less than blobs.
1896 /* Opcode: Le P1 P2 P3 P4 P5
1897 ** Synopsis: IF r[P3]<=r[P1]
1899 ** This works just like the Lt opcode except that the jump is taken if
1900 ** the content of register P3 is less than or equal to the content of
1901 ** register P1. See the Lt opcode for additional information.
1903 /* Opcode: Gt P1 P2 P3 P4 P5
1904 ** Synopsis: IF r[P3]>r[P1]
1906 ** This works just like the Lt opcode except that the jump is taken if
1907 ** the content of register P3 is greater than the content of
1908 ** register P1. See the Lt opcode for additional information.
1910 /* Opcode: Ge P1 P2 P3 P4 P5
1911 ** Synopsis: IF r[P3]>=r[P1]
1913 ** This works just like the Lt opcode except that the jump is taken if
1914 ** the content of register P3 is greater than or equal to the content of
1915 ** register P1. See the Lt opcode for additional information.
1917 case OP_Eq
: /* same as TK_EQ, jump, in1, in3 */
1918 case OP_Ne
: /* same as TK_NE, jump, in1, in3 */
1919 case OP_Lt
: /* same as TK_LT, jump, in1, in3 */
1920 case OP_Le
: /* same as TK_LE, jump, in1, in3 */
1921 case OP_Gt
: /* same as TK_GT, jump, in1, in3 */
1922 case OP_Ge
: { /* same as TK_GE, jump, in1, in3 */
1923 int res
, res2
; /* Result of the comparison of pIn1 against pIn3 */
1924 char affinity
; /* Affinity to use for comparison */
1925 u16 flags1
; /* Copy of initial value of pIn1->flags */
1926 u16 flags3
; /* Copy of initial value of pIn3->flags */
1928 pIn1
= &aMem
[pOp
->p1
];
1929 pIn3
= &aMem
[pOp
->p3
];
1930 flags1
= pIn1
->flags
;
1931 flags3
= pIn3
->flags
;
1932 if( (flags1
| flags3
)&MEM_Null
){
1933 /* One or both operands are NULL */
1934 if( pOp
->p5
& SQLITE_NULLEQ
){
1935 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1936 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1937 ** or not both operands are null.
1939 assert( pOp
->opcode
==OP_Eq
|| pOp
->opcode
==OP_Ne
);
1940 assert( (flags1
& MEM_Cleared
)==0 );
1941 assert( (pOp
->p5
& SQLITE_JUMPIFNULL
)==0 );
1942 if( (flags1
&flags3
&MEM_Null
)!=0
1943 && (flags3
&MEM_Cleared
)==0
1945 res
= 0; /* Operands are equal */
1947 res
= 1; /* Operands are not equal */
1950 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1951 ** then the result is always NULL.
1952 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1954 if( pOp
->p5
& SQLITE_STOREP2
){
1955 pOut
= &aMem
[pOp
->p2
];
1956 iCompare
= 1; /* Operands are not equal */
1957 memAboutToChange(p
, pOut
);
1958 MemSetTypeFlag(pOut
, MEM_Null
);
1959 REGISTER_TRACE(pOp
->p2
, pOut
);
1961 VdbeBranchTaken(2,3);
1962 if( pOp
->p5
& SQLITE_JUMPIFNULL
){
1969 /* Neither operand is NULL. Do a comparison. */
1970 affinity
= pOp
->p5
& SQLITE_AFF_MASK
;
1971 if( affinity
>=SQLITE_AFF_NUMERIC
){
1972 if( (flags1
| flags3
)&MEM_Str
){
1973 if( (flags1
& (MEM_Int
|MEM_Real
|MEM_Str
))==MEM_Str
){
1974 applyNumericAffinity(pIn1
,0);
1975 testcase( flags3
!=pIn3
->flags
); /* Possible if pIn1==pIn3 */
1976 flags3
= pIn3
->flags
;
1978 if( (flags3
& (MEM_Int
|MEM_Real
|MEM_Str
))==MEM_Str
){
1979 applyNumericAffinity(pIn3
,0);
1982 /* Handle the common case of integer comparison here, as an
1983 ** optimization, to avoid a call to sqlite3MemCompare() */
1984 if( (pIn1
->flags
& pIn3
->flags
& MEM_Int
)!=0 ){
1985 if( pIn3
->u
.i
> pIn1
->u
.i
){ res
= +1; goto compare_op
; }
1986 if( pIn3
->u
.i
< pIn1
->u
.i
){ res
= -1; goto compare_op
; }
1990 }else if( affinity
==SQLITE_AFF_TEXT
){
1991 if( (flags1
& MEM_Str
)==0 && (flags1
& (MEM_Int
|MEM_Real
))!=0 ){
1992 testcase( pIn1
->flags
& MEM_Int
);
1993 testcase( pIn1
->flags
& MEM_Real
);
1994 sqlite3VdbeMemStringify(pIn1
, encoding
, 1);
1995 testcase( (flags1
&MEM_Dyn
) != (pIn1
->flags
&MEM_Dyn
) );
1996 flags1
= (pIn1
->flags
& ~MEM_TypeMask
) | (flags1
& MEM_TypeMask
);
1997 assert( pIn1
!=pIn3
);
1999 if( (flags3
& MEM_Str
)==0 && (flags3
& (MEM_Int
|MEM_Real
))!=0 ){
2000 testcase( pIn3
->flags
& MEM_Int
);
2001 testcase( pIn3
->flags
& MEM_Real
);
2002 sqlite3VdbeMemStringify(pIn3
, encoding
, 1);
2003 testcase( (flags3
&MEM_Dyn
) != (pIn3
->flags
&MEM_Dyn
) );
2004 flags3
= (pIn3
->flags
& ~MEM_TypeMask
) | (flags3
& MEM_TypeMask
);
2007 assert( pOp
->p4type
==P4_COLLSEQ
|| pOp
->p4
.pColl
==0 );
2008 res
= sqlite3MemCompare(pIn3
, pIn1
, pOp
->p4
.pColl
);
2011 /* At this point, res is negative, zero, or positive if reg[P1] is
2012 ** less than, equal to, or greater than reg[P3], respectively. Compute
2013 ** the answer to this operator in res2, depending on what the comparison
2014 ** operator actually is. The next block of code depends on the fact
2015 ** that the 6 comparison operators are consecutive integers in this
2016 ** order: NE, EQ, GT, LE, LT, GE */
2017 assert( OP_Eq
==OP_Ne
+1 ); assert( OP_Gt
==OP_Ne
+2 ); assert( OP_Le
==OP_Ne
+3 );
2018 assert( OP_Lt
==OP_Ne
+4 ); assert( OP_Ge
==OP_Ne
+5 );
2019 if( res
<0 ){ /* ne, eq, gt, le, lt, ge */
2020 static const unsigned char aLTb
[] = { 1, 0, 0, 1, 1, 0 };
2021 res2
= aLTb
[pOp
->opcode
- OP_Ne
];
2023 static const unsigned char aEQb
[] = { 0, 1, 0, 1, 0, 1 };
2024 res2
= aEQb
[pOp
->opcode
- OP_Ne
];
2026 static const unsigned char aGTb
[] = { 1, 0, 1, 0, 0, 1 };
2027 res2
= aGTb
[pOp
->opcode
- OP_Ne
];
2030 /* Undo any changes made by applyAffinity() to the input registers. */
2031 assert( (pIn1
->flags
& MEM_Dyn
) == (flags1
& MEM_Dyn
) );
2032 pIn1
->flags
= flags1
;
2033 assert( (pIn3
->flags
& MEM_Dyn
) == (flags3
& MEM_Dyn
) );
2034 pIn3
->flags
= flags3
;
2036 if( pOp
->p5
& SQLITE_STOREP2
){
2037 pOut
= &aMem
[pOp
->p2
];
2039 if( (pOp
->p5
& SQLITE_KEEPNULL
)!=0 ){
2040 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
2041 ** and prevents OP_Ne from overwriting NULL with 0. This flag
2042 ** is only used in contexts where either:
2043 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
2044 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
2045 ** Therefore it is not necessary to check the content of r[P2] for
2047 assert( pOp
->opcode
==OP_Ne
|| pOp
->opcode
==OP_Eq
);
2048 assert( res2
==0 || res2
==1 );
2049 testcase( res2
==0 && pOp
->opcode
==OP_Eq
);
2050 testcase( res2
==1 && pOp
->opcode
==OP_Eq
);
2051 testcase( res2
==0 && pOp
->opcode
==OP_Ne
);
2052 testcase( res2
==1 && pOp
->opcode
==OP_Ne
);
2053 if( (pOp
->opcode
==OP_Eq
)==res2
) break;
2055 memAboutToChange(p
, pOut
);
2056 MemSetTypeFlag(pOut
, MEM_Int
);
2058 REGISTER_TRACE(pOp
->p2
, pOut
);
2060 VdbeBranchTaken(res
!=0, (pOp
->p5
& SQLITE_NULLEQ
)?2:3);
2068 /* Opcode: ElseNotEq * P2 * * *
2070 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
2071 ** If result of an OP_Eq comparison on the same two operands
2072 ** would have be NULL or false (0), then then jump to P2.
2073 ** If the result of an OP_Eq comparison on the two previous operands
2074 ** would have been true (1), then fall through.
2076 case OP_ElseNotEq
: { /* same as TK_ESCAPE, jump */
2078 assert( pOp
[-1].opcode
==OP_Lt
|| pOp
[-1].opcode
==OP_Gt
);
2079 assert( pOp
[-1].p5
& SQLITE_STOREP2
);
2080 VdbeBranchTaken(iCompare
!=0, 2);
2081 if( iCompare
!=0 ) goto jump_to_p2
;
2086 /* Opcode: Permutation * * * P4 *
2088 ** Set the permutation used by the OP_Compare operator in the next
2089 ** instruction. The permutation is stored in the P4 operand.
2091 ** The permutation is only valid until the next OP_Compare that has
2092 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2093 ** occur immediately prior to the OP_Compare.
2095 ** The first integer in the P4 integer array is the length of the array
2096 ** and does not become part of the permutation.
2098 case OP_Permutation
: {
2099 assert( pOp
->p4type
==P4_INTARRAY
);
2100 assert( pOp
->p4
.ai
);
2101 assert( pOp
[1].opcode
==OP_Compare
);
2102 assert( pOp
[1].p5
& OPFLAG_PERMUTE
);
2106 /* Opcode: Compare P1 P2 P3 P4 P5
2107 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2109 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2110 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2111 ** the comparison for use by the next OP_Jump instruct.
2113 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2114 ** determined by the most recent OP_Permutation operator. If the
2115 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2118 ** P4 is a KeyInfo structure that defines collating sequences and sort
2119 ** orders for the comparison. The permutation applies to registers
2120 ** only. The KeyInfo elements are used sequentially.
2122 ** The comparison is a sort comparison, so NULLs compare equal,
2123 ** NULLs are less than numbers, numbers are less than strings,
2124 ** and strings are less than blobs.
2131 const KeyInfo
*pKeyInfo
;
2133 CollSeq
*pColl
; /* Collating sequence to use on this term */
2134 int bRev
; /* True for DESCENDING sort order */
2135 int *aPermute
; /* The permutation */
2137 if( (pOp
->p5
& OPFLAG_PERMUTE
)==0 ){
2141 assert( pOp
[-1].opcode
==OP_Permutation
);
2142 assert( pOp
[-1].p4type
==P4_INTARRAY
);
2143 aPermute
= pOp
[-1].p4
.ai
+ 1;
2144 assert( aPermute
!=0 );
2147 pKeyInfo
= pOp
->p4
.pKeyInfo
;
2149 assert( pKeyInfo
!=0 );
2155 for(k
=0; k
<n
; k
++) if( aPermute
[k
]>mx
) mx
= aPermute
[k
];
2156 assert( p1
>0 && p1
+mx
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2157 assert( p2
>0 && p2
+mx
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2159 assert( p1
>0 && p1
+n
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2160 assert( p2
>0 && p2
+n
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2162 #endif /* SQLITE_DEBUG */
2164 idx
= aPermute
? aPermute
[i
] : i
;
2165 assert( memIsValid(&aMem
[p1
+idx
]) );
2166 assert( memIsValid(&aMem
[p2
+idx
]) );
2167 REGISTER_TRACE(p1
+idx
, &aMem
[p1
+idx
]);
2168 REGISTER_TRACE(p2
+idx
, &aMem
[p2
+idx
]);
2169 assert( i
<pKeyInfo
->nKeyField
);
2170 pColl
= pKeyInfo
->aColl
[i
];
2171 bRev
= pKeyInfo
->aSortOrder
[i
];
2172 iCompare
= sqlite3MemCompare(&aMem
[p1
+idx
], &aMem
[p2
+idx
], pColl
);
2174 if( bRev
) iCompare
= -iCompare
;
2181 /* Opcode: Jump P1 P2 P3 * *
2183 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2184 ** in the most recent OP_Compare instruction the P1 vector was less than
2185 ** equal to, or greater than the P2 vector, respectively.
2187 case OP_Jump
: { /* jump */
2189 VdbeBranchTaken(0,4); pOp
= &aOp
[pOp
->p1
- 1];
2190 }else if( iCompare
==0 ){
2191 VdbeBranchTaken(1,4); pOp
= &aOp
[pOp
->p2
- 1];
2193 VdbeBranchTaken(2,4); pOp
= &aOp
[pOp
->p3
- 1];
2198 /* Opcode: And P1 P2 P3 * *
2199 ** Synopsis: r[P3]=(r[P1] && r[P2])
2201 ** Take the logical AND of the values in registers P1 and P2 and
2202 ** write the result into register P3.
2204 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2205 ** the other input is NULL. A NULL and true or two NULLs give
2208 /* Opcode: Or P1 P2 P3 * *
2209 ** Synopsis: r[P3]=(r[P1] || r[P2])
2211 ** Take the logical OR of the values in register P1 and P2 and
2212 ** store the answer in register P3.
2214 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2215 ** even if the other input is NULL. A NULL and false or two NULLs
2216 ** give a NULL output.
2218 case OP_And
: /* same as TK_AND, in1, in2, out3 */
2219 case OP_Or
: { /* same as TK_OR, in1, in2, out3 */
2220 int v1
; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2221 int v2
; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2223 v1
= sqlite3VdbeBooleanValue(&aMem
[pOp
->p1
], 2);
2224 v2
= sqlite3VdbeBooleanValue(&aMem
[pOp
->p2
], 2);
2225 if( pOp
->opcode
==OP_And
){
2226 static const unsigned char and_logic
[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2227 v1
= and_logic
[v1
*3+v2
];
2229 static const unsigned char or_logic
[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2230 v1
= or_logic
[v1
*3+v2
];
2232 pOut
= &aMem
[pOp
->p3
];
2234 MemSetTypeFlag(pOut
, MEM_Null
);
2237 MemSetTypeFlag(pOut
, MEM_Int
);
2242 /* Opcode: IsTrue P1 P2 P3 P4 *
2243 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2245 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2246 ** IS NOT FALSE operators.
2248 ** Interpret the value in register P1 as a boolean value. Store that
2249 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2250 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2253 ** The logic is summarized like this:
2256 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2257 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2258 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2259 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2262 case OP_IsTrue
: { /* in1, out2 */
2263 assert( pOp
->p4type
==P4_INT32
);
2264 assert( pOp
->p4
.i
==0 || pOp
->p4
.i
==1 );
2265 assert( pOp
->p3
==0 || pOp
->p3
==1 );
2266 sqlite3VdbeMemSetInt64(&aMem
[pOp
->p2
],
2267 sqlite3VdbeBooleanValue(&aMem
[pOp
->p1
], pOp
->p3
) ^ pOp
->p4
.i
);
2271 /* Opcode: Not P1 P2 * * *
2272 ** Synopsis: r[P2]= !r[P1]
2274 ** Interpret the value in register P1 as a boolean value. Store the
2275 ** boolean complement in register P2. If the value in register P1 is
2276 ** NULL, then a NULL is stored in P2.
2278 case OP_Not
: { /* same as TK_NOT, in1, out2 */
2279 pIn1
= &aMem
[pOp
->p1
];
2280 pOut
= &aMem
[pOp
->p2
];
2281 if( (pIn1
->flags
& MEM_Null
)==0 ){
2282 sqlite3VdbeMemSetInt64(pOut
, !sqlite3VdbeBooleanValue(pIn1
,0));
2284 sqlite3VdbeMemSetNull(pOut
);
2289 /* Opcode: BitNot P1 P2 * * *
2290 ** Synopsis: r[P2]= ~r[P1]
2292 ** Interpret the content of register P1 as an integer. Store the
2293 ** ones-complement of the P1 value into register P2. If P1 holds
2294 ** a NULL then store a NULL in P2.
2296 case OP_BitNot
: { /* same as TK_BITNOT, in1, out2 */
2297 pIn1
= &aMem
[pOp
->p1
];
2298 pOut
= &aMem
[pOp
->p2
];
2299 sqlite3VdbeMemSetNull(pOut
);
2300 if( (pIn1
->flags
& MEM_Null
)==0 ){
2301 pOut
->flags
= MEM_Int
;
2302 pOut
->u
.i
= ~sqlite3VdbeIntValue(pIn1
);
2307 /* Opcode: Once P1 P2 * * *
2309 ** Fall through to the next instruction the first time this opcode is
2310 ** encountered on each invocation of the byte-code program. Jump to P2
2311 ** on the second and all subsequent encounters during the same invocation.
2313 ** Top-level programs determine first invocation by comparing the P1
2314 ** operand against the P1 operand on the OP_Init opcode at the beginning
2315 ** of the program. If the P1 values differ, then fall through and make
2316 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2317 ** the same then take the jump.
2319 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2320 ** whether or not the jump should be taken. The bitmask is necessary
2321 ** because the self-altering code trick does not work for recursive
2324 case OP_Once
: { /* jump */
2325 u32 iAddr
; /* Address of this instruction */
2326 assert( p
->aOp
[0].opcode
==OP_Init
);
2328 iAddr
= (int)(pOp
- p
->aOp
);
2329 if( (p
->pFrame
->aOnce
[iAddr
/8] & (1<<(iAddr
& 7)))!=0 ){
2330 VdbeBranchTaken(1, 2);
2333 p
->pFrame
->aOnce
[iAddr
/8] |= 1<<(iAddr
& 7);
2335 if( p
->aOp
[0].p1
==pOp
->p1
){
2336 VdbeBranchTaken(1, 2);
2340 VdbeBranchTaken(0, 2);
2341 pOp
->p1
= p
->aOp
[0].p1
;
2345 /* Opcode: If P1 P2 P3 * *
2347 ** Jump to P2 if the value in register P1 is true. The value
2348 ** is considered true if it is numeric and non-zero. If the value
2349 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2351 case OP_If
: { /* jump, in1 */
2353 c
= sqlite3VdbeBooleanValue(&aMem
[pOp
->p1
], pOp
->p3
);
2354 VdbeBranchTaken(c
!=0, 2);
2355 if( c
) goto jump_to_p2
;
2359 /* Opcode: IfNot P1 P2 P3 * *
2361 ** Jump to P2 if the value in register P1 is False. The value
2362 ** is considered false if it has a numeric value of zero. If the value
2363 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2365 case OP_IfNot
: { /* jump, in1 */
2367 c
= !sqlite3VdbeBooleanValue(&aMem
[pOp
->p1
], !pOp
->p3
);
2368 VdbeBranchTaken(c
!=0, 2);
2369 if( c
) goto jump_to_p2
;
2373 /* Opcode: IsNull P1 P2 * * *
2374 ** Synopsis: if r[P1]==NULL goto P2
2376 ** Jump to P2 if the value in register P1 is NULL.
2378 case OP_IsNull
: { /* same as TK_ISNULL, jump, in1 */
2379 pIn1
= &aMem
[pOp
->p1
];
2380 VdbeBranchTaken( (pIn1
->flags
& MEM_Null
)!=0, 2);
2381 if( (pIn1
->flags
& MEM_Null
)!=0 ){
2387 /* Opcode: NotNull P1 P2 * * *
2388 ** Synopsis: if r[P1]!=NULL goto P2
2390 ** Jump to P2 if the value in register P1 is not NULL.
2392 case OP_NotNull
: { /* same as TK_NOTNULL, jump, in1 */
2393 pIn1
= &aMem
[pOp
->p1
];
2394 VdbeBranchTaken( (pIn1
->flags
& MEM_Null
)==0, 2);
2395 if( (pIn1
->flags
& MEM_Null
)==0 ){
2401 /* Opcode: IfNullRow P1 P2 P3 * *
2402 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2404 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2405 ** If it is, then set register P3 to NULL and jump immediately to P2.
2406 ** If P1 is not on a NULL row, then fall through without making any
2409 case OP_IfNullRow
: { /* jump */
2410 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
2411 assert( p
->apCsr
[pOp
->p1
]!=0 );
2412 if( p
->apCsr
[pOp
->p1
]->nullRow
){
2413 sqlite3VdbeMemSetNull(aMem
+ pOp
->p3
);
2419 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2420 /* Opcode: Offset P1 P2 P3 * *
2421 ** Synopsis: r[P3] = sqlite_offset(P1)
2423 ** Store in register r[P3] the byte offset into the database file that is the
2424 ** start of the payload for the record at which that cursor P1 is currently
2427 ** P2 is the column number for the argument to the sqlite_offset() function.
2428 ** This opcode does not use P2 itself, but the P2 value is used by the
2429 ** code generator. The P1, P2, and P3 operands to this opcode are the
2430 ** same as for OP_Column.
2432 ** This opcode is only available if SQLite is compiled with the
2433 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2435 case OP_Offset
: { /* out3 */
2436 VdbeCursor
*pC
; /* The VDBE cursor */
2437 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
2438 pC
= p
->apCsr
[pOp
->p1
];
2439 pOut
= &p
->aMem
[pOp
->p3
];
2440 if( NEVER(pC
==0) || pC
->eCurType
!=CURTYPE_BTREE
){
2441 sqlite3VdbeMemSetNull(pOut
);
2443 sqlite3VdbeMemSetInt64(pOut
, sqlite3BtreeOffset(pC
->uc
.pCursor
));
2447 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2449 /* Opcode: Column P1 P2 P3 P4 P5
2450 ** Synopsis: r[P3]=PX
2452 ** Interpret the data that cursor P1 points to as a structure built using
2453 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2454 ** information about the format of the data.) Extract the P2-th column
2455 ** from this record. If there are less that (P2+1)
2456 ** values in the record, extract a NULL.
2458 ** The value extracted is stored in register P3.
2460 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2461 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2464 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2465 ** then the cache of the cursor is reset prior to extracting the column.
2466 ** The first OP_Column against a pseudo-table after the value of the content
2467 ** register has changed should have this bit set.
2469 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2470 ** the result is guaranteed to only be used as the argument of a length()
2471 ** or typeof() function, respectively. The loading of large blobs can be
2472 ** skipped for length() and all content loading can be skipped for typeof().
2475 int p2
; /* column number to retrieve */
2476 VdbeCursor
*pC
; /* The VDBE cursor */
2477 BtCursor
*pCrsr
; /* The BTree cursor */
2478 u32
*aOffset
; /* aOffset[i] is offset to start of data for i-th column */
2479 int len
; /* The length of the serialized data for the column */
2480 int i
; /* Loop counter */
2481 Mem
*pDest
; /* Where to write the extracted value */
2482 Mem sMem
; /* For storing the record being decoded */
2483 const u8
*zData
; /* Part of the record being decoded */
2484 const u8
*zHdr
; /* Next unparsed byte of the header */
2485 const u8
*zEndHdr
; /* Pointer to first byte after the header */
2486 u64 offset64
; /* 64-bit offset */
2487 u32 t
; /* A type code from the record header */
2488 Mem
*pReg
; /* PseudoTable input register */
2490 pC
= p
->apCsr
[pOp
->p1
];
2493 /* If the cursor cache is stale (meaning it is not currently point at
2494 ** the correct row) then bring it up-to-date by doing the necessary
2496 rc
= sqlite3VdbeCursorMoveto(&pC
, &p2
);
2497 if( rc
) goto abort_due_to_error
;
2499 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
2500 pDest
= &aMem
[pOp
->p3
];
2501 memAboutToChange(p
, pDest
);
2502 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
2504 assert( p2
<pC
->nField
);
2505 aOffset
= pC
->aOffset
;
2506 assert( pC
->eCurType
!=CURTYPE_VTAB
);
2507 assert( pC
->eCurType
!=CURTYPE_PSEUDO
|| pC
->nullRow
);
2508 assert( pC
->eCurType
!=CURTYPE_SORTER
);
2510 if( pC
->cacheStatus
!=p
->cacheCtr
){ /*OPTIMIZATION-IF-FALSE*/
2512 if( pC
->eCurType
==CURTYPE_PSEUDO
){
2513 /* For the special case of as pseudo-cursor, the seekResult field
2514 ** identifies the register that holds the record */
2515 assert( pC
->seekResult
>0 );
2516 pReg
= &aMem
[pC
->seekResult
];
2517 assert( pReg
->flags
& MEM_Blob
);
2518 assert( memIsValid(pReg
) );
2519 pC
->payloadSize
= pC
->szRow
= pReg
->n
;
2520 pC
->aRow
= (u8
*)pReg
->z
;
2522 sqlite3VdbeMemSetNull(pDest
);
2526 pCrsr
= pC
->uc
.pCursor
;
2527 assert( pC
->eCurType
==CURTYPE_BTREE
);
2529 assert( sqlite3BtreeCursorIsValid(pCrsr
) );
2530 pC
->payloadSize
= sqlite3BtreePayloadSize(pCrsr
);
2531 pC
->aRow
= sqlite3BtreePayloadFetch(pCrsr
, &pC
->szRow
);
2532 assert( pC
->szRow
<=pC
->payloadSize
);
2533 assert( pC
->szRow
<=65536 ); /* Maximum page size is 64KiB */
2534 if( pC
->payloadSize
> (u32
)db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
2538 pC
->cacheStatus
= p
->cacheCtr
;
2539 pC
->iHdrOffset
= getVarint32(pC
->aRow
, aOffset
[0]);
2543 if( pC
->szRow
<aOffset
[0] ){ /*OPTIMIZATION-IF-FALSE*/
2544 /* pC->aRow does not have to hold the entire row, but it does at least
2545 ** need to cover the header of the record. If pC->aRow does not contain
2546 ** the complete header, then set it to zero, forcing the header to be
2547 ** dynamically allocated. */
2551 /* Make sure a corrupt database has not given us an oversize header.
2552 ** Do this now to avoid an oversize memory allocation.
2554 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2555 ** types use so much data space that there can only be 4096 and 32 of
2556 ** them, respectively. So the maximum header length results from a
2557 ** 3-byte type for each of the maximum of 32768 columns plus three
2558 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2560 if( aOffset
[0] > 98307 || aOffset
[0] > pC
->payloadSize
){
2561 goto op_column_corrupt
;
2564 /* This is an optimization. By skipping over the first few tests
2565 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2566 ** measurable performance gain.
2568 ** This branch is taken even if aOffset[0]==0. Such a record is never
2569 ** generated by SQLite, and could be considered corruption, but we
2570 ** accept it for historical reasons. When aOffset[0]==0, the code this
2571 ** branch jumps to reads past the end of the record, but never more
2572 ** than a few bytes. Even if the record occurs at the end of the page
2573 ** content area, the "page header" comes after the page content and so
2574 ** this overread is harmless. Similar overreads can occur for a corrupt
2578 assert( pC
->nHdrParsed
<=p2
); /* Conditional skipped */
2579 testcase( aOffset
[0]==0 );
2580 goto op_column_read_header
;
2584 /* Make sure at least the first p2+1 entries of the header have been
2585 ** parsed and valid information is in aOffset[] and pC->aType[].
2587 if( pC
->nHdrParsed
<=p2
){
2588 /* If there is more header available for parsing in the record, try
2589 ** to extract additional fields up through the p2+1-th field
2591 if( pC
->iHdrOffset
<aOffset
[0] ){
2592 /* Make sure zData points to enough of the record to cover the header. */
2594 memset(&sMem
, 0, sizeof(sMem
));
2595 rc
= sqlite3VdbeMemFromBtree(pC
->uc
.pCursor
, 0, aOffset
[0], &sMem
);
2596 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
2597 zData
= (u8
*)sMem
.z
;
2602 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2603 op_column_read_header
:
2605 offset64
= aOffset
[i
];
2606 zHdr
= zData
+ pC
->iHdrOffset
;
2607 zEndHdr
= zData
+ aOffset
[0];
2608 testcase( zHdr
>=zEndHdr
);
2610 if( (t
= zHdr
[0])<0x80 ){
2612 offset64
+= sqlite3VdbeOneByteSerialTypeLen(t
);
2614 zHdr
+= sqlite3GetVarint32(zHdr
, &t
);
2615 offset64
+= sqlite3VdbeSerialTypeLen(t
);
2618 aOffset
[i
] = (u32
)(offset64
& 0xffffffff);
2619 }while( i
<=p2
&& zHdr
<zEndHdr
);
2621 /* The record is corrupt if any of the following are true:
2622 ** (1) the bytes of the header extend past the declared header size
2623 ** (2) the entire header was used but not all data was used
2624 ** (3) the end of the data extends beyond the end of the record.
2626 if( (zHdr
>=zEndHdr
&& (zHdr
>zEndHdr
|| offset64
!=pC
->payloadSize
))
2627 || (offset64
> pC
->payloadSize
)
2629 if( aOffset
[0]==0 ){
2633 if( pC
->aRow
==0 ) sqlite3VdbeMemRelease(&sMem
);
2634 goto op_column_corrupt
;
2639 pC
->iHdrOffset
= (u32
)(zHdr
- zData
);
2640 if( pC
->aRow
==0 ) sqlite3VdbeMemRelease(&sMem
);
2645 /* If after trying to extract new entries from the header, nHdrParsed is
2646 ** still not up to p2, that means that the record has fewer than p2
2647 ** columns. So the result will be either the default value or a NULL.
2649 if( pC
->nHdrParsed
<=p2
){
2650 if( pOp
->p4type
==P4_MEM
){
2651 sqlite3VdbeMemShallowCopy(pDest
, pOp
->p4
.pMem
, MEM_Static
);
2653 sqlite3VdbeMemSetNull(pDest
);
2661 /* Extract the content for the p2+1-th column. Control can only
2662 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2665 assert( p2
<pC
->nHdrParsed
);
2666 assert( rc
==SQLITE_OK
);
2667 assert( sqlite3VdbeCheckMemInvariants(pDest
) );
2668 if( VdbeMemDynamic(pDest
) ){
2669 sqlite3VdbeMemSetNull(pDest
);
2671 assert( t
==pC
->aType
[p2
] );
2672 if( pC
->szRow
>=aOffset
[p2
+1] ){
2673 /* This is the common case where the desired content fits on the original
2674 ** page - where the content is not on an overflow page */
2675 zData
= pC
->aRow
+ aOffset
[p2
];
2677 sqlite3VdbeSerialGet(zData
, t
, pDest
);
2679 /* If the column value is a string, we need a persistent value, not
2680 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2681 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2683 static const u16 aFlag
[] = { MEM_Blob
, MEM_Str
|MEM_Term
};
2684 pDest
->n
= len
= (t
-12)/2;
2685 pDest
->enc
= encoding
;
2686 if( pDest
->szMalloc
< len
+2 ){
2687 pDest
->flags
= MEM_Null
;
2688 if( sqlite3VdbeMemGrow(pDest
, len
+2, 0) ) goto no_mem
;
2690 pDest
->z
= pDest
->zMalloc
;
2692 memcpy(pDest
->z
, zData
, len
);
2694 pDest
->z
[len
+1] = 0;
2695 pDest
->flags
= aFlag
[t
&1];
2698 pDest
->enc
= encoding
;
2699 /* This branch happens only when content is on overflow pages */
2700 if( ((pOp
->p5
& (OPFLAG_LENGTHARG
|OPFLAG_TYPEOFARG
))!=0
2701 && ((t
>=12 && (t
&1)==0) || (pOp
->p5
& OPFLAG_TYPEOFARG
)!=0))
2702 || (len
= sqlite3VdbeSerialTypeLen(t
))==0
2704 /* Content is irrelevant for
2705 ** 1. the typeof() function,
2706 ** 2. the length(X) function if X is a blob, and
2707 ** 3. if the content length is zero.
2708 ** So we might as well use bogus content rather than reading
2709 ** content from disk.
2711 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2712 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2713 ** read up to 16. So 16 bytes of bogus content is supplied.
2715 static u8 aZero
[16]; /* This is the bogus content */
2716 sqlite3VdbeSerialGet(aZero
, t
, pDest
);
2718 rc
= sqlite3VdbeMemFromBtree(pC
->uc
.pCursor
, aOffset
[p2
], len
, pDest
);
2719 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
2720 sqlite3VdbeSerialGet((const u8
*)pDest
->z
, t
, pDest
);
2721 pDest
->flags
&= ~MEM_Ephem
;
2726 UPDATE_MAX_BLOBSIZE(pDest
);
2727 REGISTER_TRACE(pOp
->p3
, pDest
);
2732 pOp
= &aOp
[aOp
[0].p3
-1];
2735 rc
= SQLITE_CORRUPT_BKPT
;
2736 goto abort_due_to_error
;
2740 /* Opcode: Affinity P1 P2 * P4 *
2741 ** Synopsis: affinity(r[P1@P2])
2743 ** Apply affinities to a range of P2 registers starting with P1.
2745 ** P4 is a string that is P2 characters long. The N-th character of the
2746 ** string indicates the column affinity that should be used for the N-th
2747 ** memory cell in the range.
2750 const char *zAffinity
; /* The affinity to be applied */
2752 zAffinity
= pOp
->p4
.z
;
2753 assert( zAffinity
!=0 );
2754 assert( pOp
->p2
>0 );
2755 assert( zAffinity
[pOp
->p2
]==0 );
2756 pIn1
= &aMem
[pOp
->p1
];
2758 assert( pIn1
<= &p
->aMem
[(p
->nMem
+1 - p
->nCursor
)] );
2759 assert( memIsValid(pIn1
) );
2760 applyAffinity(pIn1
, *(zAffinity
++), encoding
);
2762 }while( zAffinity
[0] );
2766 /* Opcode: MakeRecord P1 P2 P3 P4 *
2767 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2769 ** Convert P2 registers beginning with P1 into the [record format]
2770 ** use as a data record in a database table or as a key
2771 ** in an index. The OP_Column opcode can decode the record later.
2773 ** P4 may be a string that is P2 characters long. The N-th character of the
2774 ** string indicates the column affinity that should be used for the N-th
2775 ** field of the index key.
2777 ** The mapping from character to affinity is given by the SQLITE_AFF_
2778 ** macros defined in sqliteInt.h.
2780 ** If P4 is NULL then all index fields have the affinity BLOB.
2782 case OP_MakeRecord
: {
2783 u8
*zNewRecord
; /* A buffer to hold the data for the new record */
2784 Mem
*pRec
; /* The new record */
2785 u64 nData
; /* Number of bytes of data space */
2786 int nHdr
; /* Number of bytes of header space */
2787 i64 nByte
; /* Data space required for this record */
2788 i64 nZero
; /* Number of zero bytes at the end of the record */
2789 int nVarint
; /* Number of bytes in a varint */
2790 u32 serial_type
; /* Type field */
2791 Mem
*pData0
; /* First field to be combined into the record */
2792 Mem
*pLast
; /* Last field of the record */
2793 int nField
; /* Number of fields in the record */
2794 char *zAffinity
; /* The affinity string for the record */
2795 int file_format
; /* File format to use for encoding */
2796 int i
; /* Space used in zNewRecord[] header */
2797 int j
; /* Space used in zNewRecord[] content */
2798 u32 len
; /* Length of a field */
2800 /* Assuming the record contains N fields, the record format looks
2803 ** ------------------------------------------------------------------------
2804 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2805 ** ------------------------------------------------------------------------
2807 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2810 ** Each type field is a varint representing the serial type of the
2811 ** corresponding data element (see sqlite3VdbeSerialType()). The
2812 ** hdr-size field is also a varint which is the offset from the beginning
2813 ** of the record to data0.
2815 nData
= 0; /* Number of bytes of data space */
2816 nHdr
= 0; /* Number of bytes of header space */
2817 nZero
= 0; /* Number of zero bytes at the end of the record */
2819 zAffinity
= pOp
->p4
.z
;
2820 assert( nField
>0 && pOp
->p2
>0 && pOp
->p2
+nField
<=(p
->nMem
+1 - p
->nCursor
)+1 );
2821 pData0
= &aMem
[nField
];
2823 pLast
= &pData0
[nField
-1];
2824 file_format
= p
->minWriteFileFormat
;
2826 /* Identify the output register */
2827 assert( pOp
->p3
<pOp
->p1
|| pOp
->p3
>=pOp
->p1
+pOp
->p2
);
2828 pOut
= &aMem
[pOp
->p3
];
2829 memAboutToChange(p
, pOut
);
2831 /* Apply the requested affinity to all inputs
2833 assert( pData0
<=pLast
);
2837 applyAffinity(pRec
++, *(zAffinity
++), encoding
);
2838 assert( zAffinity
[0]==0 || pRec
<=pLast
);
2839 }while( zAffinity
[0] );
2842 #ifdef SQLITE_ENABLE_NULL_TRIM
2843 /* NULLs can be safely trimmed from the end of the record, as long as
2844 ** as the schema format is 2 or more and none of the omitted columns
2845 ** have a non-NULL default value. Also, the record must be left with
2846 ** at least one field. If P5>0 then it will be one more than the
2847 ** index of the right-most column with a non-NULL default value */
2849 while( (pLast
->flags
& MEM_Null
)!=0 && nField
>pOp
->p5
){
2856 /* Loop through the elements that will make up the record to figure
2857 ** out how much space is required for the new record.
2861 assert( memIsValid(pRec
) );
2862 serial_type
= sqlite3VdbeSerialType(pRec
, file_format
, &len
);
2863 if( pRec
->flags
& MEM_Zero
){
2864 if( serial_type
==0 ){
2865 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
2866 ** table methods that never invoke sqlite3_result_xxxxx() while
2867 ** computing an unchanging column value in an UPDATE statement.
2868 ** Give such values a special internal-use-only serial-type of 10
2869 ** so that they can be passed through to xUpdate and have
2870 ** a true sqlite3_value_nochange(). */
2871 assert( pOp
->p5
==OPFLAG_NOCHNG_MAGIC
|| CORRUPT_DB
);
2874 if( sqlite3VdbeMemExpandBlob(pRec
) ) goto no_mem
;
2876 nZero
+= pRec
->u
.nZero
;
2877 len
-= pRec
->u
.nZero
;
2881 testcase( serial_type
==127 );
2882 testcase( serial_type
==128 );
2883 nHdr
+= serial_type
<=127 ? 1 : sqlite3VarintLen(serial_type
);
2884 pRec
->uTemp
= serial_type
;
2885 if( pRec
==pData0
) break;
2889 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
2890 ** which determines the total number of bytes in the header. The varint
2891 ** value is the size of the header in bytes including the size varint
2893 testcase( nHdr
==126 );
2894 testcase( nHdr
==127 );
2896 /* The common case */
2899 /* Rare case of a really large header */
2900 nVarint
= sqlite3VarintLen(nHdr
);
2902 if( nVarint
<sqlite3VarintLen(nHdr
) ) nHdr
++;
2905 if( nByte
+nZero
>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
2909 /* Make sure the output register has a buffer large enough to store
2910 ** the new record. The output register (pOp->p3) is not allowed to
2911 ** be one of the input registers (because the following call to
2912 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2914 if( sqlite3VdbeMemClearAndResize(pOut
, (int)nByte
) ){
2917 zNewRecord
= (u8
*)pOut
->z
;
2919 /* Write the record */
2920 i
= putVarint32(zNewRecord
, nHdr
);
2922 assert( pData0
<=pLast
);
2925 serial_type
= pRec
->uTemp
;
2926 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
2927 ** additional varints, one per column. */
2928 i
+= putVarint32(&zNewRecord
[i
], serial_type
); /* serial type */
2929 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
2930 ** immediately follow the header. */
2931 j
+= sqlite3VdbeSerialPut(&zNewRecord
[j
], pRec
, serial_type
); /* content */
2932 }while( (++pRec
)<=pLast
);
2936 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
2937 pOut
->n
= (int)nByte
;
2938 pOut
->flags
= MEM_Blob
;
2940 pOut
->u
.nZero
= nZero
;
2941 pOut
->flags
|= MEM_Zero
;
2943 REGISTER_TRACE(pOp
->p3
, pOut
);
2944 UPDATE_MAX_BLOBSIZE(pOut
);
2948 /* Opcode: Count P1 P2 * * *
2949 ** Synopsis: r[P2]=count()
2951 ** Store the number of entries (an integer value) in the table or index
2952 ** opened by cursor P1 in register P2
2954 #ifndef SQLITE_OMIT_BTREECOUNT
2955 case OP_Count
: { /* out2 */
2959 assert( p
->apCsr
[pOp
->p1
]->eCurType
==CURTYPE_BTREE
);
2960 pCrsr
= p
->apCsr
[pOp
->p1
]->uc
.pCursor
;
2962 nEntry
= 0; /* Not needed. Only used to silence a warning. */
2963 rc
= sqlite3BtreeCount(pCrsr
, &nEntry
);
2964 if( rc
) goto abort_due_to_error
;
2965 pOut
= out2Prerelease(p
, pOp
);
2971 /* Opcode: Savepoint P1 * * P4 *
2973 ** Open, release or rollback the savepoint named by parameter P4, depending
2974 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2975 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2977 case OP_Savepoint
: {
2978 int p1
; /* Value of P1 operand */
2979 char *zName
; /* Name of savepoint */
2982 Savepoint
*pSavepoint
;
2990 /* Assert that the p1 parameter is valid. Also that if there is no open
2991 ** transaction, then there cannot be any savepoints.
2993 assert( db
->pSavepoint
==0 || db
->autoCommit
==0 );
2994 assert( p1
==SAVEPOINT_BEGIN
||p1
==SAVEPOINT_RELEASE
||p1
==SAVEPOINT_ROLLBACK
);
2995 assert( db
->pSavepoint
|| db
->isTransactionSavepoint
==0 );
2996 assert( checkSavepointCount(db
) );
2997 assert( p
->bIsReader
);
2999 if( p1
==SAVEPOINT_BEGIN
){
3000 if( db
->nVdbeWrite
>0 ){
3001 /* A new savepoint cannot be created if there are active write
3002 ** statements (i.e. open read/write incremental blob handles).
3004 sqlite3VdbeError(p
, "cannot open savepoint - SQL statements in progress");
3007 nName
= sqlite3Strlen30(zName
);
3009 #ifndef SQLITE_OMIT_VIRTUALTABLE
3010 /* This call is Ok even if this savepoint is actually a transaction
3011 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3012 ** If this is a transaction savepoint being opened, it is guaranteed
3013 ** that the db->aVTrans[] array is empty. */
3014 assert( db
->autoCommit
==0 || db
->nVTrans
==0 );
3015 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_BEGIN
,
3016 db
->nStatement
+db
->nSavepoint
);
3017 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
3020 /* Create a new savepoint structure. */
3021 pNew
= sqlite3DbMallocRawNN(db
, sizeof(Savepoint
)+nName
+1);
3023 pNew
->zName
= (char *)&pNew
[1];
3024 memcpy(pNew
->zName
, zName
, nName
+1);
3026 /* If there is no open transaction, then mark this as a special
3027 ** "transaction savepoint". */
3028 if( db
->autoCommit
){
3030 db
->isTransactionSavepoint
= 1;
3035 /* Link the new savepoint into the database handle's list. */
3036 pNew
->pNext
= db
->pSavepoint
;
3037 db
->pSavepoint
= pNew
;
3038 pNew
->nDeferredCons
= db
->nDeferredCons
;
3039 pNew
->nDeferredImmCons
= db
->nDeferredImmCons
;
3045 /* Find the named savepoint. If there is no such savepoint, then an
3046 ** an error is returned to the user. */
3048 pSavepoint
= db
->pSavepoint
;
3049 pSavepoint
&& sqlite3StrICmp(pSavepoint
->zName
, zName
);
3050 pSavepoint
= pSavepoint
->pNext
3055 sqlite3VdbeError(p
, "no such savepoint: %s", zName
);
3057 }else if( db
->nVdbeWrite
>0 && p1
==SAVEPOINT_RELEASE
){
3058 /* It is not possible to release (commit) a savepoint if there are
3059 ** active write statements.
3061 sqlite3VdbeError(p
, "cannot release savepoint - "
3062 "SQL statements in progress");
3066 /* Determine whether or not this is a transaction savepoint. If so,
3067 ** and this is a RELEASE command, then the current transaction
3070 int isTransaction
= pSavepoint
->pNext
==0 && db
->isTransactionSavepoint
;
3071 if( isTransaction
&& p1
==SAVEPOINT_RELEASE
){
3072 if( (rc
= sqlite3VdbeCheckFk(p
, 1))!=SQLITE_OK
){
3076 if( sqlite3VdbeHalt(p
)==SQLITE_BUSY
){
3077 p
->pc
= (int)(pOp
- aOp
);
3079 p
->rc
= rc
= SQLITE_BUSY
;
3082 db
->isTransactionSavepoint
= 0;
3086 iSavepoint
= db
->nSavepoint
- iSavepoint
- 1;
3087 if( p1
==SAVEPOINT_ROLLBACK
){
3088 isSchemaChange
= (db
->mDbFlags
& DBFLAG_SchemaChange
)!=0;
3089 for(ii
=0; ii
<db
->nDb
; ii
++){
3090 rc
= sqlite3BtreeTripAllCursors(db
->aDb
[ii
].pBt
,
3091 SQLITE_ABORT_ROLLBACK
,
3093 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
3098 for(ii
=0; ii
<db
->nDb
; ii
++){
3099 rc
= sqlite3BtreeSavepoint(db
->aDb
[ii
].pBt
, p1
, iSavepoint
);
3100 if( rc
!=SQLITE_OK
){
3101 goto abort_due_to_error
;
3104 if( isSchemaChange
){
3105 sqlite3ExpirePreparedStatements(db
);
3106 sqlite3ResetAllSchemasOfConnection(db
);
3107 db
->mDbFlags
|= DBFLAG_SchemaChange
;
3111 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3112 ** savepoints nested inside of the savepoint being operated on. */
3113 while( db
->pSavepoint
!=pSavepoint
){
3114 pTmp
= db
->pSavepoint
;
3115 db
->pSavepoint
= pTmp
->pNext
;
3116 sqlite3DbFree(db
, pTmp
);
3120 /* If it is a RELEASE, then destroy the savepoint being operated on
3121 ** too. If it is a ROLLBACK TO, then set the number of deferred
3122 ** constraint violations present in the database to the value stored
3123 ** when the savepoint was created. */
3124 if( p1
==SAVEPOINT_RELEASE
){
3125 assert( pSavepoint
==db
->pSavepoint
);
3126 db
->pSavepoint
= pSavepoint
->pNext
;
3127 sqlite3DbFree(db
, pSavepoint
);
3128 if( !isTransaction
){
3132 db
->nDeferredCons
= pSavepoint
->nDeferredCons
;
3133 db
->nDeferredImmCons
= pSavepoint
->nDeferredImmCons
;
3136 if( !isTransaction
|| p1
==SAVEPOINT_ROLLBACK
){
3137 rc
= sqlite3VtabSavepoint(db
, p1
, iSavepoint
);
3138 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
3142 if( rc
) goto abort_due_to_error
;
3147 /* Opcode: AutoCommit P1 P2 * * *
3149 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3150 ** back any currently active btree transactions. If there are any active
3151 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3152 ** there are active writing VMs or active VMs that use shared cache.
3154 ** This instruction causes the VM to halt.
3156 case OP_AutoCommit
: {
3157 int desiredAutoCommit
;
3160 desiredAutoCommit
= pOp
->p1
;
3161 iRollback
= pOp
->p2
;
3162 assert( desiredAutoCommit
==1 || desiredAutoCommit
==0 );
3163 assert( desiredAutoCommit
==1 || iRollback
==0 );
3164 assert( db
->nVdbeActive
>0 ); /* At least this one VM is active */
3165 assert( p
->bIsReader
);
3167 if( desiredAutoCommit
!=db
->autoCommit
){
3169 assert( desiredAutoCommit
==1 );
3170 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
3172 }else if( desiredAutoCommit
&& db
->nVdbeWrite
>0 ){
3173 /* If this instruction implements a COMMIT and other VMs are writing
3174 ** return an error indicating that the other VMs must complete first.
3176 sqlite3VdbeError(p
, "cannot commit transaction - "
3177 "SQL statements in progress");
3179 goto abort_due_to_error
;
3180 }else if( (rc
= sqlite3VdbeCheckFk(p
, 1))!=SQLITE_OK
){
3183 db
->autoCommit
= (u8
)desiredAutoCommit
;
3185 if( sqlite3VdbeHalt(p
)==SQLITE_BUSY
){
3186 p
->pc
= (int)(pOp
- aOp
);
3187 db
->autoCommit
= (u8
)(1-desiredAutoCommit
);
3188 p
->rc
= rc
= SQLITE_BUSY
;
3191 assert( db
->nStatement
==0 );
3192 sqlite3CloseSavepoints(db
);
3193 if( p
->rc
==SQLITE_OK
){
3201 (!desiredAutoCommit
)?"cannot start a transaction within a transaction":(
3202 (iRollback
)?"cannot rollback - no transaction is active":
3203 "cannot commit - no transaction is active"));
3206 goto abort_due_to_error
;
3211 /* Opcode: Transaction P1 P2 P3 P4 P5
3213 ** Begin a transaction on database P1 if a transaction is not already
3215 ** If P2 is non-zero, then a write-transaction is started, or if a
3216 ** read-transaction is already active, it is upgraded to a write-transaction.
3217 ** If P2 is zero, then a read-transaction is started.
3219 ** P1 is the index of the database file on which the transaction is
3220 ** started. Index 0 is the main database file and index 1 is the
3221 ** file used for temporary tables. Indices of 2 or more are used for
3222 ** attached databases.
3224 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3225 ** true (this flag is set if the Vdbe may modify more than one row and may
3226 ** throw an ABORT exception), a statement transaction may also be opened.
3227 ** More specifically, a statement transaction is opened iff the database
3228 ** connection is currently not in autocommit mode, or if there are other
3229 ** active statements. A statement transaction allows the changes made by this
3230 ** VDBE to be rolled back after an error without having to roll back the
3231 ** entire transaction. If no error is encountered, the statement transaction
3232 ** will automatically commit when the VDBE halts.
3234 ** If P5!=0 then this opcode also checks the schema cookie against P3
3235 ** and the schema generation counter against P4.
3236 ** The cookie changes its value whenever the database schema changes.
3237 ** This operation is used to detect when that the cookie has changed
3238 ** and that the current process needs to reread the schema. If the schema
3239 ** cookie in P3 differs from the schema cookie in the database header or
3240 ** if the schema generation counter in P4 differs from the current
3241 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3242 ** halts. The sqlite3_step() wrapper function might then reprepare the
3243 ** statement and rerun it from the beginning.
3245 case OP_Transaction
: {
3249 assert( p
->bIsReader
);
3250 assert( p
->readOnly
==0 || pOp
->p2
==0 );
3251 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
3252 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
3253 if( pOp
->p2
&& (db
->flags
& SQLITE_QueryOnly
)!=0 ){
3254 rc
= SQLITE_READONLY
;
3255 goto abort_due_to_error
;
3257 pBt
= db
->aDb
[pOp
->p1
].pBt
;
3260 rc
= sqlite3BtreeBeginTrans(pBt
, pOp
->p2
, &iMeta
);
3261 testcase( rc
==SQLITE_BUSY_SNAPSHOT
);
3262 testcase( rc
==SQLITE_BUSY_RECOVERY
);
3263 if( rc
!=SQLITE_OK
){
3264 if( (rc
&0xff)==SQLITE_BUSY
){
3265 p
->pc
= (int)(pOp
- aOp
);
3269 goto abort_due_to_error
;
3272 if( pOp
->p2
&& p
->usesStmtJournal
3273 && (db
->autoCommit
==0 || db
->nVdbeRead
>1)
3275 assert( sqlite3BtreeIsInTrans(pBt
) );
3276 if( p
->iStatement
==0 ){
3277 assert( db
->nStatement
>=0 && db
->nSavepoint
>=0 );
3279 p
->iStatement
= db
->nSavepoint
+ db
->nStatement
;
3282 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_BEGIN
, p
->iStatement
-1);
3283 if( rc
==SQLITE_OK
){
3284 rc
= sqlite3BtreeBeginStmt(pBt
, p
->iStatement
);
3287 /* Store the current value of the database handles deferred constraint
3288 ** counter. If the statement transaction needs to be rolled back,
3289 ** the value of this counter needs to be restored too. */
3290 p
->nStmtDefCons
= db
->nDeferredCons
;
3291 p
->nStmtDefImmCons
= db
->nDeferredImmCons
;
3294 assert( pOp
->p5
==0 || pOp
->p4type
==P4_INT32
);
3297 || db
->aDb
[pOp
->p1
].pSchema
->iGeneration
!=pOp
->p4
.i
)
3300 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3301 ** version is checked to ensure that the schema has not changed since the
3302 ** SQL statement was prepared.
3304 sqlite3DbFree(db
, p
->zErrMsg
);
3305 p
->zErrMsg
= sqlite3DbStrDup(db
, "database schema has changed");
3306 /* If the schema-cookie from the database file matches the cookie
3307 ** stored with the in-memory representation of the schema, do
3308 ** not reload the schema from the database file.
3310 ** If virtual-tables are in use, this is not just an optimization.
3311 ** Often, v-tables store their data in other SQLite tables, which
3312 ** are queried from within xNext() and other v-table methods using
3313 ** prepared queries. If such a query is out-of-date, we do not want to
3314 ** discard the database schema, as the user code implementing the
3315 ** v-table would have to be ready for the sqlite3_vtab structure itself
3316 ** to be invalidated whenever sqlite3_step() is called from within
3317 ** a v-table method.
3319 if( db
->aDb
[pOp
->p1
].pSchema
->schema_cookie
!=iMeta
){
3320 sqlite3ResetOneSchema(db
, pOp
->p1
);
3325 if( rc
) goto abort_due_to_error
;
3329 /* Opcode: ReadCookie P1 P2 P3 * *
3331 ** Read cookie number P3 from database P1 and write it into register P2.
3332 ** P3==1 is the schema version. P3==2 is the database format.
3333 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3334 ** the main database file and P1==1 is the database file used to store
3335 ** temporary tables.
3337 ** There must be a read-lock on the database (either a transaction
3338 ** must be started or there must be an open cursor) before
3339 ** executing this instruction.
3341 case OP_ReadCookie
: { /* out2 */
3346 assert( p
->bIsReader
);
3349 assert( pOp
->p3
<SQLITE_N_BTREE_META
);
3350 assert( iDb
>=0 && iDb
<db
->nDb
);
3351 assert( db
->aDb
[iDb
].pBt
!=0 );
3352 assert( DbMaskTest(p
->btreeMask
, iDb
) );
3354 sqlite3BtreeGetMeta(db
->aDb
[iDb
].pBt
, iCookie
, (u32
*)&iMeta
);
3355 pOut
= out2Prerelease(p
, pOp
);
3360 /* Opcode: SetCookie P1 P2 P3 * *
3362 ** Write the integer value P3 into cookie number P2 of database P1.
3363 ** P2==1 is the schema version. P2==2 is the database format.
3364 ** P2==3 is the recommended pager cache
3365 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3366 ** database file used to store temporary tables.
3368 ** A transaction must be started before executing this opcode.
3370 case OP_SetCookie
: {
3373 sqlite3VdbeIncrWriteCounter(p
, 0);
3374 assert( pOp
->p2
<SQLITE_N_BTREE_META
);
3375 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
3376 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
3377 assert( p
->readOnly
==0 );
3378 pDb
= &db
->aDb
[pOp
->p1
];
3379 assert( pDb
->pBt
!=0 );
3380 assert( sqlite3SchemaMutexHeld(db
, pOp
->p1
, 0) );
3381 /* See note about index shifting on OP_ReadCookie */
3382 rc
= sqlite3BtreeUpdateMeta(pDb
->pBt
, pOp
->p2
, pOp
->p3
);
3383 if( pOp
->p2
==BTREE_SCHEMA_VERSION
){
3384 /* When the schema cookie changes, record the new cookie internally */
3385 pDb
->pSchema
->schema_cookie
= pOp
->p3
;
3386 db
->mDbFlags
|= DBFLAG_SchemaChange
;
3387 }else if( pOp
->p2
==BTREE_FILE_FORMAT
){
3388 /* Record changes in the file format */
3389 pDb
->pSchema
->file_format
= pOp
->p3
;
3392 /* Invalidate all prepared statements whenever the TEMP database
3393 ** schema is changed. Ticket #1644 */
3394 sqlite3ExpirePreparedStatements(db
);
3397 if( rc
) goto abort_due_to_error
;
3401 /* Opcode: OpenRead P1 P2 P3 P4 P5
3402 ** Synopsis: root=P2 iDb=P3
3404 ** Open a read-only cursor for the database table whose root page is
3405 ** P2 in a database file. The database file is determined by P3.
3406 ** P3==0 means the main database, P3==1 means the database used for
3407 ** temporary tables, and P3>1 means used the corresponding attached
3408 ** database. Give the new cursor an identifier of P1. The P1
3409 ** values need not be contiguous but all P1 values should be small integers.
3410 ** It is an error for P1 to be negative.
3414 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3415 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3416 ** of OP_SeekLE/OP_IdxGT)
3419 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3420 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3421 ** object, then table being opened must be an [index b-tree] where the
3422 ** KeyInfo object defines the content and collating
3423 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3424 ** value, then the table being opened must be a [table b-tree] with a
3425 ** number of columns no less than the value of P4.
3427 ** See also: OpenWrite, ReopenIdx
3429 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3430 ** Synopsis: root=P2 iDb=P3
3432 ** The ReopenIdx opcode works like OP_OpenRead except that it first
3433 ** checks to see if the cursor on P1 is already open on the same
3434 ** b-tree and if it is this opcode becomes a no-op. In other words,
3435 ** if the cursor is already open, do not reopen it.
3437 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
3438 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
3439 ** be the same as every other ReopenIdx or OpenRead for the same cursor
3444 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3445 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3446 ** of OP_SeekLE/OP_IdxGT)
3449 ** See also: OP_OpenRead, OP_OpenWrite
3451 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3452 ** Synopsis: root=P2 iDb=P3
3454 ** Open a read/write cursor named P1 on the table or index whose root
3455 ** page is P2 (or whose root page is held in register P2 if the
3456 ** OPFLAG_P2ISREG bit is set in P5 - see below).
3458 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3459 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3460 ** object, then table being opened must be an [index b-tree] where the
3461 ** KeyInfo object defines the content and collating
3462 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3463 ** value, then the table being opened must be a [table b-tree] with a
3464 ** number of columns no less than the value of P4.
3468 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3469 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3470 ** of OP_SeekLE/OP_IdxGT)
3471 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
3472 ** and subsequently delete entries in an index btree. This is a
3473 ** hint to the storage engine that the storage engine is allowed to
3474 ** ignore. The hint is not used by the official SQLite b*tree storage
3475 ** engine, but is used by COMDB2.
3476 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
3477 ** as the root page, not the value of P2 itself.
3480 ** This instruction works like OpenRead except that it opens the cursor
3481 ** in read/write mode.
3483 ** See also: OP_OpenRead, OP_ReopenIdx
3485 case OP_ReopenIdx
: {
3495 assert( pOp
->p5
==0 || pOp
->p5
==OPFLAG_SEEKEQ
);
3496 assert( pOp
->p4type
==P4_KEYINFO
);
3497 pCur
= p
->apCsr
[pOp
->p1
];
3498 if( pCur
&& pCur
->pgnoRoot
==(u32
)pOp
->p2
){
3499 assert( pCur
->iDb
==pOp
->p3
); /* Guaranteed by the code generator */
3500 goto open_cursor_set_hints
;
3502 /* If the cursor is not currently open or is open on a different
3503 ** index, then fall through into OP_OpenRead to force a reopen */
3507 assert( pOp
->opcode
==OP_OpenWrite
|| pOp
->p5
==0 || pOp
->p5
==OPFLAG_SEEKEQ
);
3508 assert( p
->bIsReader
);
3509 assert( pOp
->opcode
==OP_OpenRead
|| pOp
->opcode
==OP_ReopenIdx
3510 || p
->readOnly
==0 );
3513 rc
= SQLITE_ABORT_ROLLBACK
;
3514 goto abort_due_to_error
;
3521 assert( iDb
>=0 && iDb
<db
->nDb
);
3522 assert( DbMaskTest(p
->btreeMask
, iDb
) );
3523 pDb
= &db
->aDb
[iDb
];
3526 if( pOp
->opcode
==OP_OpenWrite
){
3527 assert( OPFLAG_FORDELETE
==BTREE_FORDELETE
);
3528 wrFlag
= BTREE_WRCSR
| (pOp
->p5
& OPFLAG_FORDELETE
);
3529 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
3530 if( pDb
->pSchema
->file_format
< p
->minWriteFileFormat
){
3531 p
->minWriteFileFormat
= pDb
->pSchema
->file_format
;
3536 if( pOp
->p5
& OPFLAG_P2ISREG
){
3538 assert( p2
<=(p
->nMem
+1 - p
->nCursor
) );
3539 assert( pOp
->opcode
==OP_OpenWrite
);
3541 assert( memIsValid(pIn2
) );
3542 assert( (pIn2
->flags
& MEM_Int
)!=0 );
3543 sqlite3VdbeMemIntegerify(pIn2
);
3544 p2
= (int)pIn2
->u
.i
;
3545 /* The p2 value always comes from a prior OP_CreateBtree opcode and
3546 ** that opcode will always set the p2 value to 2 or more or else fail.
3547 ** If there were a failure, the prepared statement would have halted
3548 ** before reaching this instruction. */
3551 if( pOp
->p4type
==P4_KEYINFO
){
3552 pKeyInfo
= pOp
->p4
.pKeyInfo
;
3553 assert( pKeyInfo
->enc
==ENC(db
) );
3554 assert( pKeyInfo
->db
==db
);
3555 nField
= pKeyInfo
->nAllField
;
3556 }else if( pOp
->p4type
==P4_INT32
){
3559 assert( pOp
->p1
>=0 );
3560 assert( nField
>=0 );
3561 testcase( nField
==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3562 pCur
= allocateCursor(p
, pOp
->p1
, nField
, iDb
, CURTYPE_BTREE
);
3563 if( pCur
==0 ) goto no_mem
;
3565 pCur
->isOrdered
= 1;
3566 pCur
->pgnoRoot
= p2
;
3568 pCur
->wrFlag
= wrFlag
;
3570 rc
= sqlite3BtreeCursor(pX
, p2
, wrFlag
, pKeyInfo
, pCur
->uc
.pCursor
);
3571 pCur
->pKeyInfo
= pKeyInfo
;
3572 /* Set the VdbeCursor.isTable variable. Previous versions of
3573 ** SQLite used to check if the root-page flags were sane at this point
3574 ** and report database corruption if they were not, but this check has
3575 ** since moved into the btree layer. */
3576 pCur
->isTable
= pOp
->p4type
!=P4_KEYINFO
;
3578 open_cursor_set_hints
:
3579 assert( OPFLAG_BULKCSR
==BTREE_BULKLOAD
);
3580 assert( OPFLAG_SEEKEQ
==BTREE_SEEK_EQ
);
3581 testcase( pOp
->p5
& OPFLAG_BULKCSR
);
3582 #ifdef SQLITE_ENABLE_CURSOR_HINTS
3583 testcase( pOp
->p2
& OPFLAG_SEEKEQ
);
3585 sqlite3BtreeCursorHintFlags(pCur
->uc
.pCursor
,
3586 (pOp
->p5
& (OPFLAG_BULKCSR
|OPFLAG_SEEKEQ
)));
3587 if( rc
) goto abort_due_to_error
;
3591 /* Opcode: OpenDup P1 P2 * * *
3593 ** Open a new cursor P1 that points to the same ephemeral table as
3594 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
3595 ** opcode. Only ephemeral cursors may be duplicated.
3597 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
3600 VdbeCursor
*pOrig
; /* The original cursor to be duplicated */
3601 VdbeCursor
*pCx
; /* The new cursor */
3603 pOrig
= p
->apCsr
[pOp
->p2
];
3604 assert( pOrig
->pBtx
!=0 ); /* Only ephemeral cursors can be duplicated */
3606 pCx
= allocateCursor(p
, pOp
->p1
, pOrig
->nField
, -1, CURTYPE_BTREE
);
3607 if( pCx
==0 ) goto no_mem
;
3609 pCx
->isEphemeral
= 1;
3610 pCx
->pKeyInfo
= pOrig
->pKeyInfo
;
3611 pCx
->isTable
= pOrig
->isTable
;
3612 rc
= sqlite3BtreeCursor(pOrig
->pBtx
, MASTER_ROOT
, BTREE_WRCSR
,
3613 pCx
->pKeyInfo
, pCx
->uc
.pCursor
);
3614 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
3615 ** opened for a database. Since there is already an open cursor when this
3616 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
3617 assert( rc
==SQLITE_OK
);
3622 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3623 ** Synopsis: nColumn=P2
3625 ** Open a new cursor P1 to a transient table.
3626 ** The cursor is always opened read/write even if
3627 ** the main database is read-only. The ephemeral
3628 ** table is deleted automatically when the cursor is closed.
3630 ** P2 is the number of columns in the ephemeral table.
3631 ** The cursor points to a BTree table if P4==0 and to a BTree index
3632 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3633 ** that defines the format of keys in the index.
3635 ** The P5 parameter can be a mask of the BTREE_* flags defined
3636 ** in btree.h. These flags control aspects of the operation of
3637 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3638 ** added automatically.
3640 /* Opcode: OpenAutoindex P1 P2 * P4 *
3641 ** Synopsis: nColumn=P2
3643 ** This opcode works the same as OP_OpenEphemeral. It has a
3644 ** different name to distinguish its use. Tables created using
3645 ** by this opcode will be used for automatically created transient
3646 ** indices in joins.
3648 case OP_OpenAutoindex
:
3649 case OP_OpenEphemeral
: {
3653 static const int vfsFlags
=
3654 SQLITE_OPEN_READWRITE
|
3655 SQLITE_OPEN_CREATE
|
3656 SQLITE_OPEN_EXCLUSIVE
|
3657 SQLITE_OPEN_DELETEONCLOSE
|
3658 SQLITE_OPEN_TRANSIENT_DB
;
3659 assert( pOp
->p1
>=0 );
3660 assert( pOp
->p2
>=0 );
3661 pCx
= allocateCursor(p
, pOp
->p1
, pOp
->p2
, -1, CURTYPE_BTREE
);
3662 if( pCx
==0 ) goto no_mem
;
3664 pCx
->isEphemeral
= 1;
3665 rc
= sqlite3BtreeOpen(db
->pVfs
, 0, db
, &pCx
->pBtx
,
3666 BTREE_OMIT_JOURNAL
| BTREE_SINGLE
| pOp
->p5
, vfsFlags
);
3667 if( rc
==SQLITE_OK
){
3668 rc
= sqlite3BtreeBeginTrans(pCx
->pBtx
, 1, 0);
3670 if( rc
==SQLITE_OK
){
3671 /* If a transient index is required, create it by calling
3672 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3673 ** opening it. If a transient table is required, just use the
3674 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3676 if( (pCx
->pKeyInfo
= pKeyInfo
= pOp
->p4
.pKeyInfo
)!=0 ){
3678 assert( pOp
->p4type
==P4_KEYINFO
);
3679 rc
= sqlite3BtreeCreateTable(pCx
->pBtx
, &pgno
, BTREE_BLOBKEY
| pOp
->p5
);
3680 if( rc
==SQLITE_OK
){
3681 assert( pgno
==MASTER_ROOT
+1 );
3682 assert( pKeyInfo
->db
==db
);
3683 assert( pKeyInfo
->enc
==ENC(db
) );
3684 rc
= sqlite3BtreeCursor(pCx
->pBtx
, pgno
, BTREE_WRCSR
,
3685 pKeyInfo
, pCx
->uc
.pCursor
);
3689 rc
= sqlite3BtreeCursor(pCx
->pBtx
, MASTER_ROOT
, BTREE_WRCSR
,
3690 0, pCx
->uc
.pCursor
);
3694 if( rc
) goto abort_due_to_error
;
3695 pCx
->isOrdered
= (pOp
->p5
!=BTREE_UNORDERED
);
3699 /* Opcode: SorterOpen P1 P2 P3 P4 *
3701 ** This opcode works like OP_OpenEphemeral except that it opens
3702 ** a transient index that is specifically designed to sort large
3703 ** tables using an external merge-sort algorithm.
3705 ** If argument P3 is non-zero, then it indicates that the sorter may
3706 ** assume that a stable sort considering the first P3 fields of each
3707 ** key is sufficient to produce the required results.
3709 case OP_SorterOpen
: {
3712 assert( pOp
->p1
>=0 );
3713 assert( pOp
->p2
>=0 );
3714 pCx
= allocateCursor(p
, pOp
->p1
, pOp
->p2
, -1, CURTYPE_SORTER
);
3715 if( pCx
==0 ) goto no_mem
;
3716 pCx
->pKeyInfo
= pOp
->p4
.pKeyInfo
;
3717 assert( pCx
->pKeyInfo
->db
==db
);
3718 assert( pCx
->pKeyInfo
->enc
==ENC(db
) );
3719 rc
= sqlite3VdbeSorterInit(db
, pOp
->p3
, pCx
);
3720 if( rc
) goto abort_due_to_error
;
3724 /* Opcode: SequenceTest P1 P2 * * *
3725 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3727 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3728 ** to P2. Regardless of whether or not the jump is taken, increment the
3729 ** the sequence value.
3731 case OP_SequenceTest
: {
3733 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
3734 pC
= p
->apCsr
[pOp
->p1
];
3735 assert( isSorter(pC
) );
3736 if( (pC
->seqCount
++)==0 ){
3742 /* Opcode: OpenPseudo P1 P2 P3 * *
3743 ** Synopsis: P3 columns in r[P2]
3745 ** Open a new cursor that points to a fake table that contains a single
3746 ** row of data. The content of that one row is the content of memory
3747 ** register P2. In other words, cursor P1 becomes an alias for the
3748 ** MEM_Blob content contained in register P2.
3750 ** A pseudo-table created by this opcode is used to hold a single
3751 ** row output from the sorter so that the row can be decomposed into
3752 ** individual columns using the OP_Column opcode. The OP_Column opcode
3753 ** is the only cursor opcode that works with a pseudo-table.
3755 ** P3 is the number of fields in the records that will be stored by
3756 ** the pseudo-table.
3758 case OP_OpenPseudo
: {
3761 assert( pOp
->p1
>=0 );
3762 assert( pOp
->p3
>=0 );
3763 pCx
= allocateCursor(p
, pOp
->p1
, pOp
->p3
, -1, CURTYPE_PSEUDO
);
3764 if( pCx
==0 ) goto no_mem
;
3766 pCx
->seekResult
= pOp
->p2
;
3768 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
3769 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
3770 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
3771 ** which is a performance optimization */
3772 pCx
->uc
.pCursor
= sqlite3BtreeFakeValidCursor();
3773 assert( pOp
->p5
==0 );
3777 /* Opcode: Close P1 * * * *
3779 ** Close a cursor previously opened as P1. If P1 is not
3780 ** currently open, this instruction is a no-op.
3783 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
3784 sqlite3VdbeFreeCursor(p
, p
->apCsr
[pOp
->p1
]);
3785 p
->apCsr
[pOp
->p1
] = 0;
3789 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3790 /* Opcode: ColumnsUsed P1 * * P4 *
3792 ** This opcode (which only exists if SQLite was compiled with
3793 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
3794 ** table or index for cursor P1 are used. P4 is a 64-bit integer
3795 ** (P4_INT64) in which the first 63 bits are one for each of the
3796 ** first 63 columns of the table or index that are actually used
3797 ** by the cursor. The high-order bit is set if any column after
3798 ** the 64th is used.
3800 case OP_ColumnsUsed
: {
3802 pC
= p
->apCsr
[pOp
->p1
];
3803 assert( pC
->eCurType
==CURTYPE_BTREE
);
3804 pC
->maskUsed
= *(u64
*)pOp
->p4
.pI64
;
3809 /* Opcode: SeekGE P1 P2 P3 P4 *
3810 ** Synopsis: key=r[P3@P4]
3812 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3813 ** use the value in register P3 as the key. If cursor P1 refers
3814 ** to an SQL index, then P3 is the first in an array of P4 registers
3815 ** that are used as an unpacked index key.
3817 ** Reposition cursor P1 so that it points to the smallest entry that
3818 ** is greater than or equal to the key value. If there are no records
3819 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3821 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3822 ** opcode will always land on a record that equally equals the key, or
3823 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3824 ** opcode must be followed by an IdxLE opcode with the same arguments.
3825 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
3826 ** IdxLE opcode will be used on subsequent loop iterations.
3828 ** This opcode leaves the cursor configured to move in forward order,
3829 ** from the beginning toward the end. In other words, the cursor is
3830 ** configured to use Next, not Prev.
3832 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3834 /* Opcode: SeekGT P1 P2 P3 P4 *
3835 ** Synopsis: key=r[P3@P4]
3837 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3838 ** use the value in register P3 as a key. If cursor P1 refers
3839 ** to an SQL index, then P3 is the first in an array of P4 registers
3840 ** that are used as an unpacked index key.
3842 ** Reposition cursor P1 so that it points to the smallest entry that
3843 ** is greater than the key value. If there are no records greater than
3844 ** the key and P2 is not zero, then jump to P2.
3846 ** This opcode leaves the cursor configured to move in forward order,
3847 ** from the beginning toward the end. In other words, the cursor is
3848 ** configured to use Next, not Prev.
3850 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3852 /* Opcode: SeekLT P1 P2 P3 P4 *
3853 ** Synopsis: key=r[P3@P4]
3855 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3856 ** use the value in register P3 as a key. If cursor P1 refers
3857 ** to an SQL index, then P3 is the first in an array of P4 registers
3858 ** that are used as an unpacked index key.
3860 ** Reposition cursor P1 so that it points to the largest entry that
3861 ** is less than the key value. If there are no records less than
3862 ** the key and P2 is not zero, then jump to P2.
3864 ** This opcode leaves the cursor configured to move in reverse order,
3865 ** from the end toward the beginning. In other words, the cursor is
3866 ** configured to use Prev, not Next.
3868 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3870 /* Opcode: SeekLE P1 P2 P3 P4 *
3871 ** Synopsis: key=r[P3@P4]
3873 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3874 ** use the value in register P3 as a key. If cursor P1 refers
3875 ** to an SQL index, then P3 is the first in an array of P4 registers
3876 ** that are used as an unpacked index key.
3878 ** Reposition cursor P1 so that it points to the largest entry that
3879 ** is less than or equal to the key value. If there are no records
3880 ** less than or equal to the key and P2 is not zero, then jump to P2.
3882 ** This opcode leaves the cursor configured to move in reverse order,
3883 ** from the end toward the beginning. In other words, the cursor is
3884 ** configured to use Prev, not Next.
3886 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
3887 ** opcode will always land on a record that equally equals the key, or
3888 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
3889 ** opcode must be followed by an IdxGE opcode with the same arguments.
3890 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
3891 ** IdxGE opcode will be used on subsequent loop iterations.
3893 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3895 case OP_SeekLT
: /* jump, in3 */
3896 case OP_SeekLE
: /* jump, in3 */
3897 case OP_SeekGE
: /* jump, in3 */
3898 case OP_SeekGT
: { /* jump, in3 */
3899 int res
; /* Comparison result */
3900 int oc
; /* Opcode */
3901 VdbeCursor
*pC
; /* The cursor to seek */
3902 UnpackedRecord r
; /* The key to seek for */
3903 int nField
; /* Number of columns or fields in the key */
3904 i64 iKey
; /* The rowid we are to seek to */
3905 int eqOnly
; /* Only interested in == results */
3907 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
3908 assert( pOp
->p2
!=0 );
3909 pC
= p
->apCsr
[pOp
->p1
];
3911 assert( pC
->eCurType
==CURTYPE_BTREE
);
3912 assert( OP_SeekLE
== OP_SeekLT
+1 );
3913 assert( OP_SeekGE
== OP_SeekLT
+2 );
3914 assert( OP_SeekGT
== OP_SeekLT
+3 );
3915 assert( pC
->isOrdered
);
3916 assert( pC
->uc
.pCursor
!=0 );
3921 pC
->seekOp
= pOp
->opcode
;
3925 /* The BTREE_SEEK_EQ flag is only set on index cursors */
3926 assert( sqlite3BtreeCursorHasHint(pC
->uc
.pCursor
, BTREE_SEEK_EQ
)==0
3929 /* The input value in P3 might be of any type: integer, real, string,
3930 ** blob, or NULL. But it needs to be an integer before we can do
3931 ** the seek, so convert it. */
3932 pIn3
= &aMem
[pOp
->p3
];
3933 if( (pIn3
->flags
& (MEM_Int
|MEM_Real
|MEM_Str
))==MEM_Str
){
3934 applyNumericAffinity(pIn3
, 0);
3936 iKey
= sqlite3VdbeIntValue(pIn3
);
3938 /* If the P3 value could not be converted into an integer without
3939 ** loss of information, then special processing is required... */
3940 if( (pIn3
->flags
& MEM_Int
)==0 ){
3941 if( (pIn3
->flags
& MEM_Real
)==0 ){
3942 /* If the P3 value cannot be converted into any kind of a number,
3943 ** then the seek is not possible, so jump to P2 */
3944 VdbeBranchTaken(1,2); goto jump_to_p2
;
3948 /* If the approximation iKey is larger than the actual real search
3949 ** term, substitute >= for > and < for <=. e.g. if the search term
3950 ** is 4.9 and the integer approximation 5:
3952 ** (x > 4.9) -> (x >= 5)
3953 ** (x <= 4.9) -> (x < 5)
3955 if( pIn3
->u
.r
<(double)iKey
){
3956 assert( OP_SeekGE
==(OP_SeekGT
-1) );
3957 assert( OP_SeekLT
==(OP_SeekLE
-1) );
3958 assert( (OP_SeekLE
& 0x0001)==(OP_SeekGT
& 0x0001) );
3959 if( (oc
& 0x0001)==(OP_SeekGT
& 0x0001) ) oc
--;
3962 /* If the approximation iKey is smaller than the actual real search
3963 ** term, substitute <= for < and > for >=. */
3964 else if( pIn3
->u
.r
>(double)iKey
){
3965 assert( OP_SeekLE
==(OP_SeekLT
+1) );
3966 assert( OP_SeekGT
==(OP_SeekGE
+1) );
3967 assert( (OP_SeekLT
& 0x0001)==(OP_SeekGE
& 0x0001) );
3968 if( (oc
& 0x0001)==(OP_SeekLT
& 0x0001) ) oc
++;
3971 rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, 0, (u64
)iKey
, 0, &res
);
3972 pC
->movetoTarget
= iKey
; /* Used by OP_Delete */
3973 if( rc
!=SQLITE_OK
){
3974 goto abort_due_to_error
;
3977 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
3978 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
3979 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
3981 if( sqlite3BtreeCursorHasHint(pC
->uc
.pCursor
, BTREE_SEEK_EQ
) ){
3983 assert( pOp
->opcode
==OP_SeekGE
|| pOp
->opcode
==OP_SeekLE
);
3984 assert( pOp
[1].opcode
==OP_IdxLT
|| pOp
[1].opcode
==OP_IdxGT
);
3985 assert( pOp
[1].p1
==pOp
[0].p1
);
3986 assert( pOp
[1].p2
==pOp
[0].p2
);
3987 assert( pOp
[1].p3
==pOp
[0].p3
);
3988 assert( pOp
[1].p4
.i
==pOp
[0].p4
.i
);
3992 assert( pOp
->p4type
==P4_INT32
);
3994 r
.pKeyInfo
= pC
->pKeyInfo
;
3995 r
.nField
= (u16
)nField
;
3997 /* The next line of code computes as follows, only faster:
3998 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3999 ** r.default_rc = -1;
4001 ** r.default_rc = +1;
4004 r
.default_rc
= ((1 & (oc
- OP_SeekLT
)) ? -1 : +1);
4005 assert( oc
!=OP_SeekGT
|| r
.default_rc
==-1 );
4006 assert( oc
!=OP_SeekLE
|| r
.default_rc
==-1 );
4007 assert( oc
!=OP_SeekGE
|| r
.default_rc
==+1 );
4008 assert( oc
!=OP_SeekLT
|| r
.default_rc
==+1 );
4010 r
.aMem
= &aMem
[pOp
->p3
];
4012 { int i
; for(i
=0; i
<r
.nField
; i
++) assert( memIsValid(&r
.aMem
[i
]) ); }
4015 rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, &r
, 0, 0, &res
);
4016 if( rc
!=SQLITE_OK
){
4017 goto abort_due_to_error
;
4019 if( eqOnly
&& r
.eqSeen
==0 ){
4021 goto seek_not_found
;
4024 pC
->deferredMoveto
= 0;
4025 pC
->cacheStatus
= CACHE_STALE
;
4027 sqlite3_search_count
++;
4029 if( oc
>=OP_SeekGE
){ assert( oc
==OP_SeekGE
|| oc
==OP_SeekGT
);
4030 if( res
<0 || (res
==0 && oc
==OP_SeekGT
) ){
4032 rc
= sqlite3BtreeNext(pC
->uc
.pCursor
, 0);
4033 if( rc
!=SQLITE_OK
){
4034 if( rc
==SQLITE_DONE
){
4038 goto abort_due_to_error
;
4045 assert( oc
==OP_SeekLT
|| oc
==OP_SeekLE
);
4046 if( res
>0 || (res
==0 && oc
==OP_SeekLT
) ){
4048 rc
= sqlite3BtreePrevious(pC
->uc
.pCursor
, 0);
4049 if( rc
!=SQLITE_OK
){
4050 if( rc
==SQLITE_DONE
){
4054 goto abort_due_to_error
;
4058 /* res might be negative because the table is empty. Check to
4059 ** see if this is the case.
4061 res
= sqlite3BtreeEof(pC
->uc
.pCursor
);
4065 assert( pOp
->p2
>0 );
4066 VdbeBranchTaken(res
!=0,2);
4070 assert( pOp
[1].opcode
==OP_IdxLT
|| pOp
[1].opcode
==OP_IdxGT
);
4071 pOp
++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4076 /* Opcode: SeekHit P1 P2 * * *
4077 ** Synopsis: seekHit=P2
4079 ** Set the seekHit flag on cursor P1 to the value in P2.
4080 ** The seekHit flag is used by the IfNoHope opcode.
4082 ** P1 must be a valid b-tree cursor. P2 must be a boolean value,
4087 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4088 pC
= p
->apCsr
[pOp
->p1
];
4090 assert( pOp
->p2
==0 || pOp
->p2
==1 );
4091 pC
->seekHit
= pOp
->p2
& 1;
4095 /* Opcode: Found P1 P2 P3 P4 *
4096 ** Synopsis: key=r[P3@P4]
4098 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4099 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4102 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4103 ** is a prefix of any entry in P1 then a jump is made to P2 and
4104 ** P1 is left pointing at the matching entry.
4106 ** This operation leaves the cursor in a state where it can be
4107 ** advanced in the forward direction. The Next instruction will work,
4108 ** but not the Prev instruction.
4110 ** See also: NotFound, NoConflict, NotExists. SeekGe
4112 /* Opcode: NotFound P1 P2 P3 P4 *
4113 ** Synopsis: key=r[P3@P4]
4115 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4116 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4119 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4120 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
4121 ** does contain an entry whose prefix matches the P3/P4 record then control
4122 ** falls through to the next instruction and P1 is left pointing at the
4125 ** This operation leaves the cursor in a state where it cannot be
4126 ** advanced in either direction. In other words, the Next and Prev
4127 ** opcodes do not work after this operation.
4129 ** See also: Found, NotExists, NoConflict, IfNoHope
4131 /* Opcode: IfNoHope P1 P2 P3 P4 *
4132 ** Synopsis: key=r[P3@P4]
4134 ** Register P3 is the first of P4 registers that form an unpacked
4137 ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then
4138 ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then
4139 ** check to see if there is any entry in P1 that matches the
4140 ** prefix identified by P3 and P4. If no entry matches the prefix,
4141 ** jump to P2. Otherwise fall through.
4143 ** This opcode behaves like OP_NotFound if the seekHit
4144 ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
4146 ** This opcode is used in IN clause processing for a multi-column key.
4147 ** If an IN clause is attached to an element of the key other than the
4148 ** left-most element, and if there are no matches on the most recent
4149 ** seek over the whole key, then it might be that one of the key element
4150 ** to the left is prohibiting a match, and hence there is "no hope" of
4151 ** any match regardless of how many IN clause elements are checked.
4152 ** In such a case, we abandon the IN clause search early, using this
4153 ** opcode. The opcode name comes from the fact that the
4154 ** jump is taken if there is "no hope" of achieving a match.
4156 ** See also: NotFound, SeekHit
4158 /* Opcode: NoConflict P1 P2 P3 P4 *
4159 ** Synopsis: key=r[P3@P4]
4161 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4162 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4165 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4166 ** contains any NULL value, jump immediately to P2. If all terms of the
4167 ** record are not-NULL then a check is done to determine if any row in the
4168 ** P1 index btree has a matching key prefix. If there are no matches, jump
4169 ** immediately to P2. If there is a match, fall through and leave the P1
4170 ** cursor pointing to the matching row.
4172 ** This opcode is similar to OP_NotFound with the exceptions that the
4173 ** branch is always taken if any part of the search key input is NULL.
4175 ** This operation leaves the cursor in a state where it cannot be
4176 ** advanced in either direction. In other words, the Next and Prev
4177 ** opcodes do not work after this operation.
4179 ** See also: NotFound, Found, NotExists
4181 case OP_IfNoHope
: { /* jump, in3 */
4183 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4184 pC
= p
->apCsr
[pOp
->p1
];
4186 if( pC
->seekHit
) break;
4187 /* Fall through into OP_NotFound */
4189 case OP_NoConflict
: /* jump, in3 */
4190 case OP_NotFound
: /* jump, in3 */
4191 case OP_Found
: { /* jump, in3 */
4197 UnpackedRecord
*pFree
;
4198 UnpackedRecord
*pIdxKey
;
4202 if( pOp
->opcode
!=OP_NoConflict
) sqlite3_found_count
++;
4205 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4206 assert( pOp
->p4type
==P4_INT32
);
4207 pC
= p
->apCsr
[pOp
->p1
];
4210 pC
->seekOp
= pOp
->opcode
;
4212 pIn3
= &aMem
[pOp
->p3
];
4213 assert( pC
->eCurType
==CURTYPE_BTREE
);
4214 assert( pC
->uc
.pCursor
!=0 );
4215 assert( pC
->isTable
==0 );
4217 r
.pKeyInfo
= pC
->pKeyInfo
;
4218 r
.nField
= (u16
)pOp
->p4
.i
;
4221 for(ii
=0; ii
<r
.nField
; ii
++){
4222 assert( memIsValid(&r
.aMem
[ii
]) );
4223 assert( (r
.aMem
[ii
].flags
& MEM_Zero
)==0 || r
.aMem
[ii
].n
==0 );
4224 if( ii
) REGISTER_TRACE(pOp
->p3
+ii
, &r
.aMem
[ii
]);
4230 assert( pIn3
->flags
& MEM_Blob
);
4231 rc
= ExpandBlob(pIn3
);
4232 assert( rc
==SQLITE_OK
|| rc
==SQLITE_NOMEM
);
4233 if( rc
) goto no_mem
;
4234 pFree
= pIdxKey
= sqlite3VdbeAllocUnpackedRecord(pC
->pKeyInfo
);
4235 if( pIdxKey
==0 ) goto no_mem
;
4236 sqlite3VdbeRecordUnpack(pC
->pKeyInfo
, pIn3
->n
, pIn3
->z
, pIdxKey
);
4238 pIdxKey
->default_rc
= 0;
4240 if( pOp
->opcode
==OP_NoConflict
){
4241 /* For the OP_NoConflict opcode, take the jump if any of the
4242 ** input fields are NULL, since any key with a NULL will not
4244 for(ii
=0; ii
<pIdxKey
->nField
; ii
++){
4245 if( pIdxKey
->aMem
[ii
].flags
& MEM_Null
){
4251 rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, pIdxKey
, 0, 0, &res
);
4252 if( pFree
) sqlite3DbFreeNN(db
, pFree
);
4253 if( rc
!=SQLITE_OK
){
4254 goto abort_due_to_error
;
4256 pC
->seekResult
= res
;
4257 alreadyExists
= (res
==0);
4258 pC
->nullRow
= 1-alreadyExists
;
4259 pC
->deferredMoveto
= 0;
4260 pC
->cacheStatus
= CACHE_STALE
;
4261 if( pOp
->opcode
==OP_Found
){
4262 VdbeBranchTaken(alreadyExists
!=0,2);
4263 if( alreadyExists
) goto jump_to_p2
;
4265 VdbeBranchTaken(takeJump
||alreadyExists
==0,2);
4266 if( takeJump
|| !alreadyExists
) goto jump_to_p2
;
4271 /* Opcode: SeekRowid P1 P2 P3 * *
4272 ** Synopsis: intkey=r[P3]
4274 ** P1 is the index of a cursor open on an SQL table btree (with integer
4275 ** keys). If register P3 does not contain an integer or if P1 does not
4276 ** contain a record with rowid P3 then jump immediately to P2.
4277 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4278 ** a record with rowid P3 then
4279 ** leave the cursor pointing at that record and fall through to the next
4282 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4283 ** the P3 register must be guaranteed to contain an integer value. With this
4284 ** opcode, register P3 might not contain an integer.
4286 ** The OP_NotFound opcode performs the same operation on index btrees
4287 ** (with arbitrary multi-value keys).
4289 ** This opcode leaves the cursor in a state where it cannot be advanced
4290 ** in either direction. In other words, the Next and Prev opcodes will
4291 ** not work following this opcode.
4293 ** See also: Found, NotFound, NoConflict, SeekRowid
4295 /* Opcode: NotExists P1 P2 P3 * *
4296 ** Synopsis: intkey=r[P3]
4298 ** P1 is the index of a cursor open on an SQL table btree (with integer
4299 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4300 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4301 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4302 ** leave the cursor pointing at that record and fall through to the next
4305 ** The OP_SeekRowid opcode performs the same operation but also allows the
4306 ** P3 register to contain a non-integer value, in which case the jump is
4307 ** always taken. This opcode requires that P3 always contain an integer.
4309 ** The OP_NotFound opcode performs the same operation on index btrees
4310 ** (with arbitrary multi-value keys).
4312 ** This opcode leaves the cursor in a state where it cannot be advanced
4313 ** in either direction. In other words, the Next and Prev opcodes will
4314 ** not work following this opcode.
4316 ** See also: Found, NotFound, NoConflict, SeekRowid
4318 case OP_SeekRowid
: { /* jump, in3 */
4324 pIn3
= &aMem
[pOp
->p3
];
4325 if( (pIn3
->flags
& MEM_Int
)==0 ){
4326 applyAffinity(pIn3
, SQLITE_AFF_NUMERIC
, encoding
);
4327 if( (pIn3
->flags
& MEM_Int
)==0 ) goto jump_to_p2
;
4329 /* Fall through into OP_NotExists */
4330 case OP_NotExists
: /* jump, in3 */
4331 pIn3
= &aMem
[pOp
->p3
];
4332 assert( pIn3
->flags
& MEM_Int
);
4333 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4334 pC
= p
->apCsr
[pOp
->p1
];
4337 pC
->seekOp
= OP_SeekRowid
;
4339 assert( pC
->isTable
);
4340 assert( pC
->eCurType
==CURTYPE_BTREE
);
4341 pCrsr
= pC
->uc
.pCursor
;
4345 rc
= sqlite3BtreeMovetoUnpacked(pCrsr
, 0, iKey
, 0, &res
);
4346 assert( rc
==SQLITE_OK
|| res
==0 );
4347 pC
->movetoTarget
= iKey
; /* Used by OP_Delete */
4349 pC
->cacheStatus
= CACHE_STALE
;
4350 pC
->deferredMoveto
= 0;
4351 VdbeBranchTaken(res
!=0,2);
4352 pC
->seekResult
= res
;
4354 assert( rc
==SQLITE_OK
);
4356 rc
= SQLITE_CORRUPT_BKPT
;
4361 if( rc
) goto abort_due_to_error
;
4365 /* Opcode: Sequence P1 P2 * * *
4366 ** Synopsis: r[P2]=cursor[P1].ctr++
4368 ** Find the next available sequence number for cursor P1.
4369 ** Write the sequence number into register P2.
4370 ** The sequence number on the cursor is incremented after this
4373 case OP_Sequence
: { /* out2 */
4374 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4375 assert( p
->apCsr
[pOp
->p1
]!=0 );
4376 assert( p
->apCsr
[pOp
->p1
]->eCurType
!=CURTYPE_VTAB
);
4377 pOut
= out2Prerelease(p
, pOp
);
4378 pOut
->u
.i
= p
->apCsr
[pOp
->p1
]->seqCount
++;
4383 /* Opcode: NewRowid P1 P2 P3 * *
4384 ** Synopsis: r[P2]=rowid
4386 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4387 ** The record number is not previously used as a key in the database
4388 ** table that cursor P1 points to. The new record number is written
4389 ** written to register P2.
4391 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4392 ** the largest previously generated record number. No new record numbers are
4393 ** allowed to be less than this value. When this value reaches its maximum,
4394 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4395 ** generated record number. This P3 mechanism is used to help implement the
4396 ** AUTOINCREMENT feature.
4398 case OP_NewRowid
: { /* out2 */
4399 i64 v
; /* The new rowid */
4400 VdbeCursor
*pC
; /* Cursor of table to get the new rowid */
4401 int res
; /* Result of an sqlite3BtreeLast() */
4402 int cnt
; /* Counter to limit the number of searches */
4403 Mem
*pMem
; /* Register holding largest rowid for AUTOINCREMENT */
4404 VdbeFrame
*pFrame
; /* Root frame of VDBE */
4408 pOut
= out2Prerelease(p
, pOp
);
4409 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4410 pC
= p
->apCsr
[pOp
->p1
];
4412 assert( pC
->isTable
);
4413 assert( pC
->eCurType
==CURTYPE_BTREE
);
4414 assert( pC
->uc
.pCursor
!=0 );
4416 /* The next rowid or record number (different terms for the same
4417 ** thing) is obtained in a two-step algorithm.
4419 ** First we attempt to find the largest existing rowid and add one
4420 ** to that. But if the largest existing rowid is already the maximum
4421 ** positive integer, we have to fall through to the second
4422 ** probabilistic algorithm
4424 ** The second algorithm is to select a rowid at random and see if
4425 ** it already exists in the table. If it does not exist, we have
4426 ** succeeded. If the random rowid does exist, we select a new one
4427 ** and try again, up to 100 times.
4429 assert( pC
->isTable
);
4431 #ifdef SQLITE_32BIT_ROWID
4432 # define MAX_ROWID 0x7fffffff
4434 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4435 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4436 ** to provide the constant while making all compilers happy.
4438 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4441 if( !pC
->useRandomRowid
){
4442 rc
= sqlite3BtreeLast(pC
->uc
.pCursor
, &res
);
4443 if( rc
!=SQLITE_OK
){
4444 goto abort_due_to_error
;
4447 v
= 1; /* IMP: R-61914-48074 */
4449 assert( sqlite3BtreeCursorIsValid(pC
->uc
.pCursor
) );
4450 v
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4452 pC
->useRandomRowid
= 1;
4454 v
++; /* IMP: R-29538-34987 */
4459 #ifndef SQLITE_OMIT_AUTOINCREMENT
4461 /* Assert that P3 is a valid memory cell. */
4462 assert( pOp
->p3
>0 );
4464 for(pFrame
=p
->pFrame
; pFrame
->pParent
; pFrame
=pFrame
->pParent
);
4465 /* Assert that P3 is a valid memory cell. */
4466 assert( pOp
->p3
<=pFrame
->nMem
);
4467 pMem
= &pFrame
->aMem
[pOp
->p3
];
4469 /* Assert that P3 is a valid memory cell. */
4470 assert( pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
4471 pMem
= &aMem
[pOp
->p3
];
4472 memAboutToChange(p
, pMem
);
4474 assert( memIsValid(pMem
) );
4476 REGISTER_TRACE(pOp
->p3
, pMem
);
4477 sqlite3VdbeMemIntegerify(pMem
);
4478 assert( (pMem
->flags
& MEM_Int
)!=0 ); /* mem(P3) holds an integer */
4479 if( pMem
->u
.i
==MAX_ROWID
|| pC
->useRandomRowid
){
4480 rc
= SQLITE_FULL
; /* IMP: R-17817-00630 */
4481 goto abort_due_to_error
;
4483 if( v
<pMem
->u
.i
+1 ){
4489 if( pC
->useRandomRowid
){
4490 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4491 ** largest possible integer (9223372036854775807) then the database
4492 ** engine starts picking positive candidate ROWIDs at random until
4493 ** it finds one that is not previously used. */
4494 assert( pOp
->p3
==0 ); /* We cannot be in random rowid mode if this is
4495 ** an AUTOINCREMENT table. */
4498 sqlite3_randomness(sizeof(v
), &v
);
4499 v
&= (MAX_ROWID
>>1); v
++; /* Ensure that v is greater than zero */
4500 }while( ((rc
= sqlite3BtreeMovetoUnpacked(pC
->uc
.pCursor
, 0, (u64
)v
,
4501 0, &res
))==SQLITE_OK
)
4504 if( rc
) goto abort_due_to_error
;
4506 rc
= SQLITE_FULL
; /* IMP: R-38219-53002 */
4507 goto abort_due_to_error
;
4509 assert( v
>0 ); /* EV: R-40812-03570 */
4511 pC
->deferredMoveto
= 0;
4512 pC
->cacheStatus
= CACHE_STALE
;
4518 /* Opcode: Insert P1 P2 P3 P4 P5
4519 ** Synopsis: intkey=r[P3] data=r[P2]
4521 ** Write an entry into the table of cursor P1. A new entry is
4522 ** created if it doesn't already exist or the data for an existing
4523 ** entry is overwritten. The data is the value MEM_Blob stored in register
4524 ** number P2. The key is stored in register P3. The key must
4527 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4528 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
4529 ** then rowid is stored for subsequent return by the
4530 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4532 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
4533 ** run faster by avoiding an unnecessary seek on cursor P1. However,
4534 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
4535 ** seeks on the cursor or if the most recent seek used a key equal to P3.
4537 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4538 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
4539 ** is part of an INSERT operation. The difference is only important to
4542 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
4543 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
4544 ** following a successful insert.
4546 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4547 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4548 ** and register P2 becomes ephemeral. If the cursor is changed, the
4549 ** value of register P2 will then change. Make sure this does not
4550 ** cause any problems.)
4552 ** This instruction only works on tables. The equivalent instruction
4553 ** for indices is OP_IdxInsert.
4555 /* Opcode: InsertInt P1 P2 P3 P4 P5
4556 ** Synopsis: intkey=P3 data=r[P2]
4558 ** This works exactly like OP_Insert except that the key is the
4559 ** integer value P3, not the value of the integer stored in register P3.
4562 case OP_InsertInt
: {
4563 Mem
*pData
; /* MEM cell holding data for the record to be inserted */
4564 Mem
*pKey
; /* MEM cell holding key for the record */
4565 VdbeCursor
*pC
; /* Cursor to table into which insert is written */
4566 int seekResult
; /* Result of prior seek or 0 if no USESEEKRESULT flag */
4567 const char *zDb
; /* database name - used by the update hook */
4568 Table
*pTab
; /* Table structure - used by update and pre-update hooks */
4569 BtreePayload x
; /* Payload to be inserted */
4571 pData
= &aMem
[pOp
->p2
];
4572 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4573 assert( memIsValid(pData
) );
4574 pC
= p
->apCsr
[pOp
->p1
];
4576 assert( pC
->eCurType
==CURTYPE_BTREE
);
4577 assert( pC
->uc
.pCursor
!=0 );
4578 assert( (pOp
->p5
& OPFLAG_ISNOOP
) || pC
->isTable
);
4579 assert( pOp
->p4type
==P4_TABLE
|| pOp
->p4type
>=P4_STATIC
);
4580 REGISTER_TRACE(pOp
->p2
, pData
);
4581 sqlite3VdbeIncrWriteCounter(p
, pC
);
4583 if( pOp
->opcode
==OP_Insert
){
4584 pKey
= &aMem
[pOp
->p3
];
4585 assert( pKey
->flags
& MEM_Int
);
4586 assert( memIsValid(pKey
) );
4587 REGISTER_TRACE(pOp
->p3
, pKey
);
4590 assert( pOp
->opcode
==OP_InsertInt
);
4594 if( pOp
->p4type
==P4_TABLE
&& HAS_UPDATE_HOOK(db
) ){
4595 assert( pC
->iDb
>=0 );
4596 zDb
= db
->aDb
[pC
->iDb
].zDbSName
;
4597 pTab
= pOp
->p4
.pTab
;
4598 assert( (pOp
->p5
& OPFLAG_ISNOOP
) || HasRowid(pTab
) );
4601 zDb
= 0; /* Not needed. Silence a compiler warning. */
4604 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4605 /* Invoke the pre-update hook, if any */
4607 if( db
->xPreUpdateCallback
&& !(pOp
->p5
& OPFLAG_ISUPDATE
) ){
4608 sqlite3VdbePreUpdateHook(p
, pC
, SQLITE_INSERT
, zDb
, pTab
, x
.nKey
,pOp
->p2
);
4610 if( db
->xUpdateCallback
==0 || pTab
->aCol
==0 ){
4611 /* Prevent post-update hook from running in cases when it should not */
4615 if( pOp
->p5
& OPFLAG_ISNOOP
) break;
4618 if( pOp
->p5
& OPFLAG_NCHANGE
) p
->nChange
++;
4619 if( pOp
->p5
& OPFLAG_LASTROWID
) db
->lastRowid
= x
.nKey
;
4620 assert( pData
->flags
& (MEM_Blob
|MEM_Str
) );
4623 seekResult
= ((pOp
->p5
& OPFLAG_USESEEKRESULT
) ? pC
->seekResult
: 0);
4624 if( pData
->flags
& MEM_Zero
){
4625 x
.nZero
= pData
->u
.nZero
;
4630 rc
= sqlite3BtreeInsert(pC
->uc
.pCursor
, &x
,
4631 (pOp
->p5
& (OPFLAG_APPEND
|OPFLAG_SAVEPOSITION
)), seekResult
4633 pC
->deferredMoveto
= 0;
4634 pC
->cacheStatus
= CACHE_STALE
;
4636 /* Invoke the update-hook if required. */
4637 if( rc
) goto abort_due_to_error
;
4639 assert( db
->xUpdateCallback
!=0 );
4640 assert( pTab
->aCol
!=0 );
4641 db
->xUpdateCallback(db
->pUpdateArg
,
4642 (pOp
->p5
& OPFLAG_ISUPDATE
) ? SQLITE_UPDATE
: SQLITE_INSERT
,
4643 zDb
, pTab
->zName
, x
.nKey
);
4648 /* Opcode: Delete P1 P2 P3 P4 P5
4650 ** Delete the record at which the P1 cursor is currently pointing.
4652 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
4653 ** the cursor will be left pointing at either the next or the previous
4654 ** record in the table. If it is left pointing at the next record, then
4655 ** the next Next instruction will be a no-op. As a result, in this case
4656 ** it is ok to delete a record from within a Next loop. If
4657 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
4658 ** left in an undefined state.
4660 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
4661 ** delete one of several associated with deleting a table row and all its
4662 ** associated index entries. Exactly one of those deletes is the "primary"
4663 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
4664 ** marked with the AUXDELETE flag.
4666 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
4667 ** change count is incremented (otherwise not).
4669 ** P1 must not be pseudo-table. It has to be a real table with
4672 ** If P4 is not NULL then it points to a Table object. In this case either
4673 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
4674 ** have been positioned using OP_NotFound prior to invoking this opcode in
4675 ** this case. Specifically, if one is configured, the pre-update hook is
4676 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
4677 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
4679 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
4680 ** of the memory cell that contains the value that the rowid of the row will
4681 ** be set to by the update.
4690 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4691 pC
= p
->apCsr
[pOp
->p1
];
4693 assert( pC
->eCurType
==CURTYPE_BTREE
);
4694 assert( pC
->uc
.pCursor
!=0 );
4695 assert( pC
->deferredMoveto
==0 );
4696 sqlite3VdbeIncrWriteCounter(p
, pC
);
4699 if( pOp
->p4type
==P4_TABLE
&& HasRowid(pOp
->p4
.pTab
) && pOp
->p5
==0 ){
4700 /* If p5 is zero, the seek operation that positioned the cursor prior to
4701 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
4702 ** the row that is being deleted */
4703 i64 iKey
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4704 assert( pC
->movetoTarget
==iKey
);
4708 /* If the update-hook or pre-update-hook will be invoked, set zDb to
4709 ** the name of the db to pass as to it. Also set local pTab to a copy
4710 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
4711 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
4712 ** VdbeCursor.movetoTarget to the current rowid. */
4713 if( pOp
->p4type
==P4_TABLE
&& HAS_UPDATE_HOOK(db
) ){
4714 assert( pC
->iDb
>=0 );
4715 assert( pOp
->p4
.pTab
!=0 );
4716 zDb
= db
->aDb
[pC
->iDb
].zDbSName
;
4717 pTab
= pOp
->p4
.pTab
;
4718 if( (pOp
->p5
& OPFLAG_SAVEPOSITION
)!=0 && pC
->isTable
){
4719 pC
->movetoTarget
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4722 zDb
= 0; /* Not needed. Silence a compiler warning. */
4723 pTab
= 0; /* Not needed. Silence a compiler warning. */
4726 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4727 /* Invoke the pre-update-hook if required. */
4728 if( db
->xPreUpdateCallback
&& pOp
->p4
.pTab
){
4729 assert( !(opflags
& OPFLAG_ISUPDATE
)
4730 || HasRowid(pTab
)==0
4731 || (aMem
[pOp
->p3
].flags
& MEM_Int
)
4733 sqlite3VdbePreUpdateHook(p
, pC
,
4734 (opflags
& OPFLAG_ISUPDATE
) ? SQLITE_UPDATE
: SQLITE_DELETE
,
4735 zDb
, pTab
, pC
->movetoTarget
,
4739 if( opflags
& OPFLAG_ISNOOP
) break;
4742 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
4743 assert( (pOp
->p5
& ~(OPFLAG_SAVEPOSITION
|OPFLAG_AUXDELETE
))==0 );
4744 assert( OPFLAG_SAVEPOSITION
==BTREE_SAVEPOSITION
);
4745 assert( OPFLAG_AUXDELETE
==BTREE_AUXDELETE
);
4749 if( pC
->isEphemeral
==0
4750 && (pOp
->p5
& OPFLAG_AUXDELETE
)==0
4751 && (pC
->wrFlag
& OPFLAG_FORDELETE
)==0
4755 if( pOp
->p2
& OPFLAG_NCHANGE
){
4761 rc
= sqlite3BtreeDelete(pC
->uc
.pCursor
, pOp
->p5
);
4762 pC
->cacheStatus
= CACHE_STALE
;
4764 if( rc
) goto abort_due_to_error
;
4766 /* Invoke the update-hook if required. */
4767 if( opflags
& OPFLAG_NCHANGE
){
4769 if( db
->xUpdateCallback
&& HasRowid(pTab
) ){
4770 db
->xUpdateCallback(db
->pUpdateArg
, SQLITE_DELETE
, zDb
, pTab
->zName
,
4772 assert( pC
->iDb
>=0 );
4778 /* Opcode: ResetCount * * * * *
4780 ** The value of the change counter is copied to the database handle
4781 ** change counter (returned by subsequent calls to sqlite3_changes()).
4782 ** Then the VMs internal change counter resets to 0.
4783 ** This is used by trigger programs.
4785 case OP_ResetCount
: {
4786 sqlite3VdbeSetChanges(db
, p
->nChange
);
4791 /* Opcode: SorterCompare P1 P2 P3 P4
4792 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4794 ** P1 is a sorter cursor. This instruction compares a prefix of the
4795 ** record blob in register P3 against a prefix of the entry that
4796 ** the sorter cursor currently points to. Only the first P4 fields
4797 ** of r[P3] and the sorter record are compared.
4799 ** If either P3 or the sorter contains a NULL in one of their significant
4800 ** fields (not counting the P4 fields at the end which are ignored) then
4801 ** the comparison is assumed to be equal.
4803 ** Fall through to next instruction if the two records compare equal to
4804 ** each other. Jump to P2 if they are different.
4806 case OP_SorterCompare
: {
4811 pC
= p
->apCsr
[pOp
->p1
];
4812 assert( isSorter(pC
) );
4813 assert( pOp
->p4type
==P4_INT32
);
4814 pIn3
= &aMem
[pOp
->p3
];
4815 nKeyCol
= pOp
->p4
.i
;
4817 rc
= sqlite3VdbeSorterCompare(pC
, pIn3
, nKeyCol
, &res
);
4818 VdbeBranchTaken(res
!=0,2);
4819 if( rc
) goto abort_due_to_error
;
4820 if( res
) goto jump_to_p2
;
4824 /* Opcode: SorterData P1 P2 P3 * *
4825 ** Synopsis: r[P2]=data
4827 ** Write into register P2 the current sorter data for sorter cursor P1.
4828 ** Then clear the column header cache on cursor P3.
4830 ** This opcode is normally use to move a record out of the sorter and into
4831 ** a register that is the source for a pseudo-table cursor created using
4832 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4833 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4834 ** us from having to issue a separate NullRow instruction to clear that cache.
4836 case OP_SorterData
: {
4839 pOut
= &aMem
[pOp
->p2
];
4840 pC
= p
->apCsr
[pOp
->p1
];
4841 assert( isSorter(pC
) );
4842 rc
= sqlite3VdbeSorterRowkey(pC
, pOut
);
4843 assert( rc
!=SQLITE_OK
|| (pOut
->flags
& MEM_Blob
) );
4844 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4845 if( rc
) goto abort_due_to_error
;
4846 p
->apCsr
[pOp
->p3
]->cacheStatus
= CACHE_STALE
;
4850 /* Opcode: RowData P1 P2 P3 * *
4851 ** Synopsis: r[P2]=data
4853 ** Write into register P2 the complete row content for the row at
4854 ** which cursor P1 is currently pointing.
4855 ** There is no interpretation of the data.
4856 ** It is just copied onto the P2 register exactly as
4857 ** it is found in the database file.
4859 ** If cursor P1 is an index, then the content is the key of the row.
4860 ** If cursor P2 is a table, then the content extracted is the data.
4862 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4863 ** of a real table, not a pseudo-table.
4865 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
4866 ** into the database page. That means that the content of the output
4867 ** register will be invalidated as soon as the cursor moves - including
4868 ** moves caused by other cursors that "save" the current cursors
4869 ** position in order that they can write to the same table. If P3==0
4870 ** then a copy of the data is made into memory. P3!=0 is faster, but
4873 ** If P3!=0 then the content of the P2 register is unsuitable for use
4874 ** in OP_Result and any OP_Result will invalidate the P2 register content.
4875 ** The P2 register content is invalidated by opcodes like OP_Function or
4876 ** by any use of another cursor pointing to the same table.
4883 pOut
= out2Prerelease(p
, pOp
);
4885 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4886 pC
= p
->apCsr
[pOp
->p1
];
4888 assert( pC
->eCurType
==CURTYPE_BTREE
);
4889 assert( isSorter(pC
)==0 );
4890 assert( pC
->nullRow
==0 );
4891 assert( pC
->uc
.pCursor
!=0 );
4892 pCrsr
= pC
->uc
.pCursor
;
4894 /* The OP_RowData opcodes always follow OP_NotExists or
4895 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
4896 ** that might invalidate the cursor.
4897 ** If this where not the case, on of the following assert()s
4898 ** would fail. Should this ever change (because of changes in the code
4899 ** generator) then the fix would be to insert a call to
4900 ** sqlite3VdbeCursorMoveto().
4902 assert( pC
->deferredMoveto
==0 );
4903 assert( sqlite3BtreeCursorIsValid(pCrsr
) );
4904 #if 0 /* Not required due to the previous to assert() statements */
4905 rc
= sqlite3VdbeCursorMoveto(pC
);
4906 if( rc
!=SQLITE_OK
) goto abort_due_to_error
;
4909 n
= sqlite3BtreePayloadSize(pCrsr
);
4910 if( n
>(u32
)db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
4914 rc
= sqlite3VdbeMemFromBtree(pCrsr
, 0, n
, pOut
);
4915 if( rc
) goto abort_due_to_error
;
4916 if( !pOp
->p3
) Deephemeralize(pOut
);
4917 UPDATE_MAX_BLOBSIZE(pOut
);
4918 REGISTER_TRACE(pOp
->p2
, pOut
);
4922 /* Opcode: Rowid P1 P2 * * *
4923 ** Synopsis: r[P2]=rowid
4925 ** Store in register P2 an integer which is the key of the table entry that
4926 ** P1 is currently point to.
4928 ** P1 can be either an ordinary table or a virtual table. There used to
4929 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4930 ** one opcode now works for both table types.
4932 case OP_Rowid
: { /* out2 */
4935 sqlite3_vtab
*pVtab
;
4936 const sqlite3_module
*pModule
;
4938 pOut
= out2Prerelease(p
, pOp
);
4939 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4940 pC
= p
->apCsr
[pOp
->p1
];
4942 assert( pC
->eCurType
!=CURTYPE_PSEUDO
|| pC
->nullRow
);
4944 pOut
->flags
= MEM_Null
;
4946 }else if( pC
->deferredMoveto
){
4947 v
= pC
->movetoTarget
;
4948 #ifndef SQLITE_OMIT_VIRTUALTABLE
4949 }else if( pC
->eCurType
==CURTYPE_VTAB
){
4950 assert( pC
->uc
.pVCur
!=0 );
4951 pVtab
= pC
->uc
.pVCur
->pVtab
;
4952 pModule
= pVtab
->pModule
;
4953 assert( pModule
->xRowid
);
4954 rc
= pModule
->xRowid(pC
->uc
.pVCur
, &v
);
4955 sqlite3VtabImportErrmsg(p
, pVtab
);
4956 if( rc
) goto abort_due_to_error
;
4957 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4959 assert( pC
->eCurType
==CURTYPE_BTREE
);
4960 assert( pC
->uc
.pCursor
!=0 );
4961 rc
= sqlite3VdbeCursorRestore(pC
);
4962 if( rc
) goto abort_due_to_error
;
4964 pOut
->flags
= MEM_Null
;
4967 v
= sqlite3BtreeIntegerKey(pC
->uc
.pCursor
);
4973 /* Opcode: NullRow P1 * * * *
4975 ** Move the cursor P1 to a null row. Any OP_Column operations
4976 ** that occur while the cursor is on the null row will always
4982 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
4983 pC
= p
->apCsr
[pOp
->p1
];
4986 pC
->cacheStatus
= CACHE_STALE
;
4987 if( pC
->eCurType
==CURTYPE_BTREE
){
4988 assert( pC
->uc
.pCursor
!=0 );
4989 sqlite3BtreeClearCursor(pC
->uc
.pCursor
);
4992 if( pC
->seekOp
==0 ) pC
->seekOp
= OP_NullRow
;
4997 /* Opcode: SeekEnd P1 * * * *
4999 ** Position cursor P1 at the end of the btree for the purpose of
5000 ** appending a new entry onto the btree.
5002 ** It is assumed that the cursor is used only for appending and so
5003 ** if the cursor is valid, then the cursor must already be pointing
5004 ** at the end of the btree and so no changes are made to
5007 /* Opcode: Last P1 P2 * * *
5009 ** The next use of the Rowid or Column or Prev instruction for P1
5010 ** will refer to the last entry in the database table or index.
5011 ** If the table or index is empty and P2>0, then jump immediately to P2.
5012 ** If P2 is 0 or if the table or index is not empty, fall through
5013 ** to the following instruction.
5015 ** This opcode leaves the cursor configured to move in reverse order,
5016 ** from the end toward the beginning. In other words, the cursor is
5017 ** configured to use Prev, not Next.
5020 case OP_Last
: { /* jump */
5025 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5026 pC
= p
->apCsr
[pOp
->p1
];
5028 assert( pC
->eCurType
==CURTYPE_BTREE
);
5029 pCrsr
= pC
->uc
.pCursor
;
5033 pC
->seekOp
= pOp
->opcode
;
5035 if( pOp
->opcode
==OP_SeekEnd
){
5036 assert( pOp
->p2
==0 );
5037 pC
->seekResult
= -1;
5038 if( sqlite3BtreeCursorIsValidNN(pCrsr
) ){
5042 rc
= sqlite3BtreeLast(pCrsr
, &res
);
5043 pC
->nullRow
= (u8
)res
;
5044 pC
->deferredMoveto
= 0;
5045 pC
->cacheStatus
= CACHE_STALE
;
5046 if( rc
) goto abort_due_to_error
;
5048 VdbeBranchTaken(res
!=0,2);
5049 if( res
) goto jump_to_p2
;
5054 /* Opcode: IfSmaller P1 P2 P3 * *
5056 ** Estimate the number of rows in the table P1. Jump to P2 if that
5057 ** estimate is less than approximately 2**(0.1*P3).
5059 case OP_IfSmaller
: { /* jump */
5065 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5066 pC
= p
->apCsr
[pOp
->p1
];
5068 pCrsr
= pC
->uc
.pCursor
;
5070 rc
= sqlite3BtreeFirst(pCrsr
, &res
);
5071 if( rc
) goto abort_due_to_error
;
5073 sz
= sqlite3BtreeRowCountEst(pCrsr
);
5074 if( ALWAYS(sz
>=0) && sqlite3LogEst((u64
)sz
)<pOp
->p3
) res
= 1;
5076 VdbeBranchTaken(res
!=0,2);
5077 if( res
) goto jump_to_p2
;
5082 /* Opcode: SorterSort P1 P2 * * *
5084 ** After all records have been inserted into the Sorter object
5085 ** identified by P1, invoke this opcode to actually do the sorting.
5086 ** Jump to P2 if there are no records to be sorted.
5088 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
5089 ** for Sorter objects.
5091 /* Opcode: Sort P1 P2 * * *
5093 ** This opcode does exactly the same thing as OP_Rewind except that
5094 ** it increments an undocumented global variable used for testing.
5096 ** Sorting is accomplished by writing records into a sorting index,
5097 ** then rewinding that index and playing it back from beginning to
5098 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
5099 ** rewinding so that the global variable will be incremented and
5100 ** regression tests can determine whether or not the optimizer is
5101 ** correctly optimizing out sorts.
5103 case OP_SorterSort
: /* jump */
5104 case OP_Sort
: { /* jump */
5106 sqlite3_sort_count
++;
5107 sqlite3_search_count
--;
5109 p
->aCounter
[SQLITE_STMTSTATUS_SORT
]++;
5110 /* Fall through into OP_Rewind */
5112 /* Opcode: Rewind P1 P2 * * P5
5114 ** The next use of the Rowid or Column or Next instruction for P1
5115 ** will refer to the first entry in the database table or index.
5116 ** If the table or index is empty, jump immediately to P2.
5117 ** If the table or index is not empty, fall through to the following
5120 ** If P5 is non-zero and the table is not empty, then the "skip-next"
5121 ** flag is set on the cursor so that the next OP_Next instruction
5122 ** executed on it is a no-op.
5124 ** This opcode leaves the cursor configured to move in forward order,
5125 ** from the beginning toward the end. In other words, the cursor is
5126 ** configured to use Next, not Prev.
5128 case OP_Rewind
: { /* jump */
5133 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5134 pC
= p
->apCsr
[pOp
->p1
];
5136 assert( isSorter(pC
)==(pOp
->opcode
==OP_SorterSort
) );
5139 pC
->seekOp
= OP_Rewind
;
5142 rc
= sqlite3VdbeSorterRewind(pC
, &res
);
5144 assert( pC
->eCurType
==CURTYPE_BTREE
);
5145 pCrsr
= pC
->uc
.pCursor
;
5147 rc
= sqlite3BtreeFirst(pCrsr
, &res
);
5148 #ifndef SQLITE_OMIT_WINDOWFUNC
5149 if( pOp
->p5
) sqlite3BtreeSkipNext(pCrsr
);
5151 pC
->deferredMoveto
= 0;
5152 pC
->cacheStatus
= CACHE_STALE
;
5154 if( rc
) goto abort_due_to_error
;
5155 pC
->nullRow
= (u8
)res
;
5156 assert( pOp
->p2
>0 && pOp
->p2
<p
->nOp
);
5157 VdbeBranchTaken(res
!=0,2);
5158 if( res
) goto jump_to_p2
;
5162 /* Opcode: Next P1 P2 P3 P4 P5
5164 ** Advance cursor P1 so that it points to the next key/data pair in its
5165 ** table or index. If there are no more key/value pairs then fall through
5166 ** to the following instruction. But if the cursor advance was successful,
5167 ** jump immediately to P2.
5169 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5170 ** OP_Rewind opcode used to position the cursor. Next is not allowed
5171 ** to follow SeekLT, SeekLE, or OP_Last.
5173 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
5174 ** been opened prior to this opcode or the program will segfault.
5176 ** The P3 value is a hint to the btree implementation. If P3==1, that
5177 ** means P1 is an SQL index and that this instruction could have been
5178 ** omitted if that index had been unique. P3 is usually 0. P3 is
5179 ** always either 0 or 1.
5181 ** P4 is always of type P4_ADVANCE. The function pointer points to
5182 ** sqlite3BtreeNext().
5184 ** If P5 is positive and the jump is taken, then event counter
5185 ** number P5-1 in the prepared statement is incremented.
5189 /* Opcode: Prev P1 P2 P3 P4 P5
5191 ** Back up cursor P1 so that it points to the previous key/data pair in its
5192 ** table or index. If there is no previous key/value pairs then fall through
5193 ** to the following instruction. But if the cursor backup was successful,
5194 ** jump immediately to P2.
5197 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5198 ** OP_Last opcode used to position the cursor. Prev is not allowed
5199 ** to follow SeekGT, SeekGE, or OP_Rewind.
5201 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
5202 ** not open then the behavior is undefined.
5204 ** The P3 value is a hint to the btree implementation. If P3==1, that
5205 ** means P1 is an SQL index and that this instruction could have been
5206 ** omitted if that index had been unique. P3 is usually 0. P3 is
5207 ** always either 0 or 1.
5209 ** P4 is always of type P4_ADVANCE. The function pointer points to
5210 ** sqlite3BtreePrevious().
5212 ** If P5 is positive and the jump is taken, then event counter
5213 ** number P5-1 in the prepared statement is incremented.
5215 /* Opcode: SorterNext P1 P2 * * P5
5217 ** This opcode works just like OP_Next except that P1 must be a
5218 ** sorter object for which the OP_SorterSort opcode has been
5219 ** invoked. This opcode advances the cursor to the next sorted
5220 ** record, or jumps to P2 if there are no more sorted records.
5222 case OP_SorterNext
: { /* jump */
5225 pC
= p
->apCsr
[pOp
->p1
];
5226 assert( isSorter(pC
) );
5227 rc
= sqlite3VdbeSorterNext(db
, pC
);
5229 case OP_Prev
: /* jump */
5230 case OP_Next
: /* jump */
5231 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5232 assert( pOp
->p5
<ArraySize(p
->aCounter
) );
5233 pC
= p
->apCsr
[pOp
->p1
];
5235 assert( pC
->deferredMoveto
==0 );
5236 assert( pC
->eCurType
==CURTYPE_BTREE
);
5237 assert( pOp
->opcode
!=OP_Next
|| pOp
->p4
.xAdvance
==sqlite3BtreeNext
);
5238 assert( pOp
->opcode
!=OP_Prev
|| pOp
->p4
.xAdvance
==sqlite3BtreePrevious
);
5240 /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
5241 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5242 assert( pOp
->opcode
!=OP_Next
5243 || pC
->seekOp
==OP_SeekGT
|| pC
->seekOp
==OP_SeekGE
5244 || pC
->seekOp
==OP_Rewind
|| pC
->seekOp
==OP_Found
5245 || pC
->seekOp
==OP_NullRow
);
5246 assert( pOp
->opcode
!=OP_Prev
5247 || pC
->seekOp
==OP_SeekLT
|| pC
->seekOp
==OP_SeekLE
5248 || pC
->seekOp
==OP_Last
5249 || pC
->seekOp
==OP_NullRow
);
5251 rc
= pOp
->p4
.xAdvance(pC
->uc
.pCursor
, pOp
->p3
);
5253 pC
->cacheStatus
= CACHE_STALE
;
5254 VdbeBranchTaken(rc
==SQLITE_OK
,2);
5255 if( rc
==SQLITE_OK
){
5257 p
->aCounter
[pOp
->p5
]++;
5259 sqlite3_search_count
++;
5261 goto jump_to_p2_and_check_for_interrupt
;
5263 if( rc
!=SQLITE_DONE
) goto abort_due_to_error
;
5266 goto check_for_interrupt
;
5269 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5270 ** Synopsis: key=r[P2]
5272 ** Register P2 holds an SQL index key made using the
5273 ** MakeRecord instructions. This opcode writes that key
5274 ** into the index P1. Data for the entry is nil.
5276 ** If P4 is not zero, then it is the number of values in the unpacked
5277 ** key of reg(P2). In that case, P3 is the index of the first register
5278 ** for the unpacked key. The availability of the unpacked key can sometimes
5279 ** be an optimization.
5281 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5282 ** that this insert is likely to be an append.
5284 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5285 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
5286 ** then the change counter is unchanged.
5288 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5289 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5290 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5291 ** seeks on the cursor or if the most recent seek used a key equivalent
5294 ** This instruction only works for indices. The equivalent instruction
5295 ** for tables is OP_Insert.
5297 /* Opcode: SorterInsert P1 P2 * * *
5298 ** Synopsis: key=r[P2]
5300 ** Register P2 holds an SQL index key made using the
5301 ** MakeRecord instructions. This opcode writes that key
5302 ** into the sorter P1. Data for the entry is nil.
5304 case OP_SorterInsert
: /* in2 */
5305 case OP_IdxInsert
: { /* in2 */
5309 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5310 pC
= p
->apCsr
[pOp
->p1
];
5311 sqlite3VdbeIncrWriteCounter(p
, pC
);
5313 assert( isSorter(pC
)==(pOp
->opcode
==OP_SorterInsert
) );
5314 pIn2
= &aMem
[pOp
->p2
];
5315 assert( pIn2
->flags
& MEM_Blob
);
5316 if( pOp
->p5
& OPFLAG_NCHANGE
) p
->nChange
++;
5317 assert( pC
->eCurType
==CURTYPE_BTREE
|| pOp
->opcode
==OP_SorterInsert
);
5318 assert( pC
->isTable
==0 );
5319 rc
= ExpandBlob(pIn2
);
5320 if( rc
) goto abort_due_to_error
;
5321 if( pOp
->opcode
==OP_SorterInsert
){
5322 rc
= sqlite3VdbeSorterWrite(pC
, pIn2
);
5326 x
.aMem
= aMem
+ pOp
->p3
;
5327 x
.nMem
= (u16
)pOp
->p4
.i
;
5328 rc
= sqlite3BtreeInsert(pC
->uc
.pCursor
, &x
,
5329 (pOp
->p5
& (OPFLAG_APPEND
|OPFLAG_SAVEPOSITION
)),
5330 ((pOp
->p5
& OPFLAG_USESEEKRESULT
) ? pC
->seekResult
: 0)
5332 assert( pC
->deferredMoveto
==0 );
5333 pC
->cacheStatus
= CACHE_STALE
;
5335 if( rc
) goto abort_due_to_error
;
5339 /* Opcode: IdxDelete P1 P2 P3 * *
5340 ** Synopsis: key=r[P2@P3]
5342 ** The content of P3 registers starting at register P2 form
5343 ** an unpacked index key. This opcode removes that entry from the
5344 ** index opened by cursor P1.
5346 case OP_IdxDelete
: {
5352 assert( pOp
->p3
>0 );
5353 assert( pOp
->p2
>0 && pOp
->p2
+pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
)+1 );
5354 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5355 pC
= p
->apCsr
[pOp
->p1
];
5357 assert( pC
->eCurType
==CURTYPE_BTREE
);
5358 sqlite3VdbeIncrWriteCounter(p
, pC
);
5359 pCrsr
= pC
->uc
.pCursor
;
5361 assert( pOp
->p5
==0 );
5362 r
.pKeyInfo
= pC
->pKeyInfo
;
5363 r
.nField
= (u16
)pOp
->p3
;
5365 r
.aMem
= &aMem
[pOp
->p2
];
5366 rc
= sqlite3BtreeMovetoUnpacked(pCrsr
, &r
, 0, 0, &res
);
5367 if( rc
) goto abort_due_to_error
;
5369 rc
= sqlite3BtreeDelete(pCrsr
, BTREE_AUXDELETE
);
5370 if( rc
) goto abort_due_to_error
;
5372 assert( pC
->deferredMoveto
==0 );
5373 pC
->cacheStatus
= CACHE_STALE
;
5378 /* Opcode: DeferredSeek P1 * P3 P4 *
5379 ** Synopsis: Move P3 to P1.rowid if needed
5381 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5382 ** table. This opcode does a deferred seek of the P3 table cursor
5383 ** to the row that corresponds to the current row of P1.
5385 ** This is a deferred seek. Nothing actually happens until
5386 ** the cursor is used to read a record. That way, if no reads
5387 ** occur, no unnecessary I/O happens.
5389 ** P4 may be an array of integers (type P4_INTARRAY) containing
5390 ** one entry for each column in the P3 table. If array entry a(i)
5391 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5392 ** equivalent to performing the deferred seek and then reading column i
5393 ** from P1. This information is stored in P3 and used to redirect
5394 ** reads against P3 over to P1, thus possibly avoiding the need to
5395 ** seek and read cursor P3.
5397 /* Opcode: IdxRowid P1 P2 * * *
5398 ** Synopsis: r[P2]=rowid
5400 ** Write into register P2 an integer which is the last entry in the record at
5401 ** the end of the index key pointed to by cursor P1. This integer should be
5402 ** the rowid of the table entry to which this index entry points.
5404 ** See also: Rowid, MakeRecord.
5406 case OP_DeferredSeek
:
5407 case OP_IdxRowid
: { /* out2 */
5408 VdbeCursor
*pC
; /* The P1 index cursor */
5409 VdbeCursor
*pTabCur
; /* The P2 table cursor (OP_DeferredSeek only) */
5410 i64 rowid
; /* Rowid that P1 current points to */
5412 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5413 pC
= p
->apCsr
[pOp
->p1
];
5415 assert( pC
->eCurType
==CURTYPE_BTREE
);
5416 assert( pC
->uc
.pCursor
!=0 );
5417 assert( pC
->isTable
==0 );
5418 assert( pC
->deferredMoveto
==0 );
5419 assert( !pC
->nullRow
|| pOp
->opcode
==OP_IdxRowid
);
5421 /* The IdxRowid and Seek opcodes are combined because of the commonality
5422 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5423 rc
= sqlite3VdbeCursorRestore(pC
);
5425 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5426 ** out from under the cursor. That will never happens for an IdxRowid
5427 ** or Seek opcode */
5428 if( NEVER(rc
!=SQLITE_OK
) ) goto abort_due_to_error
;
5431 rowid
= 0; /* Not needed. Only used to silence a warning. */
5432 rc
= sqlite3VdbeIdxRowid(db
, pC
->uc
.pCursor
, &rowid
);
5433 if( rc
!=SQLITE_OK
){
5434 goto abort_due_to_error
;
5436 if( pOp
->opcode
==OP_DeferredSeek
){
5437 assert( pOp
->p3
>=0 && pOp
->p3
<p
->nCursor
);
5438 pTabCur
= p
->apCsr
[pOp
->p3
];
5439 assert( pTabCur
!=0 );
5440 assert( pTabCur
->eCurType
==CURTYPE_BTREE
);
5441 assert( pTabCur
->uc
.pCursor
!=0 );
5442 assert( pTabCur
->isTable
);
5443 pTabCur
->nullRow
= 0;
5444 pTabCur
->movetoTarget
= rowid
;
5445 pTabCur
->deferredMoveto
= 1;
5446 assert( pOp
->p4type
==P4_INTARRAY
|| pOp
->p4
.ai
==0 );
5447 pTabCur
->aAltMap
= pOp
->p4
.ai
;
5448 pTabCur
->pAltCursor
= pC
;
5450 pOut
= out2Prerelease(p
, pOp
);
5454 assert( pOp
->opcode
==OP_IdxRowid
);
5455 sqlite3VdbeMemSetNull(&aMem
[pOp
->p2
]);
5460 /* Opcode: IdxGE P1 P2 P3 P4 P5
5461 ** Synopsis: key=r[P3@P4]
5463 ** The P4 register values beginning with P3 form an unpacked index
5464 ** key that omits the PRIMARY KEY. Compare this key value against the index
5465 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5466 ** fields at the end.
5468 ** If the P1 index entry is greater than or equal to the key value
5469 ** then jump to P2. Otherwise fall through to the next instruction.
5471 /* Opcode: IdxGT P1 P2 P3 P4 P5
5472 ** Synopsis: key=r[P3@P4]
5474 ** The P4 register values beginning with P3 form an unpacked index
5475 ** key that omits the PRIMARY KEY. Compare this key value against the index
5476 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
5477 ** fields at the end.
5479 ** If the P1 index entry is greater than the key value
5480 ** then jump to P2. Otherwise fall through to the next instruction.
5482 /* Opcode: IdxLT P1 P2 P3 P4 P5
5483 ** Synopsis: key=r[P3@P4]
5485 ** The P4 register values beginning with P3 form an unpacked index
5486 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5487 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5488 ** ROWID on the P1 index.
5490 ** If the P1 index entry is less than the key value then jump to P2.
5491 ** Otherwise fall through to the next instruction.
5493 /* Opcode: IdxLE P1 P2 P3 P4 P5
5494 ** Synopsis: key=r[P3@P4]
5496 ** The P4 register values beginning with P3 form an unpacked index
5497 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
5498 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
5499 ** ROWID on the P1 index.
5501 ** If the P1 index entry is less than or equal to the key value then jump
5502 ** to P2. Otherwise fall through to the next instruction.
5504 case OP_IdxLE
: /* jump */
5505 case OP_IdxGT
: /* jump */
5506 case OP_IdxLT
: /* jump */
5507 case OP_IdxGE
: { /* jump */
5512 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5513 pC
= p
->apCsr
[pOp
->p1
];
5515 assert( pC
->isOrdered
);
5516 assert( pC
->eCurType
==CURTYPE_BTREE
);
5517 assert( pC
->uc
.pCursor
!=0);
5518 assert( pC
->deferredMoveto
==0 );
5519 assert( pOp
->p5
==0 || pOp
->p5
==1 );
5520 assert( pOp
->p4type
==P4_INT32
);
5521 r
.pKeyInfo
= pC
->pKeyInfo
;
5522 r
.nField
= (u16
)pOp
->p4
.i
;
5523 if( pOp
->opcode
<OP_IdxLT
){
5524 assert( pOp
->opcode
==OP_IdxLE
|| pOp
->opcode
==OP_IdxGT
);
5527 assert( pOp
->opcode
==OP_IdxGE
|| pOp
->opcode
==OP_IdxLT
);
5530 r
.aMem
= &aMem
[pOp
->p3
];
5532 { int i
; for(i
=0; i
<r
.nField
; i
++) assert( memIsValid(&r
.aMem
[i
]) ); }
5534 res
= 0; /* Not needed. Only used to silence a warning. */
5535 rc
= sqlite3VdbeIdxKeyCompare(db
, pC
, &r
, &res
);
5536 assert( (OP_IdxLE
&1)==(OP_IdxLT
&1) && (OP_IdxGE
&1)==(OP_IdxGT
&1) );
5537 if( (pOp
->opcode
&1)==(OP_IdxLT
&1) ){
5538 assert( pOp
->opcode
==OP_IdxLE
|| pOp
->opcode
==OP_IdxLT
);
5541 assert( pOp
->opcode
==OP_IdxGE
|| pOp
->opcode
==OP_IdxGT
);
5544 VdbeBranchTaken(res
>0,2);
5545 if( rc
) goto abort_due_to_error
;
5546 if( res
>0 ) goto jump_to_p2
;
5550 /* Opcode: Destroy P1 P2 P3 * *
5552 ** Delete an entire database table or index whose root page in the database
5553 ** file is given by P1.
5555 ** The table being destroyed is in the main database file if P3==0. If
5556 ** P3==1 then the table to be clear is in the auxiliary database file
5557 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5559 ** If AUTOVACUUM is enabled then it is possible that another root page
5560 ** might be moved into the newly deleted root page in order to keep all
5561 ** root pages contiguous at the beginning of the database. The former
5562 ** value of the root page that moved - its value before the move occurred -
5563 ** is stored in register P2. If no page movement was required (because the
5564 ** table being dropped was already the last one in the database) then a
5565 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
5566 ** is stored in register P2.
5568 ** This opcode throws an error if there are any active reader VMs when
5569 ** it is invoked. This is done to avoid the difficulty associated with
5570 ** updating existing cursors when a root page is moved in an AUTOVACUUM
5571 ** database. This error is thrown even if the database is not an AUTOVACUUM
5572 ** db in order to avoid introducing an incompatibility between autovacuum
5573 ** and non-autovacuum modes.
5577 case OP_Destroy
: { /* out2 */
5581 sqlite3VdbeIncrWriteCounter(p
, 0);
5582 assert( p
->readOnly
==0 );
5583 assert( pOp
->p1
>1 );
5584 pOut
= out2Prerelease(p
, pOp
);
5585 pOut
->flags
= MEM_Null
;
5586 if( db
->nVdbeRead
> db
->nVDestroy
+1 ){
5588 p
->errorAction
= OE_Abort
;
5589 goto abort_due_to_error
;
5592 assert( DbMaskTest(p
->btreeMask
, iDb
) );
5593 iMoved
= 0; /* Not needed. Only to silence a warning. */
5594 rc
= sqlite3BtreeDropTable(db
->aDb
[iDb
].pBt
, pOp
->p1
, &iMoved
);
5595 pOut
->flags
= MEM_Int
;
5597 if( rc
) goto abort_due_to_error
;
5598 #ifndef SQLITE_OMIT_AUTOVACUUM
5600 sqlite3RootPageMoved(db
, iDb
, iMoved
, pOp
->p1
);
5601 /* All OP_Destroy operations occur on the same btree */
5602 assert( resetSchemaOnFault
==0 || resetSchemaOnFault
==iDb
+1 );
5603 resetSchemaOnFault
= iDb
+1;
5610 /* Opcode: Clear P1 P2 P3
5612 ** Delete all contents of the database table or index whose root page
5613 ** in the database file is given by P1. But, unlike Destroy, do not
5614 ** remove the table or index from the database file.
5616 ** The table being clear is in the main database file if P2==0. If
5617 ** P2==1 then the table to be clear is in the auxiliary database file
5618 ** that is used to store tables create using CREATE TEMPORARY TABLE.
5620 ** If the P3 value is non-zero, then the table referred to must be an
5621 ** intkey table (an SQL table, not an index). In this case the row change
5622 ** count is incremented by the number of rows in the table being cleared.
5623 ** If P3 is greater than zero, then the value stored in register P3 is
5624 ** also incremented by the number of rows in the table being cleared.
5626 ** See also: Destroy
5631 sqlite3VdbeIncrWriteCounter(p
, 0);
5633 assert( p
->readOnly
==0 );
5634 assert( DbMaskTest(p
->btreeMask
, pOp
->p2
) );
5635 rc
= sqlite3BtreeClearTable(
5636 db
->aDb
[pOp
->p2
].pBt
, pOp
->p1
, (pOp
->p3
? &nChange
: 0)
5639 p
->nChange
+= nChange
;
5641 assert( memIsValid(&aMem
[pOp
->p3
]) );
5642 memAboutToChange(p
, &aMem
[pOp
->p3
]);
5643 aMem
[pOp
->p3
].u
.i
+= nChange
;
5646 if( rc
) goto abort_due_to_error
;
5650 /* Opcode: ResetSorter P1 * * * *
5652 ** Delete all contents from the ephemeral table or sorter
5653 ** that is open on cursor P1.
5655 ** This opcode only works for cursors used for sorting and
5656 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5658 case OP_ResetSorter
: {
5661 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
5662 pC
= p
->apCsr
[pOp
->p1
];
5665 sqlite3VdbeSorterReset(db
, pC
->uc
.pSorter
);
5667 assert( pC
->eCurType
==CURTYPE_BTREE
);
5668 assert( pC
->isEphemeral
);
5669 rc
= sqlite3BtreeClearTableOfCursor(pC
->uc
.pCursor
);
5670 if( rc
) goto abort_due_to_error
;
5675 /* Opcode: CreateBtree P1 P2 P3 * *
5676 ** Synopsis: r[P2]=root iDb=P1 flags=P3
5678 ** Allocate a new b-tree in the main database file if P1==0 or in the
5679 ** TEMP database file if P1==1 or in an attached database if
5680 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
5681 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
5682 ** The root page number of the new b-tree is stored in register P2.
5684 case OP_CreateBtree
: { /* out2 */
5688 sqlite3VdbeIncrWriteCounter(p
, 0);
5689 pOut
= out2Prerelease(p
, pOp
);
5691 assert( pOp
->p3
==BTREE_INTKEY
|| pOp
->p3
==BTREE_BLOBKEY
);
5692 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
5693 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
5694 assert( p
->readOnly
==0 );
5695 pDb
= &db
->aDb
[pOp
->p1
];
5696 assert( pDb
->pBt
!=0 );
5697 rc
= sqlite3BtreeCreateTable(pDb
->pBt
, &pgno
, pOp
->p3
);
5698 if( rc
) goto abort_due_to_error
;
5703 /* Opcode: SqlExec * * * P4 *
5705 ** Run the SQL statement or statements specified in the P4 string.
5708 sqlite3VdbeIncrWriteCounter(p
, 0);
5710 rc
= sqlite3_exec(db
, pOp
->p4
.z
, 0, 0, 0);
5712 if( rc
) goto abort_due_to_error
;
5716 /* Opcode: ParseSchema P1 * * P4 *
5718 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5719 ** that match the WHERE clause P4.
5721 ** This opcode invokes the parser to create a new virtual machine,
5722 ** then runs the new virtual machine. It is thus a re-entrant opcode.
5724 case OP_ParseSchema
: {
5726 const char *zMaster
;
5730 /* Any prepared statement that invokes this opcode will hold mutexes
5731 ** on every btree. This is a prerequisite for invoking
5732 ** sqlite3InitCallback().
5735 for(iDb
=0; iDb
<db
->nDb
; iDb
++){
5736 assert( iDb
==1 || sqlite3BtreeHoldsMutex(db
->aDb
[iDb
].pBt
) );
5741 assert( iDb
>=0 && iDb
<db
->nDb
);
5742 assert( DbHasProperty(db
, iDb
, DB_SchemaLoaded
) );
5743 /* Used to be a conditional */ {
5744 zMaster
= MASTER_NAME
;
5746 initData
.iDb
= pOp
->p1
;
5747 initData
.pzErrMsg
= &p
->zErrMsg
;
5748 zSql
= sqlite3MPrintf(db
,
5749 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5750 db
->aDb
[iDb
].zDbSName
, zMaster
, pOp
->p4
.z
);
5752 rc
= SQLITE_NOMEM_BKPT
;
5754 assert( db
->init
.busy
==0 );
5756 initData
.rc
= SQLITE_OK
;
5757 assert( !db
->mallocFailed
);
5758 rc
= sqlite3_exec(db
, zSql
, sqlite3InitCallback
, &initData
, 0);
5759 if( rc
==SQLITE_OK
) rc
= initData
.rc
;
5760 sqlite3DbFreeNN(db
, zSql
);
5765 sqlite3ResetAllSchemasOfConnection(db
);
5766 if( rc
==SQLITE_NOMEM
){
5769 goto abort_due_to_error
;
5774 #if !defined(SQLITE_OMIT_ANALYZE)
5775 /* Opcode: LoadAnalysis P1 * * * *
5777 ** Read the sqlite_stat1 table for database P1 and load the content
5778 ** of that table into the internal index hash table. This will cause
5779 ** the analysis to be used when preparing all subsequent queries.
5781 case OP_LoadAnalysis
: {
5782 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
5783 rc
= sqlite3AnalysisLoad(db
, pOp
->p1
);
5784 if( rc
) goto abort_due_to_error
;
5787 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5789 /* Opcode: DropTable P1 * * P4 *
5791 ** Remove the internal (in-memory) data structures that describe
5792 ** the table named P4 in database P1. This is called after a table
5793 ** is dropped from disk (using the Destroy opcode) in order to keep
5794 ** the internal representation of the
5795 ** schema consistent with what is on disk.
5797 case OP_DropTable
: {
5798 sqlite3VdbeIncrWriteCounter(p
, 0);
5799 sqlite3UnlinkAndDeleteTable(db
, pOp
->p1
, pOp
->p4
.z
);
5803 /* Opcode: DropIndex P1 * * P4 *
5805 ** Remove the internal (in-memory) data structures that describe
5806 ** the index named P4 in database P1. This is called after an index
5807 ** is dropped from disk (using the Destroy opcode)
5808 ** in order to keep the internal representation of the
5809 ** schema consistent with what is on disk.
5811 case OP_DropIndex
: {
5812 sqlite3VdbeIncrWriteCounter(p
, 0);
5813 sqlite3UnlinkAndDeleteIndex(db
, pOp
->p1
, pOp
->p4
.z
);
5817 /* Opcode: DropTrigger P1 * * P4 *
5819 ** Remove the internal (in-memory) data structures that describe
5820 ** the trigger named P4 in database P1. This is called after a trigger
5821 ** is dropped from disk (using the Destroy opcode) in order to keep
5822 ** the internal representation of the
5823 ** schema consistent with what is on disk.
5825 case OP_DropTrigger
: {
5826 sqlite3VdbeIncrWriteCounter(p
, 0);
5827 sqlite3UnlinkAndDeleteTrigger(db
, pOp
->p1
, pOp
->p4
.z
);
5832 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5833 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
5835 ** Do an analysis of the currently open database. Store in
5836 ** register P1 the text of an error message describing any problems.
5837 ** If no problems are found, store a NULL in register P1.
5839 ** The register P3 contains one less than the maximum number of allowed errors.
5840 ** At most reg(P3) errors will be reported.
5841 ** In other words, the analysis stops as soon as reg(P1) errors are
5842 ** seen. Reg(P1) is updated with the number of errors remaining.
5844 ** The root page numbers of all tables in the database are integers
5845 ** stored in P4_INTARRAY argument.
5847 ** If P5 is not zero, the check is done on the auxiliary database
5848 ** file, not the main database file.
5850 ** This opcode is used to implement the integrity_check pragma.
5852 case OP_IntegrityCk
: {
5853 int nRoot
; /* Number of tables to check. (Number of root pages.) */
5854 int *aRoot
; /* Array of rootpage numbers for tables to be checked */
5855 int nErr
; /* Number of errors reported */
5856 char *z
; /* Text of the error report */
5857 Mem
*pnErr
; /* Register keeping track of errors remaining */
5859 assert( p
->bIsReader
);
5863 assert( aRoot
[0]==nRoot
);
5864 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
5865 pnErr
= &aMem
[pOp
->p3
];
5866 assert( (pnErr
->flags
& MEM_Int
)!=0 );
5867 assert( (pnErr
->flags
& (MEM_Str
|MEM_Blob
))==0 );
5868 pIn1
= &aMem
[pOp
->p1
];
5869 assert( pOp
->p5
<db
->nDb
);
5870 assert( DbMaskTest(p
->btreeMask
, pOp
->p5
) );
5871 z
= sqlite3BtreeIntegrityCheck(db
->aDb
[pOp
->p5
].pBt
, &aRoot
[1], nRoot
,
5872 (int)pnErr
->u
.i
+1, &nErr
);
5873 sqlite3VdbeMemSetNull(pIn1
);
5879 pnErr
->u
.i
-= nErr
-1;
5880 sqlite3VdbeMemSetStr(pIn1
, z
, -1, SQLITE_UTF8
, sqlite3_free
);
5882 UPDATE_MAX_BLOBSIZE(pIn1
);
5883 sqlite3VdbeChangeEncoding(pIn1
, encoding
);
5886 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5888 /* Opcode: RowSetAdd P1 P2 * * *
5889 ** Synopsis: rowset(P1)=r[P2]
5891 ** Insert the integer value held by register P2 into a RowSet object
5892 ** held in register P1.
5894 ** An assertion fails if P2 is not an integer.
5896 case OP_RowSetAdd
: { /* in1, in2 */
5897 pIn1
= &aMem
[pOp
->p1
];
5898 pIn2
= &aMem
[pOp
->p2
];
5899 assert( (pIn2
->flags
& MEM_Int
)!=0 );
5900 if( (pIn1
->flags
& MEM_RowSet
)==0 ){
5901 sqlite3VdbeMemSetRowSet(pIn1
);
5902 if( (pIn1
->flags
& MEM_RowSet
)==0 ) goto no_mem
;
5904 sqlite3RowSetInsert(pIn1
->u
.pRowSet
, pIn2
->u
.i
);
5908 /* Opcode: RowSetRead P1 P2 P3 * *
5909 ** Synopsis: r[P3]=rowset(P1)
5911 ** Extract the smallest value from the RowSet object in P1
5912 ** and put that value into register P3.
5913 ** Or, if RowSet object P1 is initially empty, leave P3
5914 ** unchanged and jump to instruction P2.
5916 case OP_RowSetRead
: { /* jump, in1, out3 */
5919 pIn1
= &aMem
[pOp
->p1
];
5920 if( (pIn1
->flags
& MEM_RowSet
)==0
5921 || sqlite3RowSetNext(pIn1
->u
.pRowSet
, &val
)==0
5923 /* The boolean index is empty */
5924 sqlite3VdbeMemSetNull(pIn1
);
5925 VdbeBranchTaken(1,2);
5926 goto jump_to_p2_and_check_for_interrupt
;
5928 /* A value was pulled from the index */
5929 VdbeBranchTaken(0,2);
5930 sqlite3VdbeMemSetInt64(&aMem
[pOp
->p3
], val
);
5932 goto check_for_interrupt
;
5935 /* Opcode: RowSetTest P1 P2 P3 P4
5936 ** Synopsis: if r[P3] in rowset(P1) goto P2
5938 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5939 ** contains a RowSet object and that RowSet object contains
5940 ** the value held in P3, jump to register P2. Otherwise, insert the
5941 ** integer in P3 into the RowSet and continue on to the
5944 ** The RowSet object is optimized for the case where sets of integers
5945 ** are inserted in distinct phases, which each set contains no duplicates.
5946 ** Each set is identified by a unique P4 value. The first set
5947 ** must have P4==0, the final set must have P4==-1, and for all other sets
5950 ** This allows optimizations: (a) when P4==0 there is no need to test
5951 ** the RowSet object for P3, as it is guaranteed not to contain it,
5952 ** (b) when P4==-1 there is no need to insert the value, as it will
5953 ** never be tested for, and (c) when a value that is part of set X is
5954 ** inserted, there is no need to search to see if the same value was
5955 ** previously inserted as part of set X (only if it was previously
5956 ** inserted as part of some other set).
5958 case OP_RowSetTest
: { /* jump, in1, in3 */
5962 pIn1
= &aMem
[pOp
->p1
];
5963 pIn3
= &aMem
[pOp
->p3
];
5965 assert( pIn3
->flags
&MEM_Int
);
5967 /* If there is anything other than a rowset object in memory cell P1,
5968 ** delete it now and initialize P1 with an empty rowset
5970 if( (pIn1
->flags
& MEM_RowSet
)==0 ){
5971 sqlite3VdbeMemSetRowSet(pIn1
);
5972 if( (pIn1
->flags
& MEM_RowSet
)==0 ) goto no_mem
;
5975 assert( pOp
->p4type
==P4_INT32
);
5976 assert( iSet
==-1 || iSet
>=0 );
5978 exists
= sqlite3RowSetTest(pIn1
->u
.pRowSet
, iSet
, pIn3
->u
.i
);
5979 VdbeBranchTaken(exists
!=0,2);
5980 if( exists
) goto jump_to_p2
;
5983 sqlite3RowSetInsert(pIn1
->u
.pRowSet
, pIn3
->u
.i
);
5989 #ifndef SQLITE_OMIT_TRIGGER
5991 /* Opcode: Program P1 P2 P3 P4 P5
5993 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5995 ** P1 contains the address of the memory cell that contains the first memory
5996 ** cell in an array of values used as arguments to the sub-program. P2
5997 ** contains the address to jump to if the sub-program throws an IGNORE
5998 ** exception using the RAISE() function. Register P3 contains the address
5999 ** of a memory cell in this (the parent) VM that is used to allocate the
6000 ** memory required by the sub-vdbe at runtime.
6002 ** P4 is a pointer to the VM containing the trigger program.
6004 ** If P5 is non-zero, then recursive program invocation is enabled.
6006 case OP_Program
: { /* jump */
6007 int nMem
; /* Number of memory registers for sub-program */
6008 int nByte
; /* Bytes of runtime space required for sub-program */
6009 Mem
*pRt
; /* Register to allocate runtime space */
6010 Mem
*pMem
; /* Used to iterate through memory cells */
6011 Mem
*pEnd
; /* Last memory cell in new array */
6012 VdbeFrame
*pFrame
; /* New vdbe frame to execute in */
6013 SubProgram
*pProgram
; /* Sub-program to execute */
6014 void *t
; /* Token identifying trigger */
6016 pProgram
= pOp
->p4
.pProgram
;
6017 pRt
= &aMem
[pOp
->p3
];
6018 assert( pProgram
->nOp
>0 );
6020 /* If the p5 flag is clear, then recursive invocation of triggers is
6021 ** disabled for backwards compatibility (p5 is set if this sub-program
6022 ** is really a trigger, not a foreign key action, and the flag set
6023 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
6025 ** It is recursive invocation of triggers, at the SQL level, that is
6026 ** disabled. In some cases a single trigger may generate more than one
6027 ** SubProgram (if the trigger may be executed with more than one different
6028 ** ON CONFLICT algorithm). SubProgram structures associated with a
6029 ** single trigger all have the same value for the SubProgram.token
6032 t
= pProgram
->token
;
6033 for(pFrame
=p
->pFrame
; pFrame
&& pFrame
->token
!=t
; pFrame
=pFrame
->pParent
);
6037 if( p
->nFrame
>=db
->aLimit
[SQLITE_LIMIT_TRIGGER_DEPTH
] ){
6039 sqlite3VdbeError(p
, "too many levels of trigger recursion");
6040 goto abort_due_to_error
;
6043 /* Register pRt is used to store the memory required to save the state
6044 ** of the current program, and the memory required at runtime to execute
6045 ** the trigger program. If this trigger has been fired before, then pRt
6046 ** is already allocated. Otherwise, it must be initialized. */
6047 if( (pRt
->flags
&MEM_Frame
)==0 ){
6048 /* SubProgram.nMem is set to the number of memory cells used by the
6049 ** program stored in SubProgram.aOp. As well as these, one memory
6050 ** cell is required for each cursor used by the program. Set local
6051 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
6053 nMem
= pProgram
->nMem
+ pProgram
->nCsr
;
6055 if( pProgram
->nCsr
==0 ) nMem
++;
6056 nByte
= ROUND8(sizeof(VdbeFrame
))
6057 + nMem
* sizeof(Mem
)
6058 + pProgram
->nCsr
* sizeof(VdbeCursor
*)
6059 + (pProgram
->nOp
+ 7)/8;
6060 pFrame
= sqlite3DbMallocZero(db
, nByte
);
6064 sqlite3VdbeMemRelease(pRt
);
6065 pRt
->flags
= MEM_Frame
;
6066 pRt
->u
.pFrame
= pFrame
;
6069 pFrame
->nChildMem
= nMem
;
6070 pFrame
->nChildCsr
= pProgram
->nCsr
;
6071 pFrame
->pc
= (int)(pOp
- aOp
);
6072 pFrame
->aMem
= p
->aMem
;
6073 pFrame
->nMem
= p
->nMem
;
6074 pFrame
->apCsr
= p
->apCsr
;
6075 pFrame
->nCursor
= p
->nCursor
;
6076 pFrame
->aOp
= p
->aOp
;
6077 pFrame
->nOp
= p
->nOp
;
6078 pFrame
->token
= pProgram
->token
;
6079 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6080 pFrame
->anExec
= p
->anExec
;
6083 pEnd
= &VdbeFrameMem(pFrame
)[pFrame
->nChildMem
];
6084 for(pMem
=VdbeFrameMem(pFrame
); pMem
!=pEnd
; pMem
++){
6085 pMem
->flags
= MEM_Undefined
;
6089 pFrame
= pRt
->u
.pFrame
;
6090 assert( pProgram
->nMem
+pProgram
->nCsr
==pFrame
->nChildMem
6091 || (pProgram
->nCsr
==0 && pProgram
->nMem
+1==pFrame
->nChildMem
) );
6092 assert( pProgram
->nCsr
==pFrame
->nChildCsr
);
6093 assert( (int)(pOp
- aOp
)==pFrame
->pc
);
6097 pFrame
->pParent
= p
->pFrame
;
6098 pFrame
->lastRowid
= db
->lastRowid
;
6099 pFrame
->nChange
= p
->nChange
;
6100 pFrame
->nDbChange
= p
->db
->nChange
;
6101 assert( pFrame
->pAuxData
==0 );
6102 pFrame
->pAuxData
= p
->pAuxData
;
6106 p
->aMem
= aMem
= VdbeFrameMem(pFrame
);
6107 p
->nMem
= pFrame
->nChildMem
;
6108 p
->nCursor
= (u16
)pFrame
->nChildCsr
;
6109 p
->apCsr
= (VdbeCursor
**)&aMem
[p
->nMem
];
6110 pFrame
->aOnce
= (u8
*)&p
->apCsr
[pProgram
->nCsr
];
6111 memset(pFrame
->aOnce
, 0, (pProgram
->nOp
+ 7)/8);
6112 p
->aOp
= aOp
= pProgram
->aOp
;
6113 p
->nOp
= pProgram
->nOp
;
6114 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6122 /* Opcode: Param P1 P2 * * *
6124 ** This opcode is only ever present in sub-programs called via the
6125 ** OP_Program instruction. Copy a value currently stored in a memory
6126 ** cell of the calling (parent) frame to cell P2 in the current frames
6127 ** address space. This is used by trigger programs to access the new.*
6128 ** and old.* values.
6130 ** The address of the cell in the parent frame is determined by adding
6131 ** the value of the P1 argument to the value of the P1 argument to the
6132 ** calling OP_Program instruction.
6134 case OP_Param
: { /* out2 */
6137 pOut
= out2Prerelease(p
, pOp
);
6139 pIn
= &pFrame
->aMem
[pOp
->p1
+ pFrame
->aOp
[pFrame
->pc
].p1
];
6140 sqlite3VdbeMemShallowCopy(pOut
, pIn
, MEM_Ephem
);
6144 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6146 #ifndef SQLITE_OMIT_FOREIGN_KEY
6147 /* Opcode: FkCounter P1 P2 * * *
6148 ** Synopsis: fkctr[P1]+=P2
6150 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6151 ** If P1 is non-zero, the database constraint counter is incremented
6152 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6153 ** statement counter is incremented (immediate foreign key constraints).
6155 case OP_FkCounter
: {
6156 if( db
->flags
& SQLITE_DeferFKs
){
6157 db
->nDeferredImmCons
+= pOp
->p2
;
6158 }else if( pOp
->p1
){
6159 db
->nDeferredCons
+= pOp
->p2
;
6161 p
->nFkConstraint
+= pOp
->p2
;
6166 /* Opcode: FkIfZero P1 P2 * * *
6167 ** Synopsis: if fkctr[P1]==0 goto P2
6169 ** This opcode tests if a foreign key constraint-counter is currently zero.
6170 ** If so, jump to instruction P2. Otherwise, fall through to the next
6173 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6174 ** is zero (the one that counts deferred constraint violations). If P1 is
6175 ** zero, the jump is taken if the statement constraint-counter is zero
6176 ** (immediate foreign key constraint violations).
6178 case OP_FkIfZero
: { /* jump */
6180 VdbeBranchTaken(db
->nDeferredCons
==0 && db
->nDeferredImmCons
==0, 2);
6181 if( db
->nDeferredCons
==0 && db
->nDeferredImmCons
==0 ) goto jump_to_p2
;
6183 VdbeBranchTaken(p
->nFkConstraint
==0 && db
->nDeferredImmCons
==0, 2);
6184 if( p
->nFkConstraint
==0 && db
->nDeferredImmCons
==0 ) goto jump_to_p2
;
6188 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6190 #ifndef SQLITE_OMIT_AUTOINCREMENT
6191 /* Opcode: MemMax P1 P2 * * *
6192 ** Synopsis: r[P1]=max(r[P1],r[P2])
6194 ** P1 is a register in the root frame of this VM (the root frame is
6195 ** different from the current frame if this instruction is being executed
6196 ** within a sub-program). Set the value of register P1 to the maximum of
6197 ** its current value and the value in register P2.
6199 ** This instruction throws an error if the memory cell is not initially
6202 case OP_MemMax
: { /* in2 */
6205 for(pFrame
=p
->pFrame
; pFrame
->pParent
; pFrame
=pFrame
->pParent
);
6206 pIn1
= &pFrame
->aMem
[pOp
->p1
];
6208 pIn1
= &aMem
[pOp
->p1
];
6210 assert( memIsValid(pIn1
) );
6211 sqlite3VdbeMemIntegerify(pIn1
);
6212 pIn2
= &aMem
[pOp
->p2
];
6213 sqlite3VdbeMemIntegerify(pIn2
);
6214 if( pIn1
->u
.i
<pIn2
->u
.i
){
6215 pIn1
->u
.i
= pIn2
->u
.i
;
6219 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6221 /* Opcode: IfPos P1 P2 P3 * *
6222 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6224 ** Register P1 must contain an integer.
6225 ** If the value of register P1 is 1 or greater, subtract P3 from the
6226 ** value in P1 and jump to P2.
6228 ** If the initial value of register P1 is less than 1, then the
6229 ** value is unchanged and control passes through to the next instruction.
6231 case OP_IfPos
: { /* jump, in1 */
6232 pIn1
= &aMem
[pOp
->p1
];
6233 assert( pIn1
->flags
&MEM_Int
);
6234 VdbeBranchTaken( pIn1
->u
.i
>0, 2);
6236 pIn1
->u
.i
-= pOp
->p3
;
6242 /* Opcode: OffsetLimit P1 P2 P3 * *
6243 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6245 ** This opcode performs a commonly used computation associated with
6246 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
6247 ** holds the offset counter. The opcode computes the combined value
6248 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
6249 ** value computed is the total number of rows that will need to be
6250 ** visited in order to complete the query.
6252 ** If r[P3] is zero or negative, that means there is no OFFSET
6253 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6255 ** if r[P1] is zero or negative, that means there is no LIMIT
6256 ** and r[P2] is set to -1.
6258 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6260 case OP_OffsetLimit
: { /* in1, out2, in3 */
6262 pIn1
= &aMem
[pOp
->p1
];
6263 pIn3
= &aMem
[pOp
->p3
];
6264 pOut
= out2Prerelease(p
, pOp
);
6265 assert( pIn1
->flags
& MEM_Int
);
6266 assert( pIn3
->flags
& MEM_Int
);
6268 if( x
<=0 || sqlite3AddInt64(&x
, pIn3
->u
.i
>0?pIn3
->u
.i
:0) ){
6269 /* If the LIMIT is less than or equal to zero, loop forever. This
6270 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
6271 ** also loop forever. This is undocumented. In fact, one could argue
6272 ** that the loop should terminate. But assuming 1 billion iterations
6273 ** per second (far exceeding the capabilities of any current hardware)
6274 ** it would take nearly 300 years to actually reach the limit. So
6275 ** looping forever is a reasonable approximation. */
6283 /* Opcode: IfNotZero P1 P2 * * *
6284 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6286 ** Register P1 must contain an integer. If the content of register P1 is
6287 ** initially greater than zero, then decrement the value in register P1.
6288 ** If it is non-zero (negative or positive) and then also jump to P2.
6289 ** If register P1 is initially zero, leave it unchanged and fall through.
6291 case OP_IfNotZero
: { /* jump, in1 */
6292 pIn1
= &aMem
[pOp
->p1
];
6293 assert( pIn1
->flags
&MEM_Int
);
6294 VdbeBranchTaken(pIn1
->u
.i
<0, 2);
6296 if( pIn1
->u
.i
>0 ) pIn1
->u
.i
--;
6302 /* Opcode: DecrJumpZero P1 P2 * * *
6303 ** Synopsis: if (--r[P1])==0 goto P2
6305 ** Register P1 must hold an integer. Decrement the value in P1
6306 ** and jump to P2 if the new value is exactly zero.
6308 case OP_DecrJumpZero
: { /* jump, in1 */
6309 pIn1
= &aMem
[pOp
->p1
];
6310 assert( pIn1
->flags
&MEM_Int
);
6311 if( pIn1
->u
.i
>SMALLEST_INT64
) pIn1
->u
.i
--;
6312 VdbeBranchTaken(pIn1
->u
.i
==0, 2);
6313 if( pIn1
->u
.i
==0 ) goto jump_to_p2
;
6318 /* Opcode: AggStep * P2 P3 P4 P5
6319 ** Synopsis: accum=r[P3] step(r[P2@P5])
6321 ** Execute the xStep function for an aggregate.
6322 ** The function has P5 arguments. P4 is a pointer to the
6323 ** FuncDef structure that specifies the function. Register P3 is the
6326 ** The P5 arguments are taken from register P2 and its
6329 /* Opcode: AggInverse * P2 P3 P4 P5
6330 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
6332 ** Execute the xInverse function for an aggregate.
6333 ** The function has P5 arguments. P4 is a pointer to the
6334 ** FuncDef structure that specifies the function. Register P3 is the
6337 ** The P5 arguments are taken from register P2 and its
6340 /* Opcode: AggStep1 P1 P2 P3 P4 P5
6341 ** Synopsis: accum=r[P3] step(r[P2@P5])
6343 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
6344 ** aggregate. The function has P5 arguments. P4 is a pointer to the
6345 ** FuncDef structure that specifies the function. Register P3 is the
6348 ** The P5 arguments are taken from register P2 and its
6351 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6352 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6353 ** the opcode is changed. In this way, the initialization of the
6354 ** sqlite3_context only happens once, instead of on each call to the
6360 sqlite3_context
*pCtx
;
6362 assert( pOp
->p4type
==P4_FUNCDEF
);
6364 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
6365 assert( n
==0 || (pOp
->p2
>0 && pOp
->p2
+n
<=(p
->nMem
+1 - p
->nCursor
)+1) );
6366 assert( pOp
->p3
<pOp
->p2
|| pOp
->p3
>=pOp
->p2
+n
);
6367 pCtx
= sqlite3DbMallocRawNN(db
, n
*sizeof(sqlite3_value
*) +
6368 (sizeof(pCtx
[0]) + sizeof(Mem
) - sizeof(sqlite3_value
*)));
6369 if( pCtx
==0 ) goto no_mem
;
6371 pCtx
->pOut
= (Mem
*)&(pCtx
->argv
[n
]);
6372 sqlite3VdbeMemInit(pCtx
->pOut
, db
, MEM_Null
);
6373 pCtx
->pFunc
= pOp
->p4
.pFunc
;
6374 pCtx
->iOp
= (int)(pOp
- aOp
);
6379 pOp
->p4type
= P4_FUNCCTX
;
6380 pOp
->p4
.pCtx
= pCtx
;
6382 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
6383 assert( pOp
->p1
==(pOp
->opcode
==OP_AggInverse
) );
6385 pOp
->opcode
= OP_AggStep1
;
6386 /* Fall through into OP_AggStep */
6390 sqlite3_context
*pCtx
;
6393 assert( pOp
->p4type
==P4_FUNCCTX
);
6394 pCtx
= pOp
->p4
.pCtx
;
6395 pMem
= &aMem
[pOp
->p3
];
6399 /* This is an OP_AggInverse call. Verify that xStep has always
6400 ** been called at least once prior to any xInverse call. */
6401 assert( pMem
->uTemp
==0x1122e0e3 );
6403 /* This is an OP_AggStep call. Mark it as such. */
6404 pMem
->uTemp
= 0x1122e0e3;
6408 /* If this function is inside of a trigger, the register array in aMem[]
6409 ** might change from one evaluation to the next. The next block of code
6410 ** checks to see if the register array has changed, and if so it
6411 ** reinitializes the relavant parts of the sqlite3_context object */
6412 if( pCtx
->pMem
!= pMem
){
6414 for(i
=pCtx
->argc
-1; i
>=0; i
--) pCtx
->argv
[i
] = &aMem
[pOp
->p2
+i
];
6418 for(i
=0; i
<pCtx
->argc
; i
++){
6419 assert( memIsValid(pCtx
->argv
[i
]) );
6420 REGISTER_TRACE(pOp
->p2
+i
, pCtx
->argv
[i
]);
6425 assert( pCtx
->pOut
->flags
==MEM_Null
);
6426 assert( pCtx
->isError
==0 );
6427 assert( pCtx
->skipFlag
==0 );
6428 #ifndef SQLITE_OMIT_WINDOWFUNC
6430 (pCtx
->pFunc
->xInverse
)(pCtx
,pCtx
->argc
,pCtx
->argv
);
6433 (pCtx
->pFunc
->xSFunc
)(pCtx
,pCtx
->argc
,pCtx
->argv
); /* IMP: R-24505-23230 */
6435 if( pCtx
->isError
){
6436 if( pCtx
->isError
>0 ){
6437 sqlite3VdbeError(p
, "%s", sqlite3_value_text(pCtx
->pOut
));
6440 if( pCtx
->skipFlag
){
6441 assert( pOp
[-1].opcode
==OP_CollSeq
);
6443 if( i
) sqlite3VdbeMemSetInt64(&aMem
[i
], 1);
6446 sqlite3VdbeMemRelease(pCtx
->pOut
);
6447 pCtx
->pOut
->flags
= MEM_Null
;
6449 if( rc
) goto abort_due_to_error
;
6451 assert( pCtx
->pOut
->flags
==MEM_Null
);
6452 assert( pCtx
->skipFlag
==0 );
6456 /* Opcode: AggFinal P1 P2 * P4 *
6457 ** Synopsis: accum=r[P1] N=P2
6459 ** P1 is the memory location that is the accumulator for an aggregate
6460 ** or window function. Execute the finalizer function
6461 ** for an aggregate and store the result in P1.
6463 ** P2 is the number of arguments that the step function takes and
6464 ** P4 is a pointer to the FuncDef for this function. The P2
6465 ** argument is not used by this opcode. It is only there to disambiguate
6466 ** functions that can take varying numbers of arguments. The
6467 ** P4 argument is only needed for the case where
6468 ** the step function was not previously called.
6470 /* Opcode: AggValue * P2 P3 P4 *
6471 ** Synopsis: r[P3]=value N=P2
6473 ** Invoke the xValue() function and store the result in register P3.
6475 ** P2 is the number of arguments that the step function takes and
6476 ** P4 is a pointer to the FuncDef for this function. The P2
6477 ** argument is not used by this opcode. It is only there to disambiguate
6478 ** functions that can take varying numbers of arguments. The
6479 ** P4 argument is only needed for the case where
6480 ** the step function was not previously called.
6485 assert( pOp
->p1
>0 && pOp
->p1
<=(p
->nMem
+1 - p
->nCursor
) );
6486 assert( pOp
->p3
==0 || pOp
->opcode
==OP_AggValue
);
6487 pMem
= &aMem
[pOp
->p1
];
6488 assert( (pMem
->flags
& ~(MEM_Null
|MEM_Agg
))==0 );
6489 #ifndef SQLITE_OMIT_WINDOWFUNC
6491 rc
= sqlite3VdbeMemAggValue(pMem
, &aMem
[pOp
->p3
], pOp
->p4
.pFunc
);
6492 pMem
= &aMem
[pOp
->p3
];
6496 rc
= sqlite3VdbeMemFinalize(pMem
, pOp
->p4
.pFunc
);
6500 sqlite3VdbeError(p
, "%s", sqlite3_value_text(pMem
));
6501 goto abort_due_to_error
;
6503 sqlite3VdbeChangeEncoding(pMem
, encoding
);
6504 UPDATE_MAX_BLOBSIZE(pMem
);
6505 if( sqlite3VdbeMemTooBig(pMem
) ){
6511 #ifndef SQLITE_OMIT_WAL
6512 /* Opcode: Checkpoint P1 P2 P3 * *
6514 ** Checkpoint database P1. This is a no-op if P1 is not currently in
6515 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
6516 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
6517 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
6518 ** WAL after the checkpoint into mem[P3+1] and the number of pages
6519 ** in the WAL that have been checkpointed after the checkpoint
6520 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
6521 ** mem[P3+2] are initialized to -1.
6523 case OP_Checkpoint
: {
6524 int i
; /* Loop counter */
6525 int aRes
[3]; /* Results */
6526 Mem
*pMem
; /* Write results here */
6528 assert( p
->readOnly
==0 );
6530 aRes
[1] = aRes
[2] = -1;
6531 assert( pOp
->p2
==SQLITE_CHECKPOINT_PASSIVE
6532 || pOp
->p2
==SQLITE_CHECKPOINT_FULL
6533 || pOp
->p2
==SQLITE_CHECKPOINT_RESTART
6534 || pOp
->p2
==SQLITE_CHECKPOINT_TRUNCATE
6536 rc
= sqlite3Checkpoint(db
, pOp
->p1
, pOp
->p2
, &aRes
[1], &aRes
[2]);
6538 if( rc
!=SQLITE_BUSY
) goto abort_due_to_error
;
6542 for(i
=0, pMem
= &aMem
[pOp
->p3
]; i
<3; i
++, pMem
++){
6543 sqlite3VdbeMemSetInt64(pMem
, (i64
)aRes
[i
]);
6549 #ifndef SQLITE_OMIT_PRAGMA
6550 /* Opcode: JournalMode P1 P2 P3 * *
6552 ** Change the journal mode of database P1 to P3. P3 must be one of the
6553 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
6554 ** modes (delete, truncate, persist, off and memory), this is a simple
6555 ** operation. No IO is required.
6557 ** If changing into or out of WAL mode the procedure is more complicated.
6559 ** Write a string containing the final journal-mode to register P2.
6561 case OP_JournalMode
: { /* out2 */
6562 Btree
*pBt
; /* Btree to change journal mode of */
6563 Pager
*pPager
; /* Pager associated with pBt */
6564 int eNew
; /* New journal mode */
6565 int eOld
; /* The old journal mode */
6566 #ifndef SQLITE_OMIT_WAL
6567 const char *zFilename
; /* Name of database file for pPager */
6570 pOut
= out2Prerelease(p
, pOp
);
6572 assert( eNew
==PAGER_JOURNALMODE_DELETE
6573 || eNew
==PAGER_JOURNALMODE_TRUNCATE
6574 || eNew
==PAGER_JOURNALMODE_PERSIST
6575 || eNew
==PAGER_JOURNALMODE_OFF
6576 || eNew
==PAGER_JOURNALMODE_MEMORY
6577 || eNew
==PAGER_JOURNALMODE_WAL
6578 || eNew
==PAGER_JOURNALMODE_QUERY
6580 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
6581 assert( p
->readOnly
==0 );
6583 pBt
= db
->aDb
[pOp
->p1
].pBt
;
6584 pPager
= sqlite3BtreePager(pBt
);
6585 eOld
= sqlite3PagerGetJournalMode(pPager
);
6586 if( eNew
==PAGER_JOURNALMODE_QUERY
) eNew
= eOld
;
6587 if( !sqlite3PagerOkToChangeJournalMode(pPager
) ) eNew
= eOld
;
6589 #ifndef SQLITE_OMIT_WAL
6590 zFilename
= sqlite3PagerFilename(pPager
, 1);
6592 /* Do not allow a transition to journal_mode=WAL for a database
6593 ** in temporary storage or if the VFS does not support shared memory
6595 if( eNew
==PAGER_JOURNALMODE_WAL
6596 && (sqlite3Strlen30(zFilename
)==0 /* Temp file */
6597 || !sqlite3PagerWalSupported(pPager
)) /* No shared-memory support */
6603 && (eOld
==PAGER_JOURNALMODE_WAL
|| eNew
==PAGER_JOURNALMODE_WAL
)
6605 if( !db
->autoCommit
|| db
->nVdbeRead
>1 ){
6608 "cannot change %s wal mode from within a transaction",
6609 (eNew
==PAGER_JOURNALMODE_WAL
? "into" : "out of")
6611 goto abort_due_to_error
;
6614 if( eOld
==PAGER_JOURNALMODE_WAL
){
6615 /* If leaving WAL mode, close the log file. If successful, the call
6616 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
6617 ** file. An EXCLUSIVE lock may still be held on the database file
6618 ** after a successful return.
6620 rc
= sqlite3PagerCloseWal(pPager
, db
);
6621 if( rc
==SQLITE_OK
){
6622 sqlite3PagerSetJournalMode(pPager
, eNew
);
6624 }else if( eOld
==PAGER_JOURNALMODE_MEMORY
){
6625 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
6626 ** as an intermediate */
6627 sqlite3PagerSetJournalMode(pPager
, PAGER_JOURNALMODE_OFF
);
6630 /* Open a transaction on the database file. Regardless of the journal
6631 ** mode, this transaction always uses a rollback journal.
6633 assert( sqlite3BtreeIsInTrans(pBt
)==0 );
6634 if( rc
==SQLITE_OK
){
6635 rc
= sqlite3BtreeSetVersion(pBt
, (eNew
==PAGER_JOURNALMODE_WAL
? 2 : 1));
6639 #endif /* ifndef SQLITE_OMIT_WAL */
6641 if( rc
) eNew
= eOld
;
6642 eNew
= sqlite3PagerSetJournalMode(pPager
, eNew
);
6644 pOut
->flags
= MEM_Str
|MEM_Static
|MEM_Term
;
6645 pOut
->z
= (char *)sqlite3JournalModename(eNew
);
6646 pOut
->n
= sqlite3Strlen30(pOut
->z
);
6647 pOut
->enc
= SQLITE_UTF8
;
6648 sqlite3VdbeChangeEncoding(pOut
, encoding
);
6649 if( rc
) goto abort_due_to_error
;
6652 #endif /* SQLITE_OMIT_PRAGMA */
6654 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
6655 /* Opcode: Vacuum P1 * * * *
6657 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
6658 ** for an attached database. The "temp" database may not be vacuumed.
6661 assert( p
->readOnly
==0 );
6662 rc
= sqlite3RunVacuum(&p
->zErrMsg
, db
, pOp
->p1
);
6663 if( rc
) goto abort_due_to_error
;
6668 #if !defined(SQLITE_OMIT_AUTOVACUUM)
6669 /* Opcode: IncrVacuum P1 P2 * * *
6671 ** Perform a single step of the incremental vacuum procedure on
6672 ** the P1 database. If the vacuum has finished, jump to instruction
6673 ** P2. Otherwise, fall through to the next instruction.
6675 case OP_IncrVacuum
: { /* jump */
6678 assert( pOp
->p1
>=0 && pOp
->p1
<db
->nDb
);
6679 assert( DbMaskTest(p
->btreeMask
, pOp
->p1
) );
6680 assert( p
->readOnly
==0 );
6681 pBt
= db
->aDb
[pOp
->p1
].pBt
;
6682 rc
= sqlite3BtreeIncrVacuum(pBt
);
6683 VdbeBranchTaken(rc
==SQLITE_DONE
,2);
6685 if( rc
!=SQLITE_DONE
) goto abort_due_to_error
;
6693 /* Opcode: Expire P1 * * * *
6695 ** Cause precompiled statements to expire. When an expired statement
6696 ** is executed using sqlite3_step() it will either automatically
6697 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
6698 ** or it will fail with SQLITE_SCHEMA.
6700 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
6701 ** then only the currently executing statement is expired.
6705 sqlite3ExpirePreparedStatements(db
);
6712 #ifndef SQLITE_OMIT_SHARED_CACHE
6713 /* Opcode: TableLock P1 P2 P3 P4 *
6714 ** Synopsis: iDb=P1 root=P2 write=P3
6716 ** Obtain a lock on a particular table. This instruction is only used when
6717 ** the shared-cache feature is enabled.
6719 ** P1 is the index of the database in sqlite3.aDb[] of the database
6720 ** on which the lock is acquired. A readlock is obtained if P3==0 or
6721 ** a write lock if P3==1.
6723 ** P2 contains the root-page of the table to lock.
6725 ** P4 contains a pointer to the name of the table being locked. This is only
6726 ** used to generate an error message if the lock cannot be obtained.
6728 case OP_TableLock
: {
6729 u8 isWriteLock
= (u8
)pOp
->p3
;
6730 if( isWriteLock
|| 0==(db
->flags
&SQLITE_ReadUncommit
) ){
6732 assert( p1
>=0 && p1
<db
->nDb
);
6733 assert( DbMaskTest(p
->btreeMask
, p1
) );
6734 assert( isWriteLock
==0 || isWriteLock
==1 );
6735 rc
= sqlite3BtreeLockTable(db
->aDb
[p1
].pBt
, pOp
->p2
, isWriteLock
);
6737 if( (rc
&0xFF)==SQLITE_LOCKED
){
6738 const char *z
= pOp
->p4
.z
;
6739 sqlite3VdbeError(p
, "database table is locked: %s", z
);
6741 goto abort_due_to_error
;
6746 #endif /* SQLITE_OMIT_SHARED_CACHE */
6748 #ifndef SQLITE_OMIT_VIRTUALTABLE
6749 /* Opcode: VBegin * * * P4 *
6751 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
6752 ** xBegin method for that table.
6754 ** Also, whether or not P4 is set, check that this is not being called from
6755 ** within a callback to a virtual table xSync() method. If it is, the error
6756 ** code will be set to SQLITE_LOCKED.
6760 pVTab
= pOp
->p4
.pVtab
;
6761 rc
= sqlite3VtabBegin(db
, pVTab
);
6762 if( pVTab
) sqlite3VtabImportErrmsg(p
, pVTab
->pVtab
);
6763 if( rc
) goto abort_due_to_error
;
6766 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6768 #ifndef SQLITE_OMIT_VIRTUALTABLE
6769 /* Opcode: VCreate P1 P2 * * *
6771 ** P2 is a register that holds the name of a virtual table in database
6772 ** P1. Call the xCreate method for that table.
6775 Mem sMem
; /* For storing the record being decoded */
6776 const char *zTab
; /* Name of the virtual table */
6778 memset(&sMem
, 0, sizeof(sMem
));
6780 /* Because P2 is always a static string, it is impossible for the
6781 ** sqlite3VdbeMemCopy() to fail */
6782 assert( (aMem
[pOp
->p2
].flags
& MEM_Str
)!=0 );
6783 assert( (aMem
[pOp
->p2
].flags
& MEM_Static
)!=0 );
6784 rc
= sqlite3VdbeMemCopy(&sMem
, &aMem
[pOp
->p2
]);
6785 assert( rc
==SQLITE_OK
);
6786 zTab
= (const char*)sqlite3_value_text(&sMem
);
6787 assert( zTab
|| db
->mallocFailed
);
6789 rc
= sqlite3VtabCallCreate(db
, pOp
->p1
, zTab
, &p
->zErrMsg
);
6791 sqlite3VdbeMemRelease(&sMem
);
6792 if( rc
) goto abort_due_to_error
;
6795 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6797 #ifndef SQLITE_OMIT_VIRTUALTABLE
6798 /* Opcode: VDestroy P1 * * P4 *
6800 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
6805 rc
= sqlite3VtabCallDestroy(db
, pOp
->p1
, pOp
->p4
.z
);
6807 if( rc
) goto abort_due_to_error
;
6810 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6812 #ifndef SQLITE_OMIT_VIRTUALTABLE
6813 /* Opcode: VOpen P1 * * P4 *
6815 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6816 ** P1 is a cursor number. This opcode opens a cursor to the virtual
6817 ** table and stores that cursor in P1.
6821 sqlite3_vtab_cursor
*pVCur
;
6822 sqlite3_vtab
*pVtab
;
6823 const sqlite3_module
*pModule
;
6825 assert( p
->bIsReader
);
6828 pVtab
= pOp
->p4
.pVtab
->pVtab
;
6829 if( pVtab
==0 || NEVER(pVtab
->pModule
==0) ){
6831 goto abort_due_to_error
;
6833 pModule
= pVtab
->pModule
;
6834 rc
= pModule
->xOpen(pVtab
, &pVCur
);
6835 sqlite3VtabImportErrmsg(p
, pVtab
);
6836 if( rc
) goto abort_due_to_error
;
6838 /* Initialize sqlite3_vtab_cursor base class */
6839 pVCur
->pVtab
= pVtab
;
6841 /* Initialize vdbe cursor object */
6842 pCur
= allocateCursor(p
, pOp
->p1
, 0, -1, CURTYPE_VTAB
);
6844 pCur
->uc
.pVCur
= pVCur
;
6847 assert( db
->mallocFailed
);
6848 pModule
->xClose(pVCur
);
6853 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6855 #ifndef SQLITE_OMIT_VIRTUALTABLE
6856 /* Opcode: VFilter P1 P2 P3 P4 *
6857 ** Synopsis: iplan=r[P3] zplan='P4'
6859 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
6860 ** the filtered result set is empty.
6862 ** P4 is either NULL or a string that was generated by the xBestIndex
6863 ** method of the module. The interpretation of the P4 string is left
6864 ** to the module implementation.
6866 ** This opcode invokes the xFilter method on the virtual table specified
6867 ** by P1. The integer query plan parameter to xFilter is stored in register
6868 ** P3. Register P3+1 stores the argc parameter to be passed to the
6869 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6870 ** additional parameters which are passed to
6871 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6873 ** A jump is made to P2 if the result set after filtering would be empty.
6875 case OP_VFilter
: { /* jump */
6878 const sqlite3_module
*pModule
;
6881 sqlite3_vtab_cursor
*pVCur
;
6882 sqlite3_vtab
*pVtab
;
6888 pQuery
= &aMem
[pOp
->p3
];
6890 pCur
= p
->apCsr
[pOp
->p1
];
6891 assert( memIsValid(pQuery
) );
6892 REGISTER_TRACE(pOp
->p3
, pQuery
);
6893 assert( pCur
->eCurType
==CURTYPE_VTAB
);
6894 pVCur
= pCur
->uc
.pVCur
;
6895 pVtab
= pVCur
->pVtab
;
6896 pModule
= pVtab
->pModule
;
6898 /* Grab the index number and argc parameters */
6899 assert( (pQuery
->flags
&MEM_Int
)!=0 && pArgc
->flags
==MEM_Int
);
6900 nArg
= (int)pArgc
->u
.i
;
6901 iQuery
= (int)pQuery
->u
.i
;
6903 /* Invoke the xFilter method */
6906 for(i
= 0; i
<nArg
; i
++){
6907 apArg
[i
] = &pArgc
[i
+1];
6909 rc
= pModule
->xFilter(pVCur
, iQuery
, pOp
->p4
.z
, nArg
, apArg
);
6910 sqlite3VtabImportErrmsg(p
, pVtab
);
6911 if( rc
) goto abort_due_to_error
;
6912 res
= pModule
->xEof(pVCur
);
6914 VdbeBranchTaken(res
!=0,2);
6915 if( res
) goto jump_to_p2
;
6918 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6920 #ifndef SQLITE_OMIT_VIRTUALTABLE
6921 /* Opcode: VColumn P1 P2 P3 * P5
6922 ** Synopsis: r[P3]=vcolumn(P2)
6924 ** Store in register P3 the value of the P2-th column of
6925 ** the current row of the virtual-table of cursor P1.
6927 ** If the VColumn opcode is being used to fetch the value of
6928 ** an unchanging column during an UPDATE operation, then the P5
6929 ** value is 1. Otherwise, P5 is 0. The P5 value is returned
6930 ** by sqlite3_vtab_nochange() routine and can be used
6931 ** by virtual table implementations to return special "no-change"
6932 ** marks which can be more efficient, depending on the virtual table.
6935 sqlite3_vtab
*pVtab
;
6936 const sqlite3_module
*pModule
;
6938 sqlite3_context sContext
;
6940 VdbeCursor
*pCur
= p
->apCsr
[pOp
->p1
];
6941 assert( pCur
->eCurType
==CURTYPE_VTAB
);
6942 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
6943 pDest
= &aMem
[pOp
->p3
];
6944 memAboutToChange(p
, pDest
);
6945 if( pCur
->nullRow
){
6946 sqlite3VdbeMemSetNull(pDest
);
6949 pVtab
= pCur
->uc
.pVCur
->pVtab
;
6950 pModule
= pVtab
->pModule
;
6951 assert( pModule
->xColumn
);
6952 memset(&sContext
, 0, sizeof(sContext
));
6953 sContext
.pOut
= pDest
;
6955 sqlite3VdbeMemSetNull(pDest
);
6956 pDest
->flags
= MEM_Null
|MEM_Zero
;
6959 MemSetTypeFlag(pDest
, MEM_Null
);
6961 rc
= pModule
->xColumn(pCur
->uc
.pVCur
, &sContext
, pOp
->p2
);
6962 sqlite3VtabImportErrmsg(p
, pVtab
);
6963 if( sContext
.isError
>0 ){
6964 sqlite3VdbeError(p
, "%s", sqlite3_value_text(pDest
));
6965 rc
= sContext
.isError
;
6967 sqlite3VdbeChangeEncoding(pDest
, encoding
);
6968 REGISTER_TRACE(pOp
->p3
, pDest
);
6969 UPDATE_MAX_BLOBSIZE(pDest
);
6971 if( sqlite3VdbeMemTooBig(pDest
) ){
6974 if( rc
) goto abort_due_to_error
;
6977 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6979 #ifndef SQLITE_OMIT_VIRTUALTABLE
6980 /* Opcode: VNext P1 P2 * * *
6982 ** Advance virtual table P1 to the next row in its result set and
6983 ** jump to instruction P2. Or, if the virtual table has reached
6984 ** the end of its result set, then fall through to the next instruction.
6986 case OP_VNext
: { /* jump */
6987 sqlite3_vtab
*pVtab
;
6988 const sqlite3_module
*pModule
;
6993 pCur
= p
->apCsr
[pOp
->p1
];
6994 assert( pCur
->eCurType
==CURTYPE_VTAB
);
6995 if( pCur
->nullRow
){
6998 pVtab
= pCur
->uc
.pVCur
->pVtab
;
6999 pModule
= pVtab
->pModule
;
7000 assert( pModule
->xNext
);
7002 /* Invoke the xNext() method of the module. There is no way for the
7003 ** underlying implementation to return an error if one occurs during
7004 ** xNext(). Instead, if an error occurs, true is returned (indicating that
7005 ** data is available) and the error code returned when xColumn or
7006 ** some other method is next invoked on the save virtual table cursor.
7008 rc
= pModule
->xNext(pCur
->uc
.pVCur
);
7009 sqlite3VtabImportErrmsg(p
, pVtab
);
7010 if( rc
) goto abort_due_to_error
;
7011 res
= pModule
->xEof(pCur
->uc
.pVCur
);
7012 VdbeBranchTaken(!res
,2);
7014 /* If there is data, jump to P2 */
7015 goto jump_to_p2_and_check_for_interrupt
;
7017 goto check_for_interrupt
;
7019 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7021 #ifndef SQLITE_OMIT_VIRTUALTABLE
7022 /* Opcode: VRename P1 * * P4 *
7024 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7025 ** This opcode invokes the corresponding xRename method. The value
7026 ** in register P1 is passed as the zName argument to the xRename method.
7029 sqlite3_vtab
*pVtab
;
7032 pVtab
= pOp
->p4
.pVtab
->pVtab
;
7033 pName
= &aMem
[pOp
->p1
];
7034 assert( pVtab
->pModule
->xRename
);
7035 assert( memIsValid(pName
) );
7036 assert( p
->readOnly
==0 );
7037 REGISTER_TRACE(pOp
->p1
, pName
);
7038 assert( pName
->flags
& MEM_Str
);
7039 testcase( pName
->enc
==SQLITE_UTF8
);
7040 testcase( pName
->enc
==SQLITE_UTF16BE
);
7041 testcase( pName
->enc
==SQLITE_UTF16LE
);
7042 rc
= sqlite3VdbeChangeEncoding(pName
, SQLITE_UTF8
);
7043 if( rc
) goto abort_due_to_error
;
7044 rc
= pVtab
->pModule
->xRename(pVtab
, pName
->z
);
7045 sqlite3VtabImportErrmsg(p
, pVtab
);
7047 if( rc
) goto abort_due_to_error
;
7052 #ifndef SQLITE_OMIT_VIRTUALTABLE
7053 /* Opcode: VUpdate P1 P2 P3 P4 P5
7054 ** Synopsis: data=r[P3@P2]
7056 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7057 ** This opcode invokes the corresponding xUpdate method. P2 values
7058 ** are contiguous memory cells starting at P3 to pass to the xUpdate
7059 ** invocation. The value in register (P3+P2-1) corresponds to the
7060 ** p2th element of the argv array passed to xUpdate.
7062 ** The xUpdate method will do a DELETE or an INSERT or both.
7063 ** The argv[0] element (which corresponds to memory cell P3)
7064 ** is the rowid of a row to delete. If argv[0] is NULL then no
7065 ** deletion occurs. The argv[1] element is the rowid of the new
7066 ** row. This can be NULL to have the virtual table select the new
7067 ** rowid for itself. The subsequent elements in the array are
7068 ** the values of columns in the new row.
7070 ** If P2==1 then no insert is performed. argv[0] is the rowid of
7073 ** P1 is a boolean flag. If it is set to true and the xUpdate call
7074 ** is successful, then the value returned by sqlite3_last_insert_rowid()
7075 ** is set to the value of the rowid for the row just inserted.
7077 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
7078 ** apply in the case of a constraint failure on an insert or update.
7081 sqlite3_vtab
*pVtab
;
7082 const sqlite3_module
*pModule
;
7089 assert( pOp
->p2
==1 || pOp
->p5
==OE_Fail
|| pOp
->p5
==OE_Rollback
7090 || pOp
->p5
==OE_Abort
|| pOp
->p5
==OE_Ignore
|| pOp
->p5
==OE_Replace
7092 assert( p
->readOnly
==0 );
7093 if( db
->mallocFailed
) goto no_mem
;
7094 sqlite3VdbeIncrWriteCounter(p
, 0);
7095 pVtab
= pOp
->p4
.pVtab
->pVtab
;
7096 if( pVtab
==0 || NEVER(pVtab
->pModule
==0) ){
7098 goto abort_due_to_error
;
7100 pModule
= pVtab
->pModule
;
7102 assert( pOp
->p4type
==P4_VTAB
);
7103 if( ALWAYS(pModule
->xUpdate
) ){
7104 u8 vtabOnConflict
= db
->vtabOnConflict
;
7106 pX
= &aMem
[pOp
->p3
];
7107 for(i
=0; i
<nArg
; i
++){
7108 assert( memIsValid(pX
) );
7109 memAboutToChange(p
, pX
);
7113 db
->vtabOnConflict
= pOp
->p5
;
7114 rc
= pModule
->xUpdate(pVtab
, nArg
, apArg
, &rowid
);
7115 db
->vtabOnConflict
= vtabOnConflict
;
7116 sqlite3VtabImportErrmsg(p
, pVtab
);
7117 if( rc
==SQLITE_OK
&& pOp
->p1
){
7118 assert( nArg
>1 && apArg
[0] && (apArg
[0]->flags
&MEM_Null
) );
7119 db
->lastRowid
= rowid
;
7121 if( (rc
&0xff)==SQLITE_CONSTRAINT
&& pOp
->p4
.pVtab
->bConstraint
){
7122 if( pOp
->p5
==OE_Ignore
){
7125 p
->errorAction
= ((pOp
->p5
==OE_Replace
) ? OE_Abort
: pOp
->p5
);
7130 if( rc
) goto abort_due_to_error
;
7134 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7136 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7137 /* Opcode: Pagecount P1 P2 * * *
7139 ** Write the current number of pages in database P1 to memory cell P2.
7141 case OP_Pagecount
: { /* out2 */
7142 pOut
= out2Prerelease(p
, pOp
);
7143 pOut
->u
.i
= sqlite3BtreeLastPage(db
->aDb
[pOp
->p1
].pBt
);
7149 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7150 /* Opcode: MaxPgcnt P1 P2 P3 * *
7152 ** Try to set the maximum page count for database P1 to the value in P3.
7153 ** Do not let the maximum page count fall below the current page count and
7154 ** do not change the maximum page count value if P3==0.
7156 ** Store the maximum page count after the change in register P2.
7158 case OP_MaxPgcnt
: { /* out2 */
7159 unsigned int newMax
;
7162 pOut
= out2Prerelease(p
, pOp
);
7163 pBt
= db
->aDb
[pOp
->p1
].pBt
;
7166 newMax
= sqlite3BtreeLastPage(pBt
);
7167 if( newMax
< (unsigned)pOp
->p3
) newMax
= (unsigned)pOp
->p3
;
7169 pOut
->u
.i
= sqlite3BtreeMaxPageCount(pBt
, newMax
);
7174 /* Opcode: Function0 P1 P2 P3 P4 P5
7175 ** Synopsis: r[P3]=func(r[P2@P5])
7177 ** Invoke a user function (P4 is a pointer to a FuncDef object that
7178 ** defines the function) with P5 arguments taken from register P2 and
7179 ** successors. The result of the function is stored in register P3.
7180 ** Register P3 must not be one of the function inputs.
7182 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7183 ** function was determined to be constant at compile time. If the first
7184 ** argument was constant then bit 0 of P1 is set. This is used to determine
7185 ** whether meta data associated with a user function argument using the
7186 ** sqlite3_set_auxdata() API may be safely retained until the next
7187 ** invocation of this opcode.
7189 ** See also: Function, AggStep, AggFinal
7191 /* Opcode: Function P1 P2 P3 P4 P5
7192 ** Synopsis: r[P3]=func(r[P2@P5])
7194 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7195 ** contains a pointer to the function to be run) with P5 arguments taken
7196 ** from register P2 and successors. The result of the function is stored
7197 ** in register P3. Register P3 must not be one of the function inputs.
7199 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7200 ** function was determined to be constant at compile time. If the first
7201 ** argument was constant then bit 0 of P1 is set. This is used to determine
7202 ** whether meta data associated with a user function argument using the
7203 ** sqlite3_set_auxdata() API may be safely retained until the next
7204 ** invocation of this opcode.
7206 ** SQL functions are initially coded as OP_Function0 with P4 pointing
7207 ** to a FuncDef object. But on first evaluation, the P4 operand is
7208 ** automatically converted into an sqlite3_context object and the operation
7209 ** changed to this OP_Function opcode. In this way, the initialization of
7210 ** the sqlite3_context object occurs only once, rather than once for each
7211 ** evaluation of the function.
7213 ** See also: Function0, AggStep, AggFinal
7216 case OP_Function0
: {
7218 sqlite3_context
*pCtx
;
7220 assert( pOp
->p4type
==P4_FUNCDEF
);
7222 assert( pOp
->p3
>0 && pOp
->p3
<=(p
->nMem
+1 - p
->nCursor
) );
7223 assert( n
==0 || (pOp
->p2
>0 && pOp
->p2
+n
<=(p
->nMem
+1 - p
->nCursor
)+1) );
7224 assert( pOp
->p3
<pOp
->p2
|| pOp
->p3
>=pOp
->p2
+n
);
7225 pCtx
= sqlite3DbMallocRawNN(db
, sizeof(*pCtx
) + (n
-1)*sizeof(sqlite3_value
*));
7226 if( pCtx
==0 ) goto no_mem
;
7228 pCtx
->pFunc
= pOp
->p4
.pFunc
;
7229 pCtx
->iOp
= (int)(pOp
- aOp
);
7233 pOp
->p4type
= P4_FUNCCTX
;
7234 pOp
->p4
.pCtx
= pCtx
;
7235 assert( OP_PureFunc
== OP_PureFunc0
+2 );
7236 assert( OP_Function
== OP_Function0
+2 );
7238 /* Fall through into OP_Function */
7243 sqlite3_context
*pCtx
;
7245 assert( pOp
->p4type
==P4_FUNCCTX
);
7246 pCtx
= pOp
->p4
.pCtx
;
7248 /* If this function is inside of a trigger, the register array in aMem[]
7249 ** might change from one evaluation to the next. The next block of code
7250 ** checks to see if the register array has changed, and if so it
7251 ** reinitializes the relavant parts of the sqlite3_context object */
7252 pOut
= &aMem
[pOp
->p3
];
7253 if( pCtx
->pOut
!= pOut
){
7255 for(i
=pCtx
->argc
-1; i
>=0; i
--) pCtx
->argv
[i
] = &aMem
[pOp
->p2
+i
];
7258 memAboutToChange(p
, pOut
);
7260 for(i
=0; i
<pCtx
->argc
; i
++){
7261 assert( memIsValid(pCtx
->argv
[i
]) );
7262 REGISTER_TRACE(pOp
->p2
+i
, pCtx
->argv
[i
]);
7265 MemSetTypeFlag(pOut
, MEM_Null
);
7266 assert( pCtx
->isError
==0 );
7267 (*pCtx
->pFunc
->xSFunc
)(pCtx
, pCtx
->argc
, pCtx
->argv
);/* IMP: R-24505-23230 */
7269 /* If the function returned an error, throw an exception */
7270 if( pCtx
->isError
){
7271 if( pCtx
->isError
>0 ){
7272 sqlite3VdbeError(p
, "%s", sqlite3_value_text(pOut
));
7275 sqlite3VdbeDeleteAuxData(db
, &p
->pAuxData
, pCtx
->iOp
, pOp
->p1
);
7277 if( rc
) goto abort_due_to_error
;
7280 /* Copy the result of the function into register P3 */
7281 if( pOut
->flags
& (MEM_Str
|MEM_Blob
) ){
7282 sqlite3VdbeChangeEncoding(pOut
, encoding
);
7283 if( sqlite3VdbeMemTooBig(pOut
) ) goto too_big
;
7286 REGISTER_TRACE(pOp
->p3
, pOut
);
7287 UPDATE_MAX_BLOBSIZE(pOut
);
7291 /* Opcode: Trace P1 P2 * P4 *
7293 ** Write P4 on the statement trace output if statement tracing is
7296 ** Operand P1 must be 0x7fffffff and P2 must positive.
7298 /* Opcode: Init P1 P2 P3 P4 *
7299 ** Synopsis: Start at P2
7301 ** Programs contain a single instance of this opcode as the very first
7304 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7305 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7306 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7308 ** If P2 is not zero, jump to instruction P2.
7310 ** Increment the value of P1 so that OP_Once opcodes will jump the
7311 ** first time they are evaluated for this run.
7313 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7314 ** error is encountered.
7317 case OP_Init
: { /* jump */
7319 #ifndef SQLITE_OMIT_TRACE
7323 /* If the P4 argument is not NULL, then it must be an SQL comment string.
7324 ** The "--" string is broken up to prevent false-positives with srcck1.c.
7326 ** This assert() provides evidence for:
7327 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7328 ** would have been returned by the legacy sqlite3_trace() interface by
7329 ** using the X argument when X begins with "--" and invoking
7330 ** sqlite3_expanded_sql(P) otherwise.
7332 assert( pOp
->p4
.z
==0 || strncmp(pOp
->p4
.z
, "-" "- ", 3)==0 );
7334 /* OP_Init is always instruction 0 */
7335 assert( pOp
==p
->aOp
|| pOp
->opcode
==OP_Trace
);
7337 #ifndef SQLITE_OMIT_TRACE
7338 if( (db
->mTrace
& (SQLITE_TRACE_STMT
|SQLITE_TRACE_LEGACY
))!=0
7340 && (zTrace
= (pOp
->p4
.z
? pOp
->p4
.z
: p
->zSql
))!=0
7342 #ifndef SQLITE_OMIT_DEPRECATED
7343 if( db
->mTrace
& SQLITE_TRACE_LEGACY
){
7344 void (*x
)(void*,const char*) = (void(*)(void*,const char*))db
->xTrace
;
7345 char *z
= sqlite3VdbeExpandSql(p
, zTrace
);
7346 x(db
->pTraceArg
, z
);
7350 if( db
->nVdbeExec
>1 ){
7351 char *z
= sqlite3MPrintf(db
, "-- %s", zTrace
);
7352 (void)db
->xTrace(SQLITE_TRACE_STMT
, db
->pTraceArg
, p
, z
);
7353 sqlite3DbFree(db
, z
);
7355 (void)db
->xTrace(SQLITE_TRACE_STMT
, db
->pTraceArg
, p
, zTrace
);
7358 #ifdef SQLITE_USE_FCNTL_TRACE
7359 zTrace
= (pOp
->p4
.z
? pOp
->p4
.z
: p
->zSql
);
7362 for(j
=0; j
<db
->nDb
; j
++){
7363 if( DbMaskTest(p
->btreeMask
, j
)==0 ) continue;
7364 sqlite3_file_control(db
, db
->aDb
[j
].zDbSName
, SQLITE_FCNTL_TRACE
, zTrace
);
7367 #endif /* SQLITE_USE_FCNTL_TRACE */
7369 if( (db
->flags
& SQLITE_SqlTrace
)!=0
7370 && (zTrace
= (pOp
->p4
.z
? pOp
->p4
.z
: p
->zSql
))!=0
7372 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace
);
7374 #endif /* SQLITE_DEBUG */
7375 #endif /* SQLITE_OMIT_TRACE */
7376 assert( pOp
->p2
>0 );
7377 if( pOp
->p1
>=sqlite3GlobalConfig
.iOnceResetThreshold
){
7378 if( pOp
->opcode
==OP_Trace
) break;
7379 for(i
=1; i
<p
->nOp
; i
++){
7380 if( p
->aOp
[i
].opcode
==OP_Once
) p
->aOp
[i
].p1
= 0;
7385 p
->aCounter
[SQLITE_STMTSTATUS_RUN
]++;
7389 #ifdef SQLITE_ENABLE_CURSOR_HINTS
7390 /* Opcode: CursorHint P1 * * P4 *
7392 ** Provide a hint to cursor P1 that it only needs to return rows that
7393 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
7394 ** to values currently held in registers. TK_COLUMN terms in the P4
7395 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
7397 case OP_CursorHint
: {
7400 assert( pOp
->p1
>=0 && pOp
->p1
<p
->nCursor
);
7401 assert( pOp
->p4type
==P4_EXPR
);
7402 pC
= p
->apCsr
[pOp
->p1
];
7404 assert( pC
->eCurType
==CURTYPE_BTREE
);
7405 sqlite3BtreeCursorHint(pC
->uc
.pCursor
, BTREE_HINT_RANGE
,
7406 pOp
->p4
.pExpr
, aMem
);
7410 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
7413 /* Opcode: Abortable * * * * *
7415 ** Verify that an Abort can happen. Assert if an Abort at this point
7416 ** might cause database corruption. This opcode only appears in debugging
7419 ** An Abort is safe if either there have been no writes, or if there is
7420 ** an active statement journal.
7422 case OP_Abortable
: {
7423 sqlite3VdbeAssertAbortable(p
);
7428 #ifdef SQLITE_DEBUG_COLUMNCACHE
7429 /* Opcode: SetTabCol P1 P2 P3 * *
7431 ** Set a flag in register REG[P3] indicating that it holds the value
7432 ** of column P2 from the table on cursor P1. This flag is checked
7433 ** by a subsequent VerifyTabCol opcode.
7435 ** This opcode only appears SQLITE_DEBUG builds. It is used to verify
7436 ** that the expression table column cache is working correctly.
7438 case OP_SetTabCol
: {
7439 aMem
[pOp
->p3
].iTabColHash
= TableColumnHash(pOp
->p1
,pOp
->p2
);
7442 /* Opcode: VerifyTabCol P1 P2 P3 * *
7444 ** Verify that register REG[P3] contains the value of column P2 from
7445 ** cursor P1. Assert() if this is not the case.
7447 ** This opcode only appears SQLITE_DEBUG builds. It is used to verify
7448 ** that the expression table column cache is working correctly.
7450 case OP_VerifyTabCol
: {
7451 assert( aMem
[pOp
->p3
].iTabColHash
== TableColumnHash(pOp
->p1
,pOp
->p2
) );
7456 /* Opcode: Noop * * * * *
7458 ** Do nothing. This instruction is often useful as a jump
7462 ** The magic Explain opcode are only inserted when explain==2 (which
7463 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
7464 ** This opcode records information from the optimizer. It is the
7465 ** the same as a no-op. This opcodesnever appears in a real VM program.
7467 default: { /* This is really OP_Noop, OP_Explain */
7468 assert( pOp
->opcode
==OP_Noop
|| pOp
->opcode
==OP_Explain
);
7473 /*****************************************************************************
7474 ** The cases of the switch statement above this line should all be indented
7475 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
7476 ** readability. From this point on down, the normal indentation rules are
7478 *****************************************************************************/
7483 u64 endTime
= sqlite3NProfileCnt
? sqlite3NProfileCnt
: sqlite3Hwtime();
7484 if( endTime
>start
) pOrigOp
->cycles
+= endTime
- start
;
7489 /* The following code adds nothing to the actual functionality
7490 ** of the program. It is only here for testing and debugging.
7491 ** On the other hand, it does burn CPU cycles every time through
7492 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
7495 assert( pOp
>=&aOp
[-1] && pOp
<&aOp
[p
->nOp
-1] );
7498 if( db
->flags
& SQLITE_VdbeTrace
){
7499 u8 opProperty
= sqlite3OpcodeProperty
[pOrigOp
->opcode
];
7500 if( rc
!=0 ) printf("rc=%d\n",rc
);
7501 if( opProperty
& (OPFLG_OUT2
) ){
7502 registerTrace(pOrigOp
->p2
, &aMem
[pOrigOp
->p2
]);
7504 if( opProperty
& OPFLG_OUT3
){
7505 registerTrace(pOrigOp
->p3
, &aMem
[pOrigOp
->p3
]);
7508 #endif /* SQLITE_DEBUG */
7510 } /* The end of the for(;;) loop the loops through opcodes */
7512 /* If we reach this point, it means that execution is finished with
7513 ** an error of some kind.
7516 if( db
->mallocFailed
) rc
= SQLITE_NOMEM_BKPT
;
7518 if( p
->zErrMsg
==0 && rc
!=SQLITE_IOERR_NOMEM
){
7519 sqlite3VdbeError(p
, "%s", sqlite3ErrStr(rc
));
7522 sqlite3SystemError(db
, rc
);
7523 testcase( sqlite3GlobalConfig
.xLog
!=0 );
7524 sqlite3_log(rc
, "statement aborts at %d: [%s] %s",
7525 (int)(pOp
- aOp
), p
->zSql
, p
->zErrMsg
);
7527 if( rc
==SQLITE_IOERR_NOMEM
) sqlite3OomFault(db
);
7529 if( resetSchemaOnFault
>0 ){
7530 sqlite3ResetOneSchema(db
, resetSchemaOnFault
-1);
7533 /* This is the only way out of this procedure. We have to
7534 ** release the mutexes on btrees that were acquired at the
7537 testcase( nVmStep
>0 );
7538 p
->aCounter
[SQLITE_STMTSTATUS_VM_STEP
] += (int)nVmStep
;
7539 sqlite3VdbeLeave(p
);
7540 assert( rc
!=SQLITE_OK
|| nExtraDelete
==0
7541 || sqlite3_strlike("DELETE%",p
->zSql
,0)!=0
7545 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
7549 sqlite3VdbeError(p
, "string or blob too big");
7551 goto abort_due_to_error
;
7553 /* Jump to here if a malloc() fails.
7556 sqlite3OomFault(db
);
7557 sqlite3VdbeError(p
, "out of memory");
7558 rc
= SQLITE_NOMEM_BKPT
;
7559 goto abort_due_to_error
;
7561 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
7564 abort_due_to_interrupt
:
7565 assert( db
->u1
.isInterrupted
);
7566 rc
= db
->mallocFailed
? SQLITE_NOMEM_BKPT
: SQLITE_INTERRUPT
;
7568 sqlite3VdbeError(p
, "%s", sqlite3ErrStr(rc
));
7569 goto abort_due_to_error
;