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"
23 ** When debugging the code generator in a symbolic debugger, one can
24 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
25 ** as they are added to the instruction stream.
28 int sqlite3VdbeAddopTrace
= 0;
33 ** Create a new virtual database engine.
35 Vdbe
*sqlite3VdbeCreate(sqlite3
*db
){
37 p
= sqlite3DbMallocZero(db
, sizeof(Vdbe
) );
46 p
->magic
= VDBE_MAGIC_INIT
;
51 ** Remember the SQL string for a prepared statement.
53 void sqlite3VdbeSetSql(Vdbe
*p
, const char *z
, int n
, int isPrepareV2
){
54 assert( isPrepareV2
==1 || isPrepareV2
==0 );
56 #ifdef SQLITE_OMIT_TRACE
57 if( !isPrepareV2
) return;
60 p
->zSql
= sqlite3DbStrNDup(p
->db
, z
, n
);
61 p
->isPrepareV2
= (u8
)isPrepareV2
;
65 ** Return the SQL associated with a prepared statement
67 const char *sqlite3_sql(sqlite3_stmt
*pStmt
){
68 Vdbe
*p
= (Vdbe
*)pStmt
;
69 return (p
&& p
->isPrepareV2
) ? p
->zSql
: 0;
73 ** Swap all content between two VDBE structures.
75 void sqlite3VdbeSwap(Vdbe
*pA
, Vdbe
*pB
){
82 pA
->pNext
= pB
->pNext
;
85 pA
->pPrev
= pB
->pPrev
;
90 pB
->isPrepareV2
= pA
->isPrepareV2
;
95 ** Turn tracing on or off
97 void sqlite3VdbeTrace(Vdbe
*p
, FILE *trace
){
103 ** Resize the Vdbe.aOp array so that it is at least one op larger than
106 ** If an out-of-memory error occurs while resizing the array, return
107 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
108 ** unchanged (this is so that any opcodes already allocated can be
109 ** correctly deallocated along with the rest of the Vdbe).
111 static int growOpArray(Vdbe
*p
){
113 int nNew
= (p
->nOpAlloc
? p
->nOpAlloc
*2 : (int)(1024/sizeof(Op
)));
114 pNew
= sqlite3DbRealloc(p
->db
, p
->aOp
, nNew
*sizeof(Op
));
116 p
->nOpAlloc
= sqlite3DbMallocSize(p
->db
, pNew
)/sizeof(Op
);
119 return (pNew
? SQLITE_OK
: SQLITE_NOMEM
);
123 ** Add a new instruction to the list of instructions current in the
124 ** VDBE. Return the address of the new instruction.
128 ** p Pointer to the VDBE
130 ** op The opcode for this instruction
132 ** p1, p2, p3 Operands
134 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
135 ** the sqlite3VdbeChangeP4() function to change the value of the P4
138 int sqlite3VdbeAddOp3(Vdbe
*p
, int op
, int p1
, int p2
, int p3
){
143 assert( p
->magic
==VDBE_MAGIC_INIT
);
144 assert( op
>0 && op
<0xff );
145 if( p
->nOpAlloc
<=i
){
146 if( growOpArray(p
) ){
152 pOp
->opcode
= (u8
)op
;
158 pOp
->p4type
= P4_NOTUSED
;
161 if( sqlite3VdbeAddopTrace
) sqlite3VdbePrintOp(0, i
, &p
->aOp
[i
]);
169 int sqlite3VdbeAddOp0(Vdbe
*p
, int op
){
170 return sqlite3VdbeAddOp3(p
, op
, 0, 0, 0);
172 int sqlite3VdbeAddOp1(Vdbe
*p
, int op
, int p1
){
173 return sqlite3VdbeAddOp3(p
, op
, p1
, 0, 0);
175 int sqlite3VdbeAddOp2(Vdbe
*p
, int op
, int p1
, int p2
){
176 return sqlite3VdbeAddOp3(p
, op
, p1
, p2
, 0);
181 ** Add an opcode that includes the p4 value as a pointer.
183 int sqlite3VdbeAddOp4(
184 Vdbe
*p
, /* Add the opcode to this VM */
185 int op
, /* The new opcode */
186 int p1
, /* The P1 operand */
187 int p2
, /* The P2 operand */
188 int p3
, /* The P3 operand */
189 const char *zP4
, /* The P4 operand */
190 int p4type
/* P4 operand type */
192 int addr
= sqlite3VdbeAddOp3(p
, op
, p1
, p2
, p3
);
193 sqlite3VdbeChangeP4(p
, addr
, zP4
, p4type
);
198 ** Add an OP_ParseSchema opcode. This routine is broken out from
199 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
200 ** as having been used.
202 ** The zWhere string must have been obtained from sqlite3_malloc().
203 ** This routine will take ownership of the allocated memory.
205 void sqlite3VdbeAddParseSchemaOp(Vdbe
*p
, int iDb
, char *zWhere
){
207 int addr
= sqlite3VdbeAddOp3(p
, OP_ParseSchema
, iDb
, 0, 0);
208 sqlite3VdbeChangeP4(p
, addr
, zWhere
, P4_DYNAMIC
);
209 for(j
=0; j
<p
->db
->nDb
; j
++) sqlite3VdbeUsesBtree(p
, j
);
213 ** Add an opcode that includes the p4 value as an integer.
215 int sqlite3VdbeAddOp4Int(
216 Vdbe
*p
, /* Add the opcode to this VM */
217 int op
, /* The new opcode */
218 int p1
, /* The P1 operand */
219 int p2
, /* The P2 operand */
220 int p3
, /* The P3 operand */
221 int p4
/* The P4 operand as an integer */
223 int addr
= sqlite3VdbeAddOp3(p
, op
, p1
, p2
, p3
);
224 sqlite3VdbeChangeP4(p
, addr
, SQLITE_INT_TO_PTR(p4
), P4_INT32
);
229 ** Create a new symbolic label for an instruction that has yet to be
230 ** coded. The symbolic label is really just a negative number. The
231 ** label can be used as the P2 value of an operation. Later, when
232 ** the label is resolved to a specific address, the VDBE will scan
233 ** through its operation list and change all values of P2 which match
234 ** the label into the resolved address.
236 ** The VDBE knows that a P2 value is a label because labels are
237 ** always negative and P2 values are suppose to be non-negative.
238 ** Hence, a negative P2 value is a label that has yet to be resolved.
240 ** Zero is returned if a malloc() fails.
242 int sqlite3VdbeMakeLabel(Vdbe
*p
){
244 assert( p
->magic
==VDBE_MAGIC_INIT
);
245 if( (i
& (i
-1))==0 ){
246 p
->aLabel
= sqlite3DbReallocOrFree(p
->db
, p
->aLabel
,
247 (i
*2+1)*sizeof(p
->aLabel
[0]));
256 ** Resolve label "x" to be the address of the next instruction to
257 ** be inserted. The parameter "x" must have been obtained from
258 ** a prior call to sqlite3VdbeMakeLabel().
260 void sqlite3VdbeResolveLabel(Vdbe
*p
, int x
){
262 assert( p
->magic
==VDBE_MAGIC_INIT
);
263 assert( j
>=0 && j
<p
->nLabel
);
265 p
->aLabel
[j
] = p
->nOp
;
270 ** Mark the VDBE as one that can only be run one time.
272 void sqlite3VdbeRunOnlyOnce(Vdbe
*p
){
276 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
279 ** The following type and function are used to iterate through all opcodes
280 ** in a Vdbe main program and each of the sub-programs (triggers) it may
281 ** invoke directly or indirectly. It should be used as follows:
286 ** memset(&sIter, 0, sizeof(sIter));
287 ** sIter.v = v; // v is of type Vdbe*
288 ** while( (pOp = opIterNext(&sIter)) ){
289 ** // Do something with pOp
291 ** sqlite3DbFree(v->db, sIter.apSub);
294 typedef struct VdbeOpIter VdbeOpIter
;
296 Vdbe
*v
; /* Vdbe to iterate through the opcodes of */
297 SubProgram
**apSub
; /* Array of subprograms */
298 int nSub
; /* Number of entries in apSub */
299 int iAddr
; /* Address of next instruction to return */
300 int iSub
; /* 0 = main program, 1 = first sub-program etc. */
302 static Op
*opIterNext(VdbeOpIter
*p
){
308 if( p
->iSub
<=p
->nSub
){
314 aOp
= p
->apSub
[p
->iSub
-1]->aOp
;
315 nOp
= p
->apSub
[p
->iSub
-1]->nOp
;
317 assert( p
->iAddr
<nOp
);
319 pRet
= &aOp
[p
->iAddr
];
326 if( pRet
->p4type
==P4_SUBPROGRAM
){
327 int nByte
= (p
->nSub
+1)*sizeof(SubProgram
*);
329 for(j
=0; j
<p
->nSub
; j
++){
330 if( p
->apSub
[j
]==pRet
->p4
.pProgram
) break;
333 p
->apSub
= sqlite3DbReallocOrFree(v
->db
, p
->apSub
, nByte
);
337 p
->apSub
[p
->nSub
++] = pRet
->p4
.pProgram
;
347 ** Check if the program stored in the VM associated with pParse may
348 ** throw an ABORT exception (causing the statement, but not entire transaction
349 ** to be rolled back). This condition is true if the main program or any
350 ** sub-programs contains any of the following:
352 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
353 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
357 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
359 ** Then check that the value of Parse.mayAbort is true if an
360 ** ABORT may be thrown, or false otherwise. Return true if it does
361 ** match, or false otherwise. This function is intended to be used as
362 ** part of an assert statement in the compiler. Similar to:
364 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
366 int sqlite3VdbeAssertMayAbort(Vdbe
*v
, int mayAbort
){
370 memset(&sIter
, 0, sizeof(sIter
));
373 while( (pOp
= opIterNext(&sIter
))!=0 ){
374 int opcode
= pOp
->opcode
;
375 if( opcode
==OP_Destroy
|| opcode
==OP_VUpdate
|| opcode
==OP_VRename
376 #ifndef SQLITE_OMIT_FOREIGN_KEY
377 || (opcode
==OP_FkCounter
&& pOp
->p1
==0 && pOp
->p2
==1)
379 || ((opcode
==OP_Halt
|| opcode
==OP_HaltIfNull
)
380 && (pOp
->p1
==SQLITE_CONSTRAINT
&& pOp
->p2
==OE_Abort
))
386 sqlite3DbFree(v
->db
, sIter
.apSub
);
388 /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
389 ** If malloc failed, then the while() loop above may not have iterated
390 ** through all opcodes and hasAbort may be set incorrectly. Return
391 ** true for this case to prevent the assert() in the callers frame
393 return ( v
->db
->mallocFailed
|| hasAbort
==mayAbort
);
395 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
398 ** Loop through the program looking for P2 values that are negative
399 ** on jump instructions. Each such value is a label. Resolve the
400 ** label by setting the P2 value to its correct non-zero value.
402 ** This routine is called once after all opcodes have been inserted.
404 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
405 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
406 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
408 ** The Op.opflags field is set on all opcodes.
410 static void resolveP2Values(Vdbe
*p
, int *pMaxFuncArgs
){
412 int nMaxArgs
= *pMaxFuncArgs
;
414 int *aLabel
= p
->aLabel
;
416 for(pOp
=p
->aOp
, i
=p
->nOp
-1; i
>=0; i
--, pOp
++){
417 u8 opcode
= pOp
->opcode
;
419 pOp
->opflags
= sqlite3OpcodeProperty
[opcode
];
420 if( opcode
==OP_Function
|| opcode
==OP_AggStep
){
421 if( pOp
->p5
>nMaxArgs
) nMaxArgs
= pOp
->p5
;
422 }else if( (opcode
==OP_Transaction
&& pOp
->p2
!=0) || opcode
==OP_Vacuum
){
424 #ifndef SQLITE_OMIT_VIRTUALTABLE
425 }else if( opcode
==OP_VUpdate
){
426 if( pOp
->p2
>nMaxArgs
) nMaxArgs
= pOp
->p2
;
427 }else if( opcode
==OP_VFilter
){
429 assert( p
->nOp
- i
>= 3 );
430 assert( pOp
[-1].opcode
==OP_Integer
);
432 if( n
>nMaxArgs
) nMaxArgs
= n
;
434 }else if( opcode
==OP_Next
|| opcode
==OP_SorterNext
){
435 pOp
->p4
.xAdvance
= sqlite3BtreeNext
;
436 pOp
->p4type
= P4_ADVANCE
;
437 }else if( opcode
==OP_Prev
){
438 pOp
->p4
.xAdvance
= sqlite3BtreePrevious
;
439 pOp
->p4type
= P4_ADVANCE
;
442 if( (pOp
->opflags
& OPFLG_JUMP
)!=0 && pOp
->p2
<0 ){
443 assert( -1-pOp
->p2
<p
->nLabel
);
444 pOp
->p2
= aLabel
[-1-pOp
->p2
];
447 sqlite3DbFree(p
->db
, p
->aLabel
);
450 *pMaxFuncArgs
= nMaxArgs
;
454 ** Return the address of the next instruction to be inserted.
456 int sqlite3VdbeCurrentAddr(Vdbe
*p
){
457 assert( p
->magic
==VDBE_MAGIC_INIT
);
462 ** This function returns a pointer to the array of opcodes associated with
463 ** the Vdbe passed as the first argument. It is the callers responsibility
464 ** to arrange for the returned array to be eventually freed using the
465 ** vdbeFreeOpArray() function.
467 ** Before returning, *pnOp is set to the number of entries in the returned
468 ** array. Also, *pnMaxArg is set to the larger of its current value and
469 ** the number of entries in the Vdbe.apArg[] array required to execute the
472 VdbeOp
*sqlite3VdbeTakeOpArray(Vdbe
*p
, int *pnOp
, int *pnMaxArg
){
473 VdbeOp
*aOp
= p
->aOp
;
474 assert( aOp
&& !p
->db
->mallocFailed
);
476 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
477 assert( p
->btreeMask
==0 );
479 resolveP2Values(p
, pnMaxArg
);
486 ** Add a whole list of operations to the operation stack. Return the
487 ** address of the first operation added.
489 int sqlite3VdbeAddOpList(Vdbe
*p
, int nOp
, VdbeOpList
const *aOp
){
491 assert( p
->magic
==VDBE_MAGIC_INIT
);
492 if( p
->nOp
+ nOp
> p
->nOpAlloc
&& growOpArray(p
) ){
498 VdbeOpList
const *pIn
= aOp
;
499 for(i
=0; i
<nOp
; i
++, pIn
++){
501 VdbeOp
*pOut
= &p
->aOp
[i
+addr
];
502 pOut
->opcode
= pIn
->opcode
;
504 if( p2
<0 && (sqlite3OpcodeProperty
[pOut
->opcode
] & OPFLG_JUMP
)!=0 ){
505 pOut
->p2
= addr
+ ADDR(p2
);
510 pOut
->p4type
= P4_NOTUSED
;
515 if( sqlite3VdbeAddopTrace
){
516 sqlite3VdbePrintOp(0, i
+addr
, &p
->aOp
[i
+addr
]);
526 ** Change the value of the P1 operand for a specific instruction.
527 ** This routine is useful when a large program is loaded from a
528 ** static array using sqlite3VdbeAddOpList but we want to make a
529 ** few minor changes to the program.
531 void sqlite3VdbeChangeP1(Vdbe
*p
, u32 addr
, int val
){
533 if( ((u32
)p
->nOp
)>addr
){
534 p
->aOp
[addr
].p1
= val
;
539 ** Change the value of the P2 operand for a specific instruction.
540 ** This routine is useful for setting a jump destination.
542 void sqlite3VdbeChangeP2(Vdbe
*p
, u32 addr
, int val
){
544 if( ((u32
)p
->nOp
)>addr
){
545 p
->aOp
[addr
].p2
= val
;
550 ** Change the value of the P3 operand for a specific instruction.
552 void sqlite3VdbeChangeP3(Vdbe
*p
, u32 addr
, int val
){
554 if( ((u32
)p
->nOp
)>addr
){
555 p
->aOp
[addr
].p3
= val
;
560 ** Change the value of the P5 operand for the most recently
563 void sqlite3VdbeChangeP5(Vdbe
*p
, u8 val
){
567 p
->aOp
[p
->nOp
-1].p5
= val
;
572 ** Change the P2 operand of instruction addr so that it points to
573 ** the address of the next instruction to be coded.
575 void sqlite3VdbeJumpHere(Vdbe
*p
, int addr
){
576 assert( addr
>=0 || p
->db
->mallocFailed
);
577 if( addr
>=0 ) sqlite3VdbeChangeP2(p
, addr
, p
->nOp
);
582 ** If the input FuncDef structure is ephemeral, then free it. If
583 ** the FuncDef is not ephermal, then do nothing.
585 static void freeEphemeralFunction(sqlite3
*db
, FuncDef
*pDef
){
586 if( ALWAYS(pDef
) && (pDef
->flags
& SQLITE_FUNC_EPHEM
)!=0 ){
587 sqlite3DbFree(db
, pDef
);
591 static void vdbeFreeOpArray(sqlite3
*, Op
*, int);
594 ** Delete a P4 value if necessary.
596 static void freeP4(sqlite3
*db
, int p4type
, void *p4
){
605 case P4_KEYINFO_HANDOFF
: {
606 sqlite3DbFree(db
, p4
);
610 if( db
->pnBytesFreed
==0 ) sqlite3_free(p4
);
614 VdbeFunc
*pVdbeFunc
= (VdbeFunc
*)p4
;
615 freeEphemeralFunction(db
, pVdbeFunc
->pFunc
);
616 if( db
->pnBytesFreed
==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc
, 0);
617 sqlite3DbFree(db
, pVdbeFunc
);
621 freeEphemeralFunction(db
, (FuncDef
*)p4
);
625 if( db
->pnBytesFreed
==0 ){
626 sqlite3ValueFree((sqlite3_value
*)p4
);
629 sqlite3DbFree(db
, p
->zMalloc
);
630 sqlite3DbFree(db
, p
);
635 if( db
->pnBytesFreed
==0 ) sqlite3VtabUnlock((VTable
*)p4
);
643 ** Free the space allocated for aOp and any p4 values allocated for the
644 ** opcodes contained within. If aOp is not NULL it is assumed to contain
647 static void vdbeFreeOpArray(sqlite3
*db
, Op
*aOp
, int nOp
){
650 for(pOp
=aOp
; pOp
<&aOp
[nOp
]; pOp
++){
651 freeP4(db
, pOp
->p4type
, pOp
->p4
.p
);
653 sqlite3DbFree(db
, pOp
->zComment
);
657 sqlite3DbFree(db
, aOp
);
661 ** Link the SubProgram object passed as the second argument into the linked
662 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
663 ** objects when the VM is no longer required.
665 void sqlite3VdbeLinkSubProgram(Vdbe
*pVdbe
, SubProgram
*p
){
666 p
->pNext
= pVdbe
->pProgram
;
671 ** Change the opcode at addr into OP_Noop
673 void sqlite3VdbeChangeToNoop(Vdbe
*p
, int addr
){
675 VdbeOp
*pOp
= &p
->aOp
[addr
];
677 freeP4(db
, pOp
->p4type
, pOp
->p4
.p
);
678 memset(pOp
, 0, sizeof(pOp
[0]));
679 pOp
->opcode
= OP_Noop
;
684 ** Change the value of the P4 operand for a specific instruction.
685 ** This routine is useful when a large program is loaded from a
686 ** static array using sqlite3VdbeAddOpList but we want to make a
687 ** few minor changes to the program.
689 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
690 ** the string is made into memory obtained from sqlite3_malloc().
691 ** A value of n==0 means copy bytes of zP4 up to and including the
692 ** first null byte. If n>0 then copy n+1 bytes of zP4.
694 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
695 ** A copy is made of the KeyInfo structure into memory obtained from
696 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
697 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
698 ** stored in memory that the caller has obtained from sqlite3_malloc. The
699 ** caller should not free the allocation, it will be freed when the Vdbe is
702 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
703 ** to a string or structure that is guaranteed to exist for the lifetime of
704 ** the Vdbe. In these cases we can just copy the pointer.
706 ** If addr<0 then change P4 on the most recently inserted instruction.
708 void sqlite3VdbeChangeP4(Vdbe
*p
, int addr
, const char *zP4
, int n
){
713 assert( p
->magic
==VDBE_MAGIC_INIT
);
714 if( p
->aOp
==0 || db
->mallocFailed
){
715 if ( n
!=P4_KEYINFO
&& n
!=P4_VTAB
) {
716 freeP4(db
, n
, (void*)*(char**)&zP4
);
721 assert( addr
<p
->nOp
);
726 freeP4(db
, pOp
->p4type
, pOp
->p4
.p
);
729 /* Note: this cast is safe, because the origin data point was an int
730 ** that was cast to a (const char *). */
731 pOp
->p4
.i
= SQLITE_PTR_TO_INT(zP4
);
732 pOp
->p4type
= P4_INT32
;
735 pOp
->p4type
= P4_NOTUSED
;
736 }else if( n
==P4_KEYINFO
){
740 nField
= ((KeyInfo
*)zP4
)->nField
;
741 nByte
= sizeof(*pKeyInfo
) + (nField
-1)*sizeof(pKeyInfo
->aColl
[0]) + nField
;
742 pKeyInfo
= sqlite3DbMallocRaw(0, nByte
);
743 pOp
->p4
.pKeyInfo
= pKeyInfo
;
746 memcpy((char*)pKeyInfo
, zP4
, nByte
- nField
);
747 aSortOrder
= pKeyInfo
->aSortOrder
;
749 pKeyInfo
->aSortOrder
= (unsigned char*)&pKeyInfo
->aColl
[nField
];
750 memcpy(pKeyInfo
->aSortOrder
, aSortOrder
, nField
);
752 pOp
->p4type
= P4_KEYINFO
;
754 p
->db
->mallocFailed
= 1;
755 pOp
->p4type
= P4_NOTUSED
;
757 }else if( n
==P4_KEYINFO_HANDOFF
){
758 pOp
->p4
.p
= (void*)zP4
;
759 pOp
->p4type
= P4_KEYINFO
;
760 }else if( n
==P4_VTAB
){
761 pOp
->p4
.p
= (void*)zP4
;
762 pOp
->p4type
= P4_VTAB
;
763 sqlite3VtabLock((VTable
*)zP4
);
764 assert( ((VTable
*)zP4
)->db
==p
->db
);
766 pOp
->p4
.p
= (void*)zP4
;
767 pOp
->p4type
= (signed char)n
;
769 if( n
==0 ) n
= sqlite3Strlen30(zP4
);
770 pOp
->p4
.z
= sqlite3DbStrNDup(p
->db
, zP4
, n
);
771 pOp
->p4type
= P4_DYNAMIC
;
777 ** Change the comment on the the most recently coded instruction. Or
778 ** insert a No-op and add the comment to that new instruction. This
779 ** makes the code easier to read during debugging. None of this happens
780 ** in a production build.
782 static void vdbeVComment(Vdbe
*p
, const char *zFormat
, va_list ap
){
783 assert( p
->nOp
>0 || p
->aOp
==0 );
784 assert( p
->aOp
==0 || p
->aOp
[p
->nOp
-1].zComment
==0 || p
->db
->mallocFailed
);
787 sqlite3DbFree(p
->db
, p
->aOp
[p
->nOp
-1].zComment
);
788 p
->aOp
[p
->nOp
-1].zComment
= sqlite3VMPrintf(p
->db
, zFormat
, ap
);
791 void sqlite3VdbeComment(Vdbe
*p
, const char *zFormat
, ...){
794 va_start(ap
, zFormat
);
795 vdbeVComment(p
, zFormat
, ap
);
799 void sqlite3VdbeNoopComment(Vdbe
*p
, const char *zFormat
, ...){
802 sqlite3VdbeAddOp0(p
, OP_Noop
);
803 va_start(ap
, zFormat
);
804 vdbeVComment(p
, zFormat
, ap
);
811 ** Return the opcode for a given address. If the address is -1, then
812 ** return the most recently inserted opcode.
814 ** If a memory allocation error has occurred prior to the calling of this
815 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
816 ** is readable but not writable, though it is cast to a writable value.
817 ** The return of a dummy opcode allows the call to continue functioning
818 ** after a OOM fault without having to check to see if the return from
819 ** this routine is a valid pointer. But because the dummy.opcode is 0,
820 ** dummy will never be written to. This is verified by code inspection and
821 ** by running with Valgrind.
823 ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
824 ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
825 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
826 ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
827 ** having to double-check to make sure that the result is non-negative. But
828 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
829 ** check the value of p->nOp-1 before continuing.
831 VdbeOp
*sqlite3VdbeGetOp(Vdbe
*p
, int addr
){
832 /* C89 specifies that the constant "dummy" will be initialized to all
833 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
834 static VdbeOp dummy
; /* Ignore the MSVC warning about no initializer */
835 assert( p
->magic
==VDBE_MAGIC_INIT
);
837 #ifdef SQLITE_OMIT_TRACE
838 if( p
->nOp
==0 ) return (VdbeOp
*)&dummy
;
842 assert( (addr
>=0 && addr
<p
->nOp
) || p
->db
->mallocFailed
);
843 if( p
->db
->mallocFailed
){
844 return (VdbeOp
*)&dummy
;
846 return &p
->aOp
[addr
];
850 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
851 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
853 ** Compute a string that describes the P4 parameter for an opcode.
854 ** Use zTemp for any required temporary buffer space.
856 static char *displayP4(Op
*pOp
, char *zTemp
, int nTemp
){
859 switch( pOp
->p4type
){
860 case P4_KEYINFO_STATIC
:
863 KeyInfo
*pKeyInfo
= pOp
->p4
.pKeyInfo
;
864 sqlite3_snprintf(nTemp
, zTemp
, "keyinfo(%d", pKeyInfo
->nField
);
865 i
= sqlite3Strlen30(zTemp
);
866 for(j
=0; j
<pKeyInfo
->nField
; j
++){
867 CollSeq
*pColl
= pKeyInfo
->aColl
[j
];
869 int n
= sqlite3Strlen30(pColl
->zName
);
871 memcpy(&zTemp
[i
],",...",4);
875 if( pKeyInfo
->aSortOrder
&& pKeyInfo
->aSortOrder
[j
] ){
878 memcpy(&zTemp
[i
], pColl
->zName
,n
+1);
880 }else if( i
+4<nTemp
-6 ){
881 memcpy(&zTemp
[i
],",nil",4);
891 CollSeq
*pColl
= pOp
->p4
.pColl
;
892 sqlite3_snprintf(nTemp
, zTemp
, "collseq(%.20s)", pColl
->zName
);
896 FuncDef
*pDef
= pOp
->p4
.pFunc
;
897 sqlite3_snprintf(nTemp
, zTemp
, "%s(%d)", pDef
->zName
, pDef
->nArg
);
901 sqlite3_snprintf(nTemp
, zTemp
, "%lld", *pOp
->p4
.pI64
);
905 sqlite3_snprintf(nTemp
, zTemp
, "%d", pOp
->p4
.i
);
909 sqlite3_snprintf(nTemp
, zTemp
, "%.16g", *pOp
->p4
.pReal
);
913 Mem
*pMem
= pOp
->p4
.pMem
;
914 if( pMem
->flags
& MEM_Str
){
916 }else if( pMem
->flags
& MEM_Int
){
917 sqlite3_snprintf(nTemp
, zTemp
, "%lld", pMem
->u
.i
);
918 }else if( pMem
->flags
& MEM_Real
){
919 sqlite3_snprintf(nTemp
, zTemp
, "%.16g", pMem
->r
);
920 }else if( pMem
->flags
& MEM_Null
){
921 sqlite3_snprintf(nTemp
, zTemp
, "NULL");
923 assert( pMem
->flags
& MEM_Blob
);
928 #ifndef SQLITE_OMIT_VIRTUALTABLE
930 sqlite3_vtab
*pVtab
= pOp
->p4
.pVtab
->pVtab
;
931 sqlite3_snprintf(nTemp
, zTemp
, "vtab:%p:%p", pVtab
, pVtab
->pModule
);
936 sqlite3_snprintf(nTemp
, zTemp
, "intarray");
939 case P4_SUBPROGRAM
: {
940 sqlite3_snprintf(nTemp
, zTemp
, "program");
961 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
963 ** The prepared statements need to know in advance the complete set of
964 ** attached databases that will be use. A mask of these databases
965 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
966 ** p->btreeMask of databases that will require a lock.
968 void sqlite3VdbeUsesBtree(Vdbe
*p
, int i
){
969 assert( i
>=0 && i
<p
->db
->nDb
&& i
<(int)sizeof(yDbMask
)*8 );
970 assert( i
<(int)sizeof(p
->btreeMask
)*8 );
971 p
->btreeMask
|= ((yDbMask
)1)<<i
;
972 if( i
!=1 && sqlite3BtreeSharable(p
->db
->aDb
[i
].pBt
) ){
973 p
->lockMask
|= ((yDbMask
)1)<<i
;
977 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
979 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
980 ** this routine obtains the mutex associated with each BtShared structure
981 ** that may be accessed by the VM passed as an argument. In doing so it also
982 ** sets the BtShared.db member of each of the BtShared structures, ensuring
983 ** that the correct busy-handler callback is invoked if required.
985 ** If SQLite is not threadsafe but does support shared-cache mode, then
986 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
987 ** of all of BtShared structures accessible via the database handle
988 ** associated with the VM.
990 ** If SQLite is not threadsafe and does not support shared-cache mode, this
991 ** function is a no-op.
993 ** The p->btreeMask field is a bitmask of all btrees that the prepared
994 ** statement p will ever use. Let N be the number of bits in p->btreeMask
995 ** corresponding to btrees that use shared cache. Then the runtime of
996 ** this routine is N*N. But as N is rarely more than 1, this should not
999 void sqlite3VdbeEnter(Vdbe
*p
){
1005 if( p
->lockMask
==0 ) return; /* The common case */
1009 for(i
=0, mask
=1; i
<nDb
; i
++, mask
+= mask
){
1010 if( i
!=1 && (mask
& p
->lockMask
)!=0 && ALWAYS(aDb
[i
].pBt
!=0) ){
1011 sqlite3BtreeEnter(aDb
[i
].pBt
);
1017 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1019 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1021 void sqlite3VdbeLeave(Vdbe
*p
){
1027 if( p
->lockMask
==0 ) return; /* The common case */
1031 for(i
=0, mask
=1; i
<nDb
; i
++, mask
+= mask
){
1032 if( i
!=1 && (mask
& p
->lockMask
)!=0 && ALWAYS(aDb
[i
].pBt
!=0) ){
1033 sqlite3BtreeLeave(aDb
[i
].pBt
);
1039 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
1041 ** Print a single opcode. This routine is used for debugging only.
1043 void sqlite3VdbePrintOp(FILE *pOut
, int pc
, Op
*pOp
){
1046 static const char *zFormat1
= "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
1047 if( pOut
==0 ) pOut
= stdout
;
1048 zP4
= displayP4(pOp
, zPtr
, sizeof(zPtr
));
1049 fprintf(pOut
, zFormat1
, pc
,
1050 sqlite3OpcodeName(pOp
->opcode
), pOp
->p1
, pOp
->p2
, pOp
->p3
, zP4
, pOp
->p5
,
1052 pOp
->zComment
? pOp
->zComment
: ""
1062 ** Release an array of N Mem elements
1064 static void releaseMemArray(Mem
*p
, int N
){
1067 sqlite3
*db
= p
->db
;
1068 u8 malloc_failed
= db
->mallocFailed
;
1069 if( db
->pnBytesFreed
){
1070 for(pEnd
=&p
[N
]; p
<pEnd
; p
++){
1071 sqlite3DbFree(db
, p
->zMalloc
);
1075 for(pEnd
=&p
[N
]; p
<pEnd
; p
++){
1076 assert( (&p
[1])==pEnd
|| p
[0].db
==p
[1].db
);
1078 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1079 ** that takes advantage of the fact that the memory cell value is
1080 ** being set to NULL after releasing any dynamic resources.
1082 ** The justification for duplicating code is that according to
1083 ** callgrind, this causes a certain test case to hit the CPU 4.7
1084 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1085 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1086 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1087 ** with no indexes using a single prepared INSERT statement, bind()
1088 ** and reset(). Inserts are grouped into a transaction.
1090 if( p
->flags
&(MEM_Agg
|MEM_Dyn
|MEM_Frame
|MEM_RowSet
) ){
1091 sqlite3VdbeMemRelease(p
);
1092 }else if( p
->zMalloc
){
1093 sqlite3DbFree(db
, p
->zMalloc
);
1097 p
->flags
= MEM_Invalid
;
1099 db
->mallocFailed
= malloc_failed
;
1104 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1105 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
1107 void sqlite3VdbeFrameDelete(VdbeFrame
*p
){
1109 Mem
*aMem
= VdbeFrameMem(p
);
1110 VdbeCursor
**apCsr
= (VdbeCursor
**)&aMem
[p
->nChildMem
];
1111 for(i
=0; i
<p
->nChildCsr
; i
++){
1112 sqlite3VdbeFreeCursor(p
->v
, apCsr
[i
]);
1114 releaseMemArray(aMem
, p
->nChildMem
);
1115 sqlite3DbFree(p
->v
->db
, p
);
1118 #ifndef SQLITE_OMIT_EXPLAIN
1120 ** Give a listing of the program in the virtual machine.
1122 ** The interface is the same as sqlite3VdbeExec(). But instead of
1123 ** running the code, it invokes the callback once for each instruction.
1124 ** This feature is used to implement "EXPLAIN".
1126 ** When p->explain==1, each instruction is listed. When
1127 ** p->explain==2, only OP_Explain instructions are listed and these
1128 ** are shown in a different format. p->explain==2 is used to implement
1129 ** EXPLAIN QUERY PLAN.
1131 ** When p->explain==1, first the main program is listed, then each of
1132 ** the trigger subprograms are listed one by one.
1134 int sqlite3VdbeList(
1135 Vdbe
*p
/* The VDBE */
1137 int nRow
; /* Stop when row count reaches this */
1138 int nSub
= 0; /* Number of sub-vdbes seen so far */
1139 SubProgram
**apSub
= 0; /* Array of sub-vdbes */
1140 Mem
*pSub
= 0; /* Memory cell hold array of subprogs */
1141 sqlite3
*db
= p
->db
; /* The database connection */
1142 int i
; /* Loop counter */
1143 int rc
= SQLITE_OK
; /* Return code */
1144 Mem
*pMem
= &p
->aMem
[1]; /* First Mem of result set */
1146 assert( p
->explain
);
1147 assert( p
->magic
==VDBE_MAGIC_RUN
);
1148 assert( p
->rc
==SQLITE_OK
|| p
->rc
==SQLITE_BUSY
|| p
->rc
==SQLITE_NOMEM
);
1150 /* Even though this opcode does not use dynamic strings for
1151 ** the result, result columns may become dynamic if the user calls
1152 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
1154 releaseMemArray(pMem
, 8);
1157 if( p
->rc
==SQLITE_NOMEM
){
1158 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1159 ** sqlite3_column_text16() failed. */
1160 db
->mallocFailed
= 1;
1161 return SQLITE_ERROR
;
1164 /* When the number of output rows reaches nRow, that means the
1165 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1166 ** nRow is the sum of the number of rows in the main program, plus
1167 ** the sum of the number of rows in all trigger subprograms encountered
1168 ** so far. The nRow value will increase as new trigger subprograms are
1169 ** encountered, but p->pc will eventually catch up to nRow.
1172 if( p
->explain
==1 ){
1173 /* The first 8 memory cells are used for the result set. So we will
1174 ** commandeer the 9th cell to use as storage for an array of pointers
1175 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1177 assert( p
->nMem
>9 );
1179 if( pSub
->flags
&MEM_Blob
){
1180 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1181 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
1182 nSub
= pSub
->n
/sizeof(Vdbe
*);
1183 apSub
= (SubProgram
**)pSub
->z
;
1185 for(i
=0; i
<nSub
; i
++){
1186 nRow
+= apSub
[i
]->nOp
;
1192 }while( i
<nRow
&& p
->explain
==2 && p
->aOp
[i
].opcode
!=OP_Explain
);
1196 }else if( db
->u1
.isInterrupted
){
1197 p
->rc
= SQLITE_INTERRUPT
;
1199 sqlite3SetString(&p
->zErrMsg
, db
, "%s", sqlite3ErrStr(p
->rc
));
1204 /* The output line number is small enough that we are still in the
1208 /* We are currently listing subprograms. Figure out which one and
1209 ** pick up the appropriate opcode. */
1212 for(j
=0; i
>=apSub
[j
]->nOp
; j
++){
1215 pOp
= &apSub
[j
]->aOp
[i
];
1217 if( p
->explain
==1 ){
1218 pMem
->flags
= MEM_Int
;
1219 pMem
->type
= SQLITE_INTEGER
;
1220 pMem
->u
.i
= i
; /* Program counter */
1223 pMem
->flags
= MEM_Static
|MEM_Str
|MEM_Term
;
1224 pMem
->z
= (char*)sqlite3OpcodeName(pOp
->opcode
); /* Opcode */
1225 assert( pMem
->z
!=0 );
1226 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1227 pMem
->type
= SQLITE_TEXT
;
1228 pMem
->enc
= SQLITE_UTF8
;
1231 /* When an OP_Program opcode is encounter (the only opcode that has
1232 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1233 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1234 ** has not already been seen.
1236 if( pOp
->p4type
==P4_SUBPROGRAM
){
1237 int nByte
= (nSub
+1)*sizeof(SubProgram
*);
1239 for(j
=0; j
<nSub
; j
++){
1240 if( apSub
[j
]==pOp
->p4
.pProgram
) break;
1242 if( j
==nSub
&& SQLITE_OK
==sqlite3VdbeMemGrow(pSub
, nByte
, nSub
!=0) ){
1243 apSub
= (SubProgram
**)pSub
->z
;
1244 apSub
[nSub
++] = pOp
->p4
.pProgram
;
1245 pSub
->flags
|= MEM_Blob
;
1246 pSub
->n
= nSub
*sizeof(SubProgram
*);
1251 pMem
->flags
= MEM_Int
;
1252 pMem
->u
.i
= pOp
->p1
; /* P1 */
1253 pMem
->type
= SQLITE_INTEGER
;
1256 pMem
->flags
= MEM_Int
;
1257 pMem
->u
.i
= pOp
->p2
; /* P2 */
1258 pMem
->type
= SQLITE_INTEGER
;
1261 pMem
->flags
= MEM_Int
;
1262 pMem
->u
.i
= pOp
->p3
; /* P3 */
1263 pMem
->type
= SQLITE_INTEGER
;
1266 if( sqlite3VdbeMemGrow(pMem
, 32, 0) ){ /* P4 */
1267 assert( p
->db
->mallocFailed
);
1268 return SQLITE_ERROR
;
1270 pMem
->flags
= MEM_Dyn
|MEM_Str
|MEM_Term
;
1271 z
= displayP4(pOp
, pMem
->z
, 32);
1273 sqlite3VdbeMemSetStr(pMem
, z
, -1, SQLITE_UTF8
, 0);
1275 assert( pMem
->z
!=0 );
1276 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1277 pMem
->enc
= SQLITE_UTF8
;
1279 pMem
->type
= SQLITE_TEXT
;
1282 if( p
->explain
==1 ){
1283 if( sqlite3VdbeMemGrow(pMem
, 4, 0) ){
1284 assert( p
->db
->mallocFailed
);
1285 return SQLITE_ERROR
;
1287 pMem
->flags
= MEM_Dyn
|MEM_Str
|MEM_Term
;
1289 sqlite3_snprintf(3, pMem
->z
, "%.2x", pOp
->p5
); /* P5 */
1290 pMem
->type
= SQLITE_TEXT
;
1291 pMem
->enc
= SQLITE_UTF8
;
1295 if( pOp
->zComment
){
1296 pMem
->flags
= MEM_Str
|MEM_Term
;
1297 pMem
->z
= pOp
->zComment
;
1298 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1299 pMem
->enc
= SQLITE_UTF8
;
1300 pMem
->type
= SQLITE_TEXT
;
1304 pMem
->flags
= MEM_Null
; /* Comment */
1305 pMem
->type
= SQLITE_NULL
;
1309 p
->nResColumn
= 8 - 4*(p
->explain
-1);
1310 p
->pResultSet
= &p
->aMem
[1];
1316 #endif /* SQLITE_OMIT_EXPLAIN */
1320 ** Print the SQL that was used to generate a VDBE program.
1322 void sqlite3VdbePrintSql(Vdbe
*p
){
1327 if( pOp
->opcode
==OP_Trace
&& pOp
->p4
.z
!=0 ){
1328 const char *z
= pOp
->p4
.z
;
1329 while( sqlite3Isspace(*z
) ) z
++;
1330 printf("SQL: [%s]\n", z
);
1335 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1337 ** Print an IOTRACE message showing SQL content.
1339 void sqlite3VdbeIOTraceSql(Vdbe
*p
){
1342 if( sqlite3IoTrace
==0 ) return;
1345 if( pOp
->opcode
==OP_Trace
&& pOp
->p4
.z
!=0 ){
1348 sqlite3_snprintf(sizeof(z
), z
, "%s", pOp
->p4
.z
);
1349 for(i
=0; sqlite3Isspace(z
[i
]); i
++){}
1350 for(j
=0; z
[i
]; i
++){
1351 if( sqlite3Isspace(z
[i
]) ){
1360 sqlite3IoTrace("SQL %s\n", z
);
1363 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1366 ** Allocate space from a fixed size buffer and return a pointer to
1367 ** that space. If insufficient space is available, return NULL.
1369 ** The pBuf parameter is the initial value of a pointer which will
1370 ** receive the new memory. pBuf is normally NULL. If pBuf is not
1371 ** NULL, it means that memory space has already been allocated and that
1372 ** this routine should not allocate any new memory. When pBuf is not
1373 ** NULL simply return pBuf. Only allocate new memory space when pBuf
1376 ** nByte is the number of bytes of space needed.
1378 ** *ppFrom points to available space and pEnd points to the end of the
1379 ** available space. When space is allocated, *ppFrom is advanced past
1380 ** the end of the allocated space.
1382 ** *pnByte is a counter of the number of bytes of space that have failed
1383 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
1384 ** request, then increment *pnByte by the amount of the request.
1386 static void *allocSpace(
1387 void *pBuf
, /* Where return pointer will be stored */
1388 int nByte
, /* Number of bytes to allocate */
1389 u8
**ppFrom
, /* IN/OUT: Allocate from *ppFrom */
1390 u8
*pEnd
, /* Pointer to 1 byte past the end of *ppFrom buffer */
1391 int *pnByte
/* If allocation cannot be made, increment *pnByte */
1393 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom
) );
1394 if( pBuf
) return pBuf
;
1395 nByte
= ROUND8(nByte
);
1396 if( &(*ppFrom
)[nByte
] <= pEnd
){
1397 pBuf
= (void*)*ppFrom
;
1406 ** Rewind the VDBE back to the beginning in preparation for
1409 void sqlite3VdbeRewind(Vdbe
*p
){
1410 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1414 assert( p
->magic
==VDBE_MAGIC_INIT
);
1416 /* There should be at least one opcode.
1420 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
1421 p
->magic
= VDBE_MAGIC_RUN
;
1424 for(i
=1; i
<p
->nMem
; i
++){
1425 assert( p
->aMem
[i
].db
==p
->db
);
1430 p
->errorAction
= OE_Abort
;
1431 p
->magic
= VDBE_MAGIC_RUN
;
1434 p
->minWriteFileFormat
= 255;
1436 p
->nFkConstraint
= 0;
1438 for(i
=0; i
<p
->nOp
; i
++){
1440 p
->aOp
[i
].cycles
= 0;
1446 ** Prepare a virtual machine for execution for the first time after
1447 ** creating the virtual machine. This involves things such
1448 ** as allocating stack space and initializing the program counter.
1449 ** After the VDBE has be prepped, it can be executed by one or more
1450 ** calls to sqlite3VdbeExec().
1452 ** This function may be called exact once on a each virtual machine.
1453 ** After this routine is called the VM has been "packaged" and is ready
1454 ** to run. After this routine is called, futher calls to
1455 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
1456 ** the Vdbe from the Parse object that helped generate it so that the
1457 ** the Vdbe becomes an independent entity and the Parse object can be
1460 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1461 ** to its initial state after it has been run.
1463 void sqlite3VdbeMakeReady(
1464 Vdbe
*p
, /* The VDBE */
1465 Parse
*pParse
/* Parsing context */
1467 sqlite3
*db
; /* The database connection */
1468 int nVar
; /* Number of parameters */
1469 int nMem
; /* Number of VM memory registers */
1470 int nCursor
; /* Number of cursors required */
1471 int nArg
; /* Number of arguments in subprograms */
1472 int nOnce
; /* Number of OP_Once instructions */
1473 int n
; /* Loop counter */
1474 u8
*zCsr
; /* Memory available for allocation */
1475 u8
*zEnd
; /* First byte past allocated memory */
1476 int nByte
; /* How much extra memory is needed */
1480 assert( pParse
!=0 );
1481 assert( p
->magic
==VDBE_MAGIC_INIT
);
1483 assert( db
->mallocFailed
==0 );
1484 nVar
= pParse
->nVar
;
1485 nMem
= pParse
->nMem
;
1486 nCursor
= pParse
->nTab
;
1487 nArg
= pParse
->nMaxArg
;
1488 nOnce
= pParse
->nOnce
;
1489 if( nOnce
==0 ) nOnce
= 1; /* Ensure at least one byte in p->aOnceFlag[] */
1491 /* For each cursor required, also allocate a memory cell. Memory
1492 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
1493 ** the vdbe program. Instead they are used to allocate space for
1494 ** VdbeCursor/BtCursor structures. The blob of memory associated with
1495 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
1496 ** stores the blob of memory associated with cursor 1, etc.
1498 ** See also: allocateCursor().
1502 /* Allocate space for memory registers, SQL variables, VDBE cursors and
1503 ** an array to marshal SQL function arguments in.
1505 zCsr
= (u8
*)&p
->aOp
[p
->nOp
]; /* Memory avaliable for allocation */
1506 zEnd
= (u8
*)&p
->aOp
[p
->nOpAlloc
]; /* First byte past end of zCsr[] */
1508 resolveP2Values(p
, &nArg
);
1509 p
->usesStmtJournal
= (u8
)(pParse
->isMultiWrite
&& pParse
->mayAbort
);
1510 if( pParse
->explain
&& nMem
<10 ){
1513 memset(zCsr
, 0, zEnd
-zCsr
);
1514 zCsr
+= (zCsr
- (u8
*)0)&7;
1515 assert( EIGHT_BYTE_ALIGNMENT(zCsr
) );
1518 /* Memory for registers, parameters, cursor, etc, is allocated in two
1519 ** passes. On the first pass, we try to reuse unused space at the
1520 ** end of the opcode array. If we are unable to satisfy all memory
1521 ** requirements by reusing the opcode array tail, then the second
1522 ** pass will fill in the rest using a fresh allocation.
1524 ** This two-pass approach that reuses as much memory as possible from
1525 ** the leftover space at the end of the opcode array can significantly
1526 ** reduce the amount of memory held by a prepared statement.
1530 p
->aMem
= allocSpace(p
->aMem
, nMem
*sizeof(Mem
), &zCsr
, zEnd
, &nByte
);
1531 p
->aVar
= allocSpace(p
->aVar
, nVar
*sizeof(Mem
), &zCsr
, zEnd
, &nByte
);
1532 p
->apArg
= allocSpace(p
->apArg
, nArg
*sizeof(Mem
*), &zCsr
, zEnd
, &nByte
);
1533 p
->azVar
= allocSpace(p
->azVar
, nVar
*sizeof(char*), &zCsr
, zEnd
, &nByte
);
1534 p
->apCsr
= allocSpace(p
->apCsr
, nCursor
*sizeof(VdbeCursor
*),
1535 &zCsr
, zEnd
, &nByte
);
1536 p
->aOnceFlag
= allocSpace(p
->aOnceFlag
, nOnce
, &zCsr
, zEnd
, &nByte
);
1538 p
->pFree
= sqlite3DbMallocZero(db
, nByte
);
1541 zEnd
= &zCsr
[nByte
];
1542 }while( nByte
&& !db
->mallocFailed
);
1544 p
->nCursor
= (u16
)nCursor
;
1545 p
->nOnceFlag
= nOnce
;
1547 p
->nVar
= (ynVar
)nVar
;
1548 for(n
=0; n
<nVar
; n
++){
1549 p
->aVar
[n
].flags
= MEM_Null
;
1554 p
->nzVar
= pParse
->nzVar
;
1555 memcpy(p
->azVar
, pParse
->azVar
, p
->nzVar
*sizeof(p
->azVar
[0]));
1556 memset(pParse
->azVar
, 0, pParse
->nzVar
*sizeof(pParse
->azVar
[0]));
1559 p
->aMem
--; /* aMem[] goes from 1..nMem */
1560 p
->nMem
= nMem
; /* not from 0..nMem-1 */
1561 for(n
=1; n
<=nMem
; n
++){
1562 p
->aMem
[n
].flags
= MEM_Invalid
;
1566 p
->explain
= pParse
->explain
;
1567 sqlite3VdbeRewind(p
);
1571 ** Close a VDBE cursor and release all the resources that cursor
1574 void sqlite3VdbeFreeCursor(Vdbe
*p
, VdbeCursor
*pCx
){
1578 sqlite3VdbeSorterClose(p
->db
, pCx
);
1580 sqlite3BtreeClose(pCx
->pBt
);
1581 /* The pCx->pCursor will be close automatically, if it exists, by
1582 ** the call above. */
1583 }else if( pCx
->pCursor
){
1584 sqlite3BtreeCloseCursor(pCx
->pCursor
);
1586 #ifndef SQLITE_OMIT_VIRTUALTABLE
1587 if( pCx
->pVtabCursor
){
1588 sqlite3_vtab_cursor
*pVtabCursor
= pCx
->pVtabCursor
;
1589 const sqlite3_module
*pModule
= pCx
->pModule
;
1590 p
->inVtabMethod
= 1;
1591 pModule
->xClose(pVtabCursor
);
1592 p
->inVtabMethod
= 0;
1598 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
1599 ** is used, for example, when a trigger sub-program is halted to restore
1600 ** control to the main program.
1602 int sqlite3VdbeFrameRestore(VdbeFrame
*pFrame
){
1603 Vdbe
*v
= pFrame
->v
;
1604 v
->aOnceFlag
= pFrame
->aOnceFlag
;
1605 v
->nOnceFlag
= pFrame
->nOnceFlag
;
1606 v
->aOp
= pFrame
->aOp
;
1607 v
->nOp
= pFrame
->nOp
;
1608 v
->aMem
= pFrame
->aMem
;
1609 v
->nMem
= pFrame
->nMem
;
1610 v
->apCsr
= pFrame
->apCsr
;
1611 v
->nCursor
= pFrame
->nCursor
;
1612 v
->db
->lastRowid
= pFrame
->lastRowid
;
1613 v
->nChange
= pFrame
->nChange
;
1618 ** Close all cursors.
1620 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
1621 ** cell array. This is necessary as the memory cell array may contain
1622 ** pointers to VdbeFrame objects, which may in turn contain pointers to
1625 static void closeAllCursors(Vdbe
*p
){
1628 for(pFrame
=p
->pFrame
; pFrame
->pParent
; pFrame
=pFrame
->pParent
);
1629 sqlite3VdbeFrameRestore(pFrame
);
1636 for(i
=0; i
<p
->nCursor
; i
++){
1637 VdbeCursor
*pC
= p
->apCsr
[i
];
1639 sqlite3VdbeFreeCursor(p
, pC
);
1645 releaseMemArray(&p
->aMem
[1], p
->nMem
);
1647 while( p
->pDelFrame
){
1648 VdbeFrame
*pDel
= p
->pDelFrame
;
1649 p
->pDelFrame
= pDel
->pParent
;
1650 sqlite3VdbeFrameDelete(pDel
);
1655 ** Clean up the VM after execution.
1657 ** This routine will automatically close any cursors, lists, and/or
1658 ** sorters that were left open. It also deletes the values of
1659 ** variables in the aVar[] array.
1661 static void Cleanup(Vdbe
*p
){
1662 sqlite3
*db
= p
->db
;
1665 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
1666 ** Vdbe.aMem[] arrays have already been cleaned up. */
1668 if( p
->apCsr
) for(i
=0; i
<p
->nCursor
; i
++) assert( p
->apCsr
[i
]==0 );
1670 for(i
=1; i
<=p
->nMem
; i
++) assert( p
->aMem
[i
].flags
==MEM_Invalid
);
1674 sqlite3DbFree(db
, p
->zErrMsg
);
1680 ** Set the number of result columns that will be returned by this SQL
1681 ** statement. This is now set at compile time, rather than during
1682 ** execution of the vdbe program so that sqlite3_column_count() can
1683 ** be called on an SQL statement before sqlite3_step().
1685 void sqlite3VdbeSetNumCols(Vdbe
*p
, int nResColumn
){
1688 sqlite3
*db
= p
->db
;
1690 releaseMemArray(p
->aColName
, p
->nResColumn
*COLNAME_N
);
1691 sqlite3DbFree(db
, p
->aColName
);
1692 n
= nResColumn
*COLNAME_N
;
1693 p
->nResColumn
= (u16
)nResColumn
;
1694 p
->aColName
= pColName
= (Mem
*)sqlite3DbMallocZero(db
, sizeof(Mem
)*n
);
1695 if( p
->aColName
==0 ) return;
1697 pColName
->flags
= MEM_Null
;
1698 pColName
->db
= p
->db
;
1704 ** Set the name of the idx'th column to be returned by the SQL statement.
1705 ** zName must be a pointer to a nul terminated string.
1707 ** This call must be made after a call to sqlite3VdbeSetNumCols().
1709 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
1710 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
1711 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
1713 int sqlite3VdbeSetColName(
1714 Vdbe
*p
, /* Vdbe being configured */
1715 int idx
, /* Index of column zName applies to */
1716 int var
, /* One of the COLNAME_* constants */
1717 const char *zName
, /* Pointer to buffer containing name */
1718 void (*xDel
)(void*) /* Memory management strategy for zName */
1722 assert( idx
<p
->nResColumn
);
1723 assert( var
<COLNAME_N
);
1724 if( p
->db
->mallocFailed
){
1725 assert( !zName
|| xDel
!=SQLITE_DYNAMIC
);
1726 return SQLITE_NOMEM
;
1728 assert( p
->aColName
!=0 );
1729 pColName
= &(p
->aColName
[idx
+var
*p
->nResColumn
]);
1730 rc
= sqlite3VdbeMemSetStr(pColName
, zName
, -1, SQLITE_UTF8
, xDel
);
1731 assert( rc
!=0 || !zName
|| (pColName
->flags
&MEM_Term
)!=0 );
1736 ** A read or write transaction may or may not be active on database handle
1737 ** db. If a transaction is active, commit it. If there is a
1738 ** write-transaction spanning more than one database file, this routine
1739 ** takes care of the master journal trickery.
1741 static int vdbeCommit(sqlite3
*db
, Vdbe
*p
){
1743 int nTrans
= 0; /* Number of databases with an active write-transaction */
1745 int needXcommit
= 0;
1747 #ifdef SQLITE_OMIT_VIRTUALTABLE
1748 /* With this option, sqlite3VtabSync() is defined to be simply
1749 ** SQLITE_OK so p is not used.
1751 UNUSED_PARAMETER(p
);
1754 /* Before doing anything else, call the xSync() callback for any
1755 ** virtual module tables written in this transaction. This has to
1756 ** be done before determining whether a master journal file is
1757 ** required, as an xSync() callback may add an attached database
1758 ** to the transaction.
1760 rc
= sqlite3VtabSync(db
, &p
->zErrMsg
);
1762 /* This loop determines (a) if the commit hook should be invoked and
1763 ** (b) how many database files have open write transactions, not
1764 ** including the temp database. (b) is important because if more than
1765 ** one database file has an open write transaction, a master journal
1766 ** file is required for an atomic commit.
1768 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1769 Btree
*pBt
= db
->aDb
[i
].pBt
;
1770 if( sqlite3BtreeIsInTrans(pBt
) ){
1772 if( i
!=1 ) nTrans
++;
1773 rc
= sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt
));
1776 if( rc
!=SQLITE_OK
){
1780 /* If there are any write-transactions at all, invoke the commit hook */
1781 if( needXcommit
&& db
->xCommitCallback
){
1782 rc
= db
->xCommitCallback(db
->pCommitArg
);
1784 return SQLITE_CONSTRAINT
;
1788 /* The simple case - no more than one database file (not counting the
1789 ** TEMP database) has a transaction active. There is no need for the
1792 ** If the return value of sqlite3BtreeGetFilename() is a zero length
1793 ** string, it means the main database is :memory: or a temp file. In
1794 ** that case we do not support atomic multi-file commits, so use the
1795 ** simple case then too.
1797 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db
->aDb
[0].pBt
))
1800 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1801 Btree
*pBt
= db
->aDb
[i
].pBt
;
1803 rc
= sqlite3BtreeCommitPhaseOne(pBt
, 0);
1807 /* Do the commit only if all databases successfully complete phase 1.
1808 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1809 ** IO error while deleting or truncating a journal file. It is unlikely,
1810 ** but could happen. In this case abandon processing and return the error.
1812 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1813 Btree
*pBt
= db
->aDb
[i
].pBt
;
1815 rc
= sqlite3BtreeCommitPhaseTwo(pBt
, 0);
1818 if( rc
==SQLITE_OK
){
1819 sqlite3VtabCommit(db
);
1823 /* The complex case - There is a multi-file write-transaction active.
1824 ** This requires a master journal file to ensure the transaction is
1825 ** committed atomicly.
1827 #ifndef SQLITE_OMIT_DISKIO
1829 sqlite3_vfs
*pVfs
= db
->pVfs
;
1831 char *zMaster
= 0; /* File-name for the master journal */
1832 char const *zMainFile
= sqlite3BtreeGetFilename(db
->aDb
[0].pBt
);
1833 sqlite3_file
*pMaster
= 0;
1839 /* Select a master journal file name */
1840 nMainFile
= sqlite3Strlen30(zMainFile
);
1841 zMaster
= sqlite3MPrintf(db
, "%s-mjXXXXXX9XXz", zMainFile
);
1842 if( zMaster
==0 ) return SQLITE_NOMEM
;
1846 if( retryCount
>100 ){
1847 sqlite3_log(SQLITE_FULL
, "MJ delete: %s", zMaster
);
1848 sqlite3OsDelete(pVfs
, zMaster
, 0);
1850 }else if( retryCount
==1 ){
1851 sqlite3_log(SQLITE_FULL
, "MJ collide: %s", zMaster
);
1855 sqlite3_randomness(sizeof(iRandom
), &iRandom
);
1856 sqlite3_snprintf(13, &zMaster
[nMainFile
], "-mj%06X9%02X",
1857 (iRandom
>>8)&0xffffff, iRandom
&0xff);
1858 /* The antipenultimate character of the master journal name must
1859 ** be "9" to avoid name collisions when using 8+3 filenames. */
1860 assert( zMaster
[sqlite3Strlen30(zMaster
)-3]=='9' );
1861 sqlite3FileSuffix3(zMainFile
, zMaster
);
1862 rc
= sqlite3OsAccess(pVfs
, zMaster
, SQLITE_ACCESS_EXISTS
, &res
);
1863 }while( rc
==SQLITE_OK
&& res
);
1864 if( rc
==SQLITE_OK
){
1865 /* Open the master journal. */
1866 rc
= sqlite3OsOpenMalloc(pVfs
, zMaster
, &pMaster
,
1867 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|
1868 SQLITE_OPEN_EXCLUSIVE
|SQLITE_OPEN_MASTER_JOURNAL
, 0
1871 if( rc
!=SQLITE_OK
){
1872 sqlite3DbFree(db
, zMaster
);
1876 /* Write the name of each database file in the transaction into the new
1877 ** master journal file. If an error occurs at this point close
1878 ** and delete the master journal file. All the individual journal files
1879 ** still have 'null' as the master journal pointer, so they will roll
1880 ** back independently if a failure occurs.
1882 for(i
=0; i
<db
->nDb
; i
++){
1883 Btree
*pBt
= db
->aDb
[i
].pBt
;
1884 if( sqlite3BtreeIsInTrans(pBt
) ){
1885 char const *zFile
= sqlite3BtreeGetJournalname(pBt
);
1887 continue; /* Ignore TEMP and :memory: databases */
1889 assert( zFile
[0]!=0 );
1890 if( !needSync
&& !sqlite3BtreeSyncDisabled(pBt
) ){
1893 rc
= sqlite3OsWrite(pMaster
, zFile
, sqlite3Strlen30(zFile
)+1, offset
);
1894 offset
+= sqlite3Strlen30(zFile
)+1;
1895 if( rc
!=SQLITE_OK
){
1896 sqlite3OsCloseFree(pMaster
);
1897 sqlite3OsDelete(pVfs
, zMaster
, 0);
1898 sqlite3DbFree(db
, zMaster
);
1904 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
1905 ** flag is set this is not required.
1908 && 0==(sqlite3OsDeviceCharacteristics(pMaster
)&SQLITE_IOCAP_SEQUENTIAL
)
1909 && SQLITE_OK
!=(rc
= sqlite3OsSync(pMaster
, SQLITE_SYNC_NORMAL
))
1911 sqlite3OsCloseFree(pMaster
);
1912 sqlite3OsDelete(pVfs
, zMaster
, 0);
1913 sqlite3DbFree(db
, zMaster
);
1917 /* Sync all the db files involved in the transaction. The same call
1918 ** sets the master journal pointer in each individual journal. If
1919 ** an error occurs here, do not delete the master journal file.
1921 ** If the error occurs during the first call to
1922 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
1923 ** master journal file will be orphaned. But we cannot delete it,
1924 ** in case the master journal file name was written into the journal
1925 ** file before the failure occurred.
1927 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1928 Btree
*pBt
= db
->aDb
[i
].pBt
;
1930 rc
= sqlite3BtreeCommitPhaseOne(pBt
, zMaster
);
1933 sqlite3OsCloseFree(pMaster
);
1934 assert( rc
!=SQLITE_BUSY
);
1935 if( rc
!=SQLITE_OK
){
1936 sqlite3DbFree(db
, zMaster
);
1940 /* Delete the master journal file. This commits the transaction. After
1941 ** doing this the directory is synced again before any individual
1942 ** transaction files are deleted.
1944 rc
= sqlite3OsDelete(pVfs
, zMaster
, 1);
1945 sqlite3DbFree(db
, zMaster
);
1951 /* All files and directories have already been synced, so the following
1952 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
1953 ** deleting or truncating journals. If something goes wrong while
1954 ** this is happening we don't really care. The integrity of the
1955 ** transaction is already guaranteed, but some stray 'cold' journals
1956 ** may be lying around. Returning an error code won't help matters.
1958 disable_simulated_io_errors();
1959 sqlite3BeginBenignMalloc();
1960 for(i
=0; i
<db
->nDb
; i
++){
1961 Btree
*pBt
= db
->aDb
[i
].pBt
;
1963 sqlite3BtreeCommitPhaseTwo(pBt
, 1);
1966 sqlite3EndBenignMalloc();
1967 enable_simulated_io_errors();
1969 sqlite3VtabCommit(db
);
1977 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1978 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1979 ** currently active. An assertion fails if the two counts do not match.
1980 ** This is an internal self-check only - it is not an essential processing
1983 ** This is a no-op if NDEBUG is defined.
1986 static void checkActiveVdbeCnt(sqlite3
*db
){
1992 if( p
->magic
==VDBE_MAGIC_RUN
&& p
->pc
>=0 ){
1994 if( p
->readOnly
==0 ) nWrite
++;
1998 assert( cnt
==db
->activeVdbeCnt
);
1999 assert( nWrite
==db
->writeVdbeCnt
);
2002 #define checkActiveVdbeCnt(x)
2006 ** If the Vdbe passed as the first argument opened a statement-transaction,
2007 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2008 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2009 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
2010 ** statement transaction is commtted.
2012 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2013 ** Otherwise SQLITE_OK.
2015 int sqlite3VdbeCloseStatement(Vdbe
*p
, int eOp
){
2016 sqlite3
*const db
= p
->db
;
2019 /* If p->iStatement is greater than zero, then this Vdbe opened a
2020 ** statement transaction that should be closed here. The only exception
2021 ** is that an IO error may have occured, causing an emergency rollback.
2022 ** In this case (db->nStatement==0), and there is nothing to do.
2024 if( db
->nStatement
&& p
->iStatement
){
2026 const int iSavepoint
= p
->iStatement
-1;
2028 assert( eOp
==SAVEPOINT_ROLLBACK
|| eOp
==SAVEPOINT_RELEASE
);
2029 assert( db
->nStatement
>0 );
2030 assert( p
->iStatement
==(db
->nStatement
+db
->nSavepoint
) );
2032 for(i
=0; i
<db
->nDb
; i
++){
2033 int rc2
= SQLITE_OK
;
2034 Btree
*pBt
= db
->aDb
[i
].pBt
;
2036 if( eOp
==SAVEPOINT_ROLLBACK
){
2037 rc2
= sqlite3BtreeSavepoint(pBt
, SAVEPOINT_ROLLBACK
, iSavepoint
);
2039 if( rc2
==SQLITE_OK
){
2040 rc2
= sqlite3BtreeSavepoint(pBt
, SAVEPOINT_RELEASE
, iSavepoint
);
2042 if( rc
==SQLITE_OK
){
2050 if( rc
==SQLITE_OK
){
2051 if( eOp
==SAVEPOINT_ROLLBACK
){
2052 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_ROLLBACK
, iSavepoint
);
2054 if( rc
==SQLITE_OK
){
2055 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_RELEASE
, iSavepoint
);
2059 /* If the statement transaction is being rolled back, also restore the
2060 ** database handles deferred constraint counter to the value it had when
2061 ** the statement transaction was opened. */
2062 if( eOp
==SAVEPOINT_ROLLBACK
){
2063 db
->nDeferredCons
= p
->nStmtDefCons
;
2070 ** This function is called when a transaction opened by the database
2071 ** handle associated with the VM passed as an argument is about to be
2072 ** committed. If there are outstanding deferred foreign key constraint
2073 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2075 ** If there are outstanding FK violations and this function returns
2076 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
2077 ** an error message to it. Then return SQLITE_ERROR.
2079 #ifndef SQLITE_OMIT_FOREIGN_KEY
2080 int sqlite3VdbeCheckFk(Vdbe
*p
, int deferred
){
2081 sqlite3
*db
= p
->db
;
2082 if( (deferred
&& db
->nDeferredCons
>0) || (!deferred
&& p
->nFkConstraint
>0) ){
2083 p
->rc
= SQLITE_CONSTRAINT
;
2084 p
->errorAction
= OE_Abort
;
2085 sqlite3SetString(&p
->zErrMsg
, db
, "foreign key constraint failed");
2086 return SQLITE_ERROR
;
2093 ** This routine is called the when a VDBE tries to halt. If the VDBE
2094 ** has made changes and is in autocommit mode, then commit those
2095 ** changes. If a rollback is needed, then do the rollback.
2097 ** This routine is the only way to move the state of a VM from
2098 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2099 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2101 ** Return an error code. If the commit could not complete because of
2102 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2103 ** means the close did not happen and needs to be repeated.
2105 int sqlite3VdbeHalt(Vdbe
*p
){
2106 int rc
; /* Used to store transient return codes */
2107 sqlite3
*db
= p
->db
;
2109 /* This function contains the logic that determines if a statement or
2110 ** transaction will be committed or rolled back as a result of the
2111 ** execution of this virtual machine.
2113 ** If any of the following errors occur:
2120 ** Then the internal cache might have been left in an inconsistent
2121 ** state. We need to rollback the statement transaction, if there is
2122 ** one, or the complete transaction if there is no statement transaction.
2125 if( p
->db
->mallocFailed
){
2126 p
->rc
= SQLITE_NOMEM
;
2128 if( p
->aOnceFlag
) memset(p
->aOnceFlag
, 0, p
->nOnceFlag
);
2130 if( p
->magic
!=VDBE_MAGIC_RUN
){
2133 checkActiveVdbeCnt(db
);
2135 /* No commit or rollback needed if the program never started */
2137 int mrc
; /* Primary error code from p->rc */
2138 int eStatementOp
= 0;
2139 int isSpecialError
; /* Set to true if a 'special' error */
2141 /* Lock all btrees used by the statement */
2142 sqlite3VdbeEnter(p
);
2144 /* Check for one of the special errors */
2146 assert( p
->rc
!=SQLITE_IOERR_BLOCKED
); /* This error no longer exists */
2147 isSpecialError
= mrc
==SQLITE_NOMEM
|| mrc
==SQLITE_IOERR
2148 || mrc
==SQLITE_INTERRUPT
|| mrc
==SQLITE_FULL
;
2149 if( isSpecialError
){
2150 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2151 ** no rollback is necessary. Otherwise, at least a savepoint
2152 ** transaction must be rolled back to restore the database to a
2153 ** consistent state.
2155 ** Even if the statement is read-only, it is important to perform
2156 ** a statement or transaction rollback operation. If the error
2157 ** occured while writing to the journal, sub-journal or database
2158 ** file as part of an effort to free up cache space (see function
2159 ** pagerStress() in pager.c), the rollback is required to restore
2160 ** the pager to a consistent state.
2162 if( !p
->readOnly
|| mrc
!=SQLITE_INTERRUPT
){
2163 if( (mrc
==SQLITE_NOMEM
|| mrc
==SQLITE_FULL
) && p
->usesStmtJournal
){
2164 eStatementOp
= SAVEPOINT_ROLLBACK
;
2166 /* We are forced to roll back the active transaction. Before doing
2167 ** so, abort any other statements this handle currently has active.
2169 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2170 sqlite3CloseSavepoints(db
);
2176 /* Check for immediate foreign key violations. */
2177 if( p
->rc
==SQLITE_OK
){
2178 sqlite3VdbeCheckFk(p
, 0);
2181 /* If the auto-commit flag is set and this is the only active writer
2182 ** VM, then we do either a commit or rollback of the current transaction.
2184 ** Note: This block also runs if one of the special errors handled
2185 ** above has occurred.
2187 if( !sqlite3VtabInSync(db
)
2189 && db
->writeVdbeCnt
==(p
->readOnly
==0)
2191 if( p
->rc
==SQLITE_OK
|| (p
->errorAction
==OE_Fail
&& !isSpecialError
) ){
2192 rc
= sqlite3VdbeCheckFk(p
, 1);
2193 if( rc
!=SQLITE_OK
){
2194 if( NEVER(p
->readOnly
) ){
2195 sqlite3VdbeLeave(p
);
2196 return SQLITE_ERROR
;
2198 rc
= SQLITE_CONSTRAINT
;
2200 /* The auto-commit flag is true, the vdbe program was successful
2201 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2202 ** key constraints to hold up the transaction. This means a commit
2204 rc
= vdbeCommit(db
, p
);
2206 if( rc
==SQLITE_BUSY
&& p
->readOnly
){
2207 sqlite3VdbeLeave(p
);
2209 }else if( rc
!=SQLITE_OK
){
2211 sqlite3RollbackAll(db
, SQLITE_OK
);
2213 db
->nDeferredCons
= 0;
2214 sqlite3CommitInternalChanges(db
);
2217 sqlite3RollbackAll(db
, SQLITE_OK
);
2220 }else if( eStatementOp
==0 ){
2221 if( p
->rc
==SQLITE_OK
|| p
->errorAction
==OE_Fail
){
2222 eStatementOp
= SAVEPOINT_RELEASE
;
2223 }else if( p
->errorAction
==OE_Abort
){
2224 eStatementOp
= SAVEPOINT_ROLLBACK
;
2226 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2227 sqlite3CloseSavepoints(db
);
2232 /* If eStatementOp is non-zero, then a statement transaction needs to
2233 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2234 ** do so. If this operation returns an error, and the current statement
2235 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2236 ** current statement error code.
2239 rc
= sqlite3VdbeCloseStatement(p
, eStatementOp
);
2241 if( p
->rc
==SQLITE_OK
|| p
->rc
==SQLITE_CONSTRAINT
){
2243 sqlite3DbFree(db
, p
->zErrMsg
);
2246 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2247 sqlite3CloseSavepoints(db
);
2252 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2253 ** has been rolled back, update the database connection change-counter.
2255 if( p
->changeCntOn
){
2256 if( eStatementOp
!=SAVEPOINT_ROLLBACK
){
2257 sqlite3VdbeSetChanges(db
, p
->nChange
);
2259 sqlite3VdbeSetChanges(db
, 0);
2264 /* Release the locks */
2265 sqlite3VdbeLeave(p
);
2268 /* We have successfully halted and closed the VM. Record this fact. */
2270 db
->activeVdbeCnt
--;
2274 assert( db
->activeVdbeCnt
>=db
->writeVdbeCnt
);
2276 p
->magic
= VDBE_MAGIC_HALT
;
2277 checkActiveVdbeCnt(db
);
2278 if( p
->db
->mallocFailed
){
2279 p
->rc
= SQLITE_NOMEM
;
2282 /* If the auto-commit flag is set to true, then any locks that were held
2283 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2284 ** to invoke any required unlock-notify callbacks.
2286 if( db
->autoCommit
){
2287 sqlite3ConnectionUnlocked(db
);
2290 assert( db
->activeVdbeCnt
>0 || db
->autoCommit
==0 || db
->nStatement
==0 );
2291 return (p
->rc
==SQLITE_BUSY
? SQLITE_BUSY
: SQLITE_OK
);
2296 ** Each VDBE holds the result of the most recent sqlite3_step() call
2297 ** in p->rc. This routine sets that result back to SQLITE_OK.
2299 void sqlite3VdbeResetStepResult(Vdbe
*p
){
2304 ** Copy the error code and error message belonging to the VDBE passed
2305 ** as the first argument to its database handle (so that they will be
2306 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2308 ** This function does not clear the VDBE error code or message, just
2309 ** copies them to the database handle.
2311 int sqlite3VdbeTransferError(Vdbe
*p
){
2312 sqlite3
*db
= p
->db
;
2315 u8 mallocFailed
= db
->mallocFailed
;
2316 sqlite3BeginBenignMalloc();
2317 sqlite3ValueSetStr(db
->pErr
, -1, p
->zErrMsg
, SQLITE_UTF8
, SQLITE_TRANSIENT
);
2318 sqlite3EndBenignMalloc();
2319 db
->mallocFailed
= mallocFailed
;
2322 sqlite3Error(db
, rc
, 0);
2328 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2329 ** Write any error messages into *pzErrMsg. Return the result code.
2331 ** After this routine is run, the VDBE should be ready to be executed
2334 ** To look at it another way, this routine resets the state of the
2335 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2338 int sqlite3VdbeReset(Vdbe
*p
){
2342 /* If the VM did not run to completion or if it encountered an
2343 ** error, then it might not have been halted properly. So halt
2348 /* If the VDBE has be run even partially, then transfer the error code
2349 ** and error message from the VDBE into the main database structure. But
2350 ** if the VDBE has just been set to run but has not actually executed any
2351 ** instructions yet, leave the main database error information unchanged.
2354 sqlite3VdbeTransferError(p
);
2355 sqlite3DbFree(db
, p
->zErrMsg
);
2357 if( p
->runOnlyOnce
) p
->expired
= 1;
2358 }else if( p
->rc
&& p
->expired
){
2359 /* The expired flag was set on the VDBE before the first call
2360 ** to sqlite3_step(). For consistency (since sqlite3_step() was
2361 ** called), set the database error in this case as well.
2363 sqlite3Error(db
, p
->rc
, 0);
2364 sqlite3ValueSetStr(db
->pErr
, -1, p
->zErrMsg
, SQLITE_UTF8
, SQLITE_TRANSIENT
);
2365 sqlite3DbFree(db
, p
->zErrMsg
);
2369 /* Reclaim all memory used by the VDBE
2373 /* Save profiling information from this VDBE run.
2377 FILE *out
= fopen("vdbe_profile.out", "a");
2380 fprintf(out
, "---- ");
2381 for(i
=0; i
<p
->nOp
; i
++){
2382 fprintf(out
, "%02x", p
->aOp
[i
].opcode
);
2385 for(i
=0; i
<p
->nOp
; i
++){
2386 fprintf(out
, "%6d %10lld %8lld ",
2389 p
->aOp
[i
].cnt
>0 ? p
->aOp
[i
].cycles
/p
->aOp
[i
].cnt
: 0
2391 sqlite3VdbePrintOp(out
, i
, &p
->aOp
[i
]);
2397 p
->magic
= VDBE_MAGIC_INIT
;
2398 return p
->rc
& db
->errMask
;
2402 ** Clean up and delete a VDBE after execution. Return an integer which is
2403 ** the result code. Write any error message text into *pzErrMsg.
2405 int sqlite3VdbeFinalize(Vdbe
*p
){
2407 if( p
->magic
==VDBE_MAGIC_RUN
|| p
->magic
==VDBE_MAGIC_HALT
){
2408 rc
= sqlite3VdbeReset(p
);
2409 assert( (rc
& p
->db
->errMask
)==rc
);
2411 sqlite3VdbeDelete(p
);
2416 ** Call the destructor for each auxdata entry in pVdbeFunc for which
2417 ** the corresponding bit in mask is clear. Auxdata entries beyond 31
2418 ** are always destroyed. To destroy all auxdata entries, call this
2419 ** routine with mask==0.
2421 void sqlite3VdbeDeleteAuxData(VdbeFunc
*pVdbeFunc
, int mask
){
2423 for(i
=0; i
<pVdbeFunc
->nAux
; i
++){
2424 struct AuxData
*pAux
= &pVdbeFunc
->apAux
[i
];
2425 if( (i
>31 || !(mask
&(((u32
)1)<<i
))) && pAux
->pAux
){
2426 if( pAux
->xDelete
){
2427 pAux
->xDelete(pAux
->pAux
);
2435 ** Free all memory associated with the Vdbe passed as the second argument.
2436 ** The difference between this function and sqlite3VdbeDelete() is that
2437 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
2438 ** the database connection.
2440 void sqlite3VdbeDeleteObject(sqlite3
*db
, Vdbe
*p
){
2441 SubProgram
*pSub
, *pNext
;
2443 assert( p
->db
==0 || p
->db
==db
);
2444 releaseMemArray(p
->aVar
, p
->nVar
);
2445 releaseMemArray(p
->aColName
, p
->nResColumn
*COLNAME_N
);
2446 for(pSub
=p
->pProgram
; pSub
; pSub
=pNext
){
2447 pNext
= pSub
->pNext
;
2448 vdbeFreeOpArray(db
, pSub
->aOp
, pSub
->nOp
);
2449 sqlite3DbFree(db
, pSub
);
2451 for(i
=p
->nzVar
-1; i
>=0; i
--) sqlite3DbFree(db
, p
->azVar
[i
]);
2452 vdbeFreeOpArray(db
, p
->aOp
, p
->nOp
);
2453 sqlite3DbFree(db
, p
->aLabel
);
2454 sqlite3DbFree(db
, p
->aColName
);
2455 sqlite3DbFree(db
, p
->zSql
);
2456 sqlite3DbFree(db
, p
->pFree
);
2457 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
2458 sqlite3DbFree(db
, p
->zExplain
);
2459 sqlite3DbFree(db
, p
->pExplain
);
2461 sqlite3DbFree(db
, p
);
2465 ** Delete an entire VDBE.
2467 void sqlite3VdbeDelete(Vdbe
*p
){
2470 if( NEVER(p
==0) ) return;
2473 p
->pPrev
->pNext
= p
->pNext
;
2475 assert( db
->pVdbe
==p
);
2476 db
->pVdbe
= p
->pNext
;
2479 p
->pNext
->pPrev
= p
->pPrev
;
2481 p
->magic
= VDBE_MAGIC_DEAD
;
2483 sqlite3VdbeDeleteObject(db
, p
);
2487 ** Make sure the cursor p is ready to read or write the row to which it
2488 ** was last positioned. Return an error code if an OOM fault or I/O error
2489 ** prevents us from positioning the cursor to its correct position.
2491 ** If a MoveTo operation is pending on the given cursor, then do that
2492 ** MoveTo now. If no move is pending, check to see if the row has been
2493 ** deleted out from under the cursor and if it has, mark the row as
2496 ** If the cursor is already pointing to the correct row and that row has
2497 ** not been deleted out from under the cursor, then this routine is a no-op.
2499 int sqlite3VdbeCursorMoveto(VdbeCursor
*p
){
2500 if( p
->deferredMoveto
){
2503 extern int sqlite3_search_count
;
2505 assert( p
->isTable
);
2506 rc
= sqlite3BtreeMovetoUnpacked(p
->pCursor
, 0, p
->movetoTarget
, 0, &res
);
2508 p
->lastRowid
= p
->movetoTarget
;
2509 if( res
!=0 ) return SQLITE_CORRUPT_BKPT
;
2510 p
->rowidIsValid
= 1;
2512 sqlite3_search_count
++;
2514 p
->deferredMoveto
= 0;
2515 p
->cacheStatus
= CACHE_STALE
;
2516 }else if( ALWAYS(p
->pCursor
) ){
2518 int rc
= sqlite3BtreeCursorHasMoved(p
->pCursor
, &hasMoved
);
2521 p
->cacheStatus
= CACHE_STALE
;
2529 ** The following functions:
2531 ** sqlite3VdbeSerialType()
2532 ** sqlite3VdbeSerialTypeLen()
2533 ** sqlite3VdbeSerialLen()
2534 ** sqlite3VdbeSerialPut()
2535 ** sqlite3VdbeSerialGet()
2537 ** encapsulate the code that serializes values for storage in SQLite
2538 ** data and index records. Each serialized value consists of a
2539 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2540 ** integer, stored as a varint.
2542 ** In an SQLite index record, the serial type is stored directly before
2543 ** the blob of data that it corresponds to. In a table record, all serial
2544 ** types are stored at the start of the record, and the blobs of data at
2545 ** the end. Hence these functions allow the caller to handle the
2546 ** serial-type and data blob seperately.
2548 ** The following table describes the various storage classes for data:
2550 ** serial type bytes of data type
2551 ** -------------- --------------- ---------------
2553 ** 1 1 signed integer
2554 ** 2 2 signed integer
2555 ** 3 3 signed integer
2556 ** 4 4 signed integer
2557 ** 5 6 signed integer
2558 ** 6 8 signed integer
2560 ** 8 0 Integer constant 0
2561 ** 9 0 Integer constant 1
2562 ** 10,11 reserved for expansion
2563 ** N>=12 and even (N-12)/2 BLOB
2564 ** N>=13 and odd (N-13)/2 text
2566 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
2567 ** of SQLite will not understand those serial types.
2571 ** Return the serial-type for the value stored in pMem.
2573 u32
sqlite3VdbeSerialType(Mem
*pMem
, int file_format
){
2574 int flags
= pMem
->flags
;
2577 if( flags
&MEM_Null
){
2580 if( flags
&MEM_Int
){
2581 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
2582 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
2585 if( file_format
>=4 && (i
&1)==i
){
2589 if( i
<(-MAX_6BYTE
) ) return 6;
2590 /* Previous test prevents: u = -(-9223372036854775808) */
2595 if( u
<=127 ) return 1;
2596 if( u
<=32767 ) return 2;
2597 if( u
<=8388607 ) return 3;
2598 if( u
<=2147483647 ) return 4;
2599 if( u
<=MAX_6BYTE
) return 5;
2602 if( flags
&MEM_Real
){
2605 assert( pMem
->db
->mallocFailed
|| flags
&(MEM_Str
|MEM_Blob
) );
2607 if( flags
& MEM_Zero
){
2611 return ((n
*2) + 12 + ((flags
&MEM_Str
)!=0));
2615 ** Return the length of the data corresponding to the supplied serial-type.
2617 u32
sqlite3VdbeSerialTypeLen(u32 serial_type
){
2618 if( serial_type
>=12 ){
2619 return (serial_type
-12)/2;
2621 static const u8 aSize
[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
2622 return aSize
[serial_type
];
2627 ** If we are on an architecture with mixed-endian floating
2628 ** points (ex: ARM7) then swap the lower 4 bytes with the
2629 ** upper 4 bytes. Return the result.
2631 ** For most architectures, this is a no-op.
2633 ** (later): It is reported to me that the mixed-endian problem
2634 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
2635 ** that early versions of GCC stored the two words of a 64-bit
2636 ** float in the wrong order. And that error has been propagated
2637 ** ever since. The blame is not necessarily with GCC, though.
2638 ** GCC might have just copying the problem from a prior compiler.
2639 ** I am also told that newer versions of GCC that follow a different
2640 ** ABI get the byte order right.
2642 ** Developers using SQLite on an ARM7 should compile and run their
2643 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
2644 ** enabled, some asserts below will ensure that the byte order of
2645 ** floating point values is correct.
2647 ** (2007-08-30) Frank van Vugt has studied this problem closely
2648 ** and has send his findings to the SQLite developers. Frank
2649 ** writes that some Linux kernels offer floating point hardware
2650 ** emulation that uses only 32-bit mantissas instead of a full
2651 ** 48-bits as required by the IEEE standard. (This is the
2652 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
2653 ** byte swapping becomes very complicated. To avoid problems,
2654 ** the necessary byte swapping is carried out using a 64-bit integer
2655 ** rather than a 64-bit float. Frank assures us that the code here
2656 ** works for him. We, the developers, have no way to independently
2657 ** verify this, but Frank seems to know what he is talking about
2660 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
2661 static u64
floatSwap(u64 in
){
2674 # define swapMixedEndianFloat(X) X = floatSwap(X)
2676 # define swapMixedEndianFloat(X)
2680 ** Write the serialized data blob for the value stored in pMem into
2681 ** buf. It is assumed that the caller has allocated sufficient space.
2682 ** Return the number of bytes written.
2684 ** nBuf is the amount of space left in buf[]. nBuf must always be
2685 ** large enough to hold the entire field. Except, if the field is
2686 ** a blob with a zero-filled tail, then buf[] might be just the right
2687 ** size to hold everything except for the zero-filled tail. If buf[]
2688 ** is only big enough to hold the non-zero prefix, then only write that
2689 ** prefix into buf[]. But if buf[] is large enough to hold both the
2690 ** prefix and the tail then write the prefix and set the tail to all
2693 ** Return the number of bytes actually written into buf[]. The number
2694 ** of bytes in the zero-filled tail is included in the return value only
2695 ** if those bytes were zeroed in buf[].
2697 u32
sqlite3VdbeSerialPut(u8
*buf
, int nBuf
, Mem
*pMem
, int file_format
){
2698 u32 serial_type
= sqlite3VdbeSerialType(pMem
, file_format
);
2701 /* Integer and Real */
2702 if( serial_type
<=7 && serial_type
>0 ){
2705 if( serial_type
==7 ){
2706 assert( sizeof(v
)==sizeof(pMem
->r
) );
2707 memcpy(&v
, &pMem
->r
, sizeof(v
));
2708 swapMixedEndianFloat(v
);
2712 len
= i
= sqlite3VdbeSerialTypeLen(serial_type
);
2713 assert( len
<=(u32
)nBuf
);
2715 buf
[i
] = (u8
)(v
&0xFF);
2721 /* String or blob */
2722 if( serial_type
>=12 ){
2723 assert( pMem
->n
+ ((pMem
->flags
& MEM_Zero
)?pMem
->u
.nZero
:0)
2724 == (int)sqlite3VdbeSerialTypeLen(serial_type
) );
2725 assert( pMem
->n
<=nBuf
);
2727 memcpy(buf
, pMem
->z
, len
);
2728 if( pMem
->flags
& MEM_Zero
){
2729 len
+= pMem
->u
.nZero
;
2731 if( len
> (u32
)nBuf
){
2734 memset(&buf
[pMem
->n
], 0, len
-pMem
->n
);
2739 /* NULL or constants 0 or 1 */
2744 ** Deserialize the data blob pointed to by buf as serial type serial_type
2745 ** and store the result in pMem. Return the number of bytes read.
2747 u32
sqlite3VdbeSerialGet(
2748 const unsigned char *buf
, /* Buffer to deserialize from */
2749 u32 serial_type
, /* Serial type to deserialize */
2750 Mem
*pMem
/* Memory cell to write value into */
2752 switch( serial_type
){
2753 case 10: /* Reserved for future use */
2754 case 11: /* Reserved for future use */
2755 case 0: { /* NULL */
2756 pMem
->flags
= MEM_Null
;
2759 case 1: { /* 1-byte signed integer */
2760 pMem
->u
.i
= (signed char)buf
[0];
2761 pMem
->flags
= MEM_Int
;
2764 case 2: { /* 2-byte signed integer */
2765 pMem
->u
.i
= (((signed char)buf
[0])<<8) | buf
[1];
2766 pMem
->flags
= MEM_Int
;
2769 case 3: { /* 3-byte signed integer */
2770 pMem
->u
.i
= (((signed char)buf
[0])<<16) | (buf
[1]<<8) | buf
[2];
2771 pMem
->flags
= MEM_Int
;
2774 case 4: { /* 4-byte signed integer */
2775 pMem
->u
.i
= (buf
[0]<<24) | (buf
[1]<<16) | (buf
[2]<<8) | buf
[3];
2776 pMem
->flags
= MEM_Int
;
2779 case 5: { /* 6-byte signed integer */
2780 u64 x
= (((signed char)buf
[0])<<8) | buf
[1];
2781 u32 y
= (buf
[2]<<24) | (buf
[3]<<16) | (buf
[4]<<8) | buf
[5];
2783 pMem
->u
.i
= *(i64
*)&x
;
2784 pMem
->flags
= MEM_Int
;
2787 case 6: /* 8-byte signed integer */
2788 case 7: { /* IEEE floating point */
2791 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
2792 /* Verify that integers and floating point values use the same
2793 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
2794 ** defined that 64-bit floating point values really are mixed
2797 static const u64 t1
= ((u64
)0x3ff00000)<<32;
2798 static const double r1
= 1.0;
2800 swapMixedEndianFloat(t2
);
2801 assert( sizeof(r1
)==sizeof(t2
) && memcmp(&r1
, &t2
, sizeof(r1
))==0 );
2804 x
= (buf
[0]<<24) | (buf
[1]<<16) | (buf
[2]<<8) | buf
[3];
2805 y
= (buf
[4]<<24) | (buf
[5]<<16) | (buf
[6]<<8) | buf
[7];
2807 if( serial_type
==6 ){
2808 pMem
->u
.i
= *(i64
*)&x
;
2809 pMem
->flags
= MEM_Int
;
2811 assert( sizeof(x
)==8 && sizeof(pMem
->r
)==8 );
2812 swapMixedEndianFloat(x
);
2813 memcpy(&pMem
->r
, &x
, sizeof(x
));
2814 pMem
->flags
= sqlite3IsNaN(pMem
->r
) ? MEM_Null
: MEM_Real
;
2818 case 8: /* Integer 0 */
2819 case 9: { /* Integer 1 */
2820 pMem
->u
.i
= serial_type
-8;
2821 pMem
->flags
= MEM_Int
;
2825 u32 len
= (serial_type
-12)/2;
2826 pMem
->z
= (char *)buf
;
2829 if( serial_type
&0x01 ){
2830 pMem
->flags
= MEM_Str
| MEM_Ephem
;
2832 pMem
->flags
= MEM_Blob
| MEM_Ephem
;
2841 ** This routine is used to allocate sufficient space for an UnpackedRecord
2842 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
2843 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
2845 ** The space is either allocated using sqlite3DbMallocRaw() or from within
2846 ** the unaligned buffer passed via the second and third arguments (presumably
2847 ** stack space). If the former, then *ppFree is set to a pointer that should
2848 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
2849 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
2850 ** before returning.
2852 ** If an OOM error occurs, NULL is returned.
2854 UnpackedRecord
*sqlite3VdbeAllocUnpackedRecord(
2855 KeyInfo
*pKeyInfo
, /* Description of the record */
2856 char *pSpace
, /* Unaligned space available */
2857 int szSpace
, /* Size of pSpace[] in bytes */
2858 char **ppFree
/* OUT: Caller should free this pointer */
2860 UnpackedRecord
*p
; /* Unpacked record to return */
2861 int nOff
; /* Increment pSpace by nOff to align it */
2862 int nByte
; /* Number of bytes required for *p */
2864 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
2865 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
2866 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
2868 nOff
= (8 - (SQLITE_PTR_TO_INT(pSpace
) & 7)) & 7;
2869 nByte
= ROUND8(sizeof(UnpackedRecord
)) + sizeof(Mem
)*(pKeyInfo
->nField
+1);
2870 if( nByte
>szSpace
+nOff
){
2871 p
= (UnpackedRecord
*)sqlite3DbMallocRaw(pKeyInfo
->db
, nByte
);
2872 *ppFree
= (char *)p
;
2875 p
= (UnpackedRecord
*)&pSpace
[nOff
];
2879 p
->aMem
= (Mem
*)&((char*)p
)[ROUND8(sizeof(UnpackedRecord
))];
2880 p
->pKeyInfo
= pKeyInfo
;
2881 p
->nField
= pKeyInfo
->nField
+ 1;
2886 ** Given the nKey-byte encoding of a record in pKey[], populate the
2887 ** UnpackedRecord structure indicated by the fourth argument with the
2888 ** contents of the decoded record.
2890 void sqlite3VdbeRecordUnpack(
2891 KeyInfo
*pKeyInfo
, /* Information about the record format */
2892 int nKey
, /* Size of the binary record */
2893 const void *pKey
, /* The binary record */
2894 UnpackedRecord
*p
/* Populate this structure before returning. */
2896 const unsigned char *aKey
= (const unsigned char *)pKey
;
2898 u32 idx
; /* Offset in aKey[] to read from */
2899 u16 u
; /* Unsigned loop counter */
2901 Mem
*pMem
= p
->aMem
;
2904 assert( EIGHT_BYTE_ALIGNMENT(pMem
) );
2905 idx
= getVarint32(aKey
, szHdr
);
2908 while( idx
<szHdr
&& u
<p
->nField
&& d
<=nKey
){
2911 idx
+= getVarint32(&aKey
[idx
], serial_type
);
2912 pMem
->enc
= pKeyInfo
->enc
;
2913 pMem
->db
= pKeyInfo
->db
;
2914 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
2916 d
+= sqlite3VdbeSerialGet(&aKey
[d
], serial_type
, pMem
);
2920 assert( u
<=pKeyInfo
->nField
+ 1 );
2925 ** This function compares the two table rows or index records
2926 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
2927 ** or positive integer if key1 is less than, equal to or
2928 ** greater than key2. The {nKey1, pKey1} key must be a blob
2929 ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
2930 ** key must be a parsed key such as obtained from
2931 ** sqlite3VdbeParseRecord.
2933 ** Key1 and Key2 do not have to contain the same number of fields.
2934 ** The key with fewer fields is usually compares less than the
2935 ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
2936 ** and the common prefixes are equal, then key1 is less than key2.
2937 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
2938 ** equal, then the keys are considered to be equal and
2939 ** the parts beyond the common prefix are ignored.
2941 int sqlite3VdbeRecordCompare(
2942 int nKey1
, const void *pKey1
, /* Left key */
2943 UnpackedRecord
*pPKey2
/* Right key */
2945 int d1
; /* Offset into aKey[] of next data element */
2946 u32 idx1
; /* Offset into aKey[] of next header element */
2947 u32 szHdr1
; /* Number of bytes in header */
2951 const unsigned char *aKey1
= (const unsigned char *)pKey1
;
2955 pKeyInfo
= pPKey2
->pKeyInfo
;
2956 mem1
.enc
= pKeyInfo
->enc
;
2957 mem1
.db
= pKeyInfo
->db
;
2958 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
2959 VVA_ONLY( mem1
.zMalloc
= 0; ) /* Only needed by assert() statements */
2961 /* Compilers may complain that mem1.u.i is potentially uninitialized.
2962 ** We could initialize it, as shown here, to silence those complaints.
2963 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
2964 ** the unnecessary initialization has a measurable negative performance
2965 ** impact, since this routine is a very high runner. And so, we choose
2966 ** to ignore the compiler warnings and leave this variable uninitialized.
2968 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
2970 idx1
= getVarint32(aKey1
, szHdr1
);
2972 nField
= pKeyInfo
->nField
;
2973 while( idx1
<szHdr1
&& i
<pPKey2
->nField
){
2976 /* Read the serial types for the next element in each key. */
2977 idx1
+= getVarint32( aKey1
+idx1
, serial_type1
);
2978 if( d1
>=nKey1
&& sqlite3VdbeSerialTypeLen(serial_type1
)>0 ) break;
2980 /* Extract the values to be compared.
2982 d1
+= sqlite3VdbeSerialGet(&aKey1
[d1
], serial_type1
, &mem1
);
2984 /* Do the comparison
2986 rc
= sqlite3MemCompare(&mem1
, &pPKey2
->aMem
[i
],
2987 i
<nField
? pKeyInfo
->aColl
[i
] : 0);
2989 assert( mem1
.zMalloc
==0 ); /* See comment below */
2991 /* Invert the result if we are using DESC sort order. */
2992 if( pKeyInfo
->aSortOrder
&& i
<nField
&& pKeyInfo
->aSortOrder
[i
] ){
2996 /* If the PREFIX_SEARCH flag is set and all fields except the final
2997 ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
2998 ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
2999 ** This is used by the OP_IsUnique opcode.
3001 if( (pPKey2
->flags
& UNPACKED_PREFIX_SEARCH
) && i
==(pPKey2
->nField
-1) ){
3002 assert( idx1
==szHdr1
&& rc
);
3003 assert( mem1
.flags
& MEM_Int
);
3004 pPKey2
->flags
&= ~UNPACKED_PREFIX_SEARCH
;
3005 pPKey2
->rowid
= mem1
.u
.i
;
3013 /* No memory allocation is ever used on mem1. Prove this using
3014 ** the following assert(). If the assert() fails, it indicates a
3015 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3017 assert( mem1
.zMalloc
==0 );
3019 /* rc==0 here means that one of the keys ran out of fields and
3020 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
3021 ** flag is set, then break the tie by treating key2 as larger.
3022 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
3023 ** are considered to be equal. Otherwise, the longer key is the
3024 ** larger. As it happens, the pPKey2 will always be the longer
3025 ** if there is a difference.
3028 if( pPKey2
->flags
& UNPACKED_INCRKEY
){
3030 }else if( pPKey2
->flags
& UNPACKED_PREFIX_MATCH
){
3032 }else if( idx1
<szHdr1
){
3040 ** pCur points at an index entry created using the OP_MakeRecord opcode.
3041 ** Read the rowid (the last field in the record) and store it in *rowid.
3042 ** Return SQLITE_OK if everything works, or an error code otherwise.
3044 ** pCur might be pointing to text obtained from a corrupt database file.
3045 ** So the content cannot be trusted. Do appropriate checks on the content.
3047 int sqlite3VdbeIdxRowid(sqlite3
*db
, BtCursor
*pCur
, i64
*rowid
){
3050 u32 szHdr
; /* Size of the header */
3051 u32 typeRowid
; /* Serial type of the rowid */
3052 u32 lenRowid
; /* Size of the rowid */
3055 UNUSED_PARAMETER(db
);
3057 /* Get the size of the index entry. Only indices entries of less
3058 ** than 2GiB are support - anything large must be database corruption.
3059 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
3060 ** this code can safely assume that nCellKey is 32-bits
3062 assert( sqlite3BtreeCursorIsValid(pCur
) );
3063 VVA_ONLY(rc
=) sqlite3BtreeKeySize(pCur
, &nCellKey
);
3064 assert( rc
==SQLITE_OK
); /* pCur is always valid so KeySize cannot fail */
3065 assert( (nCellKey
& SQLITE_MAX_U32
)==(u64
)nCellKey
);
3067 /* Read in the complete content of the index entry */
3068 memset(&m
, 0, sizeof(m
));
3069 rc
= sqlite3VdbeMemFromBtree(pCur
, 0, (int)nCellKey
, 1, &m
);
3074 /* The index entry must begin with a header size */
3075 (void)getVarint32((u8
*)m
.z
, szHdr
);
3076 testcase( szHdr
==3 );
3077 testcase( szHdr
==m
.n
);
3078 if( unlikely(szHdr
<3 || (int)szHdr
>m
.n
) ){
3079 goto idx_rowid_corruption
;
3082 /* The last field of the index should be an integer - the ROWID.
3083 ** Verify that the last entry really is an integer. */
3084 (void)getVarint32((u8
*)&m
.z
[szHdr
-1], typeRowid
);
3085 testcase( typeRowid
==1 );
3086 testcase( typeRowid
==2 );
3087 testcase( typeRowid
==3 );
3088 testcase( typeRowid
==4 );
3089 testcase( typeRowid
==5 );
3090 testcase( typeRowid
==6 );
3091 testcase( typeRowid
==8 );
3092 testcase( typeRowid
==9 );
3093 if( unlikely(typeRowid
<1 || typeRowid
>9 || typeRowid
==7) ){
3094 goto idx_rowid_corruption
;
3096 lenRowid
= sqlite3VdbeSerialTypeLen(typeRowid
);
3097 testcase( (u32
)m
.n
==szHdr
+lenRowid
);
3098 if( unlikely((u32
)m
.n
<szHdr
+lenRowid
) ){
3099 goto idx_rowid_corruption
;
3102 /* Fetch the integer off the end of the index record */
3103 sqlite3VdbeSerialGet((u8
*)&m
.z
[m
.n
-lenRowid
], typeRowid
, &v
);
3105 sqlite3VdbeMemRelease(&m
);
3108 /* Jump here if database corruption is detected after m has been
3109 ** allocated. Free the m object and return SQLITE_CORRUPT. */
3110 idx_rowid_corruption
:
3111 testcase( m
.zMalloc
!=0 );
3112 sqlite3VdbeMemRelease(&m
);
3113 return SQLITE_CORRUPT_BKPT
;
3117 ** Compare the key of the index entry that cursor pC is pointing to against
3118 ** the key string in pUnpacked. Write into *pRes a number
3119 ** that is negative, zero, or positive if pC is less than, equal to,
3120 ** or greater than pUnpacked. Return SQLITE_OK on success.
3122 ** pUnpacked is either created without a rowid or is truncated so that it
3123 ** omits the rowid at the end. The rowid at the end of the index entry
3124 ** is ignored as well. Hence, this routine only compares the prefixes
3125 ** of the keys prior to the final rowid, not the entire key.
3127 int sqlite3VdbeIdxKeyCompare(
3128 VdbeCursor
*pC
, /* The cursor to compare against */
3129 UnpackedRecord
*pUnpacked
, /* Unpacked version of key to compare against */
3130 int *res
/* Write the comparison result here */
3134 BtCursor
*pCur
= pC
->pCursor
;
3137 assert( sqlite3BtreeCursorIsValid(pCur
) );
3138 VVA_ONLY(rc
=) sqlite3BtreeKeySize(pCur
, &nCellKey
);
3139 assert( rc
==SQLITE_OK
); /* pCur is always valid so KeySize cannot fail */
3140 /* nCellKey will always be between 0 and 0xffffffff because of the say
3141 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
3142 if( nCellKey
<=0 || nCellKey
>0x7fffffff ){
3144 return SQLITE_CORRUPT_BKPT
;
3146 memset(&m
, 0, sizeof(m
));
3147 rc
= sqlite3VdbeMemFromBtree(pC
->pCursor
, 0, (int)nCellKey
, 1, &m
);
3151 assert( pUnpacked
->flags
& UNPACKED_PREFIX_MATCH
);
3152 *res
= sqlite3VdbeRecordCompare(m
.n
, m
.z
, pUnpacked
);
3153 sqlite3VdbeMemRelease(&m
);
3158 ** This routine sets the value to be returned by subsequent calls to
3159 ** sqlite3_changes() on the database handle 'db'.
3161 void sqlite3VdbeSetChanges(sqlite3
*db
, int nChange
){
3162 assert( sqlite3_mutex_held(db
->mutex
) );
3163 db
->nChange
= nChange
;
3164 db
->nTotalChange
+= nChange
;
3168 ** Set a flag in the vdbe to update the change counter when it is finalised
3171 void sqlite3VdbeCountChanges(Vdbe
*v
){
3176 ** Mark every prepared statement associated with a database connection
3179 ** An expired statement means that recompilation of the statement is
3180 ** recommend. Statements expire when things happen that make their
3181 ** programs obsolete. Removing user-defined functions or collating
3182 ** sequences, or changing an authorization function are the types of
3183 ** things that make prepared statements obsolete.
3185 void sqlite3ExpirePreparedStatements(sqlite3
*db
){
3187 for(p
= db
->pVdbe
; p
; p
=p
->pNext
){
3193 ** Return the database associated with the Vdbe.
3195 sqlite3
*sqlite3VdbeDb(Vdbe
*v
){
3200 ** Return a pointer to an sqlite3_value structure containing the value bound
3201 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
3202 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
3203 ** constants) to the value before returning it.
3205 ** The returned value must be freed by the caller using sqlite3ValueFree().
3207 sqlite3_value
*sqlite3VdbeGetValue(Vdbe
*v
, int iVar
, u8 aff
){
3210 Mem
*pMem
= &v
->aVar
[iVar
-1];
3211 if( 0==(pMem
->flags
& MEM_Null
) ){
3212 sqlite3_value
*pRet
= sqlite3ValueNew(v
->db
);
3214 sqlite3VdbeMemCopy((Mem
*)pRet
, pMem
);
3215 sqlite3ValueApplyAffinity(pRet
, aff
, SQLITE_UTF8
);
3216 sqlite3VdbeMemStoreType((Mem
*)pRet
);
3225 ** Configure SQL variable iVar so that binding a new value to it signals
3226 ** to sqlite3_reoptimize() that re-preparing the statement may result
3227 ** in a better query plan.
3229 void sqlite3VdbeSetVarmask(Vdbe
*v
, int iVar
){
3232 v
->expmask
= 0xffffffff;
3234 v
->expmask
|= ((u32
)1 << (iVar
-1));