4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code used for creating, destroying, and populating
13 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
14 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
15 ** But that file was getting too big so this subroutines were split out.
17 #include "sqliteInt.h"
24 ** When debugging the code generator in a symbolic debugger, one can
25 ** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
26 ** as they are added to the instruction stream.
29 int sqlite3_vdbe_addop_trace
= 0;
34 ** Create a new virtual database engine.
36 Vdbe
*sqlite3VdbeCreate(sqlite3
*db
){
38 p
= sqliteMalloc( sizeof(Vdbe
) );
47 p
->magic
= VDBE_MAGIC_INIT
;
52 ** Turn tracing on or off
54 void sqlite3VdbeTrace(Vdbe
*p
, FILE *trace
){
59 ** Resize the Vdbe.aOp array so that it contains at least N
60 ** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
61 ** the Vdbe.aOp array will be sized to contain exactly N
64 static void resizeOpArray(Vdbe
*p
, int N
){
65 if( p
->magic
==VDBE_MAGIC_RUN
){
68 p
->aOp
= sqliteRealloc(p
->aOp
, N
*sizeof(Op
));
69 }else if( p
->nOpAlloc
<N
){
70 int oldSize
= p
->nOpAlloc
;
72 p
->aOp
= sqliteRealloc(p
->aOp
, p
->nOpAlloc
*sizeof(Op
));
74 memset(&p
->aOp
[oldSize
], 0, (p
->nOpAlloc
-oldSize
)*sizeof(Op
));
80 ** Add a new instruction to the list of instructions current in the
81 ** VDBE. Return the address of the new instruction.
85 ** p Pointer to the VDBE
87 ** op The opcode for this instruction
89 ** p1, p2 First two of the three possible operands.
91 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
92 ** the sqlite3VdbeChangeP3() function to change the value of the P3
95 int sqlite3VdbeAddOp(Vdbe
*p
, int op
, int p1
, int p2
){
101 assert( p
->magic
==VDBE_MAGIC_INIT
);
102 resizeOpArray(p
, i
+1);
111 pOp
->p3type
= P3_NOTUSED
;
113 if( sqlite3_vdbe_addop_trace
) sqlite3VdbePrintOp(0, i
, &p
->aOp
[i
]);
119 ** Add an opcode that includes the p3 value.
121 int sqlite3VdbeOp3(Vdbe
*p
, int op
, int p1
, int p2
, const char *zP3
,int p3type
){
122 int addr
= sqlite3VdbeAddOp(p
, op
, p1
, p2
);
123 sqlite3VdbeChangeP3(p
, addr
, zP3
, p3type
);
128 ** Create a new symbolic label for an instruction that has yet to be
129 ** coded. The symbolic label is really just a negative number. The
130 ** label can be used as the P2 value of an operation. Later, when
131 ** the label is resolved to a specific address, the VDBE will scan
132 ** through its operation list and change all values of P2 which match
133 ** the label into the resolved address.
135 ** The VDBE knows that a P2 value is a label because labels are
136 ** always negative and P2 values are suppose to be non-negative.
137 ** Hence, a negative P2 value is a label that has yet to be resolved.
139 ** Zero is returned if a malloc() fails.
141 int sqlite3VdbeMakeLabel(Vdbe
*p
){
144 assert( p
->magic
==VDBE_MAGIC_INIT
);
145 if( i
>=p
->nLabelAlloc
){
146 p
->nLabelAlloc
= p
->nLabelAlloc
*2 + 10;
147 p
->aLabel
= sqliteRealloc( p
->aLabel
, p
->nLabelAlloc
*sizeof(p
->aLabel
[0]));
156 ** Resolve label "x" to be the address of the next instruction to
157 ** be inserted. The parameter "x" must have been obtained from
158 ** a prior call to sqlite3VdbeMakeLabel().
160 void sqlite3VdbeResolveLabel(Vdbe
*p
, int x
){
162 assert( p
->magic
==VDBE_MAGIC_INIT
);
163 assert( j
>=0 && j
<p
->nLabel
);
165 p
->aLabel
[j
] = p
->nOp
;
170 ** Return non-zero if opcode 'op' is guarenteed not to push more values
171 ** onto the VDBE stack than it pops off.
173 static int opcodeNoPush(u8 op
){
174 /* The 10 NOPUSH_MASK_n constants are defined in the automatically
175 ** generated header file opcodes.h. Each is a 16-bit bitmask, one
176 ** bit corresponding to each opcode implemented by the virtual
177 ** machine in vdbe.c. The bit is true if the word "no-push" appears
178 ** in a comment on the same line as the "case OP_XXX:" in
179 ** sqlite3VdbeExec() in vdbe.c.
181 ** If the bit is true, then the corresponding opcode is guarenteed not
182 ** to grow the stack when it is executed. Otherwise, it may grow the
183 ** stack by at most one entry.
185 ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
186 ** one bit for opcodes 16 to 31, and so on.
188 ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
189 ** because the file is generated by an awk program. Awk manipulates
190 ** all numbers as floating-point and we don't want to risk a rounding
191 ** error if someone builds with an awk that uses (for example) 32-bit
194 static const u32 masks
[5] = {
195 NOPUSH_MASK_0
+ (NOPUSH_MASK_1
<<16),
196 NOPUSH_MASK_2
+ (NOPUSH_MASK_3
<<16),
197 NOPUSH_MASK_4
+ (NOPUSH_MASK_5
<<16),
198 NOPUSH_MASK_6
+ (NOPUSH_MASK_7
<<16),
199 NOPUSH_MASK_8
+ (NOPUSH_MASK_9
<<16)
201 return (masks
[op
>>5] & (1<<(op
&0x1F)));
205 int sqlite3VdbeOpcodeNoPush(u8 op
){
206 return opcodeNoPush(op
);
211 ** Loop through the program looking for P2 values that are negative.
212 ** Each such value is a label. Resolve the label by setting the P2
213 ** value to its correct non-zero value.
215 ** This routine is called once after all opcodes have been inserted.
217 ** Variable *pMaxFuncArgs is set to the maximum value of any P1 argument
218 ** to an OP_Function or P2 to an OP_AggFunc opcode. This is used by
219 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
221 ** The integer *pMaxStack is set to the maximum number of vdbe stack
222 ** entries that static analysis reveals this program might need.
224 ** This routine also does the following optimization: It scans for
225 ** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
226 ** IdxInsert instructions where P2!=0. If no such instruction is
227 ** found, then every Statement instruction is changed to a Noop. In
228 ** this way, we avoid creating the statement journal file unnecessarily.
230 static void resolveP2Values(Vdbe
*p
, int *pMaxFuncArgs
, int *pMaxStack
){
233 int nMaxStack
= p
->nOp
;
235 int *aLabel
= p
->aLabel
;
236 int doesStatementRollback
= 0;
237 int hasStatementBegin
= 0;
238 for(pOp
=p
->aOp
, i
=p
->nOp
-1; i
>=0; i
--, pOp
++){
239 u8 opcode
= pOp
->opcode
;
241 /* Todo: Maybe OP_AggFunc should change to use P1 in the same
242 * way as OP_Function.
244 if( opcode
==OP_Function
){
245 if( pOp
->p1
>nMaxArgs
) nMaxArgs
= pOp
->p1
;
246 }else if( opcode
==OP_AggFunc
){
247 if( pOp
->p2
>nMaxArgs
) nMaxArgs
= pOp
->p2
;
248 }else if( opcode
==OP_Halt
){
249 if( pOp
->p1
==SQLITE_CONSTRAINT
&& pOp
->p2
==OE_Abort
){
250 doesStatementRollback
= 1;
252 }else if( opcode
==OP_IdxInsert
){
254 doesStatementRollback
= 1;
256 }else if( opcode
==OP_Statement
){
257 hasStatementBegin
= 1;
260 if( opcodeNoPush(opcode
) ){
264 if( pOp
->p2
>=0 ) continue;
265 assert( -1-pOp
->p2
<p
->nLabel
);
266 pOp
->p2
= aLabel
[-1-pOp
->p2
];
268 sqliteFree(p
->aLabel
);
271 *pMaxFuncArgs
= nMaxArgs
;
272 *pMaxStack
= nMaxStack
;
274 /* If we never rollback a statement transaction, then statement
275 ** transactions are not needed. So change every OP_Statement
276 ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
277 ** which can be expensive on some platforms.
279 if( hasStatementBegin
&& !doesStatementRollback
){
280 for(pOp
=p
->aOp
, i
=p
->nOp
-1; i
>=0; i
--, pOp
++){
281 if( pOp
->opcode
==OP_Statement
){
282 pOp
->opcode
= OP_Noop
;
289 ** Return the address of the next instruction to be inserted.
291 int sqlite3VdbeCurrentAddr(Vdbe
*p
){
292 assert( p
->magic
==VDBE_MAGIC_INIT
);
297 ** Add a whole list of operations to the operation stack. Return the
298 ** address of the first operation added.
300 int sqlite3VdbeAddOpList(Vdbe
*p
, int nOp
, VdbeOpList
const *aOp
){
302 assert( p
->magic
==VDBE_MAGIC_INIT
);
303 resizeOpArray(p
, p
->nOp
+ nOp
);
310 VdbeOpList
const *pIn
= aOp
;
311 for(i
=0; i
<nOp
; i
++, pIn
++){
313 VdbeOp
*pOut
= &p
->aOp
[i
+addr
];
314 pOut
->opcode
= pIn
->opcode
;
316 pOut
->p2
= p2
<0 ? addr
+ ADDR(p2
) : p2
;
318 pOut
->p3type
= pIn
->p3
? P3_STATIC
: P3_NOTUSED
;
320 if( sqlite3_vdbe_addop_trace
){
321 sqlite3VdbePrintOp(0, i
+addr
, &p
->aOp
[i
+addr
]);
331 ** Change the value of the P1 operand for a specific instruction.
332 ** This routine is useful when a large program is loaded from a
333 ** static array using sqlite3VdbeAddOpList but we want to make a
334 ** few minor changes to the program.
336 void sqlite3VdbeChangeP1(Vdbe
*p
, int addr
, int val
){
337 assert( p
->magic
==VDBE_MAGIC_INIT
);
338 if( p
&& addr
>=0 && p
->nOp
>addr
&& p
->aOp
){
339 p
->aOp
[addr
].p1
= val
;
344 ** Change the value of the P2 operand for a specific instruction.
345 ** This routine is useful for setting a jump destination.
347 void sqlite3VdbeChangeP2(Vdbe
*p
, int addr
, int val
){
349 assert( p
->magic
==VDBE_MAGIC_INIT
);
350 if( p
&& addr
>=0 && p
->nOp
>addr
&& p
->aOp
){
351 p
->aOp
[addr
].p2
= val
;
356 ** Change the value of the P3 operand for a specific instruction.
357 ** This routine is useful when a large program is loaded from a
358 ** static array using sqlite3VdbeAddOpList but we want to make a
359 ** few minor changes to the program.
361 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
362 ** the string is made into memory obtained from sqliteMalloc().
363 ** A value of n==0 means copy bytes of zP3 up to and including the
364 ** first null byte. If n>0 then copy n+1 bytes of zP3.
366 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
367 ** A copy is made of the KeyInfo structure into memory obtained from
368 ** sqliteMalloc, to be freed when the Vdbe is finalized.
369 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
370 ** stored in memory that the caller has obtained from sqliteMalloc. The
371 ** caller should not free the allocation, it will be freed when the Vdbe is
374 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
375 ** to a string or structure that is guaranteed to exist for the lifetime of
376 ** the Vdbe. In these cases we can just copy the pointer.
378 ** If addr<0 then change P3 on the most recently inserted instruction.
380 void sqlite3VdbeChangeP3(Vdbe
*p
, int addr
, const char *zP3
, int n
){
382 assert( p
->magic
==VDBE_MAGIC_INIT
);
383 if( p
==0 || p
->aOp
==0 ){
384 if( n
==P3_DYNAMIC
|| n
==P3_KEYINFO_HANDOFF
){
385 sqliteFree((void*)zP3
);
388 sqlite3ValueFree((sqlite3_value
*)zP3
);
392 if( addr
<0 || addr
>=p
->nOp
){
397 if( pOp
->p3
&& pOp
->p3type
==P3_DYNAMIC
){
403 pOp
->p3type
= P3_NOTUSED
;
404 }else if( n
==P3_KEYINFO
){
407 nField
= ((KeyInfo
*)zP3
)->nField
;
408 nByte
= sizeof(*pKeyInfo
) + (nField
-1)*sizeof(pKeyInfo
->aColl
[0]);
409 pKeyInfo
= sqliteMallocRaw( nByte
);
410 pOp
->p3
= (char*)pKeyInfo
;
412 memcpy(pKeyInfo
, zP3
, nByte
);
413 pOp
->p3type
= P3_KEYINFO
;
415 pOp
->p3type
= P3_NOTUSED
;
417 }else if( n
==P3_KEYINFO_HANDOFF
){
418 pOp
->p3
= (char*)zP3
;
419 pOp
->p3type
= P3_KEYINFO
;
421 pOp
->p3
= (char*)zP3
;
424 if( n
==0 ) n
= strlen(zP3
);
425 pOp
->p3
= sqliteStrNDup(zP3
, n
);
426 pOp
->p3type
= P3_DYNAMIC
;
432 ** Replace the P3 field of the most recently coded instruction with
435 void sqlite3VdbeComment(Vdbe
*p
, const char *zFormat
, ...){
438 assert( p
->aOp
==0 || p
->aOp
[p
->nOp
-1].p3
==0 );
439 va_start(ap
, zFormat
);
440 sqlite3VdbeChangeP3(p
, -1, sqlite3VMPrintf(zFormat
, ap
), P3_DYNAMIC
);
446 ** If the P3 operand to the specified instruction appears
447 ** to be a quoted string token, then this procedure removes
450 ** The quoting operator can be either a grave ascent (ASCII 0x27)
451 ** or a double quote character (ASCII 0x22). Two quotes in a row
452 ** resolve to be a single actual quote character within the string.
454 void sqlite3VdbeDequoteP3(Vdbe
*p
, int addr
){
456 assert( p
->magic
==VDBE_MAGIC_INIT
);
457 if( p
->aOp
==0 ) return;
458 if( addr
<0 || addr
>=p
->nOp
){
463 if( pOp
->p3
==0 || pOp
->p3
[0]==0 ) return;
464 if( pOp
->p3type
==P3_STATIC
){
465 pOp
->p3
= sqliteStrDup(pOp
->p3
);
466 pOp
->p3type
= P3_DYNAMIC
;
468 assert( pOp
->p3type
==P3_DYNAMIC
);
469 sqlite3Dequote(pOp
->p3
);
473 ** Search the current program starting at instruction addr for the given
474 ** opcode and P2 value. Return the address plus 1 if found and 0 if not
477 int sqlite3VdbeFindOp(Vdbe
*p
, int addr
, int op
, int p2
){
479 assert( p
->magic
==VDBE_MAGIC_INIT
);
480 for(i
=addr
; i
<p
->nOp
; i
++){
481 if( p
->aOp
[i
].opcode
==op
&& p
->aOp
[i
].p2
==p2
) return i
+1;
487 ** Return the opcode for a given address.
489 VdbeOp
*sqlite3VdbeGetOp(Vdbe
*p
, int addr
){
490 assert( p
->magic
==VDBE_MAGIC_INIT
);
491 assert( addr
>=0 && addr
<p
->nOp
);
492 return &p
->aOp
[addr
];
495 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
496 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
498 ** Compute a string that describes the P3 parameter for an opcode.
499 ** Use zTemp for any required temporary buffer space.
501 static char *displayP3(Op
*pOp
, char *zTemp
, int nTemp
){
504 switch( pOp
->p3type
){
507 KeyInfo
*pKeyInfo
= (KeyInfo
*)pOp
->p3
;
508 sprintf(zTemp
, "keyinfo(%d", pKeyInfo
->nField
);
510 for(j
=0; j
<pKeyInfo
->nField
; j
++){
511 CollSeq
*pColl
= pKeyInfo
->aColl
[j
];
513 int n
= strlen(pColl
->zName
);
515 strcpy(&zTemp
[i
],",...");
519 if( pKeyInfo
->aSortOrder
&& pKeyInfo
->aSortOrder
[j
] ){
522 strcpy(&zTemp
[i
], pColl
->zName
);
524 }else if( i
+4<nTemp
-6 ){
525 strcpy(&zTemp
[i
],",nil");
536 CollSeq
*pColl
= (CollSeq
*)pOp
->p3
;
537 sprintf(zTemp
, "collseq(%.20s)", pColl
->zName
);
542 FuncDef
*pDef
= (FuncDef
*)pOp
->p3
;
544 sprintf(zTemp
, "%.*s", nTemp
, pDef
->zName
);
545 sprintf(zNum
,"(%d)", pDef
->nArg
);
546 if( strlen(zTemp
)+strlen(zNum
)+1<=nTemp
){
554 if( zP3
==0 || pOp
->opcode
==OP_Noop
){
564 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
566 ** Print a single opcode. This routine is used for debugging only.
568 void sqlite3VdbePrintOp(FILE *pOut
, int pc
, Op
*pOp
){
571 static const char *zFormat1
= "%4d %-13s %4d %4d %s\n";
572 if( pOut
==0 ) pOut
= stdout
;
573 zP3
= displayP3(pOp
, zPtr
, sizeof(zPtr
));
574 fprintf(pOut
, zFormat1
,
575 pc
, sqlite3OpcodeNames
[pOp
->opcode
], pOp
->p1
, pOp
->p2
, zP3
);
581 ** Release an array of N Mem elements
583 static void releaseMemArray(Mem
*p
, int N
){
586 sqlite3VdbeMemRelease(p
++);
591 #ifndef SQLITE_OMIT_EXPLAIN
593 ** Give a listing of the program in the virtual machine.
595 ** The interface is the same as sqlite3VdbeExec(). But instead of
596 ** running the code, it invokes the callback once for each instruction.
597 ** This feature is used to implement "EXPLAIN".
600 Vdbe
*p
/* The VDBE */
606 assert( p
->explain
);
607 if( p
->magic
!=VDBE_MAGIC_RUN
) return SQLITE_MISUSE
;
608 assert( db
->magic
==SQLITE_MAGIC_BUSY
);
609 assert( p
->rc
==SQLITE_OK
|| p
->rc
==SQLITE_BUSY
);
611 /* Even though this opcode does not put dynamic strings onto the
612 ** the stack, they may become dynamic if the user calls
613 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
615 if( p
->pTos
==&p
->aStack
[4] ){
616 releaseMemArray(p
->aStack
, 5);
625 }else if( db
->flags
& SQLITE_Interrupt
){
626 db
->flags
&= ~SQLITE_Interrupt
;
627 p
->rc
= SQLITE_INTERRUPT
;
629 sqlite3SetString(&p
->zErrMsg
, sqlite3ErrStr(p
->rc
), (char*)0);
631 Op
*pOp
= &p
->aOp
[i
];
632 Mem
*pMem
= p
->aStack
;
633 pMem
->flags
= MEM_Int
;
634 pMem
->type
= SQLITE_INTEGER
;
635 pMem
->i
= i
; /* Program counter */
638 pMem
->flags
= MEM_Static
|MEM_Str
|MEM_Term
;
639 pMem
->z
= sqlite3OpcodeNames
[pOp
->opcode
]; /* Opcode */
640 pMem
->n
= strlen(pMem
->z
);
641 pMem
->type
= SQLITE_TEXT
;
642 pMem
->enc
= SQLITE_UTF8
;
645 pMem
->flags
= MEM_Int
;
646 pMem
->i
= pOp
->p1
; /* P1 */
647 pMem
->type
= SQLITE_INTEGER
;
650 pMem
->flags
= MEM_Int
;
651 pMem
->i
= pOp
->p2
; /* P2 */
652 pMem
->type
= SQLITE_INTEGER
;
655 pMem
->flags
= MEM_Short
|MEM_Str
|MEM_Term
; /* P3 */
656 pMem
->z
= displayP3(pOp
, pMem
->zShort
, sizeof(pMem
->zShort
));
657 pMem
->type
= SQLITE_TEXT
;
658 pMem
->enc
= SQLITE_UTF8
;
668 #endif /* SQLITE_OMIT_EXPLAIN */
671 ** Print the SQL that was used to generate a VDBE program.
673 void sqlite3VdbePrintSql(Vdbe
*p
){
678 pOp
= &p
->aOp
[nOp
-1];
679 if( pOp
->opcode
==OP_Noop
&& pOp
->p3
!=0 ){
680 const char *z
= pOp
->p3
;
681 while( isspace(*(u8
*)z
) ) z
++;
682 printf("SQL: [%s]\n", z
);
688 ** Prepare a virtual machine for execution. This involves things such
689 ** as allocating stack space and initializing the program counter.
690 ** After the VDBE has be prepped, it can be executed by one or more
691 ** calls to sqlite3VdbeExec().
693 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
696 void sqlite3VdbeMakeReady(
697 Vdbe
*p
, /* The VDBE */
698 int nVar
, /* Number of '?' see in the SQL statement */
699 int nMem
, /* Number of memory cells to allocate */
700 int nCursor
, /* Number of cursors to allocate */
701 int nAgg
, /* Number of aggregate contexts required */
702 int isExplain
/* True if the EXPLAIN keywords is present */
707 assert( p
->magic
==VDBE_MAGIC_INIT
);
709 /* There should be at least one opcode.
713 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
714 * is because the call to resizeOpArray() below may shrink the
715 * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
718 p
->magic
= VDBE_MAGIC_RUN
;
720 /* No instruction ever pushes more than a single element onto the
721 ** stack. And the stack never grows on successive executions of the
722 ** same loop. So the total number of instructions is an upper bound
723 ** on the maximum stack depth required. (Added later:) The
724 ** resolveP2Values() call computes a tighter upper bound on the
727 ** Allocation all the stack space we will ever need.
730 int nArg
; /* Maximum number of args passed to a user function. */
731 int nStack
; /* Maximum number of stack entries required */
732 resolveP2Values(p
, &nArg
, &nStack
);
733 resizeOpArray(p
, p
->nOp
);
735 assert( nStack
<p
->nOp
);
736 nStack
= isExplain
? 10 : nStack
;
737 p
->aStack
= sqliteMalloc(
738 nStack
*sizeof(p
->aStack
[0]) /* aStack */
739 + nArg
*sizeof(Mem
*) /* apArg */
740 + nVar
*sizeof(Mem
) /* aVar */
741 + nVar
*sizeof(char*) /* azVar */
742 + nMem
*sizeof(Mem
) /* aMem */
743 + nCursor
*sizeof(Cursor
*) /* apCsr */
744 + nAgg
*sizeof(Agg
) /* Aggregate contexts */
746 if( !sqlite3_malloc_failed
){
747 p
->aMem
= &p
->aStack
[nStack
];
749 p
->aVar
= &p
->aMem
[nMem
];
752 p
->apArg
= (Mem
**)&p
->aVar
[nVar
];
753 p
->azVar
= (char**)&p
->apArg
[nArg
];
754 p
->apCsr
= (Cursor
**)&p
->azVar
[nVar
];
757 p
->apAgg
= (Agg
*)&p
->apCsr
[nCursor
];
759 p
->nCursor
= nCursor
;
760 for(n
=0; n
<nVar
; n
++){
761 p
->aVar
[n
].flags
= MEM_Null
;
766 for(n
=0; n
<p
->nMem
; n
++){
767 p
->aMem
[n
].flags
= MEM_Null
;
771 if( (p
->db
->flags
& SQLITE_VdbeListing
)!=0
772 || sqlite3OsFileExists("vdbe_explain")
775 printf("VDBE Program Listing:\n");
776 sqlite3VdbePrintSql(p
);
777 for(i
=0; i
<p
->nOp
; i
++){
778 sqlite3VdbePrintOp(stdout
, i
, &p
->aOp
[i
]);
781 if( sqlite3OsFileExists("vdbe_trace") ){
785 p
->pTos
= &p
->aStack
[-1];
790 p
->errorAction
= OE_Abort
;
792 p
->explain
|= isExplain
;
793 p
->magic
= VDBE_MAGIC_RUN
;
798 for(i
=0; i
<p
->nOp
; i
++){
800 p
->aOp
[i
].cycles
= 0;
808 ** Remove any elements that remain on the sorter for the VDBE given.
810 void sqlite3VdbeSorterReset(Vdbe
*p
){
812 Sorter
*pSorter
= p
->pSort
;
813 p
->pSort
= pSorter
->pNext
;
814 sqliteFree(pSorter
->zKey
);
815 sqlite3VdbeMemRelease(&pSorter
->data
);
822 ** Free all resources allociated with AggElem pElem, an element of
825 static void freeAggElem(AggElem
*pElem
, Agg
*pAgg
){
827 for(i
=0; i
<pAgg
->nMem
; i
++){
828 Mem
*pMem
= &pElem
->aMem
[i
];
829 if( pAgg
->apFunc
&& pAgg
->apFunc
[i
] && (pMem
->flags
& MEM_AggCtx
)!=0 ){
831 ctx
.pFunc
= pAgg
->apFunc
[i
];
832 ctx
.s
.flags
= MEM_Null
;
836 (*ctx
.pFunc
->xFinalize
)(&ctx
);
838 if( pMem
->z
!=0 && pMem
->z
!=pMem
->zShort
){
841 sqlite3VdbeMemRelease(&ctx
.s
);
843 sqlite3VdbeMemRelease(pMem
);
850 ** Reset an Agg structure. Delete all its contents.
852 ** For installable aggregate functions, if the step function has been
853 ** called, make sure the finalizer function has also been called. The
854 ** finalizer might need to free memory that was allocated as part of its
855 ** private context. If the finalizer has not been called yet, call it
858 ** If db is NULL, then this is being called from sqliteVdbeReset(). In
859 ** this case clean up all references to the temp-table used for
860 ** aggregates (if it was ever opened).
862 ** If db is not NULL, then this is being called from with an OP_AggReset
863 ** opcode. Open the temp-table, if it has not already been opened and
864 ** delete the contents of the table used for aggregate information, ready
865 ** for the next round of aggregate processing.
867 int sqlite3VdbeAggReset(sqlite3
*db
, Agg
*pAgg
, KeyInfo
*pKeyInfo
){
871 if( !pAgg
) return SQLITE_OK
;
873 assert( (pCsr
&& pAgg
->nTab
>0) || (!pCsr
&& pAgg
->nTab
==0)
874 || sqlite3_malloc_failed
);
876 /* If pCsr is not NULL, then the table used for aggregate information
877 ** is open. Loop through it and free the AggElem* structure pointed at
878 ** by each entry. If the finalizer has not been called for an AggElem,
879 ** do that too. Finally, clear the btree table itself.
883 assert( pAgg
->pBtree
);
884 assert( pAgg
->nTab
>0 );
886 rc
=sqlite3BtreeFirst(pCsr
, &res
);
887 while( res
==0 && rc
==SQLITE_OK
){
889 rc
= sqlite3BtreeData(pCsr
, 0, sizeof(AggElem
*), (char *)&pElem
);
893 assert( pAgg
->apFunc
!=0 );
894 freeAggElem(pElem
, pAgg
);
895 rc
=sqlite3BtreeNext(pCsr
, &res
);
901 sqlite3BtreeCloseCursor(pCsr
);
902 sqlite3BtreeClearTable(pAgg
->pBtree
, pAgg
->nTab
);
904 /* The cursor may not be open because the aggregator was never used,
905 ** or it could be that it was used but there was no GROUP BY clause.
907 if( pAgg
->pCurrent
){
908 freeAggElem(pAgg
->pCurrent
, pAgg
);
912 /* If db is not NULL and we have not yet and we have not yet opened
913 ** the temporary btree then do so and create the table to store aggregate
916 ** If db is NULL, then close the temporary btree if it is open.
920 assert( pAgg
->nTab
==0 );
921 #ifndef SQLITE_OMIT_MEMORYDB
922 rc
= sqlite3BtreeFactory(db
, ":memory:", 0, TEMP_PAGES
, &pAgg
->pBtree
);
924 rc
= sqlite3BtreeFactory(db
, 0, 0, TEMP_PAGES
, &pAgg
->pBtree
);
926 if( rc
!=SQLITE_OK
) return rc
;
927 sqlite3BtreeBeginTrans(pAgg
->pBtree
, 1);
928 rc
= sqlite3BtreeCreateTable(pAgg
->pBtree
, &pAgg
->nTab
, 0);
929 if( rc
!=SQLITE_OK
) return rc
;
931 assert( pAgg
->nTab
!=0 );
933 rc
= sqlite3BtreeCursor(pAgg
->pBtree
, pAgg
->nTab
, 1,
934 sqlite3VdbeRecordCompare
, pKeyInfo
, &pAgg
->pCsr
);
935 if( rc
!=SQLITE_OK
) return rc
;
938 sqlite3BtreeClose(pAgg
->pBtree
);
946 sqliteFree(pAgg
->apFunc
);
959 void sqlite3VdbeKeylistFree(Keylist
*p
){
961 Keylist
*pNext
= p
->pNext
;
968 ** Close a cursor and release all the resources that cursor happens
971 void sqlite3VdbeFreeCursor(Cursor
*pCx
){
976 sqlite3BtreeCloseCursor(pCx
->pCursor
);
979 sqlite3BtreeClose(pCx
->pBt
);
981 sqliteFree(pCx
->pData
);
982 sqliteFree(pCx
->aType
);
989 static void closeAllCursors(Vdbe
*p
){
991 if( p
->apCsr
==0 ) return;
992 for(i
=0; i
<p
->nCursor
; i
++){
993 sqlite3VdbeFreeCursor(p
->apCsr
[i
]);
999 ** Clean up the VM after execution.
1001 ** This routine will automatically close any cursors, lists, and/or
1002 ** sorters that were left open. It also deletes the values of
1003 ** variables in the aVar[] array.
1005 static void Cleanup(Vdbe
*p
){
1008 releaseMemArray(p
->aStack
, 1 + (p
->pTos
- p
->aStack
));
1009 p
->pTos
= &p
->aStack
[-1];
1012 releaseMemArray(p
->aMem
, p
->nMem
);
1014 sqlite3VdbeKeylistFree(p
->pList
);
1017 if( p
->contextStack
){
1018 for(i
=0; i
<p
->contextStackTop
; i
++){
1019 sqlite3VdbeKeylistFree(p
->contextStack
[i
].pList
);
1021 sqliteFree(p
->contextStack
);
1023 sqlite3VdbeSorterReset(p
);
1024 for(i
=0; i
<p
->nAgg
; i
++){
1025 sqlite3VdbeAggReset(0, &p
->apAgg
[i
], 0);
1027 p
->contextStack
= 0;
1028 p
->contextStackDepth
= 0;
1029 p
->contextStackTop
= 0;
1030 sqliteFree(p
->zErrMsg
);
1035 ** Set the number of result columns that will be returned by this SQL
1036 ** statement. This is now set at compile time, rather than during
1037 ** execution of the vdbe program so that sqlite3_column_count() can
1038 ** be called on an SQL statement before sqlite3_step().
1040 void sqlite3VdbeSetNumCols(Vdbe
*p
, int nResColumn
){
1043 assert( 0==p
->nResColumn
);
1044 p
->nResColumn
= nResColumn
;
1046 p
->aColName
= pColName
= (Mem
*)sqliteMalloc( sizeof(Mem
)*n
);
1047 if( p
->aColName
==0 ) return;
1049 (pColName
++)->flags
= MEM_Null
;
1054 ** Set the name of the idx'th column to be returned by the SQL statement.
1055 ** zName must be a pointer to a nul terminated string.
1057 ** This call must be made after a call to sqlite3VdbeSetNumCols().
1059 ** If N==P3_STATIC it means that zName is a pointer to a constant static
1060 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then
1061 ** the string is freed using sqliteFree() when the vdbe is finished with
1062 ** it. Otherwise, N bytes of zName are copied.
1064 int sqlite3VdbeSetColName(Vdbe
*p
, int idx
, const char *zName
, int N
){
1067 assert( idx
<(2*p
->nResColumn
) );
1068 if( sqlite3_malloc_failed
) return SQLITE_NOMEM
;
1069 assert( p
->aColName
!=0 );
1070 pColName
= &(p
->aColName
[idx
]);
1071 if( N
==P3_DYNAMIC
|| N
==P3_STATIC
){
1072 rc
= sqlite3VdbeMemSetStr(pColName
, zName
, -1, SQLITE_UTF8
, SQLITE_STATIC
);
1074 rc
= sqlite3VdbeMemSetStr(pColName
, zName
, N
, SQLITE_UTF8
,SQLITE_TRANSIENT
);
1076 if( rc
==SQLITE_OK
&& N
==P3_DYNAMIC
){
1077 pColName
->flags
= (pColName
->flags
&(~MEM_Static
))|MEM_Dyn
;
1084 ** A read or write transaction may or may not be active on database handle
1085 ** db. If a transaction is active, commit it. If there is a
1086 ** write-transaction spanning more than one database file, this routine
1087 ** takes care of the master journal trickery.
1089 static int vdbeCommit(sqlite3
*db
){
1091 int nTrans
= 0; /* Number of databases with an active write-transaction */
1093 int needXcommit
= 0;
1095 for(i
=0; i
<db
->nDb
; i
++){
1096 Btree
*pBt
= db
->aDb
[i
].pBt
;
1097 if( pBt
&& sqlite3BtreeIsInTrans(pBt
) ){
1099 if( i
!=1 ) nTrans
++;
1103 /* If there are any write-transactions at all, invoke the commit hook */
1104 if( needXcommit
&& db
->xCommitCallback
){
1106 sqlite3SafetyOff(db
);
1107 rc
= db
->xCommitCallback(db
->pCommitArg
);
1108 sqlite3SafetyOn(db
);
1110 return SQLITE_CONSTRAINT
;
1114 /* The simple case - no more than one database file (not counting the
1115 ** TEMP database) has a transaction active. There is no need for the
1118 ** If the return value of sqlite3BtreeGetFilename() is a zero length
1119 ** string, it means the main database is :memory:. In that case we do
1120 ** not support atomic multi-file commits, so use the simple case then
1123 if( 0==strlen(sqlite3BtreeGetFilename(db
->aDb
[0].pBt
)) || nTrans
<=1 ){
1124 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
1125 Btree
*pBt
= db
->aDb
[i
].pBt
;
1127 rc
= sqlite3BtreeSync(pBt
, 0);
1131 /* Do the commit only if all databases successfully synced */
1132 if( rc
==SQLITE_OK
){
1133 for(i
=0; i
<db
->nDb
; i
++){
1134 Btree
*pBt
= db
->aDb
[i
].pBt
;
1136 sqlite3BtreeCommit(pBt
);
1142 /* The complex case - There is a multi-file write-transaction active.
1143 ** This requires a master journal file to ensure the transaction is
1144 ** committed atomicly.
1146 #ifndef SQLITE_OMIT_DISKIO
1148 char *zMaster
= 0; /* File-name for the master journal */
1149 char const *zMainFile
= sqlite3BtreeGetFilename(db
->aDb
[0].pBt
);
1152 /* Select a master journal file name */
1155 sqliteFree(zMaster
);
1156 sqlite3Randomness(sizeof(random
), &random
);
1157 zMaster
= sqlite3MPrintf("%s-mj%08X", zMainFile
, random
&0x7fffffff);
1159 return SQLITE_NOMEM
;
1161 }while( sqlite3OsFileExists(zMaster
) );
1163 /* Open the master journal. */
1164 memset(&master
, 0, sizeof(master
));
1165 rc
= sqlite3OsOpenExclusive(zMaster
, &master
, 0);
1166 if( rc
!=SQLITE_OK
){
1167 sqliteFree(zMaster
);
1171 /* Write the name of each database file in the transaction into the new
1172 ** master journal file. If an error occurs at this point close
1173 ** and delete the master journal file. All the individual journal files
1174 ** still have 'null' as the master journal pointer, so they will roll
1175 ** back independently if a failure occurs.
1177 for(i
=0; i
<db
->nDb
; i
++){
1178 Btree
*pBt
= db
->aDb
[i
].pBt
;
1179 if( i
==1 ) continue; /* Ignore the TEMP database */
1180 if( pBt
&& sqlite3BtreeIsInTrans(pBt
) ){
1181 char const *zFile
= sqlite3BtreeGetJournalname(pBt
);
1182 if( zFile
[0]==0 ) continue; /* Ignore :memory: databases */
1183 rc
= sqlite3OsWrite(&master
, zFile
, strlen(zFile
)+1);
1184 if( rc
!=SQLITE_OK
){
1185 sqlite3OsClose(&master
);
1186 sqlite3OsDelete(zMaster
);
1187 sqliteFree(zMaster
);
1194 /* Sync the master journal file. Before doing this, open the directory
1195 ** the master journal file is store in so that it gets synced too.
1197 zMainFile
= sqlite3BtreeGetDirname(db
->aDb
[0].pBt
);
1198 rc
= sqlite3OsOpenDirectory(zMainFile
, &master
);
1199 if( rc
!=SQLITE_OK
|| (rc
= sqlite3OsSync(&master
))!=SQLITE_OK
){
1200 sqlite3OsClose(&master
);
1201 sqlite3OsDelete(zMaster
);
1202 sqliteFree(zMaster
);
1206 /* Sync all the db files involved in the transaction. The same call
1207 ** sets the master journal pointer in each individual journal. If
1208 ** an error occurs here, do not delete the master journal file.
1210 ** If the error occurs during the first call to sqlite3BtreeSync(),
1211 ** then there is a chance that the master journal file will be
1212 ** orphaned. But we cannot delete it, in case the master journal
1213 ** file name was written into the journal file before the failure
1216 for(i
=0; i
<db
->nDb
; i
++){
1217 Btree
*pBt
= db
->aDb
[i
].pBt
;
1218 if( pBt
&& sqlite3BtreeIsInTrans(pBt
) ){
1219 rc
= sqlite3BtreeSync(pBt
, zMaster
);
1220 if( rc
!=SQLITE_OK
){
1221 sqlite3OsClose(&master
);
1222 sqliteFree(zMaster
);
1227 sqlite3OsClose(&master
);
1229 /* Delete the master journal file. This commits the transaction. After
1230 ** doing this the directory is synced again before any individual
1231 ** transaction files are deleted.
1233 rc
= sqlite3OsDelete(zMaster
);
1234 assert( rc
==SQLITE_OK
);
1235 sqliteFree(zMaster
);
1237 rc
= sqlite3OsSyncDirectory(zMainFile
);
1238 if( rc
!=SQLITE_OK
){
1239 /* This is not good. The master journal file has been deleted, but
1240 ** the directory sync failed. There is no completely safe course of
1241 ** action from here. The individual journals contain the name of the
1242 ** master journal file, but there is no way of knowing if that
1243 ** master journal exists now or if it will exist after the operating
1244 ** system crash that may follow the fsync() failure.
1249 /* All files and directories have already been synced, so the following
1250 ** calls to sqlite3BtreeCommit() are only closing files and deleting
1251 ** journals. If something goes wrong while this is happening we don't
1252 ** really care. The integrity of the transaction is already guaranteed,
1253 ** but some stray 'cold' journals may be lying around. Returning an
1254 ** error code won't help matters.
1256 for(i
=0; i
<db
->nDb
; i
++){
1257 Btree
*pBt
= db
->aDb
[i
].pBt
;
1259 sqlite3BtreeCommit(pBt
);
1269 ** Find every active VM other than pVdbe and change its status to
1270 ** aborted. This happens when one VM causes a rollback due to an
1271 ** ON CONFLICT ROLLBACK clause (for example). The other VMs must be
1272 ** aborted so that they do not have data rolled out from underneath
1273 ** them leading to a segfault.
1275 static void abortOtherActiveVdbes(Vdbe
*pVdbe
){
1277 for(pOther
=pVdbe
->db
->pVdbe
; pOther
; pOther
=pOther
->pNext
){
1278 if( pOther
==pVdbe
) continue;
1279 if( pOther
->magic
!=VDBE_MAGIC_RUN
|| pOther
->pc
<0 ) continue;
1280 closeAllCursors(pOther
);
1281 pOther
->aborted
= 1;
1286 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1287 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1288 ** currently active. An assertion fails if the two counts do not match.
1289 ** This is an internal self-check only - it is not an essential processing
1292 ** This is a no-op if NDEBUG is defined.
1295 static void checkActiveVdbeCnt(sqlite3
*db
){
1300 if( p
->magic
==VDBE_MAGIC_RUN
&& p
->pc
>=0 ){
1305 assert( cnt
==db
->activeVdbeCnt
);
1308 #define checkActiveVdbeCnt(x)
1312 ** This routine is called the when a VDBE tries to halt. If the VDBE
1313 ** has made changes and is in autocommit mode, then commit those
1314 ** changes. If a rollback is needed, then do the rollback.
1316 ** This routine is the only way to move the state of a VM from
1317 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
1319 ** Return an error code. If the commit could not complete because of
1320 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
1321 ** means the close did not happen and needs to be repeated.
1323 int sqlite3VdbeHalt(Vdbe
*p
){
1324 sqlite3
*db
= p
->db
;
1326 int (*xFunc
)(Btree
*pBt
) = 0; /* Function to call on each btree backend */
1328 if( p
->magic
!=VDBE_MAGIC_RUN
){
1329 /* Already halted. Nothing to do. */
1330 assert( p
->magic
==VDBE_MAGIC_HALT
);
1334 checkActiveVdbeCnt(db
);
1336 /* No commit or rollback needed if the program never started */
1337 }else if( db
->autoCommit
&& db
->activeVdbeCnt
==1 ){
1338 if( p
->rc
==SQLITE_OK
|| p
->errorAction
==OE_Fail
){
1339 /* The auto-commit flag is true, there are no other active queries
1340 ** using this handle and the vdbe program was successful or hit an
1341 ** 'OR FAIL' constraint. This means a commit is required.
1343 int rc
= vdbeCommit(db
);
1344 if( rc
==SQLITE_BUSY
){
1346 }else if( rc
!=SQLITE_OK
){
1348 xFunc
= sqlite3BtreeRollback
;
1351 xFunc
= sqlite3BtreeRollback
;
1354 if( p
->rc
==SQLITE_OK
|| p
->errorAction
==OE_Fail
){
1355 xFunc
= sqlite3BtreeCommitStmt
;
1356 }else if( p
->errorAction
==OE_Abort
){
1357 xFunc
= sqlite3BtreeRollbackStmt
;
1359 xFunc
= sqlite3BtreeRollback
;
1361 abortOtherActiveVdbes(p
);
1365 /* If xFunc is not NULL, then it is one of sqlite3BtreeRollback,
1366 ** sqlite3BtreeRollbackStmt or sqlite3BtreeCommitStmt. Call it once on
1367 ** each backend. If an error occurs and the return code is still
1368 ** SQLITE_OK, set the return code to the new error value.
1370 for(i
=0; xFunc
&& i
<db
->nDb
; i
++){
1372 Btree
*pBt
= db
->aDb
[i
].pBt
;
1375 if( p
->rc
==SQLITE_OK
) p
->rc
= rc
;
1379 /* If this was an INSERT, UPDATE or DELETE, set the change counter. */
1380 if( p
->changeCntOn
&& p
->pc
>=0 ){
1381 if( !xFunc
|| xFunc
==sqlite3BtreeCommitStmt
){
1382 sqlite3VdbeSetChanges(db
, p
->nChange
);
1384 sqlite3VdbeSetChanges(db
, 0);
1389 /* Rollback or commit any schema changes that occurred. */
1390 if( p
->rc
!=SQLITE_OK
){
1391 sqlite3RollbackInternalChanges(db
);
1392 }else if( db
->flags
& SQLITE_InternChanges
){
1393 sqlite3CommitInternalChanges(db
);
1396 /* We have successfully halted and closed the VM. Record this fact. */
1398 db
->activeVdbeCnt
--;
1400 p
->magic
= VDBE_MAGIC_HALT
;
1401 checkActiveVdbeCnt(db
);
1407 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
1408 ** Write any error messages into *pzErrMsg. Return the result code.
1410 ** After this routine is run, the VDBE should be ready to be executed
1413 ** To look at it another way, this routine resets the state of the
1414 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
1417 int sqlite3VdbeReset(Vdbe
*p
){
1418 if( p
->magic
!=VDBE_MAGIC_RUN
&& p
->magic
!=VDBE_MAGIC_HALT
){
1419 sqlite3Error(p
->db
, SQLITE_MISUSE
, 0);
1420 return SQLITE_MISUSE
;
1423 /* If the VM did not run to completion or if it encountered an
1424 ** error, then it might not have been halted properly. So halt
1429 /* If the VDBE has be run even partially, then transfer the error code
1430 ** and error message from the VDBE into the main database structure. But
1431 ** if the VDBE has just been set to run but has not actually executed any
1432 ** instructions yet, leave the main database error information unchanged.
1436 sqlite3Error(p
->db
, p
->rc
, "%s", p
->zErrMsg
);
1437 sqliteFree(p
->zErrMsg
);
1440 sqlite3Error(p
->db
, p
->rc
, 0);
1442 sqlite3Error(p
->db
, SQLITE_OK
, 0);
1444 }else if( p
->rc
&& p
->expired
){
1445 /* The expired flag was set on the VDBE before the first call
1446 ** to sqlite3_step(). For consistency (since sqlite3_step() was
1447 ** called), set the database error in this case as well.
1449 sqlite3Error(p
->db
, p
->rc
, 0);
1452 /* Reclaim all memory used by the VDBE
1456 /* Save profiling information from this VDBE run.
1458 assert( p
->pTos
<&p
->aStack
[p
->pc
<0?0:p
->pc
] || sqlite3_malloc_failed
==1 );
1461 FILE *out
= fopen("vdbe_profile.out", "a");
1464 fprintf(out
, "---- ");
1465 for(i
=0; i
<p
->nOp
; i
++){
1466 fprintf(out
, "%02x", p
->aOp
[i
].opcode
);
1469 for(i
=0; i
<p
->nOp
; i
++){
1470 fprintf(out
, "%6d %10lld %8lld ",
1473 p
->aOp
[i
].cnt
>0 ? p
->aOp
[i
].cycles
/p
->aOp
[i
].cnt
: 0
1475 sqlite3VdbePrintOp(out
, i
, &p
->aOp
[i
]);
1481 p
->magic
= VDBE_MAGIC_INIT
;
1483 if( p
->rc
==SQLITE_SCHEMA
){
1484 sqlite3ResetInternalSchema(p
->db
, 0);
1490 ** Clean up and delete a VDBE after execution. Return an integer which is
1491 ** the result code. Write any error message text into *pzErrMsg.
1493 int sqlite3VdbeFinalize(Vdbe
*p
){
1496 if( p
->magic
==VDBE_MAGIC_RUN
|| p
->magic
==VDBE_MAGIC_HALT
){
1497 rc
= sqlite3VdbeReset(p
);
1498 }else if( p
->magic
!=VDBE_MAGIC_INIT
){
1499 return SQLITE_MISUSE
;
1501 sqlite3VdbeDelete(p
);
1506 ** Call the destructor for each auxdata entry in pVdbeFunc for which
1507 ** the corresponding bit in mask is clear. Auxdata entries beyond 31
1508 ** are always destroyed. To destroy all auxdata entries, call this
1509 ** routine with mask==0.
1511 void sqlite3VdbeDeleteAuxData(VdbeFunc
*pVdbeFunc
, int mask
){
1513 for(i
=0; i
<pVdbeFunc
->nAux
; i
++){
1514 struct AuxData
*pAux
= &pVdbeFunc
->apAux
[i
];
1515 if( (i
>31 || !(mask
&(1<<i
))) && pAux
->pAux
){
1516 if( pAux
->xDelete
){
1517 pAux
->xDelete(pAux
->pAux
);
1525 ** Delete an entire VDBE.
1527 void sqlite3VdbeDelete(Vdbe
*p
){
1532 p
->pPrev
->pNext
= p
->pNext
;
1534 assert( p
->db
->pVdbe
==p
);
1535 p
->db
->pVdbe
= p
->pNext
;
1538 p
->pNext
->pPrev
= p
->pPrev
;
1541 for(i
=0; i
<p
->nOp
; i
++){
1542 Op
*pOp
= &p
->aOp
[i
];
1543 if( pOp
->p3type
==P3_DYNAMIC
|| pOp
->p3type
==P3_KEYINFO
){
1544 sqliteFree(pOp
->p3
);
1546 if( pOp
->p3type
==P3_VDBEFUNC
){
1547 VdbeFunc
*pVdbeFunc
= (VdbeFunc
*)pOp
->p3
;
1548 sqlite3VdbeDeleteAuxData(pVdbeFunc
, 0);
1549 sqliteFree(pVdbeFunc
);
1551 if( pOp
->p3type
==P3_MEM
){
1552 sqlite3ValueFree((sqlite3_value
*)pOp
->p3
);
1557 releaseMemArray(p
->aVar
, p
->nVar
);
1558 sqliteFree(p
->aLabel
);
1559 sqliteFree(p
->aStack
);
1560 releaseMemArray(p
->aColName
, p
->nResColumn
*2);
1561 sqliteFree(p
->aColName
);
1562 p
->magic
= VDBE_MAGIC_DEAD
;
1567 ** If a MoveTo operation is pending on the given cursor, then do that
1568 ** MoveTo now. Return an error code. If no MoveTo is pending, this
1569 ** routine does nothing and returns SQLITE_OK.
1571 int sqlite3VdbeCursorMoveto(Cursor
*p
){
1572 if( p
->deferredMoveto
){
1574 extern int sqlite3_search_count
;
1575 assert( p
->isTable
);
1577 rc
= sqlite3BtreeMoveto(p
->pCursor
, 0, p
->movetoTarget
, &res
);
1579 rc
= sqlite3BtreeMoveto(p
->pCursor
,(char*)&p
->movetoTarget
,
1584 p
->lastRowid
= keyToInt(p
->movetoTarget
);
1585 p
->rowidIsValid
= res
==0;
1587 rc
= sqlite3BtreeNext(p
->pCursor
, &res
);
1590 sqlite3_search_count
++;
1591 p
->deferredMoveto
= 0;
1598 ** The following functions:
1600 ** sqlite3VdbeSerialType()
1601 ** sqlite3VdbeSerialTypeLen()
1602 ** sqlite3VdbeSerialRead()
1603 ** sqlite3VdbeSerialLen()
1604 ** sqlite3VdbeSerialWrite()
1606 ** encapsulate the code that serializes values for storage in SQLite
1607 ** data and index records. Each serialized value consists of a
1608 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
1609 ** integer, stored as a varint.
1611 ** In an SQLite index record, the serial type is stored directly before
1612 ** the blob of data that it corresponds to. In a table record, all serial
1613 ** types are stored at the start of the record, and the blobs of data at
1614 ** the end. Hence these functions allow the caller to handle the
1615 ** serial-type and data blob seperately.
1617 ** The following table describes the various storage classes for data:
1619 ** serial type bytes of data type
1620 ** -------------- --------------- ---------------
1622 ** 1 1 signed integer
1623 ** 2 2 signed integer
1624 ** 3 3 signed integer
1625 ** 4 4 signed integer
1626 ** 5 6 signed integer
1627 ** 6 8 signed integer
1629 ** 8-11 reserved for expansion
1630 ** N>=12 and even (N-12)/2 BLOB
1631 ** N>=13 and odd (N-13)/2 text
1636 ** Return the serial-type for the value stored in pMem.
1638 u32
sqlite3VdbeSerialType(Mem
*pMem
){
1639 int flags
= pMem
->flags
;
1641 if( flags
&MEM_Null
){
1644 if( flags
&MEM_Int
){
1645 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
1646 # define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
1648 u64 u
= i
<0 ? -i
: i
;
1649 if( u
<=127 ) return 1;
1650 if( u
<=32767 ) return 2;
1651 if( u
<=8388607 ) return 3;
1652 if( u
<=2147483647 ) return 4;
1653 if( u
<=MAX_6BYTE
) return 5;
1656 if( flags
&MEM_Real
){
1659 if( flags
&MEM_Str
){
1662 return ((n
*2) + 13);
1664 if( flags
&MEM_Blob
){
1665 return (pMem
->n
*2 + 12);
1671 ** Return the length of the data corresponding to the supplied serial-type.
1673 int sqlite3VdbeSerialTypeLen(u32 serial_type
){
1674 if( serial_type
>=12 ){
1675 return (serial_type
-12)/2;
1677 static const u8 aSize
[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
1678 return aSize
[serial_type
];
1683 ** Write the serialized data blob for the value stored in pMem into
1684 ** buf. It is assumed that the caller has allocated sufficient space.
1685 ** Return the number of bytes written.
1687 int sqlite3VdbeSerialPut(unsigned char *buf
, Mem
*pMem
){
1688 u32 serial_type
= sqlite3VdbeSerialType(pMem
);
1692 if( serial_type
==0 ){
1696 /* Integer and Real */
1697 if( serial_type
<=7 ){
1700 if( serial_type
==7 ){
1701 v
= *(u64
*)&pMem
->r
;
1703 v
= *(u64
*)&pMem
->i
;
1705 len
= i
= sqlite3VdbeSerialTypeLen(serial_type
);
1713 /* String or blob */
1714 assert( serial_type
>=12 );
1715 len
= sqlite3VdbeSerialTypeLen(serial_type
);
1716 memcpy(buf
, pMem
->z
, len
);
1721 ** Deserialize the data blob pointed to by buf as serial type serial_type
1722 ** and store the result in pMem. Return the number of bytes read.
1724 int sqlite3VdbeSerialGet(
1725 const unsigned char *buf
, /* Buffer to deserialize from */
1726 u32 serial_type
, /* Serial type to deserialize */
1727 Mem
*pMem
/* Memory cell to write value into */
1729 switch( serial_type
){
1730 case 8: /* Reserved for future use */
1731 case 9: /* Reserved for future use */
1732 case 10: /* Reserved for future use */
1733 case 11: /* Reserved for future use */
1734 case 0: { /* NULL */
1735 pMem
->flags
= MEM_Null
;
1738 case 1: { /* 1-byte signed integer */
1739 pMem
->i
= (signed char)buf
[0];
1740 pMem
->flags
= MEM_Int
;
1743 case 2: { /* 2-byte signed integer */
1744 pMem
->i
= (((signed char)buf
[0])<<8) | buf
[1];
1745 pMem
->flags
= MEM_Int
;
1748 case 3: { /* 3-byte signed integer */
1749 pMem
->i
= (((signed char)buf
[0])<<16) | (buf
[1]<<8) | buf
[2];
1750 pMem
->flags
= MEM_Int
;
1753 case 4: { /* 4-byte signed integer */
1754 pMem
->i
= (buf
[0]<<24) | (buf
[1]<<16) | (buf
[2]<<8) | buf
[3];
1755 pMem
->flags
= MEM_Int
;
1758 case 5: { /* 6-byte signed integer */
1759 u64 x
= (((signed char)buf
[0])<<8) | buf
[1];
1760 u32 y
= (buf
[2]<<24) | (buf
[3]<<16) | (buf
[4]<<8) | buf
[5];
1762 pMem
->i
= *(i64
*)&x
;
1763 pMem
->flags
= MEM_Int
;
1766 case 6: /* 6-byte signed integer */
1767 case 7: { /* IEEE floating point */
1768 u64 x
= (buf
[0]<<24) | (buf
[1]<<16) | (buf
[2]<<8) | buf
[3];
1769 u32 y
= (buf
[4]<<24) | (buf
[5]<<16) | (buf
[6]<<8) | buf
[7];
1771 if( serial_type
==6 ){
1772 pMem
->i
= *(i64
*)&x
;
1773 pMem
->flags
= MEM_Int
;
1775 pMem
->r
= *(double*)&x
;
1776 pMem
->flags
= MEM_Real
;
1781 int len
= (serial_type
-12)/2;
1782 pMem
->z
= (char *)buf
;
1785 if( serial_type
&0x01 ){
1786 pMem
->flags
= MEM_Str
| MEM_Ephem
;
1788 pMem
->flags
= MEM_Blob
| MEM_Ephem
;
1797 ** This function compares the two table rows or index records specified by
1798 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
1799 ** or positive integer if {nKey1, pKey1} is less than, equal to or
1800 ** greater than {nKey2, pKey2}. Both Key1 and Key2 must be byte strings
1801 ** composed by the OP_MakeRecord opcode of the VDBE.
1803 int sqlite3VdbeRecordCompare(
1805 int nKey1
, const void *pKey1
,
1806 int nKey2
, const void *pKey2
1808 KeyInfo
*pKeyInfo
= (KeyInfo
*)userData
;
1809 u32 d1
, d2
; /* Offset into aKey[] of next data element */
1810 u32 idx1
, idx2
; /* Offset into aKey[] of next header element */
1811 u32 szHdr1
, szHdr2
; /* Number of bytes in header */
1815 const unsigned char *aKey1
= (const unsigned char *)pKey1
;
1816 const unsigned char *aKey2
= (const unsigned char *)pKey2
;
1820 mem1
.enc
= pKeyInfo
->enc
;
1821 mem2
.enc
= pKeyInfo
->enc
;
1823 idx1
= sqlite3GetVarint32(pKey1
, &szHdr1
);
1825 idx2
= sqlite3GetVarint32(pKey2
, &szHdr2
);
1827 nField
= pKeyInfo
->nField
;
1828 while( idx1
<szHdr1
&& idx2
<szHdr2
){
1832 /* Read the serial types for the next element in each key. */
1833 idx1
+= sqlite3GetVarint32(&aKey1
[idx1
], &serial_type1
);
1834 if( d1
>=nKey1
&& sqlite3VdbeSerialTypeLen(serial_type1
)>0 ) break;
1835 idx2
+= sqlite3GetVarint32(&aKey2
[idx2
], &serial_type2
);
1836 if( d2
>=nKey2
&& sqlite3VdbeSerialTypeLen(serial_type2
)>0 ) break;
1838 /* Assert that there is enough space left in each key for the blob of
1839 ** data to go with the serial type just read. This assert may fail if
1840 ** the file is corrupted. Then read the value from each key into mem1
1841 ** and mem2 respectively.
1843 d1
+= sqlite3VdbeSerialGet(&aKey1
[d1
], serial_type1
, &mem1
);
1844 d2
+= sqlite3VdbeSerialGet(&aKey2
[d2
], serial_type2
, &mem2
);
1846 rc
= sqlite3MemCompare(&mem1
, &mem2
, i
<nField
? pKeyInfo
->aColl
[i
] : 0);
1847 if( mem1
.flags
& MEM_Dyn
) sqlite3VdbeMemRelease(&mem1
);
1848 if( mem2
.flags
& MEM_Dyn
) sqlite3VdbeMemRelease(&mem2
);
1855 /* One of the keys ran out of fields, but all the fields up to that point
1856 ** were equal. If the incrKey flag is true, then the second key is
1857 ** treated as larger.
1860 if( pKeyInfo
->incrKey
){
1862 }else if( d1
<nKey1
){
1864 }else if( d2
<nKey2
){
1869 if( pKeyInfo
->aSortOrder
&& i
<pKeyInfo
->nField
&& pKeyInfo
->aSortOrder
[i
] ){
1877 ** The argument is an index entry composed using the OP_MakeRecord opcode.
1878 ** The last entry in this record should be an integer (specifically
1879 ** an integer rowid). This routine returns the number of bytes in
1882 int sqlite3VdbeIdxRowidLen(int nKey
, const u8
*aKey
){
1883 u32 szHdr
; /* Size of the header */
1884 u32 typeRowid
; /* Serial type of the rowid */
1886 sqlite3GetVarint32(aKey
, &szHdr
);
1887 sqlite3GetVarint32(&aKey
[szHdr
-1], &typeRowid
);
1888 return sqlite3VdbeSerialTypeLen(typeRowid
);
1893 ** pCur points at an index entry created using the OP_MakeRecord opcode.
1894 ** Read the rowid (the last field in the record) and store it in *rowid.
1895 ** Return SQLITE_OK if everything works, or an error code otherwise.
1897 int sqlite3VdbeIdxRowid(BtCursor
*pCur
, i64
*rowid
){
1900 u32 szHdr
; /* Size of the header */
1901 u32 typeRowid
; /* Serial type of the rowid */
1902 u32 lenRowid
; /* Size of the rowid */
1905 sqlite3BtreeKeySize(pCur
, &nCellKey
);
1907 return SQLITE_CORRUPT
;
1909 rc
= sqlite3VdbeMemFromBtree(pCur
, 0, nCellKey
, 1, &m
);
1913 sqlite3GetVarint32(m
.z
, &szHdr
);
1914 sqlite3GetVarint32(&m
.z
[szHdr
-1], &typeRowid
);
1915 lenRowid
= sqlite3VdbeSerialTypeLen(typeRowid
);
1916 sqlite3VdbeSerialGet(&m
.z
[m
.n
-lenRowid
], typeRowid
, &v
);
1918 sqlite3VdbeMemRelease(&m
);
1923 ** Compare the key of the index entry that cursor pC is point to against
1924 ** the key string in pKey (of length nKey). Write into *pRes a number
1925 ** that is negative, zero, or positive if pC is less than, equal to,
1926 ** or greater than pKey. Return SQLITE_OK on success.
1928 ** pKey is either created without a rowid or is truncated so that it
1929 ** omits the rowid at the end. The rowid at the end of the index entry
1930 ** is ignored as well.
1932 int sqlite3VdbeIdxKeyCompare(
1933 Cursor
*pC
, /* The cursor to compare against */
1934 int nKey
, const u8
*pKey
, /* The key to compare */
1935 int *res
/* Write the comparison result here */
1939 BtCursor
*pCur
= pC
->pCursor
;
1943 sqlite3BtreeKeySize(pCur
, &nCellKey
);
1948 rc
= sqlite3VdbeMemFromBtree(pC
->pCursor
, 0, nCellKey
, 1, &m
);
1952 lenRowid
= sqlite3VdbeIdxRowidLen(m
.n
, m
.z
);
1953 *res
= sqlite3VdbeRecordCompare(pC
->pKeyInfo
, m
.n
-lenRowid
, m
.z
, nKey
, pKey
);
1954 sqlite3VdbeMemRelease(&m
);
1959 ** This routine sets the value to be returned by subsequent calls to
1960 ** sqlite3_changes() on the database handle 'db'.
1962 void sqlite3VdbeSetChanges(sqlite3
*db
, int nChange
){
1963 db
->nChange
= nChange
;
1964 db
->nTotalChange
+= nChange
;
1968 ** Set a flag in the vdbe to update the change counter when it is finalised
1971 void sqlite3VdbeCountChanges(Vdbe
*v
){
1976 ** Mark every prepared statement associated with a database connection
1979 ** An expired statement means that recompilation of the statement is
1980 ** recommend. Statements expire when things happen that make their
1981 ** programs obsolete. Removing user-defined functions or collating
1982 ** sequences, or changing an authorization function are the types of
1983 ** things that make prepared statements obsolete.
1985 void sqlite3ExpirePreparedStatements(sqlite3
*db
){
1987 for(p
= db
->pVdbe
; p
; p
=p
->pNext
){
1993 ** Return the database associated with the Vdbe.
1995 sqlite3
*sqlite3VdbeDb(Vdbe
*v
){