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 ** This file contains code used for creating, destroying, and populating
13 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
14 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
15 ** But that file was getting too big so this subroutines were split out.
17 #include "sqliteInt.h"
24 ** When debugging the code generator in a symbolic debugger, one can
25 ** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
26 ** as they are added to the instruction stream.
29 int sqlite3_vdbe_addop_trace = 0;
34 ** Create a new virtual database engine.
36 Vdbe *sqlite3VdbeCreate(sqlite3 *db){
38 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
47 p->magic = VDBE_MAGIC_INIT;
52 ** Remember the SQL string for a prepared statement.
54 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
57 p->zSql = sqlite3DbStrNDup(p->db, z, n);
61 ** Return the SQL associated with a prepared statement
63 const char *sqlite3VdbeGetSql(Vdbe *p){
68 ** Swap all content between two VDBE structures.
70 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
78 pA->pNext = pB->pNext;
81 pA->pPrev = pB->pPrev;
93 ** Turn tracing on or off
95 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
101 ** Resize the Vdbe.aOp array so that it contains at least N
102 ** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
103 ** the Vdbe.aOp array will be sized to contain exactly N
104 ** elements. Vdbe.nOpAlloc is set to reflect the new size of
107 ** If an out-of-memory error occurs while resizing the array,
108 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
109 ** any opcodes already allocated can be correctly deallocated
110 ** along with the rest of the Vdbe).
112 static void resizeOpArray(Vdbe *p, int N){
113 int runMode = p->magic==VDBE_MAGIC_RUN;
114 if( runMode || p->nOpAlloc<N ){
116 int nNew = N + 100*(!runMode);
117 int oldSize = p->nOpAlloc;
118 pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
123 memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
130 ** Add a new instruction to the list of instructions current in the
131 ** VDBE. Return the address of the new instruction.
135 ** p Pointer to the VDBE
137 ** op The opcode for this instruction
139 ** p1, p2 First two of the three possible operands.
141 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
142 ** the sqlite3VdbeChangeP3() function to change the value of the P3
145 int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
150 assert( p->magic==VDBE_MAGIC_INIT );
151 if( p->nOpAlloc<=i ){
152 resizeOpArray(p, i+1);
153 if( p->db->mallocFailed ){
163 pOp->p3type = P3_NOTUSED;
166 if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
172 ** Add an opcode that includes the p3 value.
174 int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
175 int addr = sqlite3VdbeAddOp(p, op, p1, p2);
176 sqlite3VdbeChangeP3(p, addr, zP3, p3type);
181 ** Create a new symbolic label for an instruction that has yet to be
182 ** coded. The symbolic label is really just a negative number. The
183 ** label can be used as the P2 value of an operation. Later, when
184 ** the label is resolved to a specific address, the VDBE will scan
185 ** through its operation list and change all values of P2 which match
186 ** the label into the resolved address.
188 ** The VDBE knows that a P2 value is a label because labels are
189 ** always negative and P2 values are suppose to be non-negative.
190 ** Hence, a negative P2 value is a label that has yet to be resolved.
192 ** Zero is returned if a malloc() fails.
194 int sqlite3VdbeMakeLabel(Vdbe *p){
197 assert( p->magic==VDBE_MAGIC_INIT );
198 if( i>=p->nLabelAlloc ){
199 p->nLabelAlloc = p->nLabelAlloc*2 + 10;
200 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
201 p->nLabelAlloc*sizeof(p->aLabel[0]));
210 ** Resolve label "x" to be the address of the next instruction to
211 ** be inserted. The parameter "x" must have been obtained from
212 ** a prior call to sqlite3VdbeMakeLabel().
214 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
216 assert( p->magic==VDBE_MAGIC_INIT );
217 assert( j>=0 && j<p->nLabel );
219 p->aLabel[j] = p->nOp;
224 ** Return non-zero if opcode 'op' is guarenteed not to push more values
225 ** onto the VDBE stack than it pops off.
227 static int opcodeNoPush(u8 op){
228 /* The 10 NOPUSH_MASK_n constants are defined in the automatically
229 ** generated header file opcodes.h. Each is a 16-bit bitmask, one
230 ** bit corresponding to each opcode implemented by the virtual
231 ** machine in vdbe.c. The bit is true if the word "no-push" appears
232 ** in a comment on the same line as the "case OP_XXX:" in
233 ** sqlite3VdbeExec() in vdbe.c.
235 ** If the bit is true, then the corresponding opcode is guarenteed not
236 ** to grow the stack when it is executed. Otherwise, it may grow the
237 ** stack by at most one entry.
239 ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
240 ** one bit for opcodes 16 to 31, and so on.
242 ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
243 ** because the file is generated by an awk program. Awk manipulates
244 ** all numbers as floating-point and we don't want to risk a rounding
245 ** error if someone builds with an awk that uses (for example) 32-bit
248 static const u32 masks[5] = {
249 NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
250 NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
251 NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
252 NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
253 NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
256 return (masks[op>>5] & (1<<(op&0x1F)));
260 int sqlite3VdbeOpcodeNoPush(u8 op){
261 return opcodeNoPush(op);
266 ** Loop through the program looking for P2 values that are negative.
267 ** Each such value is a label. Resolve the label by setting the P2
268 ** value to its correct non-zero value.
270 ** This routine is called once after all opcodes have been inserted.
272 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
273 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
274 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
276 ** The integer *pMaxStack is set to the maximum number of vdbe stack
277 ** entries that static analysis reveals this program might need.
279 ** This routine also does the following optimization: It scans for
280 ** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
281 ** IdxInsert instructions where P2!=0. If no such instruction is
282 ** found, then every Statement instruction is changed to a Noop. In
283 ** this way, we avoid creating the statement journal file unnecessarily.
285 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
288 int nMaxStack = p->nOp;
290 int *aLabel = p->aLabel;
291 int doesStatementRollback = 0;
292 int hasStatementBegin = 0;
293 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
294 u8 opcode = pOp->opcode;
296 if( opcode==OP_Function || opcode==OP_AggStep
297 #ifndef SQLITE_OMIT_VIRTUALTABLE
298 || opcode==OP_VUpdate
301 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
303 if( opcode==OP_Halt ){
304 if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
305 doesStatementRollback = 1;
307 }else if( opcode==OP_Statement ){
308 hasStatementBegin = 1;
309 #ifndef SQLITE_OMIT_VIRTUALTABLE
310 }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
311 doesStatementRollback = 1;
312 }else if( opcode==OP_VFilter ){
314 assert( p->nOp - i >= 3 );
315 assert( pOp[-2].opcode==OP_Integer );
317 if( n>nMaxArgs ) nMaxArgs = n;
320 if( opcodeNoPush(opcode) ){
324 if( pOp->p2>=0 ) continue;
325 assert( -1-pOp->p2<p->nLabel );
326 pOp->p2 = aLabel[-1-pOp->p2];
328 sqlite3_free(p->aLabel);
331 *pMaxFuncArgs = nMaxArgs;
332 *pMaxStack = nMaxStack;
334 /* If we never rollback a statement transaction, then statement
335 ** transactions are not needed. So change every OP_Statement
336 ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
337 ** which can be expensive on some platforms.
339 if( hasStatementBegin && !doesStatementRollback ){
340 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
341 if( pOp->opcode==OP_Statement ){
342 pOp->opcode = OP_Noop;
349 ** Return the address of the next instruction to be inserted.
351 int sqlite3VdbeCurrentAddr(Vdbe *p){
352 assert( p->magic==VDBE_MAGIC_INIT );
357 ** Add a whole list of operations to the operation stack. Return the
358 ** address of the first operation added.
360 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
362 assert( p->magic==VDBE_MAGIC_INIT );
363 resizeOpArray(p, p->nOp + nOp);
364 if( p->db->mallocFailed ){
370 VdbeOpList const *pIn = aOp;
371 for(i=0; i<nOp; i++, pIn++){
373 VdbeOp *pOut = &p->aOp[i+addr];
374 pOut->opcode = pIn->opcode;
376 pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
378 pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
380 if( sqlite3_vdbe_addop_trace ){
381 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
391 ** Change the value of the P1 operand for a specific instruction.
392 ** This routine is useful when a large program is loaded from a
393 ** static array using sqlite3VdbeAddOpList but we want to make a
394 ** few minor changes to the program.
396 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
397 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
398 if( p && addr>=0 && p->nOp>addr && p->aOp ){
399 p->aOp[addr].p1 = val;
404 ** Change the value of the P2 operand for a specific instruction.
405 ** This routine is useful for setting a jump destination.
407 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
409 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
410 if( p && addr>=0 && p->nOp>addr && p->aOp ){
411 p->aOp[addr].p2 = val;
416 ** Change the P2 operand of instruction addr so that it points to
417 ** the address of the next instruction to be coded.
419 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
420 sqlite3VdbeChangeP2(p, addr, p->nOp);
425 ** If the input FuncDef structure is ephemeral, then free it. If
426 ** the FuncDef is not ephermal, then do nothing.
428 static void freeEphemeralFunction(FuncDef *pDef){
429 if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
435 ** Delete a P3 value if necessary.
437 static void freeP3(int p3type, void *p3){
442 case P3_KEYINFO_HANDOFF: {
451 VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
452 freeEphemeralFunction(pVdbeFunc->pFunc);
453 sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
454 sqlite3_free(pVdbeFunc);
458 freeEphemeralFunction((FuncDef*)p3);
462 sqlite3ValueFree((sqlite3_value*)p3);
471 ** Change N opcodes starting at addr to No-ops.
473 void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
475 VdbeOp *pOp = &p->aOp[addr];
477 freeP3(pOp->p3type, pOp->p3);
478 memset(pOp, 0, sizeof(pOp[0]));
479 pOp->opcode = OP_Noop;
486 ** Change the value of the P3 operand for a specific instruction.
487 ** This routine is useful when a large program is loaded from a
488 ** static array using sqlite3VdbeAddOpList but we want to make a
489 ** few minor changes to the program.
491 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
492 ** the string is made into memory obtained from sqlite3_malloc().
493 ** A value of n==0 means copy bytes of zP3 up to and including the
494 ** first null byte. If n>0 then copy n+1 bytes of zP3.
496 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
497 ** A copy is made of the KeyInfo structure into memory obtained from
498 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
499 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
500 ** stored in memory that the caller has obtained from sqlite3_malloc. The
501 ** caller should not free the allocation, it will be freed when the Vdbe is
504 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
505 ** to a string or structure that is guaranteed to exist for the lifetime of
506 ** the Vdbe. In these cases we can just copy the pointer.
508 ** If addr<0 then change P3 on the most recently inserted instruction.
510 void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
512 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
513 if( p==0 || p->aOp==0 || p->db->mallocFailed ){
514 if (n != P3_KEYINFO) {
515 freeP3(n, (void*)*(char**)&zP3);
519 if( addr<0 || addr>=p->nOp ){
524 freeP3(pOp->p3type, pOp->p3);
528 pOp->p3type = P3_NOTUSED;
529 }else if( n==P3_KEYINFO ){
533 nField = ((KeyInfo*)zP3)->nField;
534 nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
535 pKeyInfo = sqlite3_malloc( nByte );
536 pOp->p3 = (char*)pKeyInfo;
538 unsigned char *aSortOrder;
539 memcpy(pKeyInfo, zP3, nByte);
540 aSortOrder = pKeyInfo->aSortOrder;
542 pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
543 memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
545 pOp->p3type = P3_KEYINFO;
547 p->db->mallocFailed = 1;
548 pOp->p3type = P3_NOTUSED;
550 }else if( n==P3_KEYINFO_HANDOFF ){
551 pOp->p3 = (char*)zP3;
552 pOp->p3type = P3_KEYINFO;
554 pOp->p3 = (char*)zP3;
557 if( n==0 ) n = strlen(zP3);
558 pOp->p3 = sqlite3DbStrNDup(p->db, zP3, n);
559 pOp->p3type = P3_DYNAMIC;
565 ** Replace the P3 field of the most recently coded instruction with
568 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
570 assert( p->nOp>0 || p->aOp==0 );
571 assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || p->db->mallocFailed );
572 va_start(ap, zFormat);
573 sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(p->db, zFormat, ap), P3_DYNAMIC);
579 ** Return the opcode for a given address.
581 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
582 assert( p->magic==VDBE_MAGIC_INIT );
583 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
584 return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
587 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
588 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
590 ** Compute a string that describes the P3 parameter for an opcode.
591 ** Use zTemp for any required temporary buffer space.
593 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
596 switch( pOp->p3type ){
599 KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
600 sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
602 for(j=0; j<pKeyInfo->nField; j++){
603 CollSeq *pColl = pKeyInfo->aColl[j];
605 int n = strlen(pColl->zName);
607 memcpy(&zTemp[i],",...",4);
611 if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
614 memcpy(&zTemp[i], pColl->zName,n+1);
616 }else if( i+4<nTemp-6 ){
617 memcpy(&zTemp[i],",nil",4);
628 CollSeq *pColl = (CollSeq*)pOp->p3;
629 sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
634 FuncDef *pDef = (FuncDef*)pOp->p3;
635 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
639 #ifndef SQLITE_OMIT_VIRTUALTABLE
641 sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
642 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
649 if( zP3==0 || pOp->opcode==OP_Noop ){
660 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
663 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
665 assert( i>=0 && i<p->db->nDb );
666 assert( i<sizeof(p->btreeMask)*8 );
668 if( (p->btreeMask & mask)==0 ){
669 p->btreeMask |= mask;
670 sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
675 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
677 ** Print a single opcode. This routine is used for debugging only.
679 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
682 static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
683 if( pOut==0 ) pOut = stdout;
684 zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
685 fprintf(pOut, zFormat1,
686 pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, zP3);
692 ** Release an array of N Mem elements
694 static void releaseMemArray(Mem *p, int N){
697 assert( N<2 || p[0].db==p[1].db );
698 sqlite3VdbeMemRelease(p++);
703 #ifndef SQLITE_OMIT_EXPLAIN
705 ** Give a listing of the program in the virtual machine.
707 ** The interface is the same as sqlite3VdbeExec(). But instead of
708 ** running the code, it invokes the callback once for each instruction.
709 ** This feature is used to implement "EXPLAIN".
712 Vdbe *p /* The VDBE */
718 assert( p->explain );
719 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
720 assert( db->magic==SQLITE_MAGIC_BUSY );
721 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
723 /* Even though this opcode does not put dynamic strings onto the
724 ** the stack, they may become dynamic if the user calls
725 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
727 if( p->pTos==&p->aStack[4] ){
728 releaseMemArray(p->aStack, 5);
734 }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
738 }else if( db->u1.isInterrupted ){
739 p->rc = SQLITE_INTERRUPT;
741 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
743 Op *pOp = &p->aOp[i];
744 Mem *pMem = p->aStack;
745 pMem->flags = MEM_Int;
746 pMem->type = SQLITE_INTEGER;
747 pMem->u.i = i; /* Program counter */
750 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
751 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
752 assert( pMem->z!=0 );
753 pMem->n = strlen(pMem->z);
754 pMem->type = SQLITE_TEXT;
755 pMem->enc = SQLITE_UTF8;
758 pMem->flags = MEM_Int;
759 pMem->u.i = pOp->p1; /* P1 */
760 pMem->type = SQLITE_INTEGER;
763 pMem->flags = MEM_Int;
764 pMem->u.i = pOp->p2; /* P2 */
765 pMem->type = SQLITE_INTEGER;
768 pMem->flags = MEM_Ephem|MEM_Str|MEM_Term; /* P3 */
769 pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
770 assert( pMem->z!=0 );
771 pMem->n = strlen(pMem->z);
772 pMem->type = SQLITE_TEXT;
773 pMem->enc = SQLITE_UTF8;
775 p->nResColumn = 5 - 2*(p->explain-1);
783 #endif /* SQLITE_OMIT_EXPLAIN */
787 ** Print the SQL that was used to generate a VDBE program.
789 void sqlite3VdbePrintSql(Vdbe *p){
793 pOp = &p->aOp[nOp-1];
794 if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
795 const char *z = pOp->p3;
796 while( isspace(*(u8*)z) ) z++;
797 printf("SQL: [%s]\n", z);
802 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
804 ** Print an IOTRACE message showing SQL content.
806 void sqlite3VdbeIOTraceSql(Vdbe *p){
809 if( sqlite3_io_trace==0 ) return;
811 pOp = &p->aOp[nOp-1];
812 if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
815 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p3);
816 for(i=0; isspace((unsigned char)z[i]); i++){}
818 if( isspace((unsigned char)z[i]) ){
827 sqlite3_io_trace("SQL %s\n", z);
830 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
834 ** Prepare a virtual machine for execution. This involves things such
835 ** as allocating stack space and initializing the program counter.
836 ** After the VDBE has be prepped, it can be executed by one or more
837 ** calls to sqlite3VdbeExec().
839 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
842 void sqlite3VdbeMakeReady(
843 Vdbe *p, /* The VDBE */
844 int nVar, /* Number of '?' see in the SQL statement */
845 int nMem, /* Number of memory cells to allocate */
846 int nCursor, /* Number of cursors to allocate */
847 int isExplain /* True if the EXPLAIN keywords is present */
853 assert( p->magic==VDBE_MAGIC_INIT );
855 /* There should be at least one opcode.
859 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
860 * is because the call to resizeOpArray() below may shrink the
861 * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
864 p->magic = VDBE_MAGIC_RUN;
866 /* No instruction ever pushes more than a single element onto the
867 ** stack. And the stack never grows on successive executions of the
868 ** same loop. So the total number of instructions is an upper bound
869 ** on the maximum stack depth required. (Added later:) The
870 ** resolveP2Values() call computes a tighter upper bound on the
873 ** Allocation all the stack space we will ever need.
876 int nArg; /* Maximum number of args passed to a user function. */
877 int nStack; /* Maximum number of stack entries required */
878 resolveP2Values(p, &nArg, &nStack);
879 resizeOpArray(p, p->nOp);
881 assert( nStack<p->nOp );
885 p->aStack = sqlite3DbMallocZero(db,
886 nStack*sizeof(p->aStack[0]) /* aStack */
887 + nArg*sizeof(Mem*) /* apArg */
888 + nVar*sizeof(Mem) /* aVar */
889 + nVar*sizeof(char*) /* azVar */
890 + nMem*sizeof(Mem) /* aMem */
891 + nCursor*sizeof(Cursor*) /* apCsr */
893 if( !db->mallocFailed ){
894 p->aMem = &p->aStack[nStack];
896 p->aVar = &p->aMem[nMem];
899 p->apArg = (Mem**)&p->aVar[nVar];
900 p->azVar = (char**)&p->apArg[nArg];
901 p->apCsr = (Cursor**)&p->azVar[nVar];
902 p->nCursor = nCursor;
903 for(n=0; n<nVar; n++){
904 p->aVar[n].flags = MEM_Null;
907 for(n=0; n<nStack; n++){
908 p->aStack[n].db = db;
912 for(n=0; n<p->nMem; n++){
913 p->aMem[n].flags = MEM_Null;
917 p->pTos = &p->aStack[-1];
922 p->errorAction = OE_Abort;
924 p->explain |= isExplain;
925 p->magic = VDBE_MAGIC_RUN;
928 p->minWriteFileFormat = 255;
929 p->openedStatement = 0;
933 for(i=0; i<p->nOp; i++){
935 p->aOp[i].cycles = 0;
942 ** Close a VDBE cursor and release all the resources that cursor happens
945 void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
950 sqlite3BtreeCloseCursor(pCx->pCursor);
953 sqlite3BtreeClose(pCx->pBt);
955 #ifndef SQLITE_OMIT_VIRTUALTABLE
956 if( pCx->pVtabCursor ){
957 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
958 const sqlite3_module *pModule = pCx->pModule;
960 sqlite3SafetyOff(p->db);
961 pModule->xClose(pVtabCursor);
962 sqlite3SafetyOn(p->db);
966 sqlite3_free(pCx->pData);
967 sqlite3_free(pCx->aType);
972 ** Close all cursors except for VTab cursors that are currently
975 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
977 if( p->apCsr==0 ) return;
978 for(i=0; i<p->nCursor; i++){
979 Cursor *pC = p->apCsr[i];
980 if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
981 sqlite3VdbeFreeCursor(p, pC);
988 ** Clean up the VM after execution.
990 ** This routine will automatically close any cursors, lists, and/or
991 ** sorters that were left open. It also deletes the values of
992 ** variables in the aVar[] array.
994 static void Cleanup(Vdbe *p){
997 releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
998 p->pTos = &p->aStack[-1];
1000 closeAllCursorsExceptActiveVtabs(p);
1001 releaseMemArray(p->aMem, p->nMem);
1002 sqlite3VdbeFifoClear(&p->sFifo);
1003 if( p->contextStack ){
1004 for(i=0; i<p->contextStackTop; i++){
1005 sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
1007 sqlite3_free(p->contextStack);
1009 p->contextStack = 0;
1010 p->contextStackDepth = 0;
1011 p->contextStackTop = 0;
1012 sqlite3_free(p->zErrMsg);
1018 ** Set the number of result columns that will be returned by this SQL
1019 ** statement. This is now set at compile time, rather than during
1020 ** execution of the vdbe program so that sqlite3_column_count() can
1021 ** be called on an SQL statement before sqlite3_step().
1023 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
1027 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
1028 sqlite3_free(p->aColName);
1029 n = nResColumn*COLNAME_N;
1030 p->nResColumn = nResColumn;
1031 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
1032 if( p->aColName==0 ) return;
1034 pColName->flags = MEM_Null;
1035 pColName->db = p->db;
1041 ** Set the name of the idx'th column to be returned by the SQL statement.
1042 ** zName must be a pointer to a nul terminated string.
1044 ** This call must be made after a call to sqlite3VdbeSetNumCols().
1046 ** If N==P3_STATIC it means that zName is a pointer to a constant static
1047 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then
1048 ** the string is freed using sqlite3_free() when the vdbe is finished with
1049 ** it. Otherwise, N bytes of zName are copied.
1051 int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
1054 assert( idx<p->nResColumn );
1055 assert( var<COLNAME_N );
1056 if( p->db->mallocFailed ) return SQLITE_NOMEM;
1057 assert( p->aColName!=0 );
1058 pColName = &(p->aColName[idx+var*p->nResColumn]);
1059 if( N==P3_DYNAMIC || N==P3_STATIC ){
1060 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
1062 rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
1064 if( rc==SQLITE_OK && N==P3_DYNAMIC ){
1065 pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
1072 ** A read or write transaction may or may not be active on database handle
1073 ** db. If a transaction is active, commit it. If there is a
1074 ** write-transaction spanning more than one database file, this routine
1075 ** takes care of the master journal trickery.
1077 static int vdbeCommit(sqlite3 *db){
1079 int nTrans = 0; /* Number of databases with an active write-transaction */
1081 int needXcommit = 0;
1083 /* Before doing anything else, call the xSync() callback for any
1084 ** virtual module tables written in this transaction. This has to
1085 ** be done before determining whether a master journal file is
1086 ** required, as an xSync() callback may add an attached database
1087 ** to the transaction.
1089 rc = sqlite3VtabSync(db, rc);
1090 if( rc!=SQLITE_OK ){
1094 /* This loop determines (a) if the commit hook should be invoked and
1095 ** (b) how many database files have open write transactions, not
1096 ** including the temp database. (b) is important because if more than
1097 ** one database file has an open write transaction, a master journal
1098 ** file is required for an atomic commit.
1100 for(i=0; i<db->nDb; i++){
1101 Btree *pBt = db->aDb[i].pBt;
1102 if( sqlite3BtreeIsInTrans(pBt) ){
1104 if( i!=1 ) nTrans++;
1108 /* If there are any write-transactions at all, invoke the commit hook */
1109 if( needXcommit && db->xCommitCallback ){
1110 sqlite3SafetyOff(db);
1111 rc = db->xCommitCallback(db->pCommitArg);
1112 sqlite3SafetyOn(db);
1114 return SQLITE_CONSTRAINT;
1118 /* The simple case - no more than one database file (not counting the
1119 ** TEMP database) has a transaction active. There is no need for the
1122 ** If the return value of sqlite3BtreeGetFilename() is a zero length
1123 ** string, it means the main database is :memory:. In that case we do
1124 ** not support atomic multi-file commits, so use the simple case then
1127 if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
1128 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1129 Btree *pBt = db->aDb[i].pBt;
1131 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
1135 /* Do the commit only if all databases successfully complete phase 1.
1136 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1137 ** IO error while deleting or truncating a journal file. It is unlikely,
1138 ** but could happen. In this case abandon processing and return the error.
1140 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1141 Btree *pBt = db->aDb[i].pBt;
1143 rc = sqlite3BtreeCommitPhaseTwo(pBt);
1146 if( rc==SQLITE_OK ){
1147 sqlite3VtabCommit(db);
1151 /* The complex case - There is a multi-file write-transaction active.
1152 ** This requires a master journal file to ensure the transaction is
1153 ** committed atomicly.
1155 #ifndef SQLITE_OMIT_DISKIO
1157 sqlite3_vfs *pVfs = db->pVfs;
1159 char *zMaster = 0; /* File-name for the master journal */
1160 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
1161 sqlite3_file *pMaster = 0;
1164 /* Select a master journal file name */
1167 sqlite3_free(zMaster);
1168 sqlite3Randomness(sizeof(random), &random);
1169 zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
1171 return SQLITE_NOMEM;
1173 }while( sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS) );
1175 /* Open the master journal. */
1176 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
1177 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
1178 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
1180 if( rc!=SQLITE_OK ){
1181 sqlite3_free(zMaster);
1185 /* Write the name of each database file in the transaction into the new
1186 ** master journal file. If an error occurs at this point close
1187 ** and delete the master journal file. All the individual journal files
1188 ** still have 'null' as the master journal pointer, so they will roll
1189 ** back independently if a failure occurs.
1191 for(i=0; i<db->nDb; i++){
1192 Btree *pBt = db->aDb[i].pBt;
1193 if( i==1 ) continue; /* Ignore the TEMP database */
1194 if( sqlite3BtreeIsInTrans(pBt) ){
1195 char const *zFile = sqlite3BtreeGetJournalname(pBt);
1196 if( zFile[0]==0 ) continue; /* Ignore :memory: databases */
1197 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
1200 rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
1201 offset += strlen(zFile)+1;
1202 if( rc!=SQLITE_OK ){
1203 sqlite3OsCloseFree(pMaster);
1204 sqlite3OsDelete(pVfs, zMaster, 0);
1205 sqlite3_free(zMaster);
1211 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
1212 ** flag is set this is not required.
1214 zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
1216 && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
1217 && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
1218 sqlite3OsCloseFree(pMaster);
1219 sqlite3OsDelete(pVfs, zMaster, 0);
1220 sqlite3_free(zMaster);
1224 /* Sync all the db files involved in the transaction. The same call
1225 ** sets the master journal pointer in each individual journal. If
1226 ** an error occurs here, do not delete the master journal file.
1228 ** If the error occurs during the first call to
1229 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
1230 ** master journal file will be orphaned. But we cannot delete it,
1231 ** in case the master journal file name was written into the journal
1232 ** file before the failure occured.
1234 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1235 Btree *pBt = db->aDb[i].pBt;
1237 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
1240 sqlite3OsCloseFree(pMaster);
1241 if( rc!=SQLITE_OK ){
1242 sqlite3_free(zMaster);
1246 /* Delete the master journal file. This commits the transaction. After
1247 ** doing this the directory is synced again before any individual
1248 ** transaction files are deleted.
1250 rc = sqlite3OsDelete(pVfs, zMaster, 1);
1251 sqlite3_free(zMaster);
1257 /* All files and directories have already been synced, so the following
1258 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
1259 ** deleting or truncating journals. If something goes wrong while
1260 ** this is happening we don't really care. The integrity of the
1261 ** transaction is already guaranteed, but some stray 'cold' journals
1262 ** may be lying around. Returning an error code won't help matters.
1264 disable_simulated_io_errors();
1265 for(i=0; i<db->nDb; i++){
1266 Btree *pBt = db->aDb[i].pBt;
1268 sqlite3BtreeCommitPhaseTwo(pBt);
1271 enable_simulated_io_errors();
1273 sqlite3VtabCommit(db);
1281 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1282 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1283 ** currently active. An assertion fails if the two counts do not match.
1284 ** This is an internal self-check only - it is not an essential processing
1287 ** This is a no-op if NDEBUG is defined.
1290 static void checkActiveVdbeCnt(sqlite3 *db){
1295 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1300 assert( cnt==db->activeVdbeCnt );
1303 #define checkActiveVdbeCnt(x)
1307 ** For every Btree that in database connection db which
1308 ** has been modified, "trip" or invalidate each cursor in
1309 ** that Btree might have been modified so that the cursor
1310 ** can never be used again. This happens when a rollback
1311 *** occurs. We have to trip all the other cursors, even
1312 ** cursor from other VMs in different database connections,
1313 ** so that none of them try to use the data at which they
1314 ** were pointing and which now may have been changed due
1317 ** Remember that a rollback can delete tables complete and
1318 ** reorder rootpages. So it is not sufficient just to save
1319 ** the state of the cursor. We have to invalidate the cursor
1320 ** so that it is never used again.
1322 void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
1324 for(i=0; i<db->nDb; i++){
1325 Btree *p = db->aDb[i].pBt;
1326 if( p && sqlite3BtreeIsInTrans(p) ){
1327 sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
1333 ** This routine is called the when a VDBE tries to halt. If the VDBE
1334 ** has made changes and is in autocommit mode, then commit those
1335 ** changes. If a rollback is needed, then do the rollback.
1337 ** This routine is the only way to move the state of a VM from
1338 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
1339 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
1341 ** Return an error code. If the commit could not complete because of
1342 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
1343 ** means the close did not happen and needs to be repeated.
1345 int sqlite3VdbeHalt(Vdbe *p){
1346 sqlite3 *db = p->db;
1348 int (*xFunc)(Btree *pBt) = 0; /* Function to call on each btree backend */
1349 int isSpecialError; /* Set to true if SQLITE_NOMEM or IOERR */
1351 /* This function contains the logic that determines if a statement or
1352 ** transaction will be committed or rolled back as a result of the
1353 ** execution of this virtual machine.
1355 ** If any of the following errors occur:
1362 ** Then the internal cache might have been left in an inconsistent
1363 ** state. We need to rollback the statement transaction, if there is
1364 ** one, or the complete transaction if there is no statement transaction.
1367 if( p->db->mallocFailed ){
1368 p->rc = SQLITE_NOMEM;
1370 closeAllCursorsExceptActiveVtabs(p);
1371 if( p->magic!=VDBE_MAGIC_RUN ){
1374 checkActiveVdbeCnt(db);
1376 /* No commit or rollback needed if the program never started */
1378 int mrc; /* Primary error code from p->rc */
1380 /* Lock all btrees used by the statement */
1381 sqlite3BtreeMutexArrayEnter(&p->aMutex);
1383 /* Check for one of the special errors */
1385 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
1386 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL ;
1387 if( isSpecialError ){
1388 /* This loop does static analysis of the query to see which of the
1389 ** following three categories it falls into:
1392 ** Query with statement journal
1393 ** Query without statement journal
1395 ** We could do something more elegant than this static analysis (i.e.
1396 ** store the type of query as part of the compliation phase), but
1397 ** handling malloc() or IO failure is a fairly obscure edge case so
1398 ** this is probably easier. Todo: Might be an opportunity to reduce
1399 ** code size a very small amount though...
1401 int notReadOnly = 0;
1402 int isStatement = 0;
1403 assert(p->aOp || p->nOp==0);
1404 for(i=0; i<p->nOp; i++){
1405 switch( p->aOp[i].opcode ){
1406 case OP_Transaction:
1407 notReadOnly |= p->aOp[i].p2;
1416 /* If the query was read-only, we need do no rollback at all. Otherwise,
1417 ** proceed with the special handling.
1419 if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
1420 if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
1421 xFunc = sqlite3BtreeRollbackStmt;
1422 p->rc = SQLITE_BUSY;
1423 } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
1424 xFunc = sqlite3BtreeRollbackStmt;
1426 /* We are forced to roll back the active transaction. Before doing
1427 ** so, abort any other statements this handle currently has active.
1429 invalidateCursorsOnModifiedBtrees(db);
1430 sqlite3RollbackAll(db);
1436 /* If the auto-commit flag is set and this is the only active vdbe, then
1437 ** we do either a commit or rollback of the current transaction.
1439 ** Note: This block also runs if one of the special errors handled
1440 ** above has occured.
1442 if( db->autoCommit && db->activeVdbeCnt==1 ){
1443 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
1444 /* The auto-commit flag is true, and the vdbe program was
1445 ** successful or hit an 'OR FAIL' constraint. This means a commit
1448 int rc = vdbeCommit(db);
1449 if( rc==SQLITE_BUSY ){
1450 sqlite3BtreeMutexArrayLeave(&p->aMutex);
1452 }else if( rc!=SQLITE_OK ){
1454 sqlite3RollbackAll(db);
1456 sqlite3CommitInternalChanges(db);
1459 sqlite3RollbackAll(db);
1462 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1463 if( p->openedStatement ){
1464 xFunc = sqlite3BtreeCommitStmt;
1466 }else if( p->errorAction==OE_Abort ){
1467 xFunc = sqlite3BtreeRollbackStmt;
1469 invalidateCursorsOnModifiedBtrees(db);
1470 sqlite3RollbackAll(db);
1475 /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
1476 ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
1477 ** and the return code is still SQLITE_OK, set the return code to the new
1481 xFunc==sqlite3BtreeCommitStmt ||
1482 xFunc==sqlite3BtreeRollbackStmt
1484 for(i=0; xFunc && i<db->nDb; i++){
1486 Btree *pBt = db->aDb[i].pBt;
1489 if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
1491 sqlite3SetString(&p->zErrMsg, 0);
1496 /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
1497 ** set the change counter.
1499 if( p->changeCntOn && p->pc>=0 ){
1500 if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
1501 sqlite3VdbeSetChanges(db, p->nChange);
1503 sqlite3VdbeSetChanges(db, 0);
1508 /* Rollback or commit any schema changes that occurred. */
1509 if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
1510 sqlite3ResetInternalSchema(db, 0);
1511 db->flags = (db->flags | SQLITE_InternChanges);
1514 /* Release the locks */
1515 sqlite3BtreeMutexArrayLeave(&p->aMutex);
1518 /* We have successfully halted and closed the VM. Record this fact. */
1520 db->activeVdbeCnt--;
1522 p->magic = VDBE_MAGIC_HALT;
1523 checkActiveVdbeCnt(db);
1524 if( p->db->mallocFailed ){
1525 p->rc = SQLITE_NOMEM;
1527 checkActiveVdbeCnt(db);
1534 ** Each VDBE holds the result of the most recent sqlite3_step() call
1535 ** in p->rc. This routine sets that result back to SQLITE_OK.
1537 void sqlite3VdbeResetStepResult(Vdbe *p){
1542 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
1543 ** Write any error messages into *pzErrMsg. Return the result code.
1545 ** After this routine is run, the VDBE should be ready to be executed
1548 ** To look at it another way, this routine resets the state of the
1549 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
1552 int sqlite3VdbeReset(Vdbe *p){
1556 /* If the VM did not run to completion or if it encountered an
1557 ** error, then it might not have been halted properly. So halt
1560 sqlite3SafetyOn(db);
1562 sqlite3SafetyOff(db);
1564 /* If the VDBE has be run even partially, then transfer the error code
1565 ** and error message from the VDBE into the main database structure. But
1566 ** if the VDBE has just been set to run but has not actually executed any
1567 ** instructions yet, leave the main database error information unchanged.
1571 sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
1572 db->errCode = p->rc;
1575 sqlite3Error(db, p->rc, 0);
1577 sqlite3Error(db, SQLITE_OK, 0);
1579 }else if( p->rc && p->expired ){
1580 /* The expired flag was set on the VDBE before the first call
1581 ** to sqlite3_step(). For consistency (since sqlite3_step() was
1582 ** called), set the database error in this case as well.
1584 sqlite3Error(db, p->rc, 0);
1587 /* Reclaim all memory used by the VDBE
1591 /* Save profiling information from this VDBE run.
1593 assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
1596 FILE *out = fopen("vdbe_profile.out", "a");
1599 fprintf(out, "---- ");
1600 for(i=0; i<p->nOp; i++){
1601 fprintf(out, "%02x", p->aOp[i].opcode);
1604 for(i=0; i<p->nOp; i++){
1605 fprintf(out, "%6d %10lld %8lld ",
1608 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
1610 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
1616 p->magic = VDBE_MAGIC_INIT;
1618 return p->rc & db->errMask;
1622 ** Clean up and delete a VDBE after execution. Return an integer which is
1623 ** the result code. Write any error message text into *pzErrMsg.
1625 int sqlite3VdbeFinalize(Vdbe *p){
1627 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
1628 rc = sqlite3VdbeReset(p);
1629 assert( (rc & p->db->errMask)==rc );
1630 }else if( p->magic!=VDBE_MAGIC_INIT ){
1631 return SQLITE_MISUSE;
1633 sqlite3VdbeDelete(p);
1638 ** Call the destructor for each auxdata entry in pVdbeFunc for which
1639 ** the corresponding bit in mask is clear. Auxdata entries beyond 31
1640 ** are always destroyed. To destroy all auxdata entries, call this
1641 ** routine with mask==0.
1643 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
1645 for(i=0; i<pVdbeFunc->nAux; i++){
1646 struct AuxData *pAux = &pVdbeFunc->apAux[i];
1647 if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
1648 if( pAux->xDelete ){
1649 pAux->xDelete(pAux->pAux);
1657 ** Delete an entire VDBE.
1659 void sqlite3VdbeDelete(Vdbe *p){
1664 p->pPrev->pNext = p->pNext;
1666 assert( p->db->pVdbe==p );
1667 p->db->pVdbe = p->pNext;
1670 p->pNext->pPrev = p->pPrev;
1673 for(i=0; i<p->nOp; i++){
1674 Op *pOp = &p->aOp[i];
1675 freeP3(pOp->p3type, pOp->p3);
1677 sqlite3_free(p->aOp);
1679 releaseMemArray(p->aVar, p->nVar);
1680 sqlite3_free(p->aLabel);
1681 sqlite3_free(p->aStack);
1682 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
1683 sqlite3_free(p->aColName);
1684 sqlite3_free(p->zSql);
1685 p->magic = VDBE_MAGIC_DEAD;
1690 ** If a MoveTo operation is pending on the given cursor, then do that
1691 ** MoveTo now. Return an error code. If no MoveTo is pending, this
1692 ** routine does nothing and returns SQLITE_OK.
1694 int sqlite3VdbeCursorMoveto(Cursor *p){
1695 if( p->deferredMoveto ){
1698 extern int sqlite3_search_count;
1700 assert( p->isTable );
1701 rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
1704 p->lastRowid = keyToInt(p->movetoTarget);
1705 p->rowidIsValid = res==0;
1707 rc = sqlite3BtreeNext(p->pCursor, &res);
1711 sqlite3_search_count++;
1713 p->deferredMoveto = 0;
1714 p->cacheStatus = CACHE_STALE;
1720 ** The following functions:
1722 ** sqlite3VdbeSerialType()
1723 ** sqlite3VdbeSerialTypeLen()
1724 ** sqlite3VdbeSerialRead()
1725 ** sqlite3VdbeSerialLen()
1726 ** sqlite3VdbeSerialWrite()
1728 ** encapsulate the code that serializes values for storage in SQLite
1729 ** data and index records. Each serialized value consists of a
1730 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
1731 ** integer, stored as a varint.
1733 ** In an SQLite index record, the serial type is stored directly before
1734 ** the blob of data that it corresponds to. In a table record, all serial
1735 ** types are stored at the start of the record, and the blobs of data at
1736 ** the end. Hence these functions allow the caller to handle the
1737 ** serial-type and data blob seperately.
1739 ** The following table describes the various storage classes for data:
1741 ** serial type bytes of data type
1742 ** -------------- --------------- ---------------
1744 ** 1 1 signed integer
1745 ** 2 2 signed integer
1746 ** 3 3 signed integer
1747 ** 4 4 signed integer
1748 ** 5 6 signed integer
1749 ** 6 8 signed integer
1751 ** 8 0 Integer constant 0
1752 ** 9 0 Integer constant 1
1753 ** 10,11 reserved for expansion
1754 ** N>=12 and even (N-12)/2 BLOB
1755 ** N>=13 and odd (N-13)/2 text
1757 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
1758 ** of SQLite will not understand those serial types.
1762 ** Return the serial-type for the value stored in pMem.
1764 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
1765 int flags = pMem->flags;
1768 if( flags&MEM_Null ){
1771 if( flags&MEM_Int ){
1772 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
1773 # define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
1776 if( file_format>=4 && (i&1)==i ){
1780 if( u<=127 ) return 1;
1781 if( u<=32767 ) return 2;
1782 if( u<=8388607 ) return 3;
1783 if( u<=2147483647 ) return 4;
1784 if( u<=MAX_6BYTE ) return 5;
1787 if( flags&MEM_Real ){
1790 assert( flags&(MEM_Str|MEM_Blob) );
1792 if( flags & MEM_Zero ){
1796 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
1800 ** Return the length of the data corresponding to the supplied serial-type.
1802 int sqlite3VdbeSerialTypeLen(u32 serial_type){
1803 if( serial_type>=12 ){
1804 return (serial_type-12)/2;
1806 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
1807 return aSize[serial_type];
1812 ** If we are on an architecture with mixed-endian floating
1813 ** points (ex: ARM7) then swap the lower 4 bytes with the
1814 ** upper 4 bytes. Return the result.
1816 ** For most architectures, this is a no-op.
1818 ** (later): It is reported to me that the mixed-endian problem
1819 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
1820 ** that early versions of GCC stored the two words of a 64-bit
1821 ** float in the wrong order. And that error has been propagated
1822 ** ever since. The blame is not necessarily with GCC, though.
1823 ** GCC might have just copying the problem from a prior compiler.
1824 ** I am also told that newer versions of GCC that follow a different
1825 ** ABI get the byte order right.
1827 ** Developers using SQLite on an ARM7 should compile and run their
1828 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
1829 ** enabled, some asserts below will ensure that the byte order of
1830 ** floating point values is correct.
1832 ** (2007-08-30) Frank van Vugt has studied this problem closely
1833 ** and has send his findings to the SQLite developers. Frank
1834 ** writes that some Linux kernels offer floating point hardware
1835 ** emulation that uses only 32-bit mantissas instead of a full
1836 ** 48-bits as required by the IEEE standard. (This is the
1837 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
1838 ** byte swapping becomes very complicated. To avoid problems,
1839 ** the necessary byte swapping is carried out using a 64-bit integer
1840 ** rather than a 64-bit float. Frank assures us that the code here
1841 ** works for him. We, the developers, have no way to independently
1842 ** verify this, but Frank seems to know what he is talking about
1845 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
1846 static u64 floatSwap(u64 in){
1859 # define swapMixedEndianFloat(X) X = floatSwap(X)
1861 # define swapMixedEndianFloat(X)
1865 ** Write the serialized data blob for the value stored in pMem into
1866 ** buf. It is assumed that the caller has allocated sufficient space.
1867 ** Return the number of bytes written.
1869 ** nBuf is the amount of space left in buf[]. nBuf must always be
1870 ** large enough to hold the entire field. Except, if the field is
1871 ** a blob with a zero-filled tail, then buf[] might be just the right
1872 ** size to hold everything except for the zero-filled tail. If buf[]
1873 ** is only big enough to hold the non-zero prefix, then only write that
1874 ** prefix into buf[]. But if buf[] is large enough to hold both the
1875 ** prefix and the tail then write the prefix and set the tail to all
1878 ** Return the number of bytes actually written into buf[]. The number
1879 ** of bytes in the zero-filled tail is included in the return value only
1880 ** if those bytes were zeroed in buf[].
1882 int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
1883 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
1886 /* Integer and Real */
1887 if( serial_type<=7 && serial_type>0 ){
1890 if( serial_type==7 ){
1891 assert( sizeof(v)==sizeof(pMem->r) );
1892 memcpy(&v, &pMem->r, sizeof(v));
1893 swapMixedEndianFloat(v);
1897 len = i = sqlite3VdbeSerialTypeLen(serial_type);
1898 assert( len<=nBuf );
1906 /* String or blob */
1907 if( serial_type>=12 ){
1908 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
1909 == sqlite3VdbeSerialTypeLen(serial_type) );
1910 assert( pMem->n<=nBuf );
1912 memcpy(buf, pMem->z, len);
1913 if( pMem->flags & MEM_Zero ){
1918 memset(&buf[pMem->n], 0, len-pMem->n);
1923 /* NULL or constants 0 or 1 */
1928 ** Deserialize the data blob pointed to by buf as serial type serial_type
1929 ** and store the result in pMem. Return the number of bytes read.
1931 int sqlite3VdbeSerialGet(
1932 const unsigned char *buf, /* Buffer to deserialize from */
1933 u32 serial_type, /* Serial type to deserialize */
1934 Mem *pMem /* Memory cell to write value into */
1936 switch( serial_type ){
1937 case 10: /* Reserved for future use */
1938 case 11: /* Reserved for future use */
1939 case 0: { /* NULL */
1940 pMem->flags = MEM_Null;
1943 case 1: { /* 1-byte signed integer */
1944 pMem->u.i = (signed char)buf[0];
1945 pMem->flags = MEM_Int;
1948 case 2: { /* 2-byte signed integer */
1949 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
1950 pMem->flags = MEM_Int;
1953 case 3: { /* 3-byte signed integer */
1954 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
1955 pMem->flags = MEM_Int;
1958 case 4: { /* 4-byte signed integer */
1959 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1960 pMem->flags = MEM_Int;
1963 case 5: { /* 6-byte signed integer */
1964 u64 x = (((signed char)buf[0])<<8) | buf[1];
1965 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
1967 pMem->u.i = *(i64*)&x;
1968 pMem->flags = MEM_Int;
1971 case 6: /* 8-byte signed integer */
1972 case 7: { /* IEEE floating point */
1975 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
1976 /* Verify that integers and floating point values use the same
1977 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
1978 ** defined that 64-bit floating point values really are mixed
1981 static const u64 t1 = ((u64)0x3ff00000)<<32;
1982 static const double r1 = 1.0;
1984 swapMixedEndianFloat(t2);
1985 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
1988 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1989 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
1991 if( serial_type==6 ){
1992 pMem->u.i = *(i64*)&x;
1993 pMem->flags = MEM_Int;
1995 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
1996 swapMixedEndianFloat(x);
1997 memcpy(&pMem->r, &x, sizeof(x));
1998 pMem->flags = MEM_Real;
2002 case 8: /* Integer 0 */
2003 case 9: { /* Integer 1 */
2004 pMem->u.i = serial_type-8;
2005 pMem->flags = MEM_Int;
2009 int len = (serial_type-12)/2;
2010 pMem->z = (char *)buf;
2013 if( serial_type&0x01 ){
2014 pMem->flags = MEM_Str | MEM_Ephem;
2016 pMem->flags = MEM_Blob | MEM_Ephem;
2025 ** The header of a record consists of a sequence variable-length integers.
2026 ** These integers are almost always small and are encoded as a single byte.
2027 ** The following macro takes advantage this fact to provide a fast decode
2028 ** of the integers in a record header. It is faster for the common case
2029 ** where the integer is a single byte. It is a little slower when the
2030 ** integer is two or more bytes. But overall it is faster.
2032 ** The following expressions are equivalent:
2034 ** x = sqlite3GetVarint32( A, &B );
2036 ** x = GetVarint( A, B );
2039 #define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
2042 ** This function compares the two table rows or index records specified by
2043 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
2044 ** or positive integer if {nKey1, pKey1} is less than, equal to or
2045 ** greater than {nKey2, pKey2}. Both Key1 and Key2 must be byte strings
2046 ** composed by the OP_MakeRecord opcode of the VDBE.
2048 int sqlite3VdbeRecordCompare(
2050 int nKey1, const void *pKey1,
2051 int nKey2, const void *pKey2
2053 KeyInfo *pKeyInfo = (KeyInfo*)userData;
2054 u32 d1, d2; /* Offset into aKey[] of next data element */
2055 u32 idx1, idx2; /* Offset into aKey[] of next header element */
2056 u32 szHdr1, szHdr2; /* Number of bytes in header */
2060 const unsigned char *aKey1 = (const unsigned char *)pKey1;
2061 const unsigned char *aKey2 = (const unsigned char *)pKey2;
2065 mem1.enc = pKeyInfo->enc;
2066 mem1.db = pKeyInfo->db;
2067 mem2.enc = pKeyInfo->enc;
2068 mem2.db = pKeyInfo->db;
2070 idx1 = GetVarint(aKey1, szHdr1);
2072 idx2 = GetVarint(aKey2, szHdr2);
2074 nField = pKeyInfo->nField;
2075 while( idx1<szHdr1 && idx2<szHdr2 ){
2079 /* Read the serial types for the next element in each key. */
2080 idx1 += GetVarint( aKey1+idx1, serial_type1 );
2081 if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
2082 idx2 += GetVarint( aKey2+idx2, serial_type2 );
2083 if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
2085 /* Extract the values to be compared.
2087 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
2088 d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
2090 /* Do the comparison
2092 rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
2093 if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
2094 if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
2101 /* One of the keys ran out of fields, but all the fields up to that point
2102 ** were equal. If the incrKey flag is true, then the second key is
2103 ** treated as larger.
2106 if( pKeyInfo->incrKey ){
2108 }else if( d1<nKey1 ){
2110 }else if( d2<nKey2 ){
2113 }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
2114 && pKeyInfo->aSortOrder[i] ){
2122 ** The argument is an index entry composed using the OP_MakeRecord opcode.
2123 ** The last entry in this record should be an integer (specifically
2124 ** an integer rowid). This routine returns the number of bytes in
2127 int sqlite3VdbeIdxRowidLen(const u8 *aKey){
2128 u32 szHdr; /* Size of the header */
2129 u32 typeRowid; /* Serial type of the rowid */
2131 sqlite3GetVarint32(aKey, &szHdr);
2132 sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
2133 return sqlite3VdbeSerialTypeLen(typeRowid);
2138 ** pCur points at an index entry created using the OP_MakeRecord opcode.
2139 ** Read the rowid (the last field in the record) and store it in *rowid.
2140 ** Return SQLITE_OK if everything works, or an error code otherwise.
2142 int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
2145 u32 szHdr; /* Size of the header */
2146 u32 typeRowid; /* Serial type of the rowid */
2147 u32 lenRowid; /* Size of the rowid */
2150 sqlite3BtreeKeySize(pCur, &nCellKey);
2152 return SQLITE_CORRUPT_BKPT;
2154 rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
2158 sqlite3GetVarint32((u8*)m.z, &szHdr);
2159 sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
2160 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
2161 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
2163 sqlite3VdbeMemRelease(&m);
2168 ** Compare the key of the index entry that cursor pC is point to against
2169 ** the key string in pKey (of length nKey). Write into *pRes a number
2170 ** that is negative, zero, or positive if pC is less than, equal to,
2171 ** or greater than pKey. Return SQLITE_OK on success.
2173 ** pKey is either created without a rowid or is truncated so that it
2174 ** omits the rowid at the end. The rowid at the end of the index entry
2175 ** is ignored as well.
2177 int sqlite3VdbeIdxKeyCompare(
2178 Cursor *pC, /* The cursor to compare against */
2179 int nKey, const u8 *pKey, /* The key to compare */
2180 int *res /* Write the comparison result here */
2184 BtCursor *pCur = pC->pCursor;
2188 sqlite3BtreeKeySize(pCur, &nCellKey);
2193 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
2197 lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
2198 *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
2199 sqlite3VdbeMemRelease(&m);
2204 ** This routine sets the value to be returned by subsequent calls to
2205 ** sqlite3_changes() on the database handle 'db'.
2207 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
2208 assert( sqlite3_mutex_held(db->mutex) );
2209 db->nChange = nChange;
2210 db->nTotalChange += nChange;
2214 ** Set a flag in the vdbe to update the change counter when it is finalised
2217 void sqlite3VdbeCountChanges(Vdbe *v){
2222 ** Mark every prepared statement associated with a database connection
2225 ** An expired statement means that recompilation of the statement is
2226 ** recommend. Statements expire when things happen that make their
2227 ** programs obsolete. Removing user-defined functions or collating
2228 ** sequences, or changing an authorization function are the types of
2229 ** things that make prepared statements obsolete.
2231 void sqlite3ExpirePreparedStatements(sqlite3 *db){
2233 for(p = db->pVdbe; p; p=p->pNext){
2239 ** Return the database associated with the Vdbe.
2241 sqlite3 *sqlite3VdbeDb(Vdbe *v){