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"
21 ** Create a new virtual database engine.
23 Vdbe
*sqlite3VdbeCreate(sqlite3
*db
){
25 p
= sqlite3DbMallocZero(db
, sizeof(Vdbe
) );
34 p
->magic
= VDBE_MAGIC_INIT
;
39 ** Remember the SQL string for a prepared statement.
41 void sqlite3VdbeSetSql(Vdbe
*p
, const char *z
, int n
, int isPrepareV2
){
42 assert( isPrepareV2
==1 || isPrepareV2
==0 );
44 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
45 if( !isPrepareV2
) return;
48 p
->zSql
= sqlite3DbStrNDup(p
->db
, z
, n
);
49 p
->isPrepareV2
= (u8
)isPrepareV2
;
53 ** Return the SQL associated with a prepared statement
55 const char *sqlite3_sql(sqlite3_stmt
*pStmt
){
56 Vdbe
*p
= (Vdbe
*)pStmt
;
57 return (p
&& p
->isPrepareV2
) ? p
->zSql
: 0;
61 ** Swap all content between two VDBE structures.
63 void sqlite3VdbeSwap(Vdbe
*pA
, Vdbe
*pB
){
70 pA
->pNext
= pB
->pNext
;
73 pA
->pPrev
= pB
->pPrev
;
78 pB
->isPrepareV2
= pA
->isPrepareV2
;
83 ** Turn tracing on or off
85 void sqlite3VdbeTrace(Vdbe
*p
, FILE *trace
){
91 ** Resize the Vdbe.aOp array so that it is at least one op larger than
94 ** If an out-of-memory error occurs while resizing the array, return
95 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
96 ** unchanged (this is so that any opcodes already allocated can be
97 ** correctly deallocated along with the rest of the Vdbe).
99 static int growOpArray(Vdbe
*p
){
101 int nNew
= (p
->nOpAlloc
? p
->nOpAlloc
*2 : (int)(1024/sizeof(Op
)));
102 pNew
= sqlite3DbRealloc(p
->db
, p
->aOp
, nNew
*sizeof(Op
));
104 p
->nOpAlloc
= sqlite3DbMallocSize(p
->db
, pNew
)/sizeof(Op
);
107 return (pNew
? SQLITE_OK
: SQLITE_NOMEM
);
111 ** Add a new instruction to the list of instructions current in the
112 ** VDBE. Return the address of the new instruction.
116 ** p Pointer to the VDBE
118 ** op The opcode for this instruction
120 ** p1, p2, p3 Operands
122 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
123 ** the sqlite3VdbeChangeP4() function to change the value of the P4
126 int sqlite3VdbeAddOp3(Vdbe
*p
, int op
, int p1
, int p2
, int p3
){
131 assert( p
->magic
==VDBE_MAGIC_INIT
);
132 assert( op
>0 && op
<0xff );
133 if( p
->nOpAlloc
<=i
){
134 if( growOpArray(p
) ){
140 pOp
->opcode
= (u8
)op
;
146 pOp
->p4type
= P4_NOTUSED
;
149 if( p
->db
->flags
& SQLITE_VdbeAddopTrace
){
150 sqlite3VdbePrintOp(0, i
, &p
->aOp
[i
]);
159 int sqlite3VdbeAddOp0(Vdbe
*p
, int op
){
160 return sqlite3VdbeAddOp3(p
, op
, 0, 0, 0);
162 int sqlite3VdbeAddOp1(Vdbe
*p
, int op
, int p1
){
163 return sqlite3VdbeAddOp3(p
, op
, p1
, 0, 0);
165 int sqlite3VdbeAddOp2(Vdbe
*p
, int op
, int p1
, int p2
){
166 return sqlite3VdbeAddOp3(p
, op
, p1
, p2
, 0);
171 ** Add an opcode that includes the p4 value as a pointer.
173 int sqlite3VdbeAddOp4(
174 Vdbe
*p
, /* Add the opcode to this VM */
175 int op
, /* The new opcode */
176 int p1
, /* The P1 operand */
177 int p2
, /* The P2 operand */
178 int p3
, /* The P3 operand */
179 const char *zP4
, /* The P4 operand */
180 int p4type
/* P4 operand type */
182 int addr
= sqlite3VdbeAddOp3(p
, op
, p1
, p2
, p3
);
183 sqlite3VdbeChangeP4(p
, addr
, zP4
, p4type
);
188 ** Add an OP_ParseSchema opcode. This routine is broken out from
189 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
190 ** as having been used.
192 ** The zWhere string must have been obtained from sqlite3_malloc().
193 ** This routine will take ownership of the allocated memory.
195 void sqlite3VdbeAddParseSchemaOp(Vdbe
*p
, int iDb
, char *zWhere
){
197 int addr
= sqlite3VdbeAddOp3(p
, OP_ParseSchema
, iDb
, 0, 0);
198 sqlite3VdbeChangeP4(p
, addr
, zWhere
, P4_DYNAMIC
);
199 for(j
=0; j
<p
->db
->nDb
; j
++) sqlite3VdbeUsesBtree(p
, j
);
203 ** Add an opcode that includes the p4 value as an integer.
205 int sqlite3VdbeAddOp4Int(
206 Vdbe
*p
, /* Add the opcode to this VM */
207 int op
, /* The new opcode */
208 int p1
, /* The P1 operand */
209 int p2
, /* The P2 operand */
210 int p3
, /* The P3 operand */
211 int p4
/* The P4 operand as an integer */
213 int addr
= sqlite3VdbeAddOp3(p
, op
, p1
, p2
, p3
);
214 sqlite3VdbeChangeP4(p
, addr
, SQLITE_INT_TO_PTR(p4
), P4_INT32
);
219 ** Create a new symbolic label for an instruction that has yet to be
220 ** coded. The symbolic label is really just a negative number. The
221 ** label can be used as the P2 value of an operation. Later, when
222 ** the label is resolved to a specific address, the VDBE will scan
223 ** through its operation list and change all values of P2 which match
224 ** the label into the resolved address.
226 ** The VDBE knows that a P2 value is a label because labels are
227 ** always negative and P2 values are suppose to be non-negative.
228 ** Hence, a negative P2 value is a label that has yet to be resolved.
230 ** Zero is returned if a malloc() fails.
232 int sqlite3VdbeMakeLabel(Vdbe
*p
){
234 assert( p
->magic
==VDBE_MAGIC_INIT
);
235 if( (i
& (i
-1))==0 ){
236 p
->aLabel
= sqlite3DbReallocOrFree(p
->db
, p
->aLabel
,
237 (i
*2+1)*sizeof(p
->aLabel
[0]));
246 ** Resolve label "x" to be the address of the next instruction to
247 ** be inserted. The parameter "x" must have been obtained from
248 ** a prior call to sqlite3VdbeMakeLabel().
250 void sqlite3VdbeResolveLabel(Vdbe
*p
, int x
){
252 assert( p
->magic
==VDBE_MAGIC_INIT
);
253 assert( j
<p
->nLabel
);
254 if( j
>=0 && p
->aLabel
){
255 p
->aLabel
[j
] = p
->nOp
;
260 ** Mark the VDBE as one that can only be run one time.
262 void sqlite3VdbeRunOnlyOnce(Vdbe
*p
){
266 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
269 ** The following type and function are used to iterate through all opcodes
270 ** in a Vdbe main program and each of the sub-programs (triggers) it may
271 ** invoke directly or indirectly. It should be used as follows:
276 ** memset(&sIter, 0, sizeof(sIter));
277 ** sIter.v = v; // v is of type Vdbe*
278 ** while( (pOp = opIterNext(&sIter)) ){
279 ** // Do something with pOp
281 ** sqlite3DbFree(v->db, sIter.apSub);
284 typedef struct VdbeOpIter VdbeOpIter
;
286 Vdbe
*v
; /* Vdbe to iterate through the opcodes of */
287 SubProgram
**apSub
; /* Array of subprograms */
288 int nSub
; /* Number of entries in apSub */
289 int iAddr
; /* Address of next instruction to return */
290 int iSub
; /* 0 = main program, 1 = first sub-program etc. */
292 static Op
*opIterNext(VdbeOpIter
*p
){
298 if( p
->iSub
<=p
->nSub
){
304 aOp
= p
->apSub
[p
->iSub
-1]->aOp
;
305 nOp
= p
->apSub
[p
->iSub
-1]->nOp
;
307 assert( p
->iAddr
<nOp
);
309 pRet
= &aOp
[p
->iAddr
];
316 if( pRet
->p4type
==P4_SUBPROGRAM
){
317 int nByte
= (p
->nSub
+1)*sizeof(SubProgram
*);
319 for(j
=0; j
<p
->nSub
; j
++){
320 if( p
->apSub
[j
]==pRet
->p4
.pProgram
) break;
323 p
->apSub
= sqlite3DbReallocOrFree(v
->db
, p
->apSub
, nByte
);
327 p
->apSub
[p
->nSub
++] = pRet
->p4
.pProgram
;
337 ** Check if the program stored in the VM associated with pParse may
338 ** throw an ABORT exception (causing the statement, but not entire transaction
339 ** to be rolled back). This condition is true if the main program or any
340 ** sub-programs contains any of the following:
342 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
343 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
347 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
349 ** Then check that the value of Parse.mayAbort is true if an
350 ** ABORT may be thrown, or false otherwise. Return true if it does
351 ** match, or false otherwise. This function is intended to be used as
352 ** part of an assert statement in the compiler. Similar to:
354 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
356 int sqlite3VdbeAssertMayAbort(Vdbe
*v
, int mayAbort
){
360 memset(&sIter
, 0, sizeof(sIter
));
363 while( (pOp
= opIterNext(&sIter
))!=0 ){
364 int opcode
= pOp
->opcode
;
365 if( opcode
==OP_Destroy
|| opcode
==OP_VUpdate
|| opcode
==OP_VRename
366 #ifndef SQLITE_OMIT_FOREIGN_KEY
367 || (opcode
==OP_FkCounter
&& pOp
->p1
==0 && pOp
->p2
==1)
369 || ((opcode
==OP_Halt
|| opcode
==OP_HaltIfNull
)
370 && ((pOp
->p1
&0xff)==SQLITE_CONSTRAINT
&& pOp
->p2
==OE_Abort
))
376 sqlite3DbFree(v
->db
, sIter
.apSub
);
378 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
379 ** If malloc failed, then the while() loop above may not have iterated
380 ** through all opcodes and hasAbort may be set incorrectly. Return
381 ** true for this case to prevent the assert() in the callers frame
383 return ( v
->db
->mallocFailed
|| hasAbort
==mayAbort
);
385 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
388 ** Loop through the program looking for P2 values that are negative
389 ** on jump instructions. Each such value is a label. Resolve the
390 ** label by setting the P2 value to its correct non-zero value.
392 ** This routine is called once after all opcodes have been inserted.
394 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
395 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
396 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
398 ** The Op.opflags field is set on all opcodes.
400 static void resolveP2Values(Vdbe
*p
, int *pMaxFuncArgs
){
402 int nMaxArgs
= *pMaxFuncArgs
;
404 int *aLabel
= p
->aLabel
;
407 for(pOp
=p
->aOp
, i
=p
->nOp
-1; i
>=0; i
--, pOp
++){
408 u8 opcode
= pOp
->opcode
;
410 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
411 ** cases from this switch! */
415 if( pOp
->p5
>nMaxArgs
) nMaxArgs
= pOp
->p5
;
418 case OP_Transaction
: {
419 if( pOp
->p2
!=0 ) p
->readOnly
= 0;
427 #ifndef SQLITE_OMIT_WAL
431 case OP_JournalMode
: {
436 #ifndef SQLITE_OMIT_VIRTUALTABLE
438 if( pOp
->p2
>nMaxArgs
) nMaxArgs
= pOp
->p2
;
443 assert( p
->nOp
- i
>= 3 );
444 assert( pOp
[-1].opcode
==OP_Integer
);
446 if( n
>nMaxArgs
) nMaxArgs
= n
;
451 case OP_SorterNext
: {
452 pOp
->p4
.xAdvance
= sqlite3BtreeNext
;
453 pOp
->p4type
= P4_ADVANCE
;
457 pOp
->p4
.xAdvance
= sqlite3BtreePrevious
;
458 pOp
->p4type
= P4_ADVANCE
;
463 pOp
->opflags
= sqlite3OpcodeProperty
[opcode
];
464 if( (pOp
->opflags
& OPFLG_JUMP
)!=0 && pOp
->p2
<0 ){
465 assert( -1-pOp
->p2
<p
->nLabel
);
466 pOp
->p2
= aLabel
[-1-pOp
->p2
];
469 sqlite3DbFree(p
->db
, p
->aLabel
);
471 *pMaxFuncArgs
= nMaxArgs
;
472 assert( p
->bIsReader
!=0 || p
->btreeMask
==0 );
476 ** Return the address of the next instruction to be inserted.
478 int sqlite3VdbeCurrentAddr(Vdbe
*p
){
479 assert( p
->magic
==VDBE_MAGIC_INIT
);
484 ** This function returns a pointer to the array of opcodes associated with
485 ** the Vdbe passed as the first argument. It is the callers responsibility
486 ** to arrange for the returned array to be eventually freed using the
487 ** vdbeFreeOpArray() function.
489 ** Before returning, *pnOp is set to the number of entries in the returned
490 ** array. Also, *pnMaxArg is set to the larger of its current value and
491 ** the number of entries in the Vdbe.apArg[] array required to execute the
494 VdbeOp
*sqlite3VdbeTakeOpArray(Vdbe
*p
, int *pnOp
, int *pnMaxArg
){
495 VdbeOp
*aOp
= p
->aOp
;
496 assert( aOp
&& !p
->db
->mallocFailed
);
498 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
499 assert( p
->btreeMask
==0 );
501 resolveP2Values(p
, pnMaxArg
);
508 ** Add a whole list of operations to the operation stack. Return the
509 ** address of the first operation added.
511 int sqlite3VdbeAddOpList(Vdbe
*p
, int nOp
, VdbeOpList
const *aOp
){
513 assert( p
->magic
==VDBE_MAGIC_INIT
);
514 if( p
->nOp
+ nOp
> p
->nOpAlloc
&& growOpArray(p
) ){
520 VdbeOpList
const *pIn
= aOp
;
521 for(i
=0; i
<nOp
; i
++, pIn
++){
523 VdbeOp
*pOut
= &p
->aOp
[i
+addr
];
524 pOut
->opcode
= pIn
->opcode
;
526 if( p2
<0 && (sqlite3OpcodeProperty
[pOut
->opcode
] & OPFLG_JUMP
)!=0 ){
527 pOut
->p2
= addr
+ ADDR(p2
);
532 pOut
->p4type
= P4_NOTUSED
;
537 if( p
->db
->flags
& SQLITE_VdbeAddopTrace
){
538 sqlite3VdbePrintOp(0, i
+addr
, &p
->aOp
[i
+addr
]);
548 ** Change the value of the P1 operand for a specific instruction.
549 ** This routine is useful when a large program is loaded from a
550 ** static array using sqlite3VdbeAddOpList but we want to make a
551 ** few minor changes to the program.
553 void sqlite3VdbeChangeP1(Vdbe
*p
, u32 addr
, int val
){
555 if( ((u32
)p
->nOp
)>addr
){
556 p
->aOp
[addr
].p1
= val
;
561 ** Change the value of the P2 operand for a specific instruction.
562 ** This routine is useful for setting a jump destination.
564 void sqlite3VdbeChangeP2(Vdbe
*p
, u32 addr
, int val
){
566 if( ((u32
)p
->nOp
)>addr
){
567 p
->aOp
[addr
].p2
= val
;
572 ** Change the value of the P3 operand for a specific instruction.
574 void sqlite3VdbeChangeP3(Vdbe
*p
, u32 addr
, int val
){
576 if( ((u32
)p
->nOp
)>addr
){
577 p
->aOp
[addr
].p3
= val
;
582 ** Change the value of the P5 operand for the most recently
585 void sqlite3VdbeChangeP5(Vdbe
*p
, u8 val
){
589 p
->aOp
[p
->nOp
-1].p5
= val
;
594 ** Change the P2 operand of instruction addr so that it points to
595 ** the address of the next instruction to be coded.
597 void sqlite3VdbeJumpHere(Vdbe
*p
, int addr
){
598 if( ALWAYS(addr
>=0) ) sqlite3VdbeChangeP2(p
, addr
, p
->nOp
);
603 ** If the input FuncDef structure is ephemeral, then free it. If
604 ** the FuncDef is not ephermal, then do nothing.
606 static void freeEphemeralFunction(sqlite3
*db
, FuncDef
*pDef
){
607 if( ALWAYS(pDef
) && (pDef
->flags
& SQLITE_FUNC_EPHEM
)!=0 ){
608 sqlite3DbFree(db
, pDef
);
612 static void vdbeFreeOpArray(sqlite3
*, Op
*, int);
615 ** Delete a P4 value if necessary.
617 static void freeP4(sqlite3
*db
, int p4type
, void *p4
){
626 case P4_KEYINFO_HANDOFF
: {
627 sqlite3DbFree(db
, p4
);
631 if( db
->pnBytesFreed
==0 ) sqlite3_free(p4
);
635 freeEphemeralFunction(db
, (FuncDef
*)p4
);
639 if( db
->pnBytesFreed
==0 ){
640 sqlite3ValueFree((sqlite3_value
*)p4
);
643 sqlite3DbFree(db
, p
->zMalloc
);
644 sqlite3DbFree(db
, p
);
649 if( db
->pnBytesFreed
==0 ) sqlite3VtabUnlock((VTable
*)p4
);
657 ** Free the space allocated for aOp and any p4 values allocated for the
658 ** opcodes contained within. If aOp is not NULL it is assumed to contain
661 static void vdbeFreeOpArray(sqlite3
*db
, Op
*aOp
, int nOp
){
664 for(pOp
=aOp
; pOp
<&aOp
[nOp
]; pOp
++){
665 freeP4(db
, pOp
->p4type
, pOp
->p4
.p
);
667 sqlite3DbFree(db
, pOp
->zComment
);
671 sqlite3DbFree(db
, aOp
);
675 ** Link the SubProgram object passed as the second argument into the linked
676 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
677 ** objects when the VM is no longer required.
679 void sqlite3VdbeLinkSubProgram(Vdbe
*pVdbe
, SubProgram
*p
){
680 p
->pNext
= pVdbe
->pProgram
;
685 ** Change the opcode at addr into OP_Noop
687 void sqlite3VdbeChangeToNoop(Vdbe
*p
, int addr
){
689 VdbeOp
*pOp
= &p
->aOp
[addr
];
691 freeP4(db
, pOp
->p4type
, pOp
->p4
.p
);
692 memset(pOp
, 0, sizeof(pOp
[0]));
693 pOp
->opcode
= OP_Noop
;
698 ** Change the value of the P4 operand for a specific instruction.
699 ** This routine is useful when a large program is loaded from a
700 ** static array using sqlite3VdbeAddOpList but we want to make a
701 ** few minor changes to the program.
703 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
704 ** the string is made into memory obtained from sqlite3_malloc().
705 ** A value of n==0 means copy bytes of zP4 up to and including the
706 ** first null byte. If n>0 then copy n+1 bytes of zP4.
708 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
709 ** A copy is made of the KeyInfo structure into memory obtained from
710 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
711 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
712 ** stored in memory that the caller has obtained from sqlite3_malloc. The
713 ** caller should not free the allocation, it will be freed when the Vdbe is
716 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
717 ** to a string or structure that is guaranteed to exist for the lifetime of
718 ** the Vdbe. In these cases we can just copy the pointer.
720 ** If addr<0 then change P4 on the most recently inserted instruction.
722 void sqlite3VdbeChangeP4(Vdbe
*p
, int addr
, const char *zP4
, int n
){
727 assert( p
->magic
==VDBE_MAGIC_INIT
);
728 if( p
->aOp
==0 || db
->mallocFailed
){
729 if ( n
!=P4_KEYINFO
&& n
!=P4_VTAB
) {
730 freeP4(db
, n
, (void*)*(char**)&zP4
);
735 assert( addr
<p
->nOp
);
740 assert( pOp
->p4type
==P4_NOTUSED
|| pOp
->p4type
==P4_INT32
);
741 freeP4(db
, pOp
->p4type
, pOp
->p4
.p
);
744 /* Note: this cast is safe, because the origin data point was an int
745 ** that was cast to a (const char *). */
746 pOp
->p4
.i
= SQLITE_PTR_TO_INT(zP4
);
747 pOp
->p4type
= P4_INT32
;
750 pOp
->p4type
= P4_NOTUSED
;
751 }else if( n
==P4_KEYINFO
){
752 KeyInfo
*pOrig
, *pNew
;
754 pOrig
= (KeyInfo
*)zP4
;
755 pOp
->p4
.pKeyInfo
= pNew
= sqlite3KeyInfoAlloc(db
, pOrig
->nField
);
757 memcpy(pNew
->aColl
, pOrig
->aColl
, pOrig
->nField
*sizeof(pNew
->aColl
[0]));
758 memcpy(pNew
->aSortOrder
, pOrig
->aSortOrder
, pOrig
->nField
);
759 pOp
->p4type
= P4_KEYINFO
;
761 p
->db
->mallocFailed
= 1;
762 pOp
->p4type
= P4_NOTUSED
;
764 }else if( n
==P4_KEYINFO_HANDOFF
){
765 pOp
->p4
.p
= (void*)zP4
;
766 pOp
->p4type
= P4_KEYINFO
;
767 }else if( n
==P4_VTAB
){
768 pOp
->p4
.p
= (void*)zP4
;
769 pOp
->p4type
= P4_VTAB
;
770 sqlite3VtabLock((VTable
*)zP4
);
771 assert( ((VTable
*)zP4
)->db
==p
->db
);
773 pOp
->p4
.p
= (void*)zP4
;
774 pOp
->p4type
= (signed char)n
;
776 if( n
==0 ) n
= sqlite3Strlen30(zP4
);
777 pOp
->p4
.z
= sqlite3DbStrNDup(p
->db
, zP4
, n
);
778 pOp
->p4type
= P4_DYNAMIC
;
784 ** Change the comment on the most recently coded instruction. Or
785 ** insert a No-op and add the comment to that new instruction. This
786 ** makes the code easier to read during debugging. None of this happens
787 ** in a production build.
789 static void vdbeVComment(Vdbe
*p
, const char *zFormat
, va_list ap
){
790 assert( p
->nOp
>0 || p
->aOp
==0 );
791 assert( p
->aOp
==0 || p
->aOp
[p
->nOp
-1].zComment
==0 || p
->db
->mallocFailed
);
794 sqlite3DbFree(p
->db
, p
->aOp
[p
->nOp
-1].zComment
);
795 p
->aOp
[p
->nOp
-1].zComment
= sqlite3VMPrintf(p
->db
, zFormat
, ap
);
798 void sqlite3VdbeComment(Vdbe
*p
, const char *zFormat
, ...){
801 va_start(ap
, zFormat
);
802 vdbeVComment(p
, zFormat
, ap
);
806 void sqlite3VdbeNoopComment(Vdbe
*p
, const char *zFormat
, ...){
809 sqlite3VdbeAddOp0(p
, OP_Noop
);
810 va_start(ap
, zFormat
);
811 vdbeVComment(p
, zFormat
, ap
);
818 ** Return the opcode for a given address. If the address is -1, then
819 ** return the most recently inserted opcode.
821 ** If a memory allocation error has occurred prior to the calling of this
822 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
823 ** is readable but not writable, though it is cast to a writable value.
824 ** The return of a dummy opcode allows the call to continue functioning
825 ** after a OOM fault without having to check to see if the return from
826 ** this routine is a valid pointer. But because the dummy.opcode is 0,
827 ** dummy will never be written to. This is verified by code inspection and
828 ** by running with Valgrind.
830 ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
831 ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
832 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
833 ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
834 ** having to double-check to make sure that the result is non-negative. But
835 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
836 ** check the value of p->nOp-1 before continuing.
838 VdbeOp
*sqlite3VdbeGetOp(Vdbe
*p
, int addr
){
839 /* C89 specifies that the constant "dummy" will be initialized to all
840 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
841 static VdbeOp dummy
; /* Ignore the MSVC warning about no initializer */
842 assert( p
->magic
==VDBE_MAGIC_INIT
);
844 #ifdef SQLITE_OMIT_TRACE
845 if( p
->nOp
==0 ) return (VdbeOp
*)&dummy
;
849 assert( (addr
>=0 && addr
<p
->nOp
) || p
->db
->mallocFailed
);
850 if( p
->db
->mallocFailed
){
851 return (VdbeOp
*)&dummy
;
853 return &p
->aOp
[addr
];
857 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
858 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
860 ** Compute a string that describes the P4 parameter for an opcode.
861 ** Use zTemp for any required temporary buffer space.
863 static char *displayP4(Op
*pOp
, char *zTemp
, int nTemp
){
866 switch( pOp
->p4type
){
867 case P4_KEYINFO_STATIC
:
870 KeyInfo
*pKeyInfo
= pOp
->p4
.pKeyInfo
;
871 assert( pKeyInfo
->aSortOrder
!=0 );
872 sqlite3_snprintf(nTemp
, zTemp
, "keyinfo(%d", pKeyInfo
->nField
);
873 i
= sqlite3Strlen30(zTemp
);
874 for(j
=0; j
<pKeyInfo
->nField
; j
++){
875 CollSeq
*pColl
= pKeyInfo
->aColl
[j
];
876 const char *zColl
= pColl
? pColl
->zName
: "nil";
877 int n
= sqlite3Strlen30(zColl
);
879 memcpy(&zTemp
[i
],",...",4);
883 if( pKeyInfo
->aSortOrder
[j
] ){
886 memcpy(&zTemp
[i
], zColl
, n
+1);
895 CollSeq
*pColl
= pOp
->p4
.pColl
;
896 sqlite3_snprintf(nTemp
, zTemp
, "collseq(%.20s)", pColl
->zName
);
900 FuncDef
*pDef
= pOp
->p4
.pFunc
;
901 sqlite3_snprintf(nTemp
, zTemp
, "%s(%d)", pDef
->zName
, pDef
->nArg
);
905 sqlite3_snprintf(nTemp
, zTemp
, "%lld", *pOp
->p4
.pI64
);
909 sqlite3_snprintf(nTemp
, zTemp
, "%d", pOp
->p4
.i
);
913 sqlite3_snprintf(nTemp
, zTemp
, "%.16g", *pOp
->p4
.pReal
);
917 Mem
*pMem
= pOp
->p4
.pMem
;
918 if( pMem
->flags
& MEM_Str
){
920 }else if( pMem
->flags
& MEM_Int
){
921 sqlite3_snprintf(nTemp
, zTemp
, "%lld", pMem
->u
.i
);
922 }else if( pMem
->flags
& MEM_Real
){
923 sqlite3_snprintf(nTemp
, zTemp
, "%.16g", pMem
->r
);
924 }else if( pMem
->flags
& MEM_Null
){
925 sqlite3_snprintf(nTemp
, zTemp
, "NULL");
927 assert( pMem
->flags
& MEM_Blob
);
932 #ifndef SQLITE_OMIT_VIRTUALTABLE
934 sqlite3_vtab
*pVtab
= pOp
->p4
.pVtab
->pVtab
;
935 sqlite3_snprintf(nTemp
, zTemp
, "vtab:%p:%p", pVtab
, pVtab
->pModule
);
940 sqlite3_snprintf(nTemp
, zTemp
, "intarray");
943 case P4_SUBPROGRAM
: {
944 sqlite3_snprintf(nTemp
, zTemp
, "program");
965 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
967 ** The prepared statements need to know in advance the complete set of
968 ** attached databases that will be use. A mask of these databases
969 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
970 ** p->btreeMask of databases that will require a lock.
972 void sqlite3VdbeUsesBtree(Vdbe
*p
, int i
){
973 assert( i
>=0 && i
<p
->db
->nDb
&& i
<(int)sizeof(yDbMask
)*8 );
974 assert( i
<(int)sizeof(p
->btreeMask
)*8 );
975 p
->btreeMask
|= ((yDbMask
)1)<<i
;
976 if( i
!=1 && sqlite3BtreeSharable(p
->db
->aDb
[i
].pBt
) ){
977 p
->lockMask
|= ((yDbMask
)1)<<i
;
981 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
983 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
984 ** this routine obtains the mutex associated with each BtShared structure
985 ** that may be accessed by the VM passed as an argument. In doing so it also
986 ** sets the BtShared.db member of each of the BtShared structures, ensuring
987 ** that the correct busy-handler callback is invoked if required.
989 ** If SQLite is not threadsafe but does support shared-cache mode, then
990 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
991 ** of all of BtShared structures accessible via the database handle
992 ** associated with the VM.
994 ** If SQLite is not threadsafe and does not support shared-cache mode, this
995 ** function is a no-op.
997 ** The p->btreeMask field is a bitmask of all btrees that the prepared
998 ** statement p will ever use. Let N be the number of bits in p->btreeMask
999 ** corresponding to btrees that use shared cache. Then the runtime of
1000 ** this routine is N*N. But as N is rarely more than 1, this should not
1003 void sqlite3VdbeEnter(Vdbe
*p
){
1009 if( p
->lockMask
==0 ) return; /* The common case */
1013 for(i
=0, mask
=1; i
<nDb
; i
++, mask
+= mask
){
1014 if( i
!=1 && (mask
& p
->lockMask
)!=0 && ALWAYS(aDb
[i
].pBt
!=0) ){
1015 sqlite3BtreeEnter(aDb
[i
].pBt
);
1021 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1023 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1025 void sqlite3VdbeLeave(Vdbe
*p
){
1031 if( p
->lockMask
==0 ) return; /* The common case */
1035 for(i
=0, mask
=1; i
<nDb
; i
++, mask
+= mask
){
1036 if( i
!=1 && (mask
& p
->lockMask
)!=0 && ALWAYS(aDb
[i
].pBt
!=0) ){
1037 sqlite3BtreeLeave(aDb
[i
].pBt
);
1043 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
1045 ** Print a single opcode. This routine is used for debugging only.
1047 void sqlite3VdbePrintOp(FILE *pOut
, int pc
, Op
*pOp
){
1050 static const char *zFormat1
= "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
1051 if( pOut
==0 ) pOut
= stdout
;
1052 zP4
= displayP4(pOp
, zPtr
, sizeof(zPtr
));
1053 fprintf(pOut
, zFormat1
, pc
,
1054 sqlite3OpcodeName(pOp
->opcode
), pOp
->p1
, pOp
->p2
, pOp
->p3
, zP4
, pOp
->p5
,
1056 pOp
->zComment
? pOp
->zComment
: ""
1066 ** Release an array of N Mem elements
1068 static void releaseMemArray(Mem
*p
, int N
){
1071 sqlite3
*db
= p
->db
;
1072 u8 malloc_failed
= db
->mallocFailed
;
1073 if( db
->pnBytesFreed
){
1074 for(pEnd
=&p
[N
]; p
<pEnd
; p
++){
1075 sqlite3DbFree(db
, p
->zMalloc
);
1079 for(pEnd
=&p
[N
]; p
<pEnd
; p
++){
1080 assert( (&p
[1])==pEnd
|| p
[0].db
==p
[1].db
);
1082 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1083 ** that takes advantage of the fact that the memory cell value is
1084 ** being set to NULL after releasing any dynamic resources.
1086 ** The justification for duplicating code is that according to
1087 ** callgrind, this causes a certain test case to hit the CPU 4.7
1088 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1089 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1090 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1091 ** with no indexes using a single prepared INSERT statement, bind()
1092 ** and reset(). Inserts are grouped into a transaction.
1094 if( p
->flags
&(MEM_Agg
|MEM_Dyn
|MEM_Frame
|MEM_RowSet
) ){
1095 sqlite3VdbeMemRelease(p
);
1096 }else if( p
->zMalloc
){
1097 sqlite3DbFree(db
, p
->zMalloc
);
1101 p
->flags
= MEM_Invalid
;
1103 db
->mallocFailed
= malloc_failed
;
1108 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1109 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
1111 void sqlite3VdbeFrameDelete(VdbeFrame
*p
){
1113 Mem
*aMem
= VdbeFrameMem(p
);
1114 VdbeCursor
**apCsr
= (VdbeCursor
**)&aMem
[p
->nChildMem
];
1115 for(i
=0; i
<p
->nChildCsr
; i
++){
1116 sqlite3VdbeFreeCursor(p
->v
, apCsr
[i
]);
1118 releaseMemArray(aMem
, p
->nChildMem
);
1119 sqlite3DbFree(p
->v
->db
, p
);
1122 #ifndef SQLITE_OMIT_EXPLAIN
1124 ** Give a listing of the program in the virtual machine.
1126 ** The interface is the same as sqlite3VdbeExec(). But instead of
1127 ** running the code, it invokes the callback once for each instruction.
1128 ** This feature is used to implement "EXPLAIN".
1130 ** When p->explain==1, each instruction is listed. When
1131 ** p->explain==2, only OP_Explain instructions are listed and these
1132 ** are shown in a different format. p->explain==2 is used to implement
1133 ** EXPLAIN QUERY PLAN.
1135 ** When p->explain==1, first the main program is listed, then each of
1136 ** the trigger subprograms are listed one by one.
1138 int sqlite3VdbeList(
1139 Vdbe
*p
/* The VDBE */
1141 int nRow
; /* Stop when row count reaches this */
1142 int nSub
= 0; /* Number of sub-vdbes seen so far */
1143 SubProgram
**apSub
= 0; /* Array of sub-vdbes */
1144 Mem
*pSub
= 0; /* Memory cell hold array of subprogs */
1145 sqlite3
*db
= p
->db
; /* The database connection */
1146 int i
; /* Loop counter */
1147 int rc
= SQLITE_OK
; /* Return code */
1148 Mem
*pMem
= &p
->aMem
[1]; /* First Mem of result set */
1150 assert( p
->explain
);
1151 assert( p
->magic
==VDBE_MAGIC_RUN
);
1152 assert( p
->rc
==SQLITE_OK
|| p
->rc
==SQLITE_BUSY
|| p
->rc
==SQLITE_NOMEM
);
1154 /* Even though this opcode does not use dynamic strings for
1155 ** the result, result columns may become dynamic if the user calls
1156 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
1158 releaseMemArray(pMem
, 8);
1161 if( p
->rc
==SQLITE_NOMEM
){
1162 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1163 ** sqlite3_column_text16() failed. */
1164 db
->mallocFailed
= 1;
1165 return SQLITE_ERROR
;
1168 /* When the number of output rows reaches nRow, that means the
1169 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1170 ** nRow is the sum of the number of rows in the main program, plus
1171 ** the sum of the number of rows in all trigger subprograms encountered
1172 ** so far. The nRow value will increase as new trigger subprograms are
1173 ** encountered, but p->pc will eventually catch up to nRow.
1176 if( p
->explain
==1 ){
1177 /* The first 8 memory cells are used for the result set. So we will
1178 ** commandeer the 9th cell to use as storage for an array of pointers
1179 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1181 assert( p
->nMem
>9 );
1183 if( pSub
->flags
&MEM_Blob
){
1184 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1185 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
1186 nSub
= pSub
->n
/sizeof(Vdbe
*);
1187 apSub
= (SubProgram
**)pSub
->z
;
1189 for(i
=0; i
<nSub
; i
++){
1190 nRow
+= apSub
[i
]->nOp
;
1196 }while( i
<nRow
&& p
->explain
==2 && p
->aOp
[i
].opcode
!=OP_Explain
);
1200 }else if( db
->u1
.isInterrupted
){
1201 p
->rc
= SQLITE_INTERRUPT
;
1203 sqlite3SetString(&p
->zErrMsg
, db
, "%s", sqlite3ErrStr(p
->rc
));
1208 /* The output line number is small enough that we are still in the
1212 /* We are currently listing subprograms. Figure out which one and
1213 ** pick up the appropriate opcode. */
1216 for(j
=0; i
>=apSub
[j
]->nOp
; j
++){
1219 pOp
= &apSub
[j
]->aOp
[i
];
1221 if( p
->explain
==1 ){
1222 pMem
->flags
= MEM_Int
;
1223 pMem
->type
= SQLITE_INTEGER
;
1224 pMem
->u
.i
= i
; /* Program counter */
1227 pMem
->flags
= MEM_Static
|MEM_Str
|MEM_Term
;
1228 pMem
->z
= (char*)sqlite3OpcodeName(pOp
->opcode
); /* Opcode */
1229 assert( pMem
->z
!=0 );
1230 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1231 pMem
->type
= SQLITE_TEXT
;
1232 pMem
->enc
= SQLITE_UTF8
;
1235 /* When an OP_Program opcode is encounter (the only opcode that has
1236 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1237 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1238 ** has not already been seen.
1240 if( pOp
->p4type
==P4_SUBPROGRAM
){
1241 int nByte
= (nSub
+1)*sizeof(SubProgram
*);
1243 for(j
=0; j
<nSub
; j
++){
1244 if( apSub
[j
]==pOp
->p4
.pProgram
) break;
1246 if( j
==nSub
&& SQLITE_OK
==sqlite3VdbeMemGrow(pSub
, nByte
, nSub
!=0) ){
1247 apSub
= (SubProgram
**)pSub
->z
;
1248 apSub
[nSub
++] = pOp
->p4
.pProgram
;
1249 pSub
->flags
|= MEM_Blob
;
1250 pSub
->n
= nSub
*sizeof(SubProgram
*);
1255 pMem
->flags
= MEM_Int
;
1256 pMem
->u
.i
= pOp
->p1
; /* P1 */
1257 pMem
->type
= SQLITE_INTEGER
;
1260 pMem
->flags
= MEM_Int
;
1261 pMem
->u
.i
= pOp
->p2
; /* P2 */
1262 pMem
->type
= SQLITE_INTEGER
;
1265 pMem
->flags
= MEM_Int
;
1266 pMem
->u
.i
= pOp
->p3
; /* P3 */
1267 pMem
->type
= SQLITE_INTEGER
;
1270 if( sqlite3VdbeMemGrow(pMem
, 32, 0) ){ /* P4 */
1271 assert( p
->db
->mallocFailed
);
1272 return SQLITE_ERROR
;
1274 pMem
->flags
= MEM_Dyn
|MEM_Str
|MEM_Term
;
1275 z
= displayP4(pOp
, pMem
->z
, 32);
1277 sqlite3VdbeMemSetStr(pMem
, z
, -1, SQLITE_UTF8
, 0);
1279 assert( pMem
->z
!=0 );
1280 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1281 pMem
->enc
= SQLITE_UTF8
;
1283 pMem
->type
= SQLITE_TEXT
;
1286 if( p
->explain
==1 ){
1287 if( sqlite3VdbeMemGrow(pMem
, 4, 0) ){
1288 assert( p
->db
->mallocFailed
);
1289 return SQLITE_ERROR
;
1291 pMem
->flags
= MEM_Dyn
|MEM_Str
|MEM_Term
;
1293 sqlite3_snprintf(3, pMem
->z
, "%.2x", pOp
->p5
); /* P5 */
1294 pMem
->type
= SQLITE_TEXT
;
1295 pMem
->enc
= SQLITE_UTF8
;
1299 if( pOp
->zComment
){
1300 pMem
->flags
= MEM_Str
|MEM_Term
;
1301 pMem
->z
= pOp
->zComment
;
1302 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1303 pMem
->enc
= SQLITE_UTF8
;
1304 pMem
->type
= SQLITE_TEXT
;
1308 pMem
->flags
= MEM_Null
; /* Comment */
1309 pMem
->type
= SQLITE_NULL
;
1313 p
->nResColumn
= 8 - 4*(p
->explain
-1);
1314 p
->pResultSet
= &p
->aMem
[1];
1320 #endif /* SQLITE_OMIT_EXPLAIN */
1324 ** Print the SQL that was used to generate a VDBE program.
1326 void sqlite3VdbePrintSql(Vdbe
*p
){
1331 if( pOp
->opcode
==OP_Trace
&& pOp
->p4
.z
!=0 ){
1332 const char *z
= pOp
->p4
.z
;
1333 while( sqlite3Isspace(*z
) ) z
++;
1334 printf("SQL: [%s]\n", z
);
1339 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1341 ** Print an IOTRACE message showing SQL content.
1343 void sqlite3VdbeIOTraceSql(Vdbe
*p
){
1346 if( sqlite3IoTrace
==0 ) return;
1349 if( pOp
->opcode
==OP_Trace
&& pOp
->p4
.z
!=0 ){
1352 sqlite3_snprintf(sizeof(z
), z
, "%s", pOp
->p4
.z
);
1353 for(i
=0; sqlite3Isspace(z
[i
]); i
++){}
1354 for(j
=0; z
[i
]; i
++){
1355 if( sqlite3Isspace(z
[i
]) ){
1364 sqlite3IoTrace("SQL %s\n", z
);
1367 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1370 ** Allocate space from a fixed size buffer and return a pointer to
1371 ** that space. If insufficient space is available, return NULL.
1373 ** The pBuf parameter is the initial value of a pointer which will
1374 ** receive the new memory. pBuf is normally NULL. If pBuf is not
1375 ** NULL, it means that memory space has already been allocated and that
1376 ** this routine should not allocate any new memory. When pBuf is not
1377 ** NULL simply return pBuf. Only allocate new memory space when pBuf
1380 ** nByte is the number of bytes of space needed.
1382 ** *ppFrom points to available space and pEnd points to the end of the
1383 ** available space. When space is allocated, *ppFrom is advanced past
1384 ** the end of the allocated space.
1386 ** *pnByte is a counter of the number of bytes of space that have failed
1387 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
1388 ** request, then increment *pnByte by the amount of the request.
1390 static void *allocSpace(
1391 void *pBuf
, /* Where return pointer will be stored */
1392 int nByte
, /* Number of bytes to allocate */
1393 u8
**ppFrom
, /* IN/OUT: Allocate from *ppFrom */
1394 u8
*pEnd
, /* Pointer to 1 byte past the end of *ppFrom buffer */
1395 int *pnByte
/* If allocation cannot be made, increment *pnByte */
1397 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom
) );
1398 if( pBuf
) return pBuf
;
1399 nByte
= ROUND8(nByte
);
1400 if( &(*ppFrom
)[nByte
] <= pEnd
){
1401 pBuf
= (void*)*ppFrom
;
1410 ** Rewind the VDBE back to the beginning in preparation for
1413 void sqlite3VdbeRewind(Vdbe
*p
){
1414 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1418 assert( p
->magic
==VDBE_MAGIC_INIT
);
1420 /* There should be at least one opcode.
1424 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
1425 p
->magic
= VDBE_MAGIC_RUN
;
1428 for(i
=1; i
<p
->nMem
; i
++){
1429 assert( p
->aMem
[i
].db
==p
->db
);
1434 p
->errorAction
= OE_Abort
;
1435 p
->magic
= VDBE_MAGIC_RUN
;
1438 p
->minWriteFileFormat
= 255;
1440 p
->nFkConstraint
= 0;
1442 for(i
=0; i
<p
->nOp
; i
++){
1444 p
->aOp
[i
].cycles
= 0;
1450 ** Prepare a virtual machine for execution for the first time after
1451 ** creating the virtual machine. This involves things such
1452 ** as allocating stack space and initializing the program counter.
1453 ** After the VDBE has be prepped, it can be executed by one or more
1454 ** calls to sqlite3VdbeExec().
1456 ** This function may be called exact once on a each virtual machine.
1457 ** After this routine is called the VM has been "packaged" and is ready
1458 ** to run. After this routine is called, futher calls to
1459 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
1460 ** the Vdbe from the Parse object that helped generate it so that the
1461 ** the Vdbe becomes an independent entity and the Parse object can be
1464 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1465 ** to its initial state after it has been run.
1467 void sqlite3VdbeMakeReady(
1468 Vdbe
*p
, /* The VDBE */
1469 Parse
*pParse
/* Parsing context */
1471 sqlite3
*db
; /* The database connection */
1472 int nVar
; /* Number of parameters */
1473 int nMem
; /* Number of VM memory registers */
1474 int nCursor
; /* Number of cursors required */
1475 int nArg
; /* Number of arguments in subprograms */
1476 int nOnce
; /* Number of OP_Once instructions */
1477 int n
; /* Loop counter */
1478 u8
*zCsr
; /* Memory available for allocation */
1479 u8
*zEnd
; /* First byte past allocated memory */
1480 int nByte
; /* How much extra memory is needed */
1484 assert( pParse
!=0 );
1485 assert( p
->magic
==VDBE_MAGIC_INIT
);
1487 assert( db
->mallocFailed
==0 );
1488 nVar
= pParse
->nVar
;
1489 nMem
= pParse
->nMem
;
1490 nCursor
= pParse
->nTab
;
1491 nArg
= pParse
->nMaxArg
;
1492 nOnce
= pParse
->nOnce
;
1493 if( nOnce
==0 ) nOnce
= 1; /* Ensure at least one byte in p->aOnceFlag[] */
1495 /* For each cursor required, also allocate a memory cell. Memory
1496 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
1497 ** the vdbe program. Instead they are used to allocate space for
1498 ** VdbeCursor/BtCursor structures. The blob of memory associated with
1499 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
1500 ** stores the blob of memory associated with cursor 1, etc.
1502 ** See also: allocateCursor().
1506 /* Allocate space for memory registers, SQL variables, VDBE cursors and
1507 ** an array to marshal SQL function arguments in.
1509 zCsr
= (u8
*)&p
->aOp
[p
->nOp
]; /* Memory avaliable for allocation */
1510 zEnd
= (u8
*)&p
->aOp
[p
->nOpAlloc
]; /* First byte past end of zCsr[] */
1512 resolveP2Values(p
, &nArg
);
1513 p
->usesStmtJournal
= (u8
)(pParse
->isMultiWrite
&& pParse
->mayAbort
);
1514 if( pParse
->explain
&& nMem
<10 ){
1517 memset(zCsr
, 0, zEnd
-zCsr
);
1518 zCsr
+= (zCsr
- (u8
*)0)&7;
1519 assert( EIGHT_BYTE_ALIGNMENT(zCsr
) );
1522 /* Memory for registers, parameters, cursor, etc, is allocated in two
1523 ** passes. On the first pass, we try to reuse unused space at the
1524 ** end of the opcode array. If we are unable to satisfy all memory
1525 ** requirements by reusing the opcode array tail, then the second
1526 ** pass will fill in the rest using a fresh allocation.
1528 ** This two-pass approach that reuses as much memory as possible from
1529 ** the leftover space at the end of the opcode array can significantly
1530 ** reduce the amount of memory held by a prepared statement.
1534 p
->aMem
= allocSpace(p
->aMem
, nMem
*sizeof(Mem
), &zCsr
, zEnd
, &nByte
);
1535 p
->aVar
= allocSpace(p
->aVar
, nVar
*sizeof(Mem
), &zCsr
, zEnd
, &nByte
);
1536 p
->apArg
= allocSpace(p
->apArg
, nArg
*sizeof(Mem
*), &zCsr
, zEnd
, &nByte
);
1537 p
->azVar
= allocSpace(p
->azVar
, nVar
*sizeof(char*), &zCsr
, zEnd
, &nByte
);
1538 p
->apCsr
= allocSpace(p
->apCsr
, nCursor
*sizeof(VdbeCursor
*),
1539 &zCsr
, zEnd
, &nByte
);
1540 p
->aOnceFlag
= allocSpace(p
->aOnceFlag
, nOnce
, &zCsr
, zEnd
, &nByte
);
1542 p
->pFree
= sqlite3DbMallocZero(db
, nByte
);
1545 zEnd
= &zCsr
[nByte
];
1546 }while( nByte
&& !db
->mallocFailed
);
1548 p
->nCursor
= nCursor
;
1549 p
->nOnceFlag
= nOnce
;
1551 p
->nVar
= (ynVar
)nVar
;
1552 for(n
=0; n
<nVar
; n
++){
1553 p
->aVar
[n
].flags
= MEM_Null
;
1558 p
->nzVar
= pParse
->nzVar
;
1559 memcpy(p
->azVar
, pParse
->azVar
, p
->nzVar
*sizeof(p
->azVar
[0]));
1560 memset(pParse
->azVar
, 0, pParse
->nzVar
*sizeof(pParse
->azVar
[0]));
1563 p
->aMem
--; /* aMem[] goes from 1..nMem */
1564 p
->nMem
= nMem
; /* not from 0..nMem-1 */
1565 for(n
=1; n
<=nMem
; n
++){
1566 p
->aMem
[n
].flags
= MEM_Invalid
;
1570 p
->explain
= pParse
->explain
;
1571 sqlite3VdbeRewind(p
);
1575 ** Close a VDBE cursor and release all the resources that cursor
1578 void sqlite3VdbeFreeCursor(Vdbe
*p
, VdbeCursor
*pCx
){
1582 sqlite3VdbeSorterClose(p
->db
, pCx
);
1584 sqlite3BtreeClose(pCx
->pBt
);
1585 /* The pCx->pCursor will be close automatically, if it exists, by
1586 ** the call above. */
1587 }else if( pCx
->pCursor
){
1588 sqlite3BtreeCloseCursor(pCx
->pCursor
);
1590 #ifndef SQLITE_OMIT_VIRTUALTABLE
1591 if( pCx
->pVtabCursor
){
1592 sqlite3_vtab_cursor
*pVtabCursor
= pCx
->pVtabCursor
;
1593 const sqlite3_module
*pModule
= pCx
->pModule
;
1594 p
->inVtabMethod
= 1;
1595 pModule
->xClose(pVtabCursor
);
1596 p
->inVtabMethod
= 0;
1602 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
1603 ** is used, for example, when a trigger sub-program is halted to restore
1604 ** control to the main program.
1606 int sqlite3VdbeFrameRestore(VdbeFrame
*pFrame
){
1607 Vdbe
*v
= pFrame
->v
;
1608 v
->aOnceFlag
= pFrame
->aOnceFlag
;
1609 v
->nOnceFlag
= pFrame
->nOnceFlag
;
1610 v
->aOp
= pFrame
->aOp
;
1611 v
->nOp
= pFrame
->nOp
;
1612 v
->aMem
= pFrame
->aMem
;
1613 v
->nMem
= pFrame
->nMem
;
1614 v
->apCsr
= pFrame
->apCsr
;
1615 v
->nCursor
= pFrame
->nCursor
;
1616 v
->db
->lastRowid
= pFrame
->lastRowid
;
1617 v
->nChange
= pFrame
->nChange
;
1622 ** Close all cursors.
1624 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
1625 ** cell array. This is necessary as the memory cell array may contain
1626 ** pointers to VdbeFrame objects, which may in turn contain pointers to
1629 static void closeAllCursors(Vdbe
*p
){
1632 for(pFrame
=p
->pFrame
; pFrame
->pParent
; pFrame
=pFrame
->pParent
);
1633 sqlite3VdbeFrameRestore(pFrame
);
1640 for(i
=0; i
<p
->nCursor
; i
++){
1641 VdbeCursor
*pC
= p
->apCsr
[i
];
1643 sqlite3VdbeFreeCursor(p
, pC
);
1649 releaseMemArray(&p
->aMem
[1], p
->nMem
);
1651 while( p
->pDelFrame
){
1652 VdbeFrame
*pDel
= p
->pDelFrame
;
1653 p
->pDelFrame
= pDel
->pParent
;
1654 sqlite3VdbeFrameDelete(pDel
);
1657 /* Delete any auxdata allocations made by the VM */
1658 sqlite3VdbeDeleteAuxData(p
, -1, 0);
1659 assert( p
->pAuxData
==0 );
1663 ** Clean up the VM after execution.
1665 ** This routine will automatically close any cursors, lists, and/or
1666 ** sorters that were left open. It also deletes the values of
1667 ** variables in the aVar[] array.
1669 static void Cleanup(Vdbe
*p
){
1670 sqlite3
*db
= p
->db
;
1673 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
1674 ** Vdbe.aMem[] arrays have already been cleaned up. */
1676 if( p
->apCsr
) for(i
=0; i
<p
->nCursor
; i
++) assert( p
->apCsr
[i
]==0 );
1678 for(i
=1; i
<=p
->nMem
; i
++) assert( p
->aMem
[i
].flags
==MEM_Invalid
);
1682 sqlite3DbFree(db
, p
->zErrMsg
);
1688 ** Set the number of result columns that will be returned by this SQL
1689 ** statement. This is now set at compile time, rather than during
1690 ** execution of the vdbe program so that sqlite3_column_count() can
1691 ** be called on an SQL statement before sqlite3_step().
1693 void sqlite3VdbeSetNumCols(Vdbe
*p
, int nResColumn
){
1696 sqlite3
*db
= p
->db
;
1698 releaseMemArray(p
->aColName
, p
->nResColumn
*COLNAME_N
);
1699 sqlite3DbFree(db
, p
->aColName
);
1700 n
= nResColumn
*COLNAME_N
;
1701 p
->nResColumn
= (u16
)nResColumn
;
1702 p
->aColName
= pColName
= (Mem
*)sqlite3DbMallocZero(db
, sizeof(Mem
)*n
);
1703 if( p
->aColName
==0 ) return;
1705 pColName
->flags
= MEM_Null
;
1706 pColName
->db
= p
->db
;
1712 ** Set the name of the idx'th column to be returned by the SQL statement.
1713 ** zName must be a pointer to a nul terminated string.
1715 ** This call must be made after a call to sqlite3VdbeSetNumCols().
1717 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
1718 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
1719 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
1721 int sqlite3VdbeSetColName(
1722 Vdbe
*p
, /* Vdbe being configured */
1723 int idx
, /* Index of column zName applies to */
1724 int var
, /* One of the COLNAME_* constants */
1725 const char *zName
, /* Pointer to buffer containing name */
1726 void (*xDel
)(void*) /* Memory management strategy for zName */
1730 assert( idx
<p
->nResColumn
);
1731 assert( var
<COLNAME_N
);
1732 if( p
->db
->mallocFailed
){
1733 assert( !zName
|| xDel
!=SQLITE_DYNAMIC
);
1734 return SQLITE_NOMEM
;
1736 assert( p
->aColName
!=0 );
1737 pColName
= &(p
->aColName
[idx
+var
*p
->nResColumn
]);
1738 rc
= sqlite3VdbeMemSetStr(pColName
, zName
, -1, SQLITE_UTF8
, xDel
);
1739 assert( rc
!=0 || !zName
|| (pColName
->flags
&MEM_Term
)!=0 );
1744 ** A read or write transaction may or may not be active on database handle
1745 ** db. If a transaction is active, commit it. If there is a
1746 ** write-transaction spanning more than one database file, this routine
1747 ** takes care of the master journal trickery.
1749 static int vdbeCommit(sqlite3
*db
, Vdbe
*p
){
1751 int nTrans
= 0; /* Number of databases with an active write-transaction */
1753 int needXcommit
= 0;
1755 #ifdef SQLITE_OMIT_VIRTUALTABLE
1756 /* With this option, sqlite3VtabSync() is defined to be simply
1757 ** SQLITE_OK so p is not used.
1759 UNUSED_PARAMETER(p
);
1762 /* Before doing anything else, call the xSync() callback for any
1763 ** virtual module tables written in this transaction. This has to
1764 ** be done before determining whether a master journal file is
1765 ** required, as an xSync() callback may add an attached database
1766 ** to the transaction.
1768 rc
= sqlite3VtabSync(db
, p
);
1770 /* This loop determines (a) if the commit hook should be invoked and
1771 ** (b) how many database files have open write transactions, not
1772 ** including the temp database. (b) is important because if more than
1773 ** one database file has an open write transaction, a master journal
1774 ** file is required for an atomic commit.
1776 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1777 Btree
*pBt
= db
->aDb
[i
].pBt
;
1778 if( sqlite3BtreeIsInTrans(pBt
) ){
1780 if( i
!=1 ) nTrans
++;
1781 sqlite3BtreeEnter(pBt
);
1782 rc
= sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt
));
1783 sqlite3BtreeLeave(pBt
);
1786 if( rc
!=SQLITE_OK
){
1790 /* If there are any write-transactions at all, invoke the commit hook */
1791 if( needXcommit
&& db
->xCommitCallback
){
1792 rc
= db
->xCommitCallback(db
->pCommitArg
);
1794 return SQLITE_CONSTRAINT_COMMITHOOK
;
1798 /* The simple case - no more than one database file (not counting the
1799 ** TEMP database) has a transaction active. There is no need for the
1802 ** If the return value of sqlite3BtreeGetFilename() is a zero length
1803 ** string, it means the main database is :memory: or a temp file. In
1804 ** that case we do not support atomic multi-file commits, so use the
1805 ** simple case then too.
1807 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db
->aDb
[0].pBt
))
1810 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1811 Btree
*pBt
= db
->aDb
[i
].pBt
;
1813 rc
= sqlite3BtreeCommitPhaseOne(pBt
, 0);
1817 /* Do the commit only if all databases successfully complete phase 1.
1818 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1819 ** IO error while deleting or truncating a journal file. It is unlikely,
1820 ** but could happen. In this case abandon processing and return the error.
1822 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1823 Btree
*pBt
= db
->aDb
[i
].pBt
;
1825 rc
= sqlite3BtreeCommitPhaseTwo(pBt
, 0);
1828 if( rc
==SQLITE_OK
){
1829 sqlite3VtabCommit(db
);
1833 /* The complex case - There is a multi-file write-transaction active.
1834 ** This requires a master journal file to ensure the transaction is
1835 ** committed atomicly.
1837 #ifndef SQLITE_OMIT_DISKIO
1839 sqlite3_vfs
*pVfs
= db
->pVfs
;
1841 char *zMaster
= 0; /* File-name for the master journal */
1842 char const *zMainFile
= sqlite3BtreeGetFilename(db
->aDb
[0].pBt
);
1843 sqlite3_file
*pMaster
= 0;
1849 /* Select a master journal file name */
1850 nMainFile
= sqlite3Strlen30(zMainFile
);
1851 zMaster
= sqlite3MPrintf(db
, "%s-mjXXXXXX9XXz", zMainFile
);
1852 if( zMaster
==0 ) return SQLITE_NOMEM
;
1856 if( retryCount
>100 ){
1857 sqlite3_log(SQLITE_FULL
, "MJ delete: %s", zMaster
);
1858 sqlite3OsDelete(pVfs
, zMaster
, 0);
1860 }else if( retryCount
==1 ){
1861 sqlite3_log(SQLITE_FULL
, "MJ collide: %s", zMaster
);
1865 sqlite3_randomness(sizeof(iRandom
), &iRandom
);
1866 sqlite3_snprintf(13, &zMaster
[nMainFile
], "-mj%06X9%02X",
1867 (iRandom
>>8)&0xffffff, iRandom
&0xff);
1868 /* The antipenultimate character of the master journal name must
1869 ** be "9" to avoid name collisions when using 8+3 filenames. */
1870 assert( zMaster
[sqlite3Strlen30(zMaster
)-3]=='9' );
1871 sqlite3FileSuffix3(zMainFile
, zMaster
);
1872 rc
= sqlite3OsAccess(pVfs
, zMaster
, SQLITE_ACCESS_EXISTS
, &res
);
1873 }while( rc
==SQLITE_OK
&& res
);
1874 if( rc
==SQLITE_OK
){
1875 /* Open the master journal. */
1876 rc
= sqlite3OsOpenMalloc(pVfs
, zMaster
, &pMaster
,
1877 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|
1878 SQLITE_OPEN_EXCLUSIVE
|SQLITE_OPEN_MASTER_JOURNAL
, 0
1881 if( rc
!=SQLITE_OK
){
1882 sqlite3DbFree(db
, zMaster
);
1886 /* Write the name of each database file in the transaction into the new
1887 ** master journal file. If an error occurs at this point close
1888 ** and delete the master journal file. All the individual journal files
1889 ** still have 'null' as the master journal pointer, so they will roll
1890 ** back independently if a failure occurs.
1892 for(i
=0; i
<db
->nDb
; i
++){
1893 Btree
*pBt
= db
->aDb
[i
].pBt
;
1894 if( sqlite3BtreeIsInTrans(pBt
) ){
1895 char const *zFile
= sqlite3BtreeGetJournalname(pBt
);
1897 continue; /* Ignore TEMP and :memory: databases */
1899 assert( zFile
[0]!=0 );
1900 if( !needSync
&& !sqlite3BtreeSyncDisabled(pBt
) ){
1903 rc
= sqlite3OsWrite(pMaster
, zFile
, sqlite3Strlen30(zFile
)+1, offset
);
1904 offset
+= sqlite3Strlen30(zFile
)+1;
1905 if( rc
!=SQLITE_OK
){
1906 sqlite3OsCloseFree(pMaster
);
1907 sqlite3OsDelete(pVfs
, zMaster
, 0);
1908 sqlite3DbFree(db
, zMaster
);
1914 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
1915 ** flag is set this is not required.
1918 && 0==(sqlite3OsDeviceCharacteristics(pMaster
)&SQLITE_IOCAP_SEQUENTIAL
)
1919 && SQLITE_OK
!=(rc
= sqlite3OsSync(pMaster
, SQLITE_SYNC_NORMAL
))
1921 sqlite3OsCloseFree(pMaster
);
1922 sqlite3OsDelete(pVfs
, zMaster
, 0);
1923 sqlite3DbFree(db
, zMaster
);
1927 /* Sync all the db files involved in the transaction. The same call
1928 ** sets the master journal pointer in each individual journal. If
1929 ** an error occurs here, do not delete the master journal file.
1931 ** If the error occurs during the first call to
1932 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
1933 ** master journal file will be orphaned. But we cannot delete it,
1934 ** in case the master journal file name was written into the journal
1935 ** file before the failure occurred.
1937 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1938 Btree
*pBt
= db
->aDb
[i
].pBt
;
1940 rc
= sqlite3BtreeCommitPhaseOne(pBt
, zMaster
);
1943 sqlite3OsCloseFree(pMaster
);
1944 assert( rc
!=SQLITE_BUSY
);
1945 if( rc
!=SQLITE_OK
){
1946 sqlite3DbFree(db
, zMaster
);
1950 /* Delete the master journal file. This commits the transaction. After
1951 ** doing this the directory is synced again before any individual
1952 ** transaction files are deleted.
1954 rc
= sqlite3OsDelete(pVfs
, zMaster
, 1);
1955 sqlite3DbFree(db
, zMaster
);
1961 /* All files and directories have already been synced, so the following
1962 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
1963 ** deleting or truncating journals. If something goes wrong while
1964 ** this is happening we don't really care. The integrity of the
1965 ** transaction is already guaranteed, but some stray 'cold' journals
1966 ** may be lying around. Returning an error code won't help matters.
1968 disable_simulated_io_errors();
1969 sqlite3BeginBenignMalloc();
1970 for(i
=0; i
<db
->nDb
; i
++){
1971 Btree
*pBt
= db
->aDb
[i
].pBt
;
1973 sqlite3BtreeCommitPhaseTwo(pBt
, 1);
1976 sqlite3EndBenignMalloc();
1977 enable_simulated_io_errors();
1979 sqlite3VtabCommit(db
);
1987 ** This routine checks that the sqlite3.nVdbeActive count variable
1988 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1989 ** currently active. An assertion fails if the two counts do not match.
1990 ** This is an internal self-check only - it is not an essential processing
1993 ** This is a no-op if NDEBUG is defined.
1996 static void checkActiveVdbeCnt(sqlite3
*db
){
2003 if( p
->magic
==VDBE_MAGIC_RUN
&& p
->pc
>=0 ){
2005 if( p
->readOnly
==0 ) nWrite
++;
2006 if( p
->bIsReader
) nRead
++;
2010 assert( cnt
==db
->nVdbeActive
);
2011 assert( nWrite
==db
->nVdbeWrite
);
2012 assert( nRead
==db
->nVdbeRead
);
2015 #define checkActiveVdbeCnt(x)
2019 ** If the Vdbe passed as the first argument opened a statement-transaction,
2020 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2021 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2022 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
2023 ** statement transaction is committed.
2025 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2026 ** Otherwise SQLITE_OK.
2028 int sqlite3VdbeCloseStatement(Vdbe
*p
, int eOp
){
2029 sqlite3
*const db
= p
->db
;
2032 /* If p->iStatement is greater than zero, then this Vdbe opened a
2033 ** statement transaction that should be closed here. The only exception
2034 ** is that an IO error may have occurred, causing an emergency rollback.
2035 ** In this case (db->nStatement==0), and there is nothing to do.
2037 if( db
->nStatement
&& p
->iStatement
){
2039 const int iSavepoint
= p
->iStatement
-1;
2041 assert( eOp
==SAVEPOINT_ROLLBACK
|| eOp
==SAVEPOINT_RELEASE
);
2042 assert( db
->nStatement
>0 );
2043 assert( p
->iStatement
==(db
->nStatement
+db
->nSavepoint
) );
2045 for(i
=0; i
<db
->nDb
; i
++){
2046 int rc2
= SQLITE_OK
;
2047 Btree
*pBt
= db
->aDb
[i
].pBt
;
2049 if( eOp
==SAVEPOINT_ROLLBACK
){
2050 rc2
= sqlite3BtreeSavepoint(pBt
, SAVEPOINT_ROLLBACK
, iSavepoint
);
2052 if( rc2
==SQLITE_OK
){
2053 rc2
= sqlite3BtreeSavepoint(pBt
, SAVEPOINT_RELEASE
, iSavepoint
);
2055 if( rc
==SQLITE_OK
){
2063 if( rc
==SQLITE_OK
){
2064 if( eOp
==SAVEPOINT_ROLLBACK
){
2065 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_ROLLBACK
, iSavepoint
);
2067 if( rc
==SQLITE_OK
){
2068 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_RELEASE
, iSavepoint
);
2072 /* If the statement transaction is being rolled back, also restore the
2073 ** database handles deferred constraint counter to the value it had when
2074 ** the statement transaction was opened. */
2075 if( eOp
==SAVEPOINT_ROLLBACK
){
2076 db
->nDeferredCons
= p
->nStmtDefCons
;
2077 db
->nDeferredImmCons
= p
->nStmtDefImmCons
;
2084 ** This function is called when a transaction opened by the database
2085 ** handle associated with the VM passed as an argument is about to be
2086 ** committed. If there are outstanding deferred foreign key constraint
2087 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2089 ** If there are outstanding FK violations and this function returns
2090 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2091 ** and write an error message to it. Then return SQLITE_ERROR.
2093 #ifndef SQLITE_OMIT_FOREIGN_KEY
2094 int sqlite3VdbeCheckFk(Vdbe
*p
, int deferred
){
2095 sqlite3
*db
= p
->db
;
2096 if( (deferred
&& (db
->nDeferredCons
+db
->nDeferredImmCons
)>0)
2097 || (!deferred
&& p
->nFkConstraint
>0)
2099 p
->rc
= SQLITE_CONSTRAINT_FOREIGNKEY
;
2100 p
->errorAction
= OE_Abort
;
2101 sqlite3SetString(&p
->zErrMsg
, db
, "foreign key constraint failed");
2102 return SQLITE_ERROR
;
2109 ** This routine is called the when a VDBE tries to halt. If the VDBE
2110 ** has made changes and is in autocommit mode, then commit those
2111 ** changes. If a rollback is needed, then do the rollback.
2113 ** This routine is the only way to move the state of a VM from
2114 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2115 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2117 ** Return an error code. If the commit could not complete because of
2118 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2119 ** means the close did not happen and needs to be repeated.
2121 int sqlite3VdbeHalt(Vdbe
*p
){
2122 int rc
; /* Used to store transient return codes */
2123 sqlite3
*db
= p
->db
;
2125 /* This function contains the logic that determines if a statement or
2126 ** transaction will be committed or rolled back as a result of the
2127 ** execution of this virtual machine.
2129 ** If any of the following errors occur:
2136 ** Then the internal cache might have been left in an inconsistent
2137 ** state. We need to rollback the statement transaction, if there is
2138 ** one, or the complete transaction if there is no statement transaction.
2141 if( p
->db
->mallocFailed
){
2142 p
->rc
= SQLITE_NOMEM
;
2144 if( p
->aOnceFlag
) memset(p
->aOnceFlag
, 0, p
->nOnceFlag
);
2146 if( p
->magic
!=VDBE_MAGIC_RUN
){
2149 checkActiveVdbeCnt(db
);
2151 /* No commit or rollback needed if the program never started or if the
2152 ** SQL statement does not read or write a database file. */
2153 if( p
->pc
>=0 && p
->bIsReader
){
2154 int mrc
; /* Primary error code from p->rc */
2155 int eStatementOp
= 0;
2156 int isSpecialError
; /* Set to true if a 'special' error */
2158 /* Lock all btrees used by the statement */
2159 sqlite3VdbeEnter(p
);
2161 /* Check for one of the special errors */
2163 assert( p
->rc
!=SQLITE_IOERR_BLOCKED
); /* This error no longer exists */
2164 isSpecialError
= mrc
==SQLITE_NOMEM
|| mrc
==SQLITE_IOERR
2165 || mrc
==SQLITE_INTERRUPT
|| mrc
==SQLITE_FULL
;
2166 if( isSpecialError
){
2167 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2168 ** no rollback is necessary. Otherwise, at least a savepoint
2169 ** transaction must be rolled back to restore the database to a
2170 ** consistent state.
2172 ** Even if the statement is read-only, it is important to perform
2173 ** a statement or transaction rollback operation. If the error
2174 ** occurred while writing to the journal, sub-journal or database
2175 ** file as part of an effort to free up cache space (see function
2176 ** pagerStress() in pager.c), the rollback is required to restore
2177 ** the pager to a consistent state.
2179 if( !p
->readOnly
|| mrc
!=SQLITE_INTERRUPT
){
2180 if( (mrc
==SQLITE_NOMEM
|| mrc
==SQLITE_FULL
) && p
->usesStmtJournal
){
2181 eStatementOp
= SAVEPOINT_ROLLBACK
;
2183 /* We are forced to roll back the active transaction. Before doing
2184 ** so, abort any other statements this handle currently has active.
2186 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2187 sqlite3CloseSavepoints(db
);
2193 /* Check for immediate foreign key violations. */
2194 if( p
->rc
==SQLITE_OK
){
2195 sqlite3VdbeCheckFk(p
, 0);
2198 /* If the auto-commit flag is set and this is the only active writer
2199 ** VM, then we do either a commit or rollback of the current transaction.
2201 ** Note: This block also runs if one of the special errors handled
2202 ** above has occurred.
2204 if( !sqlite3VtabInSync(db
)
2206 && db
->nVdbeWrite
==(p
->readOnly
==0)
2208 if( p
->rc
==SQLITE_OK
|| (p
->errorAction
==OE_Fail
&& !isSpecialError
) ){
2209 rc
= sqlite3VdbeCheckFk(p
, 1);
2210 if( rc
!=SQLITE_OK
){
2211 if( NEVER(p
->readOnly
) ){
2212 sqlite3VdbeLeave(p
);
2213 return SQLITE_ERROR
;
2215 rc
= SQLITE_CONSTRAINT_FOREIGNKEY
;
2217 /* The auto-commit flag is true, the vdbe program was successful
2218 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2219 ** key constraints to hold up the transaction. This means a commit
2221 rc
= vdbeCommit(db
, p
);
2223 if( rc
==SQLITE_BUSY
&& p
->readOnly
){
2224 sqlite3VdbeLeave(p
);
2226 }else if( rc
!=SQLITE_OK
){
2228 sqlite3RollbackAll(db
, SQLITE_OK
);
2230 db
->nDeferredCons
= 0;
2231 db
->nDeferredImmCons
= 0;
2232 db
->flags
&= ~SQLITE_DeferFKs
;
2233 sqlite3CommitInternalChanges(db
);
2236 sqlite3RollbackAll(db
, SQLITE_OK
);
2239 }else if( eStatementOp
==0 ){
2240 if( p
->rc
==SQLITE_OK
|| p
->errorAction
==OE_Fail
){
2241 eStatementOp
= SAVEPOINT_RELEASE
;
2242 }else if( p
->errorAction
==OE_Abort
){
2243 eStatementOp
= SAVEPOINT_ROLLBACK
;
2245 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2246 sqlite3CloseSavepoints(db
);
2251 /* If eStatementOp is non-zero, then a statement transaction needs to
2252 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2253 ** do so. If this operation returns an error, and the current statement
2254 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2255 ** current statement error code.
2258 rc
= sqlite3VdbeCloseStatement(p
, eStatementOp
);
2260 if( p
->rc
==SQLITE_OK
|| (p
->rc
&0xff)==SQLITE_CONSTRAINT
){
2262 sqlite3DbFree(db
, p
->zErrMsg
);
2265 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2266 sqlite3CloseSavepoints(db
);
2271 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2272 ** has been rolled back, update the database connection change-counter.
2274 if( p
->changeCntOn
){
2275 if( eStatementOp
!=SAVEPOINT_ROLLBACK
){
2276 sqlite3VdbeSetChanges(db
, p
->nChange
);
2278 sqlite3VdbeSetChanges(db
, 0);
2283 /* Release the locks */
2284 sqlite3VdbeLeave(p
);
2287 /* We have successfully halted and closed the VM. Record this fact. */
2290 if( !p
->readOnly
) db
->nVdbeWrite
--;
2291 if( p
->bIsReader
) db
->nVdbeRead
--;
2292 assert( db
->nVdbeActive
>=db
->nVdbeRead
);
2293 assert( db
->nVdbeRead
>=db
->nVdbeWrite
);
2294 assert( db
->nVdbeWrite
>=0 );
2296 p
->magic
= VDBE_MAGIC_HALT
;
2297 checkActiveVdbeCnt(db
);
2298 if( p
->db
->mallocFailed
){
2299 p
->rc
= SQLITE_NOMEM
;
2302 /* If the auto-commit flag is set to true, then any locks that were held
2303 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2304 ** to invoke any required unlock-notify callbacks.
2306 if( db
->autoCommit
){
2307 sqlite3ConnectionUnlocked(db
);
2310 assert( db
->nVdbeActive
>0 || db
->autoCommit
==0 || db
->nStatement
==0 );
2311 return (p
->rc
==SQLITE_BUSY
? SQLITE_BUSY
: SQLITE_OK
);
2316 ** Each VDBE holds the result of the most recent sqlite3_step() call
2317 ** in p->rc. This routine sets that result back to SQLITE_OK.
2319 void sqlite3VdbeResetStepResult(Vdbe
*p
){
2324 ** Copy the error code and error message belonging to the VDBE passed
2325 ** as the first argument to its database handle (so that they will be
2326 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2328 ** This function does not clear the VDBE error code or message, just
2329 ** copies them to the database handle.
2331 int sqlite3VdbeTransferError(Vdbe
*p
){
2332 sqlite3
*db
= p
->db
;
2335 u8 mallocFailed
= db
->mallocFailed
;
2336 sqlite3BeginBenignMalloc();
2337 sqlite3ValueSetStr(db
->pErr
, -1, p
->zErrMsg
, SQLITE_UTF8
, SQLITE_TRANSIENT
);
2338 sqlite3EndBenignMalloc();
2339 db
->mallocFailed
= mallocFailed
;
2342 sqlite3Error(db
, rc
, 0);
2347 #ifdef SQLITE_ENABLE_SQLLOG
2349 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2352 static void vdbeInvokeSqllog(Vdbe
*v
){
2353 if( sqlite3GlobalConfig
.xSqllog
&& v
->rc
==SQLITE_OK
&& v
->zSql
&& v
->pc
>=0 ){
2354 char *zExpanded
= sqlite3VdbeExpandSql(v
, v
->zSql
);
2355 assert( v
->db
->init
.busy
==0 );
2357 sqlite3GlobalConfig
.xSqllog(
2358 sqlite3GlobalConfig
.pSqllogArg
, v
->db
, zExpanded
, 1
2360 sqlite3DbFree(v
->db
, zExpanded
);
2365 # define vdbeInvokeSqllog(x)
2369 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2370 ** Write any error messages into *pzErrMsg. Return the result code.
2372 ** After this routine is run, the VDBE should be ready to be executed
2375 ** To look at it another way, this routine resets the state of the
2376 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2379 int sqlite3VdbeReset(Vdbe
*p
){
2383 /* If the VM did not run to completion or if it encountered an
2384 ** error, then it might not have been halted properly. So halt
2389 /* If the VDBE has be run even partially, then transfer the error code
2390 ** and error message from the VDBE into the main database structure. But
2391 ** if the VDBE has just been set to run but has not actually executed any
2392 ** instructions yet, leave the main database error information unchanged.
2395 vdbeInvokeSqllog(p
);
2396 sqlite3VdbeTransferError(p
);
2397 sqlite3DbFree(db
, p
->zErrMsg
);
2399 if( p
->runOnlyOnce
) p
->expired
= 1;
2400 }else if( p
->rc
&& p
->expired
){
2401 /* The expired flag was set on the VDBE before the first call
2402 ** to sqlite3_step(). For consistency (since sqlite3_step() was
2403 ** called), set the database error in this case as well.
2405 sqlite3Error(db
, p
->rc
, 0);
2406 sqlite3ValueSetStr(db
->pErr
, -1, p
->zErrMsg
, SQLITE_UTF8
, SQLITE_TRANSIENT
);
2407 sqlite3DbFree(db
, p
->zErrMsg
);
2411 /* Reclaim all memory used by the VDBE
2415 /* Save profiling information from this VDBE run.
2419 FILE *out
= fopen("vdbe_profile.out", "a");
2422 fprintf(out
, "---- ");
2423 for(i
=0; i
<p
->nOp
; i
++){
2424 fprintf(out
, "%02x", p
->aOp
[i
].opcode
);
2427 for(i
=0; i
<p
->nOp
; i
++){
2428 fprintf(out
, "%6d %10lld %8lld ",
2431 p
->aOp
[i
].cnt
>0 ? p
->aOp
[i
].cycles
/p
->aOp
[i
].cnt
: 0
2433 sqlite3VdbePrintOp(out
, i
, &p
->aOp
[i
]);
2439 p
->magic
= VDBE_MAGIC_INIT
;
2440 return p
->rc
& db
->errMask
;
2444 ** Clean up and delete a VDBE after execution. Return an integer which is
2445 ** the result code. Write any error message text into *pzErrMsg.
2447 int sqlite3VdbeFinalize(Vdbe
*p
){
2449 if( p
->magic
==VDBE_MAGIC_RUN
|| p
->magic
==VDBE_MAGIC_HALT
){
2450 rc
= sqlite3VdbeReset(p
);
2451 assert( (rc
& p
->db
->errMask
)==rc
);
2453 sqlite3VdbeDelete(p
);
2458 ** If parameter iOp is less than zero, then invoke the destructor for
2459 ** all auxiliary data pointers currently cached by the VM passed as
2460 ** the first argument.
2462 ** Or, if iOp is greater than or equal to zero, then the destructor is
2463 ** only invoked for those auxiliary data pointers created by the user
2464 ** function invoked by the OP_Function opcode at instruction iOp of
2465 ** VM pVdbe, and only then if:
2467 ** * the associated function parameter is the 32nd or later (counting
2468 ** from left to right), or
2470 ** * the corresponding bit in argument mask is clear (where the first
2471 ** function parameter corrsponds to bit 0 etc.).
2473 void sqlite3VdbeDeleteAuxData(Vdbe
*pVdbe
, int iOp
, int mask
){
2474 AuxData
**pp
= &pVdbe
->pAuxData
;
2476 AuxData
*pAux
= *pp
;
2478 || (pAux
->iOp
==iOp
&& (pAux
->iArg
>31 || !(mask
& ((u32
)1<<pAux
->iArg
))))
2480 if( pAux
->xDelete
){
2481 pAux
->xDelete(pAux
->pAux
);
2484 sqlite3DbFree(pVdbe
->db
, pAux
);
2492 ** Free all memory associated with the Vdbe passed as the second argument,
2493 ** except for object itself, which is preserved.
2495 ** The difference between this function and sqlite3VdbeDelete() is that
2496 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
2497 ** the database connection and frees the object itself.
2499 void sqlite3VdbeClearObject(sqlite3
*db
, Vdbe
*p
){
2500 SubProgram
*pSub
, *pNext
;
2502 assert( p
->db
==0 || p
->db
==db
);
2503 releaseMemArray(p
->aVar
, p
->nVar
);
2504 releaseMemArray(p
->aColName
, p
->nResColumn
*COLNAME_N
);
2505 for(pSub
=p
->pProgram
; pSub
; pSub
=pNext
){
2506 pNext
= pSub
->pNext
;
2507 vdbeFreeOpArray(db
, pSub
->aOp
, pSub
->nOp
);
2508 sqlite3DbFree(db
, pSub
);
2510 for(i
=p
->nzVar
-1; i
>=0; i
--) sqlite3DbFree(db
, p
->azVar
[i
]);
2511 vdbeFreeOpArray(db
, p
->aOp
, p
->nOp
);
2512 sqlite3DbFree(db
, p
->aLabel
);
2513 sqlite3DbFree(db
, p
->aColName
);
2514 sqlite3DbFree(db
, p
->zSql
);
2515 sqlite3DbFree(db
, p
->pFree
);
2516 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
2517 sqlite3DbFree(db
, p
->zExplain
);
2518 sqlite3DbFree(db
, p
->pExplain
);
2523 ** Delete an entire VDBE.
2525 void sqlite3VdbeDelete(Vdbe
*p
){
2528 if( NEVER(p
==0) ) return;
2530 assert( sqlite3_mutex_held(db
->mutex
) );
2531 sqlite3VdbeClearObject(db
, p
);
2533 p
->pPrev
->pNext
= p
->pNext
;
2535 assert( db
->pVdbe
==p
);
2536 db
->pVdbe
= p
->pNext
;
2539 p
->pNext
->pPrev
= p
->pPrev
;
2541 p
->magic
= VDBE_MAGIC_DEAD
;
2543 sqlite3DbFree(db
, p
);
2547 ** Make sure the cursor p is ready to read or write the row to which it
2548 ** was last positioned. Return an error code if an OOM fault or I/O error
2549 ** prevents us from positioning the cursor to its correct position.
2551 ** If a MoveTo operation is pending on the given cursor, then do that
2552 ** MoveTo now. If no move is pending, check to see if the row has been
2553 ** deleted out from under the cursor and if it has, mark the row as
2556 ** If the cursor is already pointing to the correct row and that row has
2557 ** not been deleted out from under the cursor, then this routine is a no-op.
2559 int sqlite3VdbeCursorMoveto(VdbeCursor
*p
){
2560 if( p
->deferredMoveto
){
2563 extern int sqlite3_search_count
;
2565 assert( p
->isTable
);
2566 rc
= sqlite3BtreeMovetoUnpacked(p
->pCursor
, 0, p
->movetoTarget
, 0, &res
);
2568 p
->lastRowid
= p
->movetoTarget
;
2569 if( res
!=0 ) return SQLITE_CORRUPT_BKPT
;
2570 p
->rowidIsValid
= 1;
2572 sqlite3_search_count
++;
2574 p
->deferredMoveto
= 0;
2575 p
->cacheStatus
= CACHE_STALE
;
2576 }else if( ALWAYS(p
->pCursor
) ){
2578 int rc
= sqlite3BtreeCursorHasMoved(p
->pCursor
, &hasMoved
);
2581 p
->cacheStatus
= CACHE_STALE
;
2589 ** The following functions:
2591 ** sqlite3VdbeSerialType()
2592 ** sqlite3VdbeSerialTypeLen()
2593 ** sqlite3VdbeSerialLen()
2594 ** sqlite3VdbeSerialPut()
2595 ** sqlite3VdbeSerialGet()
2597 ** encapsulate the code that serializes values for storage in SQLite
2598 ** data and index records. Each serialized value consists of a
2599 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2600 ** integer, stored as a varint.
2602 ** In an SQLite index record, the serial type is stored directly before
2603 ** the blob of data that it corresponds to. In a table record, all serial
2604 ** types are stored at the start of the record, and the blobs of data at
2605 ** the end. Hence these functions allow the caller to handle the
2606 ** serial-type and data blob separately.
2608 ** The following table describes the various storage classes for data:
2610 ** serial type bytes of data type
2611 ** -------------- --------------- ---------------
2613 ** 1 1 signed integer
2614 ** 2 2 signed integer
2615 ** 3 3 signed integer
2616 ** 4 4 signed integer
2617 ** 5 6 signed integer
2618 ** 6 8 signed integer
2620 ** 8 0 Integer constant 0
2621 ** 9 0 Integer constant 1
2622 ** 10,11 reserved for expansion
2623 ** N>=12 and even (N-12)/2 BLOB
2624 ** N>=13 and odd (N-13)/2 text
2626 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
2627 ** of SQLite will not understand those serial types.
2631 ** Return the serial-type for the value stored in pMem.
2633 u32
sqlite3VdbeSerialType(Mem
*pMem
, int file_format
){
2634 int flags
= pMem
->flags
;
2637 if( flags
&MEM_Null
){
2640 if( flags
&MEM_Int
){
2641 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
2642 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
2646 if( i
<(-MAX_6BYTE
) ) return 6;
2647 /* Previous test prevents: u = -(-9223372036854775808) */
2653 return ((i
&1)==i
&& file_format
>=4) ? 8+(u32
)u
: 1;
2655 if( u
<=32767 ) return 2;
2656 if( u
<=8388607 ) return 3;
2657 if( u
<=2147483647 ) return 4;
2658 if( u
<=MAX_6BYTE
) return 5;
2661 if( flags
&MEM_Real
){
2664 assert( pMem
->db
->mallocFailed
|| flags
&(MEM_Str
|MEM_Blob
) );
2666 if( flags
& MEM_Zero
){
2670 return ((n
*2) + 12 + ((flags
&MEM_Str
)!=0));
2674 ** Return the length of the data corresponding to the supplied serial-type.
2676 u32
sqlite3VdbeSerialTypeLen(u32 serial_type
){
2677 if( serial_type
>=12 ){
2678 return (serial_type
-12)/2;
2680 static const u8 aSize
[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
2681 return aSize
[serial_type
];
2686 ** If we are on an architecture with mixed-endian floating
2687 ** points (ex: ARM7) then swap the lower 4 bytes with the
2688 ** upper 4 bytes. Return the result.
2690 ** For most architectures, this is a no-op.
2692 ** (later): It is reported to me that the mixed-endian problem
2693 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
2694 ** that early versions of GCC stored the two words of a 64-bit
2695 ** float in the wrong order. And that error has been propagated
2696 ** ever since. The blame is not necessarily with GCC, though.
2697 ** GCC might have just copying the problem from a prior compiler.
2698 ** I am also told that newer versions of GCC that follow a different
2699 ** ABI get the byte order right.
2701 ** Developers using SQLite on an ARM7 should compile and run their
2702 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
2703 ** enabled, some asserts below will ensure that the byte order of
2704 ** floating point values is correct.
2706 ** (2007-08-30) Frank van Vugt has studied this problem closely
2707 ** and has send his findings to the SQLite developers. Frank
2708 ** writes that some Linux kernels offer floating point hardware
2709 ** emulation that uses only 32-bit mantissas instead of a full
2710 ** 48-bits as required by the IEEE standard. (This is the
2711 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
2712 ** byte swapping becomes very complicated. To avoid problems,
2713 ** the necessary byte swapping is carried out using a 64-bit integer
2714 ** rather than a 64-bit float. Frank assures us that the code here
2715 ** works for him. We, the developers, have no way to independently
2716 ** verify this, but Frank seems to know what he is talking about
2719 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
2720 static u64
floatSwap(u64 in
){
2733 # define swapMixedEndianFloat(X) X = floatSwap(X)
2735 # define swapMixedEndianFloat(X)
2739 ** Write the serialized data blob for the value stored in pMem into
2740 ** buf. It is assumed that the caller has allocated sufficient space.
2741 ** Return the number of bytes written.
2743 ** nBuf is the amount of space left in buf[]. nBuf must always be
2744 ** large enough to hold the entire field. Except, if the field is
2745 ** a blob with a zero-filled tail, then buf[] might be just the right
2746 ** size to hold everything except for the zero-filled tail. If buf[]
2747 ** is only big enough to hold the non-zero prefix, then only write that
2748 ** prefix into buf[]. But if buf[] is large enough to hold both the
2749 ** prefix and the tail then write the prefix and set the tail to all
2752 ** Return the number of bytes actually written into buf[]. The number
2753 ** of bytes in the zero-filled tail is included in the return value only
2754 ** if those bytes were zeroed in buf[].
2756 u32
sqlite3VdbeSerialPut(u8
*buf
, int nBuf
, Mem
*pMem
, int file_format
){
2757 u32 serial_type
= sqlite3VdbeSerialType(pMem
, file_format
);
2760 /* Integer and Real */
2761 if( serial_type
<=7 && serial_type
>0 ){
2764 if( serial_type
==7 ){
2765 assert( sizeof(v
)==sizeof(pMem
->r
) );
2766 memcpy(&v
, &pMem
->r
, sizeof(v
));
2767 swapMixedEndianFloat(v
);
2771 len
= i
= sqlite3VdbeSerialTypeLen(serial_type
);
2772 assert( len
<=(u32
)nBuf
);
2774 buf
[i
] = (u8
)(v
&0xFF);
2780 /* String or blob */
2781 if( serial_type
>=12 ){
2782 assert( pMem
->n
+ ((pMem
->flags
& MEM_Zero
)?pMem
->u
.nZero
:0)
2783 == (int)sqlite3VdbeSerialTypeLen(serial_type
) );
2784 assert( pMem
->n
<=nBuf
);
2786 memcpy(buf
, pMem
->z
, len
);
2787 if( pMem
->flags
& MEM_Zero
){
2788 len
+= pMem
->u
.nZero
;
2790 if( len
> (u32
)nBuf
){
2793 memset(&buf
[pMem
->n
], 0, len
-pMem
->n
);
2798 /* NULL or constants 0 or 1 */
2803 ** Deserialize the data blob pointed to by buf as serial type serial_type
2804 ** and store the result in pMem. Return the number of bytes read.
2806 u32
sqlite3VdbeSerialGet(
2807 const unsigned char *buf
, /* Buffer to deserialize from */
2808 u32 serial_type
, /* Serial type to deserialize */
2809 Mem
*pMem
/* Memory cell to write value into */
2811 switch( serial_type
){
2812 case 10: /* Reserved for future use */
2813 case 11: /* Reserved for future use */
2814 case 0: { /* NULL */
2815 pMem
->flags
= MEM_Null
;
2818 case 1: { /* 1-byte signed integer */
2819 pMem
->u
.i
= (signed char)buf
[0];
2820 pMem
->flags
= MEM_Int
;
2823 case 2: { /* 2-byte signed integer */
2824 pMem
->u
.i
= (((signed char)buf
[0])<<8) | buf
[1];
2825 pMem
->flags
= MEM_Int
;
2828 case 3: { /* 3-byte signed integer */
2829 pMem
->u
.i
= (((signed char)buf
[0])<<16) | (buf
[1]<<8) | buf
[2];
2830 pMem
->flags
= MEM_Int
;
2833 case 4: { /* 4-byte signed integer */
2834 pMem
->u
.i
= (buf
[0]<<24) | (buf
[1]<<16) | (buf
[2]<<8) | buf
[3];
2835 pMem
->flags
= MEM_Int
;
2838 case 5: { /* 6-byte signed integer */
2839 u64 x
= (((signed char)buf
[0])<<8) | buf
[1];
2840 u32 y
= (buf
[2]<<24) | (buf
[3]<<16) | (buf
[4]<<8) | buf
[5];
2842 pMem
->u
.i
= *(i64
*)&x
;
2843 pMem
->flags
= MEM_Int
;
2846 case 6: /* 8-byte signed integer */
2847 case 7: { /* IEEE floating point */
2850 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
2851 /* Verify that integers and floating point values use the same
2852 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
2853 ** defined that 64-bit floating point values really are mixed
2856 static const u64 t1
= ((u64
)0x3ff00000)<<32;
2857 static const double r1
= 1.0;
2859 swapMixedEndianFloat(t2
);
2860 assert( sizeof(r1
)==sizeof(t2
) && memcmp(&r1
, &t2
, sizeof(r1
))==0 );
2863 x
= (buf
[0]<<24) | (buf
[1]<<16) | (buf
[2]<<8) | buf
[3];
2864 y
= (buf
[4]<<24) | (buf
[5]<<16) | (buf
[6]<<8) | buf
[7];
2866 if( serial_type
==6 ){
2867 pMem
->u
.i
= *(i64
*)&x
;
2868 pMem
->flags
= MEM_Int
;
2870 assert( sizeof(x
)==8 && sizeof(pMem
->r
)==8 );
2871 swapMixedEndianFloat(x
);
2872 memcpy(&pMem
->r
, &x
, sizeof(x
));
2873 pMem
->flags
= sqlite3IsNaN(pMem
->r
) ? MEM_Null
: MEM_Real
;
2877 case 8: /* Integer 0 */
2878 case 9: { /* Integer 1 */
2879 pMem
->u
.i
= serial_type
-8;
2880 pMem
->flags
= MEM_Int
;
2884 u32 len
= (serial_type
-12)/2;
2885 pMem
->z
= (char *)buf
;
2888 if( serial_type
&0x01 ){
2889 pMem
->flags
= MEM_Str
| MEM_Ephem
;
2891 pMem
->flags
= MEM_Blob
| MEM_Ephem
;
2900 ** This routine is used to allocate sufficient space for an UnpackedRecord
2901 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
2902 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
2904 ** The space is either allocated using sqlite3DbMallocRaw() or from within
2905 ** the unaligned buffer passed via the second and third arguments (presumably
2906 ** stack space). If the former, then *ppFree is set to a pointer that should
2907 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
2908 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
2909 ** before returning.
2911 ** If an OOM error occurs, NULL is returned.
2913 UnpackedRecord
*sqlite3VdbeAllocUnpackedRecord(
2914 KeyInfo
*pKeyInfo
, /* Description of the record */
2915 char *pSpace
, /* Unaligned space available */
2916 int szSpace
, /* Size of pSpace[] in bytes */
2917 char **ppFree
/* OUT: Caller should free this pointer */
2919 UnpackedRecord
*p
; /* Unpacked record to return */
2920 int nOff
; /* Increment pSpace by nOff to align it */
2921 int nByte
; /* Number of bytes required for *p */
2923 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
2924 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
2925 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
2927 nOff
= (8 - (SQLITE_PTR_TO_INT(pSpace
) & 7)) & 7;
2928 nByte
= ROUND8(sizeof(UnpackedRecord
)) + sizeof(Mem
)*(pKeyInfo
->nField
+1);
2929 if( nByte
>szSpace
+nOff
){
2930 p
= (UnpackedRecord
*)sqlite3DbMallocRaw(pKeyInfo
->db
, nByte
);
2931 *ppFree
= (char *)p
;
2934 p
= (UnpackedRecord
*)&pSpace
[nOff
];
2938 p
->aMem
= (Mem
*)&((char*)p
)[ROUND8(sizeof(UnpackedRecord
))];
2939 assert( pKeyInfo
->aSortOrder
!=0 );
2940 p
->pKeyInfo
= pKeyInfo
;
2941 p
->nField
= pKeyInfo
->nField
+ 1;
2946 ** Given the nKey-byte encoding of a record in pKey[], populate the
2947 ** UnpackedRecord structure indicated by the fourth argument with the
2948 ** contents of the decoded record.
2950 void sqlite3VdbeRecordUnpack(
2951 KeyInfo
*pKeyInfo
, /* Information about the record format */
2952 int nKey
, /* Size of the binary record */
2953 const void *pKey
, /* The binary record */
2954 UnpackedRecord
*p
/* Populate this structure before returning. */
2956 const unsigned char *aKey
= (const unsigned char *)pKey
;
2958 u32 idx
; /* Offset in aKey[] to read from */
2959 u16 u
; /* Unsigned loop counter */
2961 Mem
*pMem
= p
->aMem
;
2964 assert( EIGHT_BYTE_ALIGNMENT(pMem
) );
2965 idx
= getVarint32(aKey
, szHdr
);
2968 while( idx
<szHdr
&& u
<p
->nField
&& d
<=nKey
){
2971 idx
+= getVarint32(&aKey
[idx
], serial_type
);
2972 pMem
->enc
= pKeyInfo
->enc
;
2973 pMem
->db
= pKeyInfo
->db
;
2974 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
2976 d
+= sqlite3VdbeSerialGet(&aKey
[d
], serial_type
, pMem
);
2980 assert( u
<=pKeyInfo
->nField
+ 1 );
2985 ** This function compares the two table rows or index records
2986 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
2987 ** or positive integer if key1 is less than, equal to or
2988 ** greater than key2. The {nKey1, pKey1} key must be a blob
2989 ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
2990 ** key must be a parsed key such as obtained from
2991 ** sqlite3VdbeParseRecord.
2993 ** Key1 and Key2 do not have to contain the same number of fields.
2994 ** The key with fewer fields is usually compares less than the
2995 ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
2996 ** and the common prefixes are equal, then key1 is less than key2.
2997 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
2998 ** equal, then the keys are considered to be equal and
2999 ** the parts beyond the common prefix are ignored.
3001 int sqlite3VdbeRecordCompare(
3002 int nKey1
, const void *pKey1
, /* Left key */
3003 UnpackedRecord
*pPKey2
/* Right key */
3005 u32 d1
; /* Offset into aKey[] of next data element */
3006 u32 idx1
; /* Offset into aKey[] of next header element */
3007 u32 szHdr1
; /* Number of bytes in header */
3010 const unsigned char *aKey1
= (const unsigned char *)pKey1
;
3014 pKeyInfo
= pPKey2
->pKeyInfo
;
3015 mem1
.enc
= pKeyInfo
->enc
;
3016 mem1
.db
= pKeyInfo
->db
;
3017 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
3018 VVA_ONLY( mem1
.zMalloc
= 0; ) /* Only needed by assert() statements */
3020 /* Compilers may complain that mem1.u.i is potentially uninitialized.
3021 ** We could initialize it, as shown here, to silence those complaints.
3022 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3023 ** the unnecessary initialization has a measurable negative performance
3024 ** impact, since this routine is a very high runner. And so, we choose
3025 ** to ignore the compiler warnings and leave this variable uninitialized.
3027 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
3029 idx1
= getVarint32(aKey1
, szHdr1
);
3031 assert( pKeyInfo
->nField
+1>=pPKey2
->nField
);
3032 assert( pKeyInfo
->aSortOrder
!=0 );
3033 while( idx1
<szHdr1
&& i
<pPKey2
->nField
){
3036 /* Read the serial types for the next element in each key. */
3037 idx1
+= getVarint32( aKey1
+idx1
, serial_type1
);
3039 /* Verify that there is enough key space remaining to avoid
3040 ** a buffer overread. The "d1+serial_type1+2" subexpression will
3041 ** always be greater than or equal to the amount of required key space.
3042 ** Use that approximation to avoid the more expensive call to
3043 ** sqlite3VdbeSerialTypeLen() in the common case.
3045 if( d1
+serial_type1
+2>(u32
)nKey1
3046 && d1
+sqlite3VdbeSerialTypeLen(serial_type1
)>(u32
)nKey1
3051 /* Extract the values to be compared.
3053 d1
+= sqlite3VdbeSerialGet(&aKey1
[d1
], serial_type1
, &mem1
);
3055 /* Do the comparison
3057 rc
= sqlite3MemCompare(&mem1
, &pPKey2
->aMem
[i
], pKeyInfo
->aColl
[i
]);
3059 assert( mem1
.zMalloc
==0 ); /* See comment below */
3061 /* Invert the result if we are using DESC sort order. */
3062 if( pKeyInfo
->aSortOrder
[i
] ){
3066 /* If the PREFIX_SEARCH flag is set and all fields except the final
3067 ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
3068 ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
3069 ** This is used by the OP_IsUnique opcode.
3071 if( (pPKey2
->flags
& UNPACKED_PREFIX_SEARCH
) && i
==(pPKey2
->nField
-1) ){
3072 assert( idx1
==szHdr1
&& rc
);
3073 assert( mem1
.flags
& MEM_Int
);
3074 pPKey2
->flags
&= ~UNPACKED_PREFIX_SEARCH
;
3075 pPKey2
->rowid
= mem1
.u
.i
;
3083 /* No memory allocation is ever used on mem1. Prove this using
3084 ** the following assert(). If the assert() fails, it indicates a
3085 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3087 assert( mem1
.zMalloc
==0 );
3089 /* rc==0 here means that one of the keys ran out of fields and
3090 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
3091 ** flag is set, then break the tie by treating key2 as larger.
3092 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
3093 ** are considered to be equal. Otherwise, the longer key is the
3094 ** larger. As it happens, the pPKey2 will always be the longer
3095 ** if there is a difference.
3098 if( pPKey2
->flags
& UNPACKED_INCRKEY
){
3100 }else if( pPKey2
->flags
& UNPACKED_PREFIX_MATCH
){
3102 }else if( idx1
<szHdr1
){
3110 ** pCur points at an index entry created using the OP_MakeRecord opcode.
3111 ** Read the rowid (the last field in the record) and store it in *rowid.
3112 ** Return SQLITE_OK if everything works, or an error code otherwise.
3114 ** pCur might be pointing to text obtained from a corrupt database file.
3115 ** So the content cannot be trusted. Do appropriate checks on the content.
3117 int sqlite3VdbeIdxRowid(sqlite3
*db
, BtCursor
*pCur
, i64
*rowid
){
3120 u32 szHdr
; /* Size of the header */
3121 u32 typeRowid
; /* Serial type of the rowid */
3122 u32 lenRowid
; /* Size of the rowid */
3125 UNUSED_PARAMETER(db
);
3127 /* Get the size of the index entry. Only indices entries of less
3128 ** than 2GiB are support - anything large must be database corruption.
3129 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
3130 ** this code can safely assume that nCellKey is 32-bits
3132 assert( sqlite3BtreeCursorIsValid(pCur
) );
3133 VVA_ONLY(rc
=) sqlite3BtreeKeySize(pCur
, &nCellKey
);
3134 assert( rc
==SQLITE_OK
); /* pCur is always valid so KeySize cannot fail */
3135 assert( (nCellKey
& SQLITE_MAX_U32
)==(u64
)nCellKey
);
3137 /* Read in the complete content of the index entry */
3138 memset(&m
, 0, sizeof(m
));
3139 rc
= sqlite3VdbeMemFromBtree(pCur
, 0, (int)nCellKey
, 1, &m
);
3144 /* The index entry must begin with a header size */
3145 (void)getVarint32((u8
*)m
.z
, szHdr
);
3146 testcase( szHdr
==3 );
3147 testcase( szHdr
==m
.n
);
3148 if( unlikely(szHdr
<3 || (int)szHdr
>m
.n
) ){
3149 goto idx_rowid_corruption
;
3152 /* The last field of the index should be an integer - the ROWID.
3153 ** Verify that the last entry really is an integer. */
3154 (void)getVarint32((u8
*)&m
.z
[szHdr
-1], typeRowid
);
3155 testcase( typeRowid
==1 );
3156 testcase( typeRowid
==2 );
3157 testcase( typeRowid
==3 );
3158 testcase( typeRowid
==4 );
3159 testcase( typeRowid
==5 );
3160 testcase( typeRowid
==6 );
3161 testcase( typeRowid
==8 );
3162 testcase( typeRowid
==9 );
3163 if( unlikely(typeRowid
<1 || typeRowid
>9 || typeRowid
==7) ){
3164 goto idx_rowid_corruption
;
3166 lenRowid
= sqlite3VdbeSerialTypeLen(typeRowid
);
3167 testcase( (u32
)m
.n
==szHdr
+lenRowid
);
3168 if( unlikely((u32
)m
.n
<szHdr
+lenRowid
) ){
3169 goto idx_rowid_corruption
;
3172 /* Fetch the integer off the end of the index record */
3173 sqlite3VdbeSerialGet((u8
*)&m
.z
[m
.n
-lenRowid
], typeRowid
, &v
);
3175 sqlite3VdbeMemRelease(&m
);
3178 /* Jump here if database corruption is detected after m has been
3179 ** allocated. Free the m object and return SQLITE_CORRUPT. */
3180 idx_rowid_corruption
:
3181 testcase( m
.zMalloc
!=0 );
3182 sqlite3VdbeMemRelease(&m
);
3183 return SQLITE_CORRUPT_BKPT
;
3187 ** Compare the key of the index entry that cursor pC is pointing to against
3188 ** the key string in pUnpacked. Write into *pRes a number
3189 ** that is negative, zero, or positive if pC is less than, equal to,
3190 ** or greater than pUnpacked. Return SQLITE_OK on success.
3192 ** pUnpacked is either created without a rowid or is truncated so that it
3193 ** omits the rowid at the end. The rowid at the end of the index entry
3194 ** is ignored as well. Hence, this routine only compares the prefixes
3195 ** of the keys prior to the final rowid, not the entire key.
3197 int sqlite3VdbeIdxKeyCompare(
3198 VdbeCursor
*pC
, /* The cursor to compare against */
3199 UnpackedRecord
*pUnpacked
, /* Unpacked version of key to compare against */
3200 int *res
/* Write the comparison result here */
3204 BtCursor
*pCur
= pC
->pCursor
;
3207 assert( sqlite3BtreeCursorIsValid(pCur
) );
3208 VVA_ONLY(rc
=) sqlite3BtreeKeySize(pCur
, &nCellKey
);
3209 assert( rc
==SQLITE_OK
); /* pCur is always valid so KeySize cannot fail */
3210 /* nCellKey will always be between 0 and 0xffffffff because of the say
3211 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
3212 if( nCellKey
<=0 || nCellKey
>0x7fffffff ){
3214 return SQLITE_CORRUPT_BKPT
;
3216 memset(&m
, 0, sizeof(m
));
3217 rc
= sqlite3VdbeMemFromBtree(pC
->pCursor
, 0, (int)nCellKey
, 1, &m
);
3221 assert( pUnpacked
->flags
& UNPACKED_PREFIX_MATCH
);
3222 *res
= sqlite3VdbeRecordCompare(m
.n
, m
.z
, pUnpacked
);
3223 sqlite3VdbeMemRelease(&m
);
3228 ** This routine sets the value to be returned by subsequent calls to
3229 ** sqlite3_changes() on the database handle 'db'.
3231 void sqlite3VdbeSetChanges(sqlite3
*db
, int nChange
){
3232 assert( sqlite3_mutex_held(db
->mutex
) );
3233 db
->nChange
= nChange
;
3234 db
->nTotalChange
+= nChange
;
3238 ** Set a flag in the vdbe to update the change counter when it is finalised
3241 void sqlite3VdbeCountChanges(Vdbe
*v
){
3246 ** Mark every prepared statement associated with a database connection
3249 ** An expired statement means that recompilation of the statement is
3250 ** recommend. Statements expire when things happen that make their
3251 ** programs obsolete. Removing user-defined functions or collating
3252 ** sequences, or changing an authorization function are the types of
3253 ** things that make prepared statements obsolete.
3255 void sqlite3ExpirePreparedStatements(sqlite3
*db
){
3257 for(p
= db
->pVdbe
; p
; p
=p
->pNext
){
3263 ** Return the database associated with the Vdbe.
3265 sqlite3
*sqlite3VdbeDb(Vdbe
*v
){
3270 ** Return a pointer to an sqlite3_value structure containing the value bound
3271 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
3272 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
3273 ** constants) to the value before returning it.
3275 ** The returned value must be freed by the caller using sqlite3ValueFree().
3277 sqlite3_value
*sqlite3VdbeGetBoundValue(Vdbe
*v
, int iVar
, u8 aff
){
3280 Mem
*pMem
= &v
->aVar
[iVar
-1];
3281 if( 0==(pMem
->flags
& MEM_Null
) ){
3282 sqlite3_value
*pRet
= sqlite3ValueNew(v
->db
);
3284 sqlite3VdbeMemCopy((Mem
*)pRet
, pMem
);
3285 sqlite3ValueApplyAffinity(pRet
, aff
, SQLITE_UTF8
);
3286 sqlite3VdbeMemStoreType((Mem
*)pRet
);
3295 ** Configure SQL variable iVar so that binding a new value to it signals
3296 ** to sqlite3_reoptimize() that re-preparing the statement may result
3297 ** in a better query plan.
3299 void sqlite3VdbeSetVarmask(Vdbe
*v
, int iVar
){
3302 v
->expmask
= 0xffffffff;
3304 v
->expmask
|= ((u32
)1 << (iVar
-1));
3308 #ifndef SQLITE_OMIT_VIRTUALTABLE
3310 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
3311 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
3312 ** in memory obtained from sqlite3DbMalloc).
3314 void sqlite3VtabImportErrmsg(Vdbe
*p
, sqlite3_vtab
*pVtab
){
3315 sqlite3
*db
= p
->db
;
3316 sqlite3DbFree(db
, p
->zErrMsg
);
3317 p
->zErrMsg
= sqlite3DbStrDup(db
, pVtab
->zErrMsg
);
3318 sqlite3_free(pVtab
->zErrMsg
);
3321 #endif /* SQLITE_OMIT_VIRTUALTABLE */